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");
276 GlobalValue *GV = MO.getGlobal();
277 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
278 bool isThreadLocal = GVar && GVar->isThreadLocal();
280 if (!isMemOp && !isCallOp) O << '$';
282 std::string Name = Mang->getValueName(GV);
283 X86SharedAsmPrinter::decorateName(Name, GV);
285 if (printStub(TM, Subtarget)) {
286 // Link-once, External, or Weakly-linked global variables need
287 // non-lazily-resolved stubs
288 if (GV->isDeclaration() ||
289 GV->hasWeakLinkage() ||
290 GV->hasLinkOnceLinkage()) {
291 // Dynamically-resolved functions need a stub for the function.
292 if (isCallOp && isa<Function>(GV)) {
293 FnStubs.insert(Name);
294 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
296 GVStubs.insert(Name);
297 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
300 if (GV->hasDLLImportLinkage())
305 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
306 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
309 if (GV->hasDLLImportLinkage()) {
314 if (isCallOp && isa<Function>(GV)) {
315 if (printGOT(TM, Subtarget)) {
316 // Assemble call via PLT for non-local symbols
317 if (!GV->hasHiddenVisibility() || GV->isDeclaration())
320 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
321 // Save function name for later type emission
322 FnStubs.insert(Name);
326 if (GV->hasExternalWeakLinkage())
327 ExtWeakSymbols.insert(GV);
329 int Offset = MO.getOffset();
336 if (TM.getRelocationModel() == Reloc::PIC_)
337 O << "@TLSGD"; // general dynamic TLS model
339 if (GV->isDeclaration())
340 O << "@INDNTPOFF"; // initial exec TLS model
342 O << "@NTPOFF"; // local exec TLS model
343 } else if (isMemOp) {
344 if (printGOT(TM, Subtarget)) {
345 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
349 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
350 if ((GV->hasExternalLinkage() ||
351 GV->hasWeakLinkage() ||
352 GV->hasLinkOnceLinkage()) &&
353 TM.getRelocationModel() != Reloc::Static)
355 // Use rip when possible to reduce code size, except when
356 // index or base register are also part of the address. e.g.
357 // foo(%rip)(%rcx,%rax,4) is not legal
364 case MachineOperand::MO_ExternalSymbol: {
365 bool isCallOp = Modifier && !strcmp(Modifier, "call");
366 std::string Name(TAI->getGlobalPrefix());
367 Name += MO.getSymbolName();
368 if (isCallOp && printStub(TM, Subtarget)) {
369 FnStubs.insert(Name);
370 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
373 if (!isCallOp) O << '$';
376 if (printGOT(TM, Subtarget)) {
377 std::string GOTName(TAI->getGlobalPrefix());
378 GOTName+="_GLOBAL_OFFSET_TABLE_";
380 // HACK! Emit extra offset to PC during printing GOT offset to
381 // compensate for the size of popl instruction. The resulting code
385 // popl %some_register
386 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
388 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
394 if (!isCallOp && Subtarget->isPICStyleRIPRel())
400 O << "<unknown operand type>"; return;
404 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
405 unsigned char value = MI->getOperand(Op).getImmedValue();
406 assert(value <= 7 && "Invalid ssecc argument!");
408 case 0: O << "eq"; break;
409 case 1: O << "lt"; break;
410 case 2: O << "le"; break;
411 case 3: O << "unord"; break;
412 case 4: O << "neq"; break;
413 case 5: O << "nlt"; break;
414 case 6: O << "nle"; break;
415 case 7: O << "ord"; break;
419 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
420 const char *Modifier){
421 assert(isMem(MI, Op) && "Invalid memory reference!");
422 MachineOperand BaseReg = MI->getOperand(Op);
423 MachineOperand IndexReg = MI->getOperand(Op+2);
424 const MachineOperand &DispSpec = MI->getOperand(Op+3);
426 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
427 if (DispSpec.isGlobalAddress() ||
428 DispSpec.isConstantPoolIndex() ||
429 DispSpec.isJumpTableIndex()) {
430 printOperand(MI, Op+3, "mem", NotRIPRel);
432 int DispVal = DispSpec.getImmedValue();
433 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
437 if (IndexReg.getReg() || BaseReg.getReg()) {
438 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
439 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
441 // There are cases where we can end up with ESP/RSP in the indexreg slot.
442 // If this happens, swap the base/index register to support assemblers that
443 // don't work when the index is *SP.
444 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
445 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
446 std::swap(BaseReg, IndexReg);
447 std::swap(BaseRegOperand, IndexRegOperand);
451 if (BaseReg.getReg())
452 printOperand(MI, Op+BaseRegOperand, Modifier);
454 if (IndexReg.getReg()) {
456 printOperand(MI, Op+IndexRegOperand, Modifier);
458 O << "," << ScaleVal;
464 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
465 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
466 O << label << "\n" << label << ":";
470 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
472 const MRegisterInfo &RI = *TM.getRegisterInfo();
473 unsigned Reg = MO.getReg();
475 default: return true; // Unknown mode.
476 case 'b': // Print QImode register
477 Reg = getX86SubSuperRegister(Reg, MVT::i8);
479 case 'h': // Print QImode high register
480 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
482 case 'w': // Print HImode register
483 Reg = getX86SubSuperRegister(Reg, MVT::i16);
485 case 'k': // Print SImode register
486 Reg = getX86SubSuperRegister(Reg, MVT::i32);
491 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
492 O << (char)tolower(*Name);
496 /// PrintAsmOperand - Print out an operand for an inline asm expression.
498 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
500 const char *ExtraCode) {
501 // Does this asm operand have a single letter operand modifier?
502 if (ExtraCode && ExtraCode[0]) {
503 if (ExtraCode[1] != 0) return true; // Unknown modifier.
505 switch (ExtraCode[0]) {
506 default: return true; // Unknown modifier.
507 case 'c': // Don't print "$" before a global var name or constant.
508 printOperand(MI, OpNo, "mem");
510 case 'b': // Print QImode register
511 case 'h': // Print QImode high register
512 case 'w': // Print HImode register
513 case 'k': // Print SImode register
514 if (MI->getOperand(OpNo).isReg())
515 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
516 printOperand(MI, OpNo);
519 case 'P': // Don't print @PLT, but do print as memory.
520 printOperand(MI, OpNo, "mem");
525 printOperand(MI, OpNo);
529 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
532 const char *ExtraCode) {
533 if (ExtraCode && ExtraCode[0])
534 return true; // Unknown modifier.
535 printMemReference(MI, OpNo);
539 /// printMachineInstruction -- Print out a single X86 LLVM instruction
540 /// MI in Intel syntax to the current output stream.
542 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
545 // See if a truncate instruction can be turned into a nop.
546 switch (MI->getOpcode()) {
548 case X86::TRUNC_64to32:
549 case X86::TRUNC_64to16:
550 case X86::TRUNC_32to16:
551 case X86::TRUNC_32to8:
552 case X86::TRUNC_16to8:
553 case X86::TRUNC_32_to8:
554 case X86::TRUNC_16_to8: {
555 const MachineOperand &MO0 = MI->getOperand(0);
556 const MachineOperand &MO1 = MI->getOperand(1);
557 unsigned Reg0 = MO0.getReg();
558 unsigned Reg1 = MO1.getReg();
559 unsigned Opc = MI->getOpcode();
560 if (Opc == X86::TRUNC_64to32)
561 Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
562 else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
563 Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
565 Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
566 O << TAI->getCommentString() << " TRUNCATE ";
571 case X86::PsMOVZX64rr32:
572 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
576 // Call the autogenerated instruction printer routines.
577 printInstruction(MI);
580 // Include the auto-generated portion of the assembly writer.
581 #include "X86GenAsmWriter.inc"