写一个pass以替换所有llvm指令

时间:2016-01-29 00:28:05

标签: c++11 llvm

我正在尝试编写一个llvm传递来通过乘法替换所有BinaryOperator指令,问题是只更换了第一条指令:

virtual bool runOnFunction(Function &F) {
  for (auto &B : F) {
     for (BasicBlock::iterator DI = B.begin(); DI != B.end(); ) {
      Instruction *Inst = DI++;

      if (auto *op = dyn_cast<BinaryOperator>(&*Inst)) {
        // Insert at the point where the instruction `op` appears.
        IRBuilder<> builder(op);

        // Make a multiply with the same operands as `op`.
        Value *lhs = op->getOperand(0);
        Value *rhs = op->getOperand(1);
        Value *mul = builder.CreateMul(lhs, rhs);

        // Everywhere the old instruction was used as an operand, use our
        // new multiply instruction instead.
        for (auto &U : op->uses()) {
          User *user = U.getUser();  // A User is anything with operands.
          user->setOperand(U.getOperandNo(), mul);
        }


        // We modified the code.
        return true;
      }


    }
  }

  return false;
}

2 个答案:

答案 0 :(得分:1)

试试这个

virtual bool runOnFunction(Function &F) {
  bool bModified = false;
 for (auto &B : F) {
  for (BasicBlock::iterator DI = B.begin(); DI != B.end(); ) {
   Instruction *Inst = DI++;

   if (auto *op = dyn_cast<BinaryOperator>(&*Inst)) {
    // Insert at the point where the instruction `op` appears.
    IRBuilder<> builder(op);

    // Make a multiply with the same operands as `op`.
    Value *lhs = op->getOperand(0);
    Value *rhs = op->getOperand(1);
    Value *mul = builder.CreateMul(lhs, rhs);

    // Everywhere the old instruction was used as an operand, use our
    // new multiply instruction instead.
    for (auto &U : op->uses()) {
      User *user = U.getUser();  // A User is anything with operands.
      user->setOperand(U.getOperandNo(), mul);
     }

    // We modified the code.
    bModified |= true;
    }
   }
 }
 return bModified;
}

答案 1 :(得分:0)

此代码完成工作:

 for (BasicBlock::iterator DI = B.begin(); DI != B.end(); ) {

  Instruction *Inst = DI++;

  if (auto *op = dyn_cast<BinaryOperator>(&*Inst)) {
    // Insert at the point where the instruction `op` appears.
    IRBuilder<> builder(op);

    // Make a multiply with the same operands as `op`.
    Value *lhs = op->getOperand(0);
    Value *rhs = op->getOperand(1);
    Value *mul = builder.CreateMul(lhs, rhs);

    // Everywhere the old instruction was used as an operand, use our
    // new multiply instruction instead.
    for (auto &U : op->uses()) {
      User *user = U.getUser();  // A User is anything with operands.
      user->setOperand(U.getOperandNo(), mul);
    }

    // We modified the code.

  }

  return true;
}