如何修复此“FunctionPass”,使其不会进入无限循环?

How to fix this `FunctionPass` such that it doesn't go into an infinite loop?

以下代码试图创建一个 FunctionPass 来遍历所有 BasicBlock,并将 a + b 更改为 (a xor b) + 2 * (a and b) 以进行混淆。

现在,当我使用 ReplaceInstWithValue 时,迭代器失效,程序进入无限循环。

我已经尝试了多种方法来解决这个问题,但 none 被证明是有用的。

我该如何更改程序,使其遍历程序中的所有指令,而不会在第一条 add 指令上进入无限循环?

#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <map>
#include <string>

using namespace llvm;

namespace {
struct CountOp : public FunctionPass {
    std::map<std::string, int> bbNameToId;

    static char ID;

    CountOp() : FunctionPass(ID) {}

    virtual bool runOnFunction(Function &F) {

        for (Function::iterator bs = F.begin(), be = F.end(); bs != be; ++bs) {
            for (BasicBlock::iterator is = bs->begin(), ie = be->end(); is != ie; ++is) {
                Instruction& inst  = *is;
                BinaryOperator* binop = dyn_cast<BinaryOperator>(&inst);

                if (!binop) {
                    continue;
                }

                unsigned opcode = binop->getOpcode();
                errs() << binop->getOpcodeName() << "\n";

                if (opcode != Instruction::Add) {
                    continue;
                }

                IRBuilder<> builder(binop);
                Value* v = builder.CreateAdd(builder.CreateXor(binop->getOperand(0), binop->getOperand(1)), 
                                             builder.CreateMul(ConstantInt::get(binop->getType(), 2), 
                                                               builder.CreateAnd(binop->getOperand(0), binop->getOperand(1))));

                ReplaceInstWithValue(bs->getInstList(), is, v);
            } 
        }   


        return true;
    }
};
}

char CountOp::ID = 0;
static RegisterPass<CountOp> X("opChanger", "Change add operations", false, false);

其实问题出在for语句:

for (BasicBlock::iterator is = bs->begin(), ie = be->end(); is != ie; ++is).

ie 应该初始化为 bs->end() 而不是 be->end().

那么这个例子就可以正常工作了。