[LLVMdev] How can I output assembly comments from emitPrologue()?

Devang Patel
Mon, 28 Nov 2011 17:26:21 -0000

On Nov 20, 2011, at 8:13 AM, Stephen McGruer wrote:

> So, an update. I have managed to generate comments, although it does create
a non-existent instruction. My method is as follows (and I would appreciate any
comments on how to do it "better", although note that this won't
make it into the final code :).)
>
> 1. I declared a "fake" instruction type to hold comments, ala:
>
> class FakeInst<dag outs, dag ins, string asmstr, list<dag>
pattern> : Instruction {
>   field bits<32> Inst;
>
>   let Namespace = "XXX"
>   let Inst{31-0} = 0;
>
>   dag OutOperandList = outs;
>   dag InOperandList = ins;
>   let AsmString = asmstr;
>   let Pattern = pattern;
> }
>
> 2. I then defined a comment instruction, ala:
>
> def COMMENT : FakeInst<(outs), (ins Reg:$fake), "; $fake",
[]>;
>
> 3. I added the following to printOperand(...) in XXXAsmPrinter.cpp:
>
> switch (MO.getType()) {
>   ...
>   case MachineOperand::MO_Metadata:
>     O <<
cast<MDString>(MO.getMetadata()->getOperand(0))->getString();
>     break;
>   ...
> }
>
> 4. Finally, whenever I needed to emit comments I call the following:
>
> MDNode* comment = MDNode::get(getGlobalContext(),
ArrayRef<Value*>(MDString::get(getGlobalContext(), "COMMENT
HERE")));
> BuildMI(MBB, MBBI, dl, TII.get(XXX::COMMENT)).addMetadata(comment);
>
>
>
> So, this seems to work, although it will create an empty instruction (I
think). That could probably be cleaned up before MC emission, but I would really
just remove the comments anyway. Any suggestions on a better way to do this (or
a pointer to some obvious existing solution!) welcome :).

You don't need to create new fake instruction. You can attach your comment
to any existing machine instruction.

	MI->addOperand(MachineOperand::CreateMetadata(comment));

-
Devang