【问题标题】:Set value for llvm::ConstantInt设置 llvm::ConstantInt 的值
【发布时间】:2012-02-08 15:13:06
【问题描述】:

我在玩 LLVM。我考虑过在中间代码中更改常量的值。但是,对于 llvm::ConstantInt 类,我没有看到 setvalue 函数。知道如何修改 IR 代码中的常量值吗?

【问题讨论】:

    标签: c++ c llvm clang


    【解决方案1】:

    ConstantInt 是一个工厂,不是吗?类有get method 来构造新的常量:

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

    所以,我认为,您不能修改现有的 ConstantInt。如果要修改 IR,则应尝试更改指向参数的指针(更改 IR 本身,而不是常量对象)。

    也许你想要这样的东西(请记住,我对 LLVM 的经验为零;而且我几乎可以肯定这个例子是不正确的)。

    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);
    }
    

    要单独“修改”一个常量,有一个解决方案(递增和递减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 有关于创建和不删除Constantshttp://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
    

    【讨论】:

    • 我希望@Anton Korobeynikov 能够回答或评论我的代码。你也应该知道,setOperand 不能改变本身就是常数的东西。
    • 成功了!对于一个从未使用过它的人(你)来说真是太棒了!还展示了 LLVM 的编写有多好,因为它很容易学习和使用!
    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多