In LLVM IR, I want to copy a set of Instructions and paste those instructions to another place in IR through LLVM pass. How to do this?
Asked Answered
P

2

6

I want to copy these set of instructions from one part and paste to that in another part in 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
Pulcheria answered 9/4, 2017 at 7:1 Comment(0)
D
1

Assuming you are using C++ API, you will just have to clone each instruction separately while fixing references between them. Something like the following:

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);
}
Delaminate answered 9/4, 2017 at 16:40 Comment(0)
E
1

In my experience, the provided solution failed, as RemapInstruction was called before the vmap was populated with all of the cloned instructions. Here is my updated solution:

    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);
    }
Elastin answered 3/6, 2021 at 13:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.