在LLVM IR中,我想复制一组指令并通过LLVM传递将这些指令粘贴到IR中的另一个位置。这该怎么做?

时间:2017-04-09 07:01:48

标签: llvm llvm-ir

我想从一个部分复制这些指令集并粘贴到IR中的另一个部分

  %0 = load i32, i32* @x, align 4
  %1 = load i32, i32* @y, align 4
  %add = add nsw i32 %0, %1
  %2 = load i32, i32* @n, align 4
  %cmp = icmp slt i32 %add, %2
  %conv = zext i1 %cmp to i32

2 个答案:

答案 0 :(得分:1)

假设您使用的是C ++ API,则每个指令必须单独clone,而fixing references之间只需ObHighchartsBundle。如下所示:

llvm::ValueToValueMapTy vmap;

for (auto *inst: instructions_to_clone) {
  auto *new_inst = inst->clone();
  new_inst->insertBefore(insertion_pos);
  vmap[inst] = new_inst;
  llvm::RemapInstruction(new_inst, vmap,
                         RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
}

答案 1 :(得分:0)

根据我的经验,提供的解决方案失败了,因为在使用所有克隆指令填充 vmap 之前调用了 RemapInstruction。这是我更新的解决方案:

    std::vector<llvm::Instruction*> new_instructions;
    if (toCopy.size() > 0) {
        llvm::Instruction * insertPt = toCopy[0]->getParent()->getParent()->getEntryBlock().getFirstNonPHIOrDbg();
        for (auto *inst: toCopy) {
            auto *new_inst = inst->clone();
            new_inst->insertBefore(insertPt);
            new_instructions.push_back(new_inst);
            vmap[inst] = new_inst;
            insertPt = new_inst->getNextNode();
        }
    }

    for (auto * i : new_instructions) {
        llvm::RemapInstruction(i, vmap, RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
    }