1 //===-- X86ATTAsmPrinter.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 AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/Target/TargetAsmInfo.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/ADT/Statistic.h"
32 STATISTIC(EmittedInsts, "Number of machine instrs printed");
34 static std::string computePICLabel(unsigned FnNum,
35 const TargetAsmInfo *TAI,
36 const X86Subtarget* Subtarget) {
38 if (Subtarget->isTargetDarwin())
39 label = "\"L" + utostr_32(FnNum) + "$pb\"";
40 else if (Subtarget->isTargetELF())
41 label = ".Lllvm$" + utostr_32(FnNum) + "$piclabel";
43 assert(0 && "Don't know how to print PIC label!\n");
48 /// getSectionForFunction - Return the section that we should emit the
49 /// specified function body into.
50 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
51 switch (F.getLinkage()) {
52 default: assert(0 && "Unknown linkage type!");
53 case Function::InternalLinkage:
54 case Function::DLLExportLinkage:
55 case Function::ExternalLinkage:
56 return TAI->getTextSection();
57 case Function::WeakLinkage:
58 case Function::LinkOnceLinkage:
59 if (Subtarget->isTargetDarwin()) {
60 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
61 } else if (Subtarget->isTargetCygMing()) {
62 return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"\n";
64 return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
65 ",\"ax\",@progbits\n";
70 /// runOnMachineFunction - This uses the printMachineInstruction()
71 /// method to print assembly for each instruction.
73 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
74 if (Subtarget->isTargetDarwin() ||
75 Subtarget->isTargetELF() ||
76 Subtarget->isTargetCygMing()) {
77 // Let PassManager know we need debug information and relay
78 // the MachineModuleInfo address on to DwarfWriter.
79 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
82 SetupMachineFunction(MF);
85 // Print out constants referenced by the function
86 EmitConstantPool(MF.getConstantPool());
88 // Print out labels for the function.
89 const Function *F = MF.getFunction();
90 unsigned CC = F->getCallingConv();
92 // Populate function information map. Actually, We don't want to populate
93 // non-stdcall or non-fastcall functions' information right now.
94 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
95 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
97 X86SharedAsmPrinter::decorateName(CurrentFnName, F);
99 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
101 switch (F->getLinkage()) {
102 default: assert(0 && "Unknown linkage type!");
103 case Function::InternalLinkage: // Symbols default to internal.
104 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
106 case Function::DLLExportLinkage:
107 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
109 case Function::ExternalLinkage:
110 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
111 O << "\t.globl\t" << CurrentFnName << "\n";
113 case Function::LinkOnceLinkage:
114 case Function::WeakLinkage:
115 if (Subtarget->isTargetDarwin()) {
116 O << "\t.globl\t" << CurrentFnName << "\n";
117 O << "\t.weak_definition\t" << CurrentFnName << "\n";
118 } else if (Subtarget->isTargetCygMing()) {
119 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
120 O << "\t.globl " << CurrentFnName << "\n";
121 O << "\t.linkonce discard\n";
123 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
124 O << "\t.weak " << CurrentFnName << "\n";
128 if (F->hasHiddenVisibility())
129 if (const char *Directive = TAI->getHiddenDirective())
130 O << Directive << CurrentFnName << "\n";
132 if (Subtarget->isTargetELF())
133 O << "\t.type " << CurrentFnName << ",@function\n";
134 else if (Subtarget->isTargetCygMing()) {
135 O << "\t.def\t " << CurrentFnName
137 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
138 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
142 O << CurrentFnName << ":\n";
143 // Add some workaround for linkonce linkage on Cygwin\MinGW
144 if (Subtarget->isTargetCygMing() &&
145 (F->getLinkage() == Function::LinkOnceLinkage ||
146 F->getLinkage() == Function::WeakLinkage))
147 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
149 if (Subtarget->isTargetDarwin() ||
150 Subtarget->isTargetELF() ||
151 Subtarget->isTargetCygMing()) {
152 // Emit pre-function debug information.
153 DW.BeginFunction(&MF);
156 // Print out code for the function.
157 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
159 // Print a label for the basic block.
160 if (I->pred_begin() != I->pred_end()) {
161 printBasicBlockLabel(I, true);
164 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
166 // Print the assembly for the instruction.
168 printMachineInstruction(II);
172 // Print out jump tables referenced by the function.
174 // Mac OS X requires that the jump table follow the function, so that the jump
175 // table is part of the same atom that the function is in.
176 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
178 if (TAI->hasDotTypeDotSizeDirective())
179 O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
181 if (Subtarget->isTargetDarwin() ||
182 Subtarget->isTargetELF() ||
183 Subtarget->isTargetCygMing()) {
184 // Emit post-function debug information.
188 // We didn't modify anything.
192 static inline bool printGOT(TargetMachine &TM, const X86Subtarget* ST) {
193 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
196 static inline bool printStub(TargetMachine &TM, const X86Subtarget* ST) {
197 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
200 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
201 const char *Modifier, bool NotRIPRel) {
202 const MachineOperand &MO = MI->getOperand(OpNo);
203 const MRegisterInfo &RI = *TM.getRegisterInfo();
204 switch (MO.getType()) {
205 case MachineOperand::MO_Register: {
206 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
207 "Virtual registers should not make it this far!");
209 unsigned Reg = MO.getReg();
210 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
211 MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
212 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
213 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
214 Reg = getX86SubSuperRegister(Reg, VT);
216 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
217 O << (char)tolower(*Name);
221 case MachineOperand::MO_Immediate:
223 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
225 O << MO.getImmedValue();
227 case MachineOperand::MO_MachineBasicBlock:
228 printBasicBlockLabel(MO.getMachineBasicBlock());
230 case MachineOperand::MO_JumpTableIndex: {
231 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
232 if (!isMemOp) O << '$';
233 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
234 << MO.getJumpTableIndex();
236 if (TM.getRelocationModel() == Reloc::PIC_) {
237 if (Subtarget->isPICStyleStub())
238 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
240 else if (Subtarget->isPICStyleGOT())
244 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
248 case MachineOperand::MO_ConstantPoolIndex: {
249 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
250 if (!isMemOp) O << '$';
251 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
252 << MO.getConstantPoolIndex();
254 if (TM.getRelocationModel() == Reloc::PIC_) {
255 if (Subtarget->isPICStyleStub())
256 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
258 else if (Subtarget->isPICStyleGOT())
262 int Offset = MO.getOffset();
268 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
272 case MachineOperand::MO_GlobalAddress: {
273 bool isCallOp = Modifier && !strcmp(Modifier, "call");
274 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
275 bool needCloseParen = false;
277 GlobalValue *GV = MO.getGlobal();
278 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
279 bool isThreadLocal = GVar && GVar->isThreadLocal();
281 std::string Name = Mang->getValueName(GV);
282 X86SharedAsmPrinter::decorateName(Name, GV);
284 if (!isMemOp && !isCallOp)
286 else if (Name[0] == '$') {
287 // The name begins with a dollar-sign. In order to avoid having it look
288 // like an integer immediate to the assembler, enclose it in parens.
290 needCloseParen = true;
293 if (printStub(TM, Subtarget)) {
294 // Link-once, External, or Weakly-linked global variables need
295 // non-lazily-resolved stubs
296 if (GV->isDeclaration() ||
297 GV->hasWeakLinkage() ||
298 GV->hasLinkOnceLinkage()) {
299 // Dynamically-resolved functions need a stub for the function.
300 if (isCallOp && isa<Function>(GV)) {
301 FnStubs.insert(Name);
302 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
304 GVStubs.insert(Name);
305 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
308 if (GV->hasDLLImportLinkage())
313 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
314 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
317 if (GV->hasDLLImportLinkage()) {
322 if (isCallOp && isa<Function>(GV)) {
323 if (printGOT(TM, Subtarget)) {
324 // Assemble call via PLT for non-local symbols
325 if (!GV->hasHiddenVisibility() || GV->isDeclaration())
328 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
329 // Save function name for later type emission
330 FnStubs.insert(Name);
334 if (GV->hasExternalWeakLinkage())
335 ExtWeakSymbols.insert(GV);
337 int Offset = MO.getOffset();
344 if (TM.getRelocationModel() == Reloc::PIC_)
345 O << "@TLSGD"; // general dynamic TLS model
347 if (GV->isDeclaration())
348 O << "@INDNTPOFF"; // initial exec TLS model
350 O << "@NTPOFF"; // local exec TLS model
351 } else if (isMemOp) {
352 if (printGOT(TM, Subtarget)) {
353 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
357 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
358 if ((GV->hasExternalLinkage() ||
359 GV->hasWeakLinkage() ||
360 GV->hasLinkOnceLinkage()) &&
361 TM.getRelocationModel() != Reloc::Static)
364 if (needCloseParen) {
365 needCloseParen = false;
369 // Use rip when possible to reduce code size, except when
370 // index or base register are also part of the address. e.g.
371 // foo(%rip)(%rcx,%rax,4) is not legal
381 case MachineOperand::MO_ExternalSymbol: {
382 bool isCallOp = Modifier && !strcmp(Modifier, "call");
383 bool needCloseParen = false;
384 std::string Name(TAI->getGlobalPrefix());
385 Name += MO.getSymbolName();
386 if (isCallOp && printStub(TM, Subtarget)) {
387 FnStubs.insert(Name);
388 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
393 else if (Name[0] == '$') {
394 // The name begins with a dollar-sign. In order to avoid having it look
395 // like an integer immediate to the assembler, enclose it in parens.
397 needCloseParen = true;
402 if (printGOT(TM, Subtarget)) {
403 std::string GOTName(TAI->getGlobalPrefix());
404 GOTName+="_GLOBAL_OFFSET_TABLE_";
406 // HACK! Emit extra offset to PC during printing GOT offset to
407 // compensate for the size of popl instruction. The resulting code
411 // popl %some_register
412 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
414 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
423 if (!isCallOp && Subtarget->isPICStyleRIPRel())
429 O << "<unknown operand type>"; return;
433 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
434 unsigned char value = MI->getOperand(Op).getImmedValue();
435 assert(value <= 7 && "Invalid ssecc argument!");
437 case 0: O << "eq"; break;
438 case 1: O << "lt"; break;
439 case 2: O << "le"; break;
440 case 3: O << "unord"; break;
441 case 4: O << "neq"; break;
442 case 5: O << "nlt"; break;
443 case 6: O << "nle"; break;
444 case 7: O << "ord"; break;
448 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
449 const char *Modifier){
450 assert(isMem(MI, Op) && "Invalid memory reference!");
451 MachineOperand BaseReg = MI->getOperand(Op);
452 MachineOperand IndexReg = MI->getOperand(Op+2);
453 const MachineOperand &DispSpec = MI->getOperand(Op+3);
455 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
456 if (DispSpec.isGlobalAddress() ||
457 DispSpec.isConstantPoolIndex() ||
458 DispSpec.isJumpTableIndex()) {
459 printOperand(MI, Op+3, "mem", NotRIPRel);
461 int DispVal = DispSpec.getImmedValue();
462 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
466 if (IndexReg.getReg() || BaseReg.getReg()) {
467 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
468 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
470 // There are cases where we can end up with ESP/RSP in the indexreg slot.
471 // If this happens, swap the base/index register to support assemblers that
472 // don't work when the index is *SP.
473 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
474 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
475 std::swap(BaseReg, IndexReg);
476 std::swap(BaseRegOperand, IndexRegOperand);
480 if (BaseReg.getReg())
481 printOperand(MI, Op+BaseRegOperand, Modifier);
483 if (IndexReg.getReg()) {
485 printOperand(MI, Op+IndexRegOperand, Modifier);
487 O << "," << ScaleVal;
493 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
494 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
495 O << label << "\n" << label << ":";
499 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
501 const MRegisterInfo &RI = *TM.getRegisterInfo();
502 unsigned Reg = MO.getReg();
504 default: return true; // Unknown mode.
505 case 'b': // Print QImode register
506 Reg = getX86SubSuperRegister(Reg, MVT::i8);
508 case 'h': // Print QImode high register
509 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
511 case 'w': // Print HImode register
512 Reg = getX86SubSuperRegister(Reg, MVT::i16);
514 case 'k': // Print SImode register
515 Reg = getX86SubSuperRegister(Reg, MVT::i32);
520 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
521 O << (char)tolower(*Name);
525 /// PrintAsmOperand - Print out an operand for an inline asm expression.
527 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
529 const char *ExtraCode) {
530 // Does this asm operand have a single letter operand modifier?
531 if (ExtraCode && ExtraCode[0]) {
532 if (ExtraCode[1] != 0) return true; // Unknown modifier.
534 switch (ExtraCode[0]) {
535 default: return true; // Unknown modifier.
536 case 'c': // Don't print "$" before a global var name or constant.
537 printOperand(MI, OpNo, "mem");
539 case 'b': // Print QImode register
540 case 'h': // Print QImode high register
541 case 'w': // Print HImode register
542 case 'k': // Print SImode register
543 if (MI->getOperand(OpNo).isReg())
544 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
545 printOperand(MI, OpNo);
548 case 'P': // Don't print @PLT, but do print as memory.
549 printOperand(MI, OpNo, "mem");
554 printOperand(MI, OpNo);
558 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
561 const char *ExtraCode) {
562 if (ExtraCode && ExtraCode[0])
563 return true; // Unknown modifier.
564 printMemReference(MI, OpNo);
568 /// printMachineInstruction -- Print out a single X86 LLVM instruction
569 /// MI in Intel syntax to the current output stream.
571 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
574 // See if a truncate instruction can be turned into a nop.
575 switch (MI->getOpcode()) {
577 case X86::TRUNC_64to32:
578 case X86::TRUNC_64to16:
579 case X86::TRUNC_32to16:
580 case X86::TRUNC_32to8:
581 case X86::TRUNC_16to8:
582 case X86::TRUNC_32_to8:
583 case X86::TRUNC_16_to8: {
584 const MachineOperand &MO0 = MI->getOperand(0);
585 const MachineOperand &MO1 = MI->getOperand(1);
586 unsigned Reg0 = MO0.getReg();
587 unsigned Reg1 = MO1.getReg();
588 unsigned Opc = MI->getOpcode();
589 if (Opc == X86::TRUNC_64to32)
590 Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
591 else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
592 Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
594 Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
595 O << TAI->getCommentString() << " TRUNCATE ";
600 case X86::PsMOVZX64rr32:
601 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
605 // Call the autogenerated instruction printer routines.
606 printInstruction(MI);
609 // Include the auto-generated portion of the assembly writer.
610 #include "X86GenAsmWriter.inc"