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 and AT&T format assembly
12 // language. This printer is the output mechanism used by `llc' and `lli
13 // -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
18 #include "X86TargetMachine.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/CommandLine.h"
32 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
33 enum AsmWriterFlavor { att, intel };
35 cl::opt<AsmWriterFlavor>
36 AsmWriterFlavor("x86-asm-syntax",
37 cl::desc("Choose style of code to emit from X86 backend:"),
39 clEnumVal(att, " Emit AT&T-style assembly"),
40 clEnumVal(intel, " Emit Intel-style assembly"),
44 struct X86SharedAsmPrinter : public AsmPrinter {
45 X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM)
46 : AsmPrinter(O, TM), forCygwin(false) { }
48 bool doInitialization(Module &M);
49 void printConstantPool(MachineConstantPool *MCP);
50 bool doFinalization(Module &M);
55 static bool isScale(const MachineOperand &MO) {
56 return MO.isImmediate() &&
57 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
58 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
61 static bool isMem(const MachineInstr *MI, unsigned Op) {
62 if (MI->getOperand(Op).isFrameIndex()) return true;
63 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
64 return Op+4 <= MI->getNumOperands() &&
65 MI->getOperand(Op ).isRegister() && isScale(MI->getOperand(Op+1)) &&
66 MI->getOperand(Op+2).isRegister() && (MI->getOperand(Op+3).isImmediate() ||
67 MI->getOperand(Op+3).isGlobalAddress());
70 // SwitchSection - Switch to the specified section of the executable if we are
73 static void SwitchSection(std::ostream &OS, std::string &CurSection,
74 const char *NewSection) {
75 if (CurSection != NewSection) {
76 CurSection = NewSection;
77 if (!CurSection.empty())
78 OS << "\t" << NewSection << "\n";
82 /// doInitialization - determine
83 bool X86SharedAsmPrinter::doInitialization(Module& M) {
85 const std::string& TT = M.getTargetTriple();
87 forCygwin = TT.find("cygwin") != std::string::npos ||
88 TT.find("mingw") != std::string::npos;
89 else if (TT.empty()) {
90 #if defined(__CYGWIN__) || defined(__MINGW32__)
98 return AsmPrinter::doInitialization(M);
101 /// printConstantPool - Print to the current output stream assembly
102 /// representations of the constants in the constant pool MCP. This is
103 /// used to print out constants which have been "spilled to memory" by
104 /// the code generator.
106 void X86SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
107 const std::vector<Constant*> &CP = MCP->getConstants();
108 const TargetData &TD = TM.getTargetData();
110 if (CP.empty()) return;
112 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
113 O << "\t.section .rodata\n";
114 emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
115 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
117 emitGlobalConstant(CP[i]);
121 bool X86SharedAsmPrinter::doFinalization(Module &M) {
122 const TargetData &TD = TM.getTargetData();
123 std::string CurSection;
125 // Print out module-level global variables here.
126 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
127 if (I->hasInitializer()) { // External global require no code
129 std::string name = Mang->getValueName(I);
130 Constant *C = I->getInitializer();
131 unsigned Size = TD.getTypeSize(C->getType());
132 unsigned Align = TD.getTypeAlignmentShift(C->getType());
134 if (C->isNullValue() &&
135 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
136 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
137 SwitchSection(O, CurSection, ".data");
138 if (!forCygwin && I->hasInternalLinkage())
139 O << "\t.local " << name << "\n";
141 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType());
143 O << "," << (1 << Align);
145 WriteAsOperand(O, I, true, true, &M);
148 switch (I->getLinkage()) {
149 case GlobalValue::LinkOnceLinkage:
150 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
151 // Nonnull linkonce -> weak
152 O << "\t.weak " << name << "\n";
153 SwitchSection(O, CurSection, "");
154 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
156 case GlobalValue::AppendingLinkage:
157 // FIXME: appending linkage variables should go into a section of
158 // their name or something. For now, just emit them as external.
159 case GlobalValue::ExternalLinkage:
160 // If external or appending, declare as a global symbol
161 O << "\t.globl " << name << "\n";
163 case GlobalValue::InternalLinkage:
164 if (C->isNullValue())
165 SwitchSection(O, CurSection, ".bss");
167 SwitchSection(O, CurSection, ".data");
169 case GlobalValue::GhostLinkage:
170 std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n";
174 emitAlignment(Align);
176 O << "\t.type " << name << ",@object\n";
177 O << "\t.size " << name << "," << Size << "\n";
179 O << name << ":\t\t\t\t# ";
180 WriteAsOperand(O, I, true, true, &M);
182 WriteAsOperand(O, C, false, false, &M);
184 emitGlobalConstant(C);
188 AsmPrinter::doFinalization(M);
189 return false; // success
193 struct X86IntelAsmPrinter : public X86SharedAsmPrinter {
194 X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM)
195 : X86SharedAsmPrinter(O, TM) { }
197 virtual const char *getPassName() const {
198 return "X86 Intel-Style Assembly Printer";
201 /// printInstruction - This method is automatically generated by tablegen
202 /// from the instruction set description. This method returns true if the
203 /// machine instruction was sufficiently described to print it, otherwise it
205 bool printInstruction(const MachineInstr *MI);
207 // This method is used by the tablegen'erated instruction printer.
208 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
209 const MachineOperand &MO = MI->getOperand(OpNo);
210 if (MO.getType() == MachineOperand::MO_MachineRegister) {
211 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
212 // Bug Workaround: See note in Printer::doInitialization about %.
213 O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
219 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
221 printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
224 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
227 default: assert(0 && "Unknown arg size!");
228 case MVT::i8: O << "BYTE PTR "; break;
229 case MVT::i16: O << "WORD PTR "; break;
231 case MVT::f32: O << "DWORD PTR "; break;
233 case MVT::f64: O << "QWORD PTR "; break;
234 case MVT::f80: O << "XWORD PTR "; break;
236 printMemReference(MI, OpNo);
239 void printMachineInstruction(const MachineInstr *MI);
240 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
241 void printMemReference(const MachineInstr *MI, unsigned Op);
242 bool runOnMachineFunction(MachineFunction &F);
243 bool doInitialization(Module &M);
245 } // end of anonymous namespace
248 // Include the auto-generated portion of the assembly writer.
249 #include "X86GenAsmWriter1.inc"
252 /// runOnMachineFunction - This uses the printMachineInstruction()
253 /// method to print assembly for each instruction.
255 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
256 setupMachineFunction(MF);
259 // Print out constants referenced by the function
260 printConstantPool(MF.getConstantPool());
262 // Print out labels for the function.
265 O << "\t.globl\t" << CurrentFnName << "\n";
267 O << "\t.type\t" << CurrentFnName << ", @function\n";
268 O << CurrentFnName << ":\n";
270 // Print out code for the function.
271 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
273 // Print a label for the basic block if there are any predecessors.
274 if (I->pred_begin() != I->pred_end())
275 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
276 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
277 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
279 // Print the assembly for the instruction.
281 printMachineInstruction(II);
285 // We didn't modify anything.
289 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
290 bool elideOffsetKeyword /* = false */) {
291 const MRegisterInfo &RI = *TM.getRegisterInfo();
292 switch (MO.getType()) {
293 case MachineOperand::MO_VirtualRegister:
294 if (Value *V = MO.getVRegValueOrNull()) {
295 O << "<" << V->getName() << ">";
299 case MachineOperand::MO_MachineRegister:
300 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
301 // Bug Workaround: See note in Printer::doInitialization about %.
302 O << "%" << RI.get(MO.getReg()).Name;
304 O << "%reg" << MO.getReg();
307 case MachineOperand::MO_SignExtendedImmed:
308 case MachineOperand::MO_UnextendedImmed:
309 O << (int)MO.getImmedValue();
311 case MachineOperand::MO_MachineBasicBlock: {
312 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
313 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
314 << "_" << MBBOp->getNumber () << "\t# "
315 << MBBOp->getBasicBlock ()->getName ();
318 case MachineOperand::MO_PCRelativeDisp:
319 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
322 case MachineOperand::MO_GlobalAddress: {
323 if (!elideOffsetKeyword)
325 O << Mang->getValueName(MO.getGlobal());
326 int Offset = MO.getOffset();
328 O << " + " << Offset;
330 O << " - " << -Offset;
333 case MachineOperand::MO_ExternalSymbol:
334 O << GlobalPrefix << 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 const MachineOperand &BaseReg = MI->getOperand(Op);
345 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
346 const MachineOperand &IndexReg = MI->getOperand(Op+2);
347 const MachineOperand &DispSpec = MI->getOperand(Op+3);
349 if (BaseReg.isFrameIndex()) {
350 O << "[frame slot #" << BaseReg.getFrameIndex();
351 if (DispSpec.getImmedValue())
352 O << " + " << DispSpec.getImmedValue();
355 } else if (BaseReg.isConstantPoolIndex()) {
356 O << "[.CPI" << CurrentFnName << "_"
357 << BaseReg.getConstantPoolIndex();
359 if (IndexReg.getReg()) {
362 O << ScaleVal << "*";
366 if (DispSpec.getImmedValue())
367 O << " + " << DispSpec.getImmedValue();
373 bool NeedPlus = false;
374 if (BaseReg.getReg()) {
375 printOp(BaseReg, true);
379 if (IndexReg.getReg()) {
380 if (NeedPlus) O << " + ";
382 O << ScaleVal << "*";
387 if (DispSpec.isGlobalAddress()) {
390 printOp(DispSpec, true);
392 int DispVal = DispSpec.getImmedValue();
393 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
408 /// printMachineInstruction -- Print out a single X86 LLVM instruction
409 /// MI in Intel syntax to the current output stream.
411 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
414 // Call the autogenerated instruction printer routines.
415 printInstruction(MI);
418 bool X86IntelAsmPrinter::doInitialization(Module &M) {
419 AsmPrinter::doInitialization(M);
420 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
422 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
423 // instruction as a reference to the register named sp, and if you try to
424 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
425 // before being looked up in the symbol table. This creates spurious
426 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
427 // mode, and decorate all register names with percent signs.
428 O << "\t.intel_syntax\n";
435 struct X86ATTAsmPrinter : public X86SharedAsmPrinter {
436 X86ATTAsmPrinter(std::ostream &O, TargetMachine &TM)
437 : X86SharedAsmPrinter(O, TM) { }
439 virtual const char *getPassName() const {
440 return "X86 AT&T-Style Assembly Printer";
443 /// printInstruction - This method is automatically generated by tablegen
444 /// from the instruction set description. This method returns true if the
445 /// machine instruction was sufficiently described to print it, otherwise it
447 bool printInstruction(const MachineInstr *MI);
449 // This method is used by the tablegen'erated instruction printer.
450 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
451 printOp(MI->getOperand(OpNo));
454 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
456 printOp(MI->getOperand(OpNo), true); // Don't print '$' prefix.
459 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
461 printMemReference(MI, OpNo);
464 void printMachineInstruction(const MachineInstr *MI);
465 void printOp(const MachineOperand &MO, bool isCallOperand = false);
466 void printMemReference(const MachineInstr *MI, unsigned Op);
467 bool runOnMachineFunction(MachineFunction &F);
469 } // end of anonymous namespace
472 // Include the auto-generated portion of the assembly writer.
473 #include "X86GenAsmWriter.inc"
476 /// runOnMachineFunction - This uses the printMachineInstruction()
477 /// method to print assembly for each instruction.
479 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
480 setupMachineFunction(MF);
483 // Print out constants referenced by the function
484 printConstantPool(MF.getConstantPool());
486 // Print out labels for the function.
489 O << "\t.globl\t" << CurrentFnName << "\n";
491 O << "\t.type\t" << CurrentFnName << ", @function\n";
492 O << CurrentFnName << ":\n";
494 // Print out code for the function.
495 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
497 // Print a label for the basic block.
498 if (I->pred_begin() != I->pred_end())
499 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
500 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
501 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
503 // Print the assembly for the instruction.
505 printMachineInstruction(II);
509 // We didn't modify anything.
513 void X86ATTAsmPrinter::printOp(const MachineOperand &MO, bool isCallOp) {
514 const MRegisterInfo &RI = *TM.getRegisterInfo();
515 switch (MO.getType()) {
516 case MachineOperand::MO_VirtualRegister:
517 case MachineOperand::MO_MachineRegister:
518 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
519 "Virtual registers should not make it this far!");
521 for (const char *Name = RI.get(MO.getReg()).Name; *Name; ++Name)
522 O << (char)tolower(*Name);
525 case MachineOperand::MO_SignExtendedImmed:
526 case MachineOperand::MO_UnextendedImmed:
527 O << '$' << (int)MO.getImmedValue();
529 case MachineOperand::MO_MachineBasicBlock: {
530 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
531 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
532 << "_" << MBBOp->getNumber () << "\t# "
533 << MBBOp->getBasicBlock ()->getName ();
536 case MachineOperand::MO_PCRelativeDisp:
537 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
540 case MachineOperand::MO_GlobalAddress: {
541 if (!isCallOp) O << '$';
542 O << Mang->getValueName(MO.getGlobal());
543 int Offset = MO.getOffset();
550 case MachineOperand::MO_ExternalSymbol:
551 if (!isCallOp) O << '$';
552 O << GlobalPrefix << MO.getSymbolName();
555 O << "<unknown operand type>"; return;
559 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
560 assert(isMem(MI, Op) && "Invalid memory reference!");
562 const MachineOperand &BaseReg = MI->getOperand(Op);
563 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
564 const MachineOperand &IndexReg = MI->getOperand(Op+2);
565 const MachineOperand &DispSpec = MI->getOperand(Op+3);
567 if (BaseReg.isFrameIndex()) {
568 O << "[frame slot #" << BaseReg.getFrameIndex();
569 if (DispSpec.getImmedValue())
570 O << " + " << DispSpec.getImmedValue();
573 } else if (BaseReg.isConstantPoolIndex()) {
574 O << ".CPI" << CurrentFnName << "_"
575 << BaseReg.getConstantPoolIndex();
576 if (DispSpec.getImmedValue())
577 O << "+" << DispSpec.getImmedValue();
578 if (IndexReg.getReg()) {
582 O << "," << ScaleVal;
588 if (DispSpec.isGlobalAddress()) {
589 printOp(DispSpec, true);
591 int DispVal = DispSpec.getImmedValue();
592 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
596 if (IndexReg.getReg() || BaseReg.getReg()) {
598 if (BaseReg.getReg())
601 if (IndexReg.getReg()) {
605 O << "," << ScaleVal;
613 /// printMachineInstruction -- Print out a single X86 LLVM instruction
614 /// MI in Intel syntax to the current output stream.
616 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
618 // Call the autogenerated instruction printer routines.
619 printInstruction(MI);
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) {
630 assert(0 && "Unknown asm flavor!");
632 return new X86IntelAsmPrinter(o, tm);
634 return new X86ATTAsmPrinter(o, tm);