Target-independent machine-code analysis pass on LLVM

I’m trying to build an analysis pass over LLVM target-independent machine code.
However, I need the machine code to be “as close to its future target-specific code
as possible”. As far as I understand the LLVM backend infrastructure,
the following applies:

  • the LLVM IR abstracts the input code, allowing for many analysis and optimization
    passes to take place;
  • after that, a series of passes converts the IR representation into other temporary
    structures, by taking target-specific decisions;
  • finally, at the very beginning of code emission, there are MachineFunctions,
    i.e., CFGs composed of MachineBasicBlocks (sequences of MachineInstrs);
  • during code emission, MachineInstrs are converted into MCInsts, which are later
    emitted as either target-specific assembly or binary object.

Since my goal is to deal with target-independent code, I must not write a pass
to be executed by a single target-specific module. Yet, I have not found how to
properly add a pass just before code emission.

As a workaround, I’ve added a stub in file:


to call my analysis method over MachineFunctions. Despite the fact that it does work,
I’d like to know if is there any elegant/correct way to do such analysis.

Notice my pass simply analyzes such structures, thus not modifying any of them.
Also, it simply works because every target-specific code-emission module inherits
from LLMV::AsmPrinter, which means I have my analysis called upon
any target-specific compilation (with llc -march=… input.bc).

Any ideas/suggestions on how to implement such analysis without resorting
to adding stubs/function calls on the AsmPrinter?


Is LLVMTargetMachine::addPassesToEmitFile() in lib/CodeGen/LLVMTargetMachine.cpp before the AsmPrinter pass late enough for your pass?