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<X86FunctionInfo>();
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 if (!isMemOp && !isCallOp) O << '$';
277 GlobalValue *GV = MO.getGlobal();
278 std::string Name = Mang->getValueName(GV);
279 X86SharedAsmPrinter::decorateName(Name, GV);
281 if (printStub(TM, Subtarget)) {
282 // Link-once, External, or Weakly-linked global variables need
283 // non-lazily-resolved stubs
284 if (GV->isDeclaration() ||
285 GV->hasWeakLinkage() ||
286 GV->hasLinkOnceLinkage()) {
287 // Dynamically-resolved functions need a stub for the function.
288 if (isCallOp && isa<Function>(GV)) {
289 FnStubs.insert(Name);
290 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
292 GVStubs.insert(Name);
293 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
296 if (GV->hasDLLImportLinkage())
301 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
302 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
305 if (GV->hasDLLImportLinkage()) {
310 if (isCallOp && isa<Function>(GV)) {
311 if (printGOT(TM, Subtarget)) {
312 // Assemble call via PLT for non-local symbols
313 if (!GV->hasHiddenVisibility() || GV->isDeclaration())
316 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
317 // Save function name for later type emission
318 FnStubs.insert(Name);
322 if (GV->hasExternalWeakLinkage())
323 ExtWeakSymbols.insert(GV);
325 int Offset = MO.getOffset();
332 if (printGOT(TM, Subtarget)) {
333 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
337 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
338 if ((GV->hasExternalLinkage() ||
339 GV->hasWeakLinkage() ||
340 GV->hasLinkOnceLinkage()) &&
341 TM.getRelocationModel() != Reloc::Static)
343 // Use rip when possible to reduce code size, except when
344 // index or base register are also part of the address. e.g.
345 // foo(%rip)(%rcx,%rax,4) is not legal
352 case MachineOperand::MO_ExternalSymbol: {
353 bool isCallOp = Modifier && !strcmp(Modifier, "call");
354 std::string Name(TAI->getGlobalPrefix());
355 Name += MO.getSymbolName();
356 if (isCallOp && printStub(TM, Subtarget)) {
357 FnStubs.insert(Name);
358 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
361 if (!isCallOp) O << '$';
364 if (printGOT(TM, Subtarget)) {
365 std::string GOTName(TAI->getGlobalPrefix());
366 GOTName+="_GLOBAL_OFFSET_TABLE_";
368 // HACK! Emit extra offset to PC during printing GOT offset to
369 // compensate for the size of popl instruction. The resulting code
373 // popl %some_register
374 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
376 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
382 if (!isCallOp && Subtarget->isPICStyleRIPRel())
388 O << "<unknown operand type>"; return;
392 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
393 unsigned char value = MI->getOperand(Op).getImmedValue();
394 assert(value <= 7 && "Invalid ssecc argument!");
396 case 0: O << "eq"; break;
397 case 1: O << "lt"; break;
398 case 2: O << "le"; break;
399 case 3: O << "unord"; break;
400 case 4: O << "neq"; break;
401 case 5: O << "nlt"; break;
402 case 6: O << "nle"; break;
403 case 7: O << "ord"; break;
407 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
408 const char *Modifier){
409 assert(isMem(MI, Op) && "Invalid memory reference!");
410 MachineOperand BaseReg = MI->getOperand(Op);
411 MachineOperand IndexReg = MI->getOperand(Op+2);
412 const MachineOperand &DispSpec = MI->getOperand(Op+3);
414 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
415 if (DispSpec.isGlobalAddress() ||
416 DispSpec.isConstantPoolIndex() ||
417 DispSpec.isJumpTableIndex()) {
418 printOperand(MI, Op+3, "mem", NotRIPRel);
420 int DispVal = DispSpec.getImmedValue();
421 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
425 if (IndexReg.getReg() || BaseReg.getReg()) {
426 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
427 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
429 // There are cases where we can end up with ESP/RSP in the indexreg slot.
430 // If this happens, swap the base/index register to support assemblers that
431 // don't work when the index is *SP.
432 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
433 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
434 std::swap(BaseReg, IndexReg);
435 std::swap(BaseRegOperand, IndexRegOperand);
439 if (BaseReg.getReg())
440 printOperand(MI, Op+BaseRegOperand, Modifier);
442 if (IndexReg.getReg()) {
444 printOperand(MI, Op+IndexRegOperand, Modifier);
446 O << "," << ScaleVal;
452 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
453 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
454 O << label << "\n" << label << ":";
458 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
460 const MRegisterInfo &RI = *TM.getRegisterInfo();
461 unsigned Reg = MO.getReg();
463 default: return true; // Unknown mode.
464 case 'b': // Print QImode register
465 Reg = getX86SubSuperRegister(Reg, MVT::i8);
467 case 'h': // Print QImode high register
468 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
470 case 'w': // Print HImode register
471 Reg = getX86SubSuperRegister(Reg, MVT::i16);
473 case 'k': // Print SImode register
474 Reg = getX86SubSuperRegister(Reg, MVT::i32);
479 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
480 O << (char)tolower(*Name);
484 /// PrintAsmOperand - Print out an operand for an inline asm expression.
486 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
488 const char *ExtraCode) {
489 // Does this asm operand have a single letter operand modifier?
490 if (ExtraCode && ExtraCode[0]) {
491 if (ExtraCode[1] != 0) return true; // Unknown modifier.
493 switch (ExtraCode[0]) {
494 default: return true; // Unknown modifier.
495 case 'c': // Don't print "$" before a global var name or constant.
496 printOperand(MI, OpNo, "mem");
498 case 'b': // Print QImode register
499 case 'h': // Print QImode high register
500 case 'w': // Print HImode register
501 case 'k': // Print SImode register
502 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
506 printOperand(MI, OpNo);
510 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
513 const char *ExtraCode) {
514 if (ExtraCode && ExtraCode[0])
515 return true; // Unknown modifier.
516 printMemReference(MI, OpNo);
520 /// printMachineInstruction -- Print out a single X86 LLVM instruction
521 /// MI in Intel syntax to the current output stream.
523 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
526 // See if a truncate instruction can be turned into a nop.
527 switch (MI->getOpcode()) {
529 case X86::TRUNC_64to32:
530 case X86::TRUNC_64to16:
531 case X86::TRUNC_32to16:
532 case X86::TRUNC_32to8:
533 case X86::TRUNC_16to8:
534 case X86::TRUNC_32_to8:
535 case X86::TRUNC_16_to8: {
536 const MachineOperand &MO0 = MI->getOperand(0);
537 const MachineOperand &MO1 = MI->getOperand(1);
538 unsigned Reg0 = MO0.getReg();
539 unsigned Reg1 = MO1.getReg();
540 unsigned Opc = MI->getOpcode();
541 if (Opc == X86::TRUNC_64to32)
542 Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
543 else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
544 Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
546 Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
547 O << TAI->getCommentString() << " TRUNCATE ";
552 case X86::PsMOVZX64rr32:
553 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
557 // Call the autogenerated instruction printer routines.
558 printInstruction(MI);
561 // Include the auto-generated portion of the assembly writer.
562 #include "X86GenAsmWriter.inc"