Replacing a machine instruction in a machine function pass

I’m writing a machine function pass that very simply iterates over instructions and in a certain case replaces the opcode of one instruction with another opcode I’ve introduced. Ideally I’d like to change the opcode of the machine instruction object I’m iterating over, but this doesn’t seem possible with the API, so instead I’m creating a new instruction before the existing one with BuildMI and then erasing the original. I’m using the following code to do this and wanted to make sure this actually achieves what I want:

    MachineInstr &NewMI = BuildMI(MBB, MI, DL, TII->get(NewOpcode));
    NewMI.copyImplicitOps(MF, MI);
    NewMI.cloneMemRefs(MF, MI);
    NewMI.cloneInstrSymbols(MF, MI);
    MI.eraseFromParent();

I’m hoping this will give the NewMI all the same operands and properties of MI but with a different opcode. For instance, copyImplicitOps seems to do what I want, but I’m unsure what ‘implicit’ means here - will any be left out that I’d have to copy over manually? And do I need cloneMemRefs and cloneInstrSymbols? Lastly are there any other properties I need to copy over?

Thanks

You can change the opcode with MI.setDesc(TII->get(NewOpcode)); See the SystemZShortenInst pass for example.

  • Implicit operands: these are operands the instruction use/modifies, which are not explicitly stated in the instruction.
  • Memrefs: memory reference descriptors, which further describe the memory accessed by an instruction.
  • Instruction symbols: it is possible to attach a label to an instruction. The label is emitted either before or after the instruction.
1 Like

Perfect, thanks!