2012-02-14 48 views
0

比較IR操作我有一個IR看起來像這樣:具有恆定的LLVM

%5=icmp eq i32 %4,0 

我要檢查,如果ICMP指令的第二個操作數爲0或別的東西。我使用了getOperand(1),它返回格式爲Value *的結果。我怎樣才能比較它與常數0?

+0

專爲0,則是'val-> isZero()',多一點棘手的其他常量。我建議使用'match',參見InstructionSimplify.cpp瞭解大量示例。 – 2012-02-14 11:59:24

+0

@ SK邏輯:'Value'本身沒有'isZero',這是'ConstantInt'的一種方法。查看我的答案獲取更多詳情 – 2012-02-14 13:59:17

+0

@EliBendersky,當然,向ConstantInt提供動態演員是非常成功的。 – 2012-02-14 14:26:22

回答

3

這裏有一個抽樣合格可以運行發現了這一點:

class DetectZeroValuePass : public FunctionPass { 
public: 
    static char ID; 

    DetectZeroValuePass() 
     : FunctionPass(ID) 
    {} 

    virtual bool runOnFunction(Function &F) { 
     for (Function::iterator bb = F.begin(), bb_e = F.end(); bb != bb_e; ++bb) { 
      for (BasicBlock::iterator ii = bb->begin(), ii_e = bb->end(); ii != ii_e; ++ii) { 
       if (CmpInst *cmpInst = dyn_cast<CmpInst>(&*ii)) { 
        handle_cmp(cmpInst); 
       } 
      } 
     } 
    } 

    void handle_cmp(CmpInst *cmpInst) { 
     // Detect cmp instructions with the second operand being 0 
     if (cmpInst->getNumOperands() >= 2) { 
      Value *secondOperand = cmpInst->getOperand(1); 
      if (ConstantInt *CI = dyn_cast<ConstantInt>(secondOperand)) 
       if (CI->isZero()) { 
        errs() << "In the following instruction, second operand is 0\n"; 
        cmpInst->dump(); 
       } 
     } 
    } 
};