1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to Intel assembly -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to Intel-format assembly language. This
12 // printer is the output mechanism used by `llc' and `lli -print-machineinstrs'
15 //===----------------------------------------------------------------------===//
18 #include "X86InstrInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/MachineCodeEmitter.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/CommandLine.h"
37 static bool isScale(const MachineOperand &MO) {
38 return MO.isImmediate() &&
39 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
40 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
43 static bool isMem(const MachineInstr *MI, unsigned Op) {
44 if (MI->getOperand(Op).isFrameIndex()) return true;
45 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
46 return Op+4 <= MI->getNumOperands() &&
47 MI->getOperand(Op ).isRegister() && isScale(MI->getOperand(Op+1)) &&
48 MI->getOperand(Op+2).isRegister() && MI->getOperand(Op+3).isImmediate();
51 // SwitchSection - Switch to the specified section of the executable if we are
54 static void SwitchSection(std::ostream &OS, std::string &CurSection,
55 const char *NewSection) {
56 if (CurSection != NewSection) {
57 CurSection = NewSection;
58 if (!CurSection.empty())
59 OS << "\t" << NewSection << "\n";
64 struct X86SharedAsmPrinter : public AsmPrinter {
65 X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM)
66 : AsmPrinter(O, TM) { }
68 void printConstantPool(MachineConstantPool *MCP);
69 bool doFinalization(Module &M);
73 /// printConstantPool - Print to the current output stream assembly
74 /// representations of the constants in the constant pool MCP. This is
75 /// used to print out constants which have been "spilled to memory" by
76 /// the code generator.
78 void X86SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
79 const std::vector<Constant*> &CP = MCP->getConstants();
80 const TargetData &TD = TM.getTargetData();
82 if (CP.empty()) return;
84 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
85 O << "\t.section .rodata\n";
86 emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
87 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
89 emitGlobalConstant(CP[i]);
93 bool X86SharedAsmPrinter::doFinalization(Module &M) {
94 const TargetData &TD = TM.getTargetData();
95 std::string CurSection;
97 // Print out module-level global variables here.
98 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
99 if (I->hasInitializer()) { // External global require no code
101 std::string name = Mang->getValueName(I);
102 Constant *C = I->getInitializer();
103 unsigned Size = TD.getTypeSize(C->getType());
104 unsigned Align = TD.getTypeAlignmentShift(C->getType());
106 if (C->isNullValue() &&
107 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
108 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
109 SwitchSection(O, CurSection, ".data");
110 if (I->hasInternalLinkage())
111 O << "\t.local " << name << "\n";
113 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
114 << "," << (1 << Align);
116 WriteAsOperand(O, I, true, true, &M);
119 switch (I->getLinkage()) {
120 case GlobalValue::LinkOnceLinkage:
121 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
122 // Nonnull linkonce -> weak
123 O << "\t.weak " << name << "\n";
124 SwitchSection(O, CurSection, "");
125 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
127 case GlobalValue::AppendingLinkage:
128 // FIXME: appending linkage variables should go into a section of
129 // their name or something. For now, just emit them as external.
130 case GlobalValue::ExternalLinkage:
131 // If external or appending, declare as a global symbol
132 O << "\t.globl " << name << "\n";
134 case GlobalValue::InternalLinkage:
135 if (C->isNullValue())
136 SwitchSection(O, CurSection, ".bss");
138 SwitchSection(O, CurSection, ".data");
142 emitAlignment(Align);
143 O << "\t.type " << name << ",@object\n";
144 O << "\t.size " << name << "," << Size << "\n";
145 O << name << ":\t\t\t\t# ";
146 WriteAsOperand(O, I, true, true, &M);
148 WriteAsOperand(O, C, false, false, &M);
150 emitGlobalConstant(C);
154 AsmPrinter::doFinalization(M);
155 return false; // success
159 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
160 enum AsmWriterFlavor { att, intel };
162 cl::opt<AsmWriterFlavor>
163 AsmWriterFlavor("x86-asm-syntax",
164 cl::desc("Choose style of code to emit from X86 backend:"),
166 clEnumVal(att, " Emit AT&T-style assembly"),
167 clEnumVal(intel, " Emit Intel-style assembly"),
171 struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
172 GasBugWorkaroundEmitter(std::ostream& o)
173 : O(o), OldFlags(O.flags()), firstByte(true) {
177 ~GasBugWorkaroundEmitter() {
181 virtual void emitByte(unsigned char B) {
182 if (!firstByte) O << "\n\t";
184 O << ".byte 0x" << (unsigned) B;
187 // These should never be called
188 virtual void emitWord(unsigned W) { assert(0); }
189 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
190 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
191 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
192 virtual uint64_t getCurrentPCValue() { abort(); }
193 virtual uint64_t forceCompilationOf(Function *F) { abort(); }
197 std::ios::fmtflags OldFlags;
201 struct X86IntelAsmPrinter : public X86SharedAsmPrinter {
202 X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM)
203 : X86SharedAsmPrinter(O, TM) { }
205 virtual const char *getPassName() const {
206 return "X86 Intel-Style Assembly Printer";
209 /// printInstruction - This method is automatically generated by tablegen
210 /// from the instruction set description. This method returns true if the
211 /// machine instruction was sufficiently described to print it, otherwise it
213 bool printInstruction(const MachineInstr *MI);
215 // This method is used by the tablegen'erated instruction printer.
216 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
217 const MachineOperand &MO = MI->getOperand(OpNo);
218 if (MO.getType() == MachineOperand::MO_MachineRegister) {
219 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
220 // Bug Workaround: See note in Printer::doInitialization about %.
221 O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
227 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
229 printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
232 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
235 default: assert(0 && "Unknown arg size!");
236 case MVT::i8: O << "BYTE PTR "; break;
237 case MVT::i16: O << "WORD PTR "; break;
239 case MVT::f32: O << "DWORD PTR "; break;
241 case MVT::f64: O << "QWORD PTR "; break;
242 case MVT::f80: O << "XWORD PTR "; break;
244 printMemReference(MI, OpNo);
247 void printMachineInstruction(const MachineInstr *MI);
248 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
249 void printMemReference(const MachineInstr *MI, unsigned Op);
250 bool runOnMachineFunction(MachineFunction &F);
251 bool doInitialization(Module &M);
253 } // end of anonymous namespace
256 // Include the auto-generated portion of the assembly writer.
257 #include "X86GenIntelAsmWriter.inc"
260 /// runOnMachineFunction - This uses the printMachineInstruction()
261 /// method to print assembly for each instruction.
263 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
264 setupMachineFunction(MF);
267 // Print out constants referenced by the function
268 printConstantPool(MF.getConstantPool());
270 // Print out labels for the function.
273 O << "\t.globl\t" << CurrentFnName << "\n";
274 O << "\t.type\t" << CurrentFnName << ", @function\n";
275 O << CurrentFnName << ":\n";
277 // Print out code for the function.
278 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
280 // Print a label for the basic block.
281 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
282 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
283 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
285 // Print the assembly for the instruction.
287 printMachineInstruction(II);
291 // We didn't modify anything.
295 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
296 bool elideOffsetKeyword /* = false */) {
297 const MRegisterInfo &RI = *TM.getRegisterInfo();
298 switch (MO.getType()) {
299 case MachineOperand::MO_VirtualRegister:
300 if (Value *V = MO.getVRegValueOrNull()) {
301 O << "<" << V->getName() << ">";
305 case MachineOperand::MO_MachineRegister:
306 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
307 // Bug Workaround: See note in Printer::doInitialization about %.
308 O << "%" << RI.get(MO.getReg()).Name;
310 O << "%reg" << MO.getReg();
313 case MachineOperand::MO_SignExtendedImmed:
314 case MachineOperand::MO_UnextendedImmed:
315 O << (int)MO.getImmedValue();
317 case MachineOperand::MO_MachineBasicBlock: {
318 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
319 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
320 << "_" << MBBOp->getNumber () << "\t# "
321 << MBBOp->getBasicBlock ()->getName ();
324 case MachineOperand::MO_PCRelativeDisp:
325 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
328 case MachineOperand::MO_GlobalAddress:
329 if (!elideOffsetKeyword)
331 O << Mang->getValueName(MO.getGlobal());
333 case MachineOperand::MO_ExternalSymbol:
334 O << MO.getSymbolName();
337 O << "<unknown operand type>"; return;
341 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
342 assert(isMem(MI, Op) && "Invalid memory reference!");
344 if (MI->getOperand(Op).isFrameIndex()) {
345 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
346 if (MI->getOperand(Op+3).getImmedValue())
347 O << " + " << MI->getOperand(Op+3).getImmedValue();
350 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
351 O << "[.CPI" << CurrentFnName << "_"
352 << MI->getOperand(Op).getConstantPoolIndex();
353 if (MI->getOperand(Op+3).getImmedValue())
354 O << " + " << MI->getOperand(Op+3).getImmedValue();
359 const MachineOperand &BaseReg = MI->getOperand(Op);
360 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
361 const MachineOperand &IndexReg = MI->getOperand(Op+2);
362 int DispVal = MI->getOperand(Op+3).getImmedValue();
365 bool NeedPlus = false;
366 if (BaseReg.getReg()) {
371 if (IndexReg.getReg()) {
372 if (NeedPlus) O << " + ";
374 O << ScaleVal << "*";
393 /// printMachineInstruction -- Print out a single X86 LLVM instruction
394 /// MI in Intel syntax to the current output stream.
396 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
401 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]" is misassembled
402 // by gas in intel_syntax mode as its 32-bit equivalent "fstp DWORD PTR
403 // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
405 // The 80-bit FP load instruction "fld XWORD PTR [...]" is misassembled by gas
406 // in intel_syntax mode as its 32-bit equivalent "fld DWORD PTR
407 // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
409 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an invalid opcode,
410 // saying "64 bit operations are only supported in 64 bit modes." libopcodes
411 // disassembles it as "fild DWORD PTR [...]", which is wrong. Workaround:
412 // Output the raw opcode bytes instead of the instruction.
414 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an invalid opcode,
415 // saying "64 bit operations are only supported in 64 bit modes." libopcodes
416 // disassembles it as "fistpll DWORD PTR [...]", which is wrong. Workaround:
417 // Output the raw opcode bytes instead of the instruction.
418 switch (MI->getOpcode()) {
423 GasBugWorkaroundEmitter gwe(O);
424 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
428 // Call the autogenerated instruction printer routines.
429 bool Handled = printInstruction(MI);
432 assert(0 && "Do not know how to print this instruction!");
437 bool X86IntelAsmPrinter::doInitialization(Module &M) {
438 AsmPrinter::doInitialization(M);
439 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
441 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
442 // instruction as a reference to the register named sp, and if you try to
443 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
444 // before being looked up in the symbol table. This creates spurious
445 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
446 // mode, and decorate all register names with percent signs.
447 O << "\t.intel_syntax\n";
454 struct X86ATTAsmPrinter : public X86SharedAsmPrinter {
455 X86ATTAsmPrinter(std::ostream &O, TargetMachine &TM)
456 : X86SharedAsmPrinter(O, TM) { }
458 virtual const char *getPassName() const {
459 return "X86 AT&T-Style Assembly Printer";
462 /// printInstruction - This method is automatically generated by tablegen
463 /// from the instruction set description. This method returns true if the
464 /// machine instruction was sufficiently described to print it, otherwise it
466 bool printInstruction(const MachineInstr *MI);
468 // This method is used by the tablegen'erated instruction printer.
469 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
470 printOp(MI->getOperand(OpNo));
473 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
475 printOp(MI->getOperand(OpNo), true); // Don't print '$' prefix.
478 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
480 printMemReference(MI, OpNo);
483 void printMachineInstruction(const MachineInstr *MI);
484 void printOp(const MachineOperand &MO, bool isCallOperand = false);
485 void printMemReference(const MachineInstr *MI, unsigned Op);
486 bool runOnMachineFunction(MachineFunction &F);
488 } // end of anonymous namespace
491 // Include the auto-generated portion of the assembly writer.
492 #include "X86GenATTAsmWriter.inc"
495 /// runOnMachineFunction - This uses the printMachineInstruction()
496 /// method to print assembly for each instruction.
498 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
499 setupMachineFunction(MF);
502 // Print out constants referenced by the function
503 printConstantPool(MF.getConstantPool());
505 // Print out labels for the function.
508 O << "\t.globl\t" << CurrentFnName << "\n";
509 O << "\t.type\t" << CurrentFnName << ", @function\n";
510 O << CurrentFnName << ":\n";
512 // Print out code for the function.
513 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
515 // Print a label for the basic block.
516 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
517 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
518 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
520 // Print the assembly for the instruction.
522 printMachineInstruction(II);
526 // We didn't modify anything.
530 void X86ATTAsmPrinter::printOp(const MachineOperand &MO, bool isCallOp) {
531 const MRegisterInfo &RI = *TM.getRegisterInfo();
532 switch (MO.getType()) {
533 case MachineOperand::MO_VirtualRegister:
534 case MachineOperand::MO_MachineRegister:
535 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
536 "Virtual registers should not make it this far!");
538 for (const char *Name = RI.get(MO.getReg()).Name; *Name; ++Name)
539 O << (char)tolower(*Name);
542 case MachineOperand::MO_SignExtendedImmed:
543 case MachineOperand::MO_UnextendedImmed:
544 O << '$' << (int)MO.getImmedValue();
546 case MachineOperand::MO_MachineBasicBlock: {
547 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
548 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
549 << "_" << MBBOp->getNumber () << "\t# "
550 << MBBOp->getBasicBlock ()->getName ();
553 case MachineOperand::MO_PCRelativeDisp:
554 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
557 case MachineOperand::MO_GlobalAddress:
558 if (!isCallOp) O << '$';
559 O << Mang->getValueName(MO.getGlobal());
561 case MachineOperand::MO_ExternalSymbol:
562 if (!isCallOp) O << '$';
563 O << MO.getSymbolName();
566 O << "<unknown operand type>"; return;
570 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
571 assert(isMem(MI, Op) && "Invalid memory reference!");
573 if (MI->getOperand(Op).isFrameIndex()) {
574 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
575 if (MI->getOperand(Op+3).getImmedValue())
576 O << " + " << MI->getOperand(Op+3).getImmedValue();
579 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
580 O << ".CPI" << CurrentFnName << "_"
581 << MI->getOperand(Op).getConstantPoolIndex();
582 if (MI->getOperand(Op+3).getImmedValue())
583 O << " + " << MI->getOperand(Op+3).getImmedValue();
587 const MachineOperand &BaseReg = MI->getOperand(Op);
588 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
589 const MachineOperand &IndexReg = MI->getOperand(Op+2);
590 int DispVal = MI->getOperand(Op+3).getImmedValue();
592 if (DispVal) O << DispVal;
595 if (BaseReg.getReg())
598 if (IndexReg.getReg()) {
602 O << "," << ScaleVal;
609 /// printMachineInstruction -- Print out a single X86 LLVM instruction
610 /// MI in Intel syntax to the current output stream.
612 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
614 // Call the autogenerated instruction printer routines.
615 if (!printInstruction(MI)) {
617 assert(0 && "Do not know how to print this instruction!");
623 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
624 /// for a MachineFunction to the given output stream, using the given target
625 /// machine description.
627 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
628 switch (AsmWriterFlavor) {
629 default: assert(0 && "Unknown asm flavor!");
631 return new X86IntelAsmPrinter(o, tm);
633 return new X86ATTAsmPrinter(o, tm);