24

I am writing an optimization for my compiler and I use LLVM IR as my Intermediate Language. I have parsed the input file and converted it to LLVM IR. During optimization, I need to retrieve the operands of the instructions. I am able to find getOpCode() in the Instruction class, but unable to retrieve the operand list. How do I go about that?

River
  • 8,585
  • 14
  • 54
  • 67
Chethan Ravindranath
  • 2,001
  • 2
  • 16
  • 28

2 Answers2

35

There are lots of operand accessors, usually provided by the class llvm::User, whose doxygen page is: http://llvm.org/doxygen/classllvm_1_1User.html There's getNumOperands() and getOperand(unsigned int), as well as iterator-style accessors op_begin() and op_end().

For example, given Instruction %X = add i32 %a, 2, I->getOperand(0) will return the Value* for %a, and I->getOperand(1) will return the Value* for i32 2 (castable to ConstantInt).

Thomson
  • 20,586
  • 28
  • 90
  • 134
  • 7
    How do I get `%X`? – Jithin Pavithran Mar 16 '18 at 13:58
  • 1
    I've found that it really depends on the type. For MachineInstrunctions it seems that zeroth operand is the return value, while arguments start from 1. For regular instruction it looks like the Instruction itself is the return type (can be casted to Value*). Not 100% sure though, this part is not really documented and I couldn't find any good info on it (apart from this SO question). – Dan M. Nov 01 '18 at 11:51
5

For instance, if you have Instruction* I1, I1->getOperand(0) will return the first operand of type Value*. You can go further, using I1->getOperand(0)->getName() that will return the name of the operand. See Value class methods.

River
  • 8,585
  • 14
  • 54
  • 67
Alex
  • 340
  • 4
  • 17