Reusing code to output assembly for loading immediates into registers

I have a question regarding organising my LLVM code.

I currently have a function XXISelDAGToDAG.cpp (where XX is a custom backend name) which loads an immediate into a register. Depending on the size of the immediate it uses different assembly instructions. However in this file, the outputs of the functions are SDNodes.

Later on in the lowering process in XXRegisterInfo.cpp, eliminateFrameIndex(), I have another situation where I want to load an immediate into a register and want to reuse this algorithm which choses instructions based on the size of the immediate but in this case want to use the BuildMI functions as I’m no longer working with the SelectionDAG.

I’m wondering if there’s a way for me to have a single function I can call from different places that does this so that I only have a single point in my codebase where the algorithm for loading an immediate into a register is found. Mainly, so in the future if there are changes, multiple locations need not be tracked.


You might want to look at how we handle this in the RISC-V backend - see RISCVMatInt.cpp and generateInstSeq, which is used both to generate SelectionDAG nodes (see SelectImm in RISCVISelDAGToDAG) and MCInsts (see emitLoadImm in RISCVAsmParser.cpp).

EDIT: Oh, and MachineInsts in movImm in RISCVInstrInfo.cpp.

1 Like

Thanks, that worked well.