以下代码是尝试创建遍历所有FunctionPassBasicBlock,并将a + b更改为(a xor b) + 2 * (a and b)进行混淆的尝试。

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

我尝试了几种解决此问题的方法,但是没有一种方法被证明是有用的。

我将如何更改程序,以使其遍历程序中的所有指令,而不会在第一个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()

然后该示例工作正常。

关于c++ - 如何修复此 `FunctionPass`使其不会陷入无限循环?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42055999/

10-11 02:37