Set value for llvm::ConstantInt

主宰稳场 提交于 2019-12-31 16:50:00

问题


I'm playing around with LLVM. I thought about changing value of a constant in the intermediate code. However, for the class llvm::ConstantInt, I don't see a setvalue function. Any idea how can I modify value of a constant in the IR code?


回答1:


ConstantInt is a factory, isn't it? Class has the get method to construct new constant:

     /* ... return a ConstantInt for the given value. */
00069   static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);

So, I think, you can't modify existing ConstantInt. If you want to modify IR, you should try to change pointer to argument (change the IR itself, but not the constant object).

May be you want something like this (please remember, I have zero experience with LLVM; and I'm almost sure example is incorrect).

Instruction *I = /* your argument */;
/* check that instruction is of needed format, e.g: */
if (I->getOpcode() == Instruction::Add) {
   /* read the first operand of instruction */
   Value *oldvalue = I->getOperand(0);

   /* construct new constant; here 0x1234 is used as value */
   Value *newvalue = ConstantInt::get(oldValue->getType(), 0x1234); 

   /* replace operand with new value */
   I->setOperand(0, newvalue);
}

To "modify" a constant alone there is a solution (increment and decrement are illustrated):

 /// AddOne - Add one to a ConstantInt.
 static Constant *AddOne(Constant *C) {
   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
 }

 /// SubOne - Subtract one from a ConstantInt.
 static Constant *SubOne(ConstantInt *C) {
   return ConstantInt::get(C->getContext(), C->getValue()-1);
 }

PS, Constant.h has important comment in the begging about creating and non-deleting of Constants http://llvm.org/docs/doxygen/html/Constant_8h_source.html

00035 /// Note that Constants are immutable (once created they never change) 
00036 /// and are fully shared by structural equivalence.  This means that two 
00037 /// structurally equivalent constants will always have the same address.  
00038 /// Constants are created on demand as needed and never deleted: thus clients 
00039 /// don't have to worry about the lifetime of the objects.
00040 /// @brief LLVM Constant Representation


来源:https://stackoverflow.com/questions/9196009/set-value-for-llvmconstantint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!