1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetOptions.h"
37 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39 static std::string getPICLabelString(unsigned FnNum,
40 const TargetAsmInfo *TAI,
41 const X86Subtarget* Subtarget) {
43 if (Subtarget->isTargetDarwin())
44 label = "\"L" + utostr_32(FnNum) + "$pb\"";
45 else if (Subtarget->isTargetELF())
46 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
48 assert(0 && "Don't know how to print PIC label!\n");
53 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
54 const TargetData *TD) {
55 X86MachineFunctionInfo Info;
58 switch (F->getCallingConv()) {
59 case CallingConv::X86_StdCall:
60 Info.setDecorationStyle(StdCall);
62 case CallingConv::X86_FastCall:
63 Info.setDecorationStyle(FastCall);
70 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
71 AI != AE; ++AI, ++argNum) {
72 const Type* Ty = AI->getType();
74 // 'Dereference' type in case of byval parameter attribute
75 if (F->paramHasAttr(argNum, Attribute::ByVal))
76 Ty = cast<PointerType>(Ty)->getElementType();
78 // Size should be aligned to DWORD boundary
79 Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
82 // We're not supporting tooooo huge arguments :)
83 Info.setBytesToPopOnReturn((unsigned int)Size);
87 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
88 /// Don't print things like \\n or \\0.
89 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
90 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
96 /// decorateName - Query FunctionInfoMap and use this information for various
98 void X86ATTAsmPrinter::decorateName(std::string &Name,
99 const GlobalValue *GV) {
100 const Function *F = dyn_cast<Function>(GV);
103 // We don't want to decorate non-stdcall or non-fastcall functions right now
104 unsigned CC = F->getCallingConv();
105 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
108 // Decorate names only when we're targeting Cygwin/Mingw32 targets
109 if (!Subtarget->isTargetCygMing())
112 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
114 const X86MachineFunctionInfo *Info;
115 if (info_item == FunctionInfoMap.end()) {
116 // Calculate apropriate function info and populate map
117 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
118 Info = &FunctionInfoMap[F];
120 Info = &info_item->second;
123 const FunctionType *FT = F->getFunctionType();
124 switch (Info->getDecorationStyle()) {
128 // "Pure" variadic functions do not receive @0 suffix.
129 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
130 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
131 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
134 // "Pure" variadic functions do not receive @0 suffix.
135 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
136 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
137 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
139 if (Name[0] == '_') {
146 assert(0 && "Unsupported DecorationStyle");
150 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
151 const Function *F = MF.getFunction();
153 decorateName(CurrentFnName, F);
155 SwitchToSection(TAI->SectionForGlobal(F));
157 unsigned FnAlign = 4;
158 if (F->hasFnAttr(Attribute::OptimizeForSize))
160 switch (F->getLinkage()) {
161 default: assert(0 && "Unknown linkage type!");
162 case Function::InternalLinkage: // Symbols default to internal.
163 case Function::PrivateLinkage:
164 EmitAlignment(FnAlign, F);
166 case Function::DLLExportLinkage:
167 case Function::ExternalLinkage:
168 EmitAlignment(FnAlign, F);
169 O << "\t.globl\t" << CurrentFnName << '\n';
171 case Function::LinkOnceAnyLinkage:
172 case Function::LinkOnceODRLinkage:
173 case Function::WeakAnyLinkage:
174 case Function::WeakODRLinkage:
175 EmitAlignment(FnAlign, F);
176 if (Subtarget->isTargetDarwin()) {
177 O << "\t.globl\t" << CurrentFnName << '\n';
178 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
179 } else if (Subtarget->isTargetCygMing()) {
180 O << "\t.globl\t" << CurrentFnName << "\n"
181 "\t.linkonce discard\n";
183 O << "\t.weak\t" << CurrentFnName << '\n';
188 printVisibility(CurrentFnName, F->getVisibility());
190 if (Subtarget->isTargetELF())
191 O << "\t.type\t" << CurrentFnName << ",@function\n";
192 else if (Subtarget->isTargetCygMing()) {
193 O << "\t.def\t " << CurrentFnName
195 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
196 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
200 O << CurrentFnName << ":\n";
201 // Add some workaround for linkonce linkage on Cygwin\MinGW
202 if (Subtarget->isTargetCygMing() &&
203 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
204 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
207 /// runOnMachineFunction - This uses the printMachineInstruction()
208 /// method to print assembly for each instruction.
210 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
211 const Function *F = MF.getFunction();
213 unsigned CC = F->getCallingConv();
215 SetupMachineFunction(MF);
218 // Populate function information map. Actually, We don't want to populate
219 // non-stdcall or non-fastcall functions' information right now.
220 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
221 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
223 // Print out constants referenced by the function
224 EmitConstantPool(MF.getConstantPool());
226 if (F->hasDLLExportLinkage())
227 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
229 // Print the 'header' of function
230 emitFunctionHeader(MF);
232 // Emit pre-function debug and/or EH information.
233 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
234 DW->BeginFunction(&MF);
236 // Print out code for the function.
237 bool hasAnyRealCode = false;
238 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
240 // Print a label for the basic block.
241 if (!I->pred_empty()) {
242 printBasicBlockLabel(I, true, true);
245 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
247 // Print the assembly for the instruction.
249 hasAnyRealCode = true;
250 printMachineInstruction(II);
254 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
255 // If the function is empty, then we need to emit *something*. Otherwise,
256 // the function's label might be associated with something that it wasn't
257 // meant to be associated with. We emit a noop in this situation.
258 // We are assuming inline asms are code.
262 if (TAI->hasDotTypeDotSizeDirective())
263 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
265 // Emit post-function debug information.
266 if (TAI->doesSupportDebugInformation())
267 DW->EndFunction(&MF);
269 // Print out jump tables referenced by the function.
270 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
274 // We didn't modify anything.
278 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
279 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
282 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
283 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
284 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
287 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
288 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
291 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
292 const char *Modifier, bool NotRIPRel) {
293 const MachineOperand &MO = MI->getOperand(OpNo);
294 switch (MO.getType()) {
295 case MachineOperand::MO_Register: {
296 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
297 "Virtual registers should not make it this far!");
299 unsigned Reg = MO.getReg();
300 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
301 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
302 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
303 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
304 Reg = getX86SubSuperRegister(Reg, VT);
306 O << TRI->getAsmName(Reg);
310 case MachineOperand::MO_Immediate:
311 if (!Modifier || (strcmp(Modifier, "debug") &&
312 strcmp(Modifier, "mem") &&
313 strcmp(Modifier, "call")))
317 case MachineOperand::MO_MachineBasicBlock:
318 printBasicBlockLabel(MO.getMBB());
320 case MachineOperand::MO_JumpTableIndex: {
321 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
322 if (!isMemOp) O << '$';
323 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
326 if (TM.getRelocationModel() == Reloc::PIC_) {
327 if (Subtarget->isPICStyleStub())
328 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
330 else if (Subtarget->isPICStyleGOT())
334 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
338 case MachineOperand::MO_ConstantPoolIndex: {
339 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
340 if (!isMemOp) O << '$';
341 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
344 if (TM.getRelocationModel() == Reloc::PIC_) {
345 if (Subtarget->isPICStyleStub())
346 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
348 else if (Subtarget->isPICStyleGOT())
352 printOffset(MO.getOffset());
354 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
358 case MachineOperand::MO_GlobalAddress: {
359 bool isCallOp = Modifier && !strcmp(Modifier, "call");
360 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
361 bool needCloseParen = false;
363 const GlobalValue *GV = MO.getGlobal();
364 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
366 // If GV is an alias then use the aliasee for determining
368 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
369 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
372 bool isThreadLocal = GVar && GVar->isThreadLocal();
374 std::string Name = Mang->getValueName(GV);
375 decorateName(Name, GV);
377 if (!isMemOp && !isCallOp)
379 else if (Name[0] == '$') {
380 // The name begins with a dollar-sign. In order to avoid having it look
381 // like an integer immediate to the assembler, enclose it in parens.
383 needCloseParen = true;
386 if (shouldPrintStub(TM, Subtarget)) {
387 // Link-once, declaration, or Weakly-linked global variables need
388 // non-lazily-resolved stubs
389 if (GV->isDeclaration() || GV->isWeakForLinker()) {
390 // Dynamically-resolved functions need a stub for the function.
391 if (isCallOp && isa<Function>(GV)) {
392 // Function stubs are no longer needed for Mac OS X 10.5 and up.
393 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
396 FnStubs.insert(Name);
397 printSuffixedName(Name, "$stub");
399 } else if (GV->hasHiddenVisibility()) {
400 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
401 // Definition is not definitely in the current translation unit.
404 HiddenGVStubs.insert(Name);
405 printSuffixedName(Name, "$non_lazy_ptr");
408 GVStubs.insert(Name);
409 printSuffixedName(Name, "$non_lazy_ptr");
412 if (GV->hasDLLImportLinkage())
417 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
418 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
420 if (GV->hasDLLImportLinkage()) {
426 if (shouldPrintPLT(TM, Subtarget)) {
427 // Assemble call via PLT for externally visible symbols
428 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
429 !GV->hasLocalLinkage())
432 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
433 // Save function name for later type emission
434 FnStubs.insert(Name);
438 if (GV->hasExternalWeakLinkage())
439 ExtWeakSymbols.insert(GV);
441 printOffset(MO.getOffset());
444 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
446 case TLSModel::GeneralDynamic:
449 case TLSModel::LocalDynamic:
450 // O << "@TLSLD"; // local dynamic not implemented
453 case TLSModel::InitialExec:
454 if (Subtarget->is64Bit())
455 O << "@TLSGD"; // 64 bit intial exec not implemented
459 case TLSModel::LocalExec:
460 if (Subtarget->is64Bit())
461 O << "@TLSGD"; // 64 bit local exec not implemented
466 assert (0 && "Unknown TLS model");
468 } else if (isMemOp) {
469 if (shouldPrintGOT(TM, Subtarget)) {
470 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
474 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
475 TM.getRelocationModel() != Reloc::Static) {
476 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
479 if (needCloseParen) {
480 needCloseParen = false;
484 // Use rip when possible to reduce code size, except when
485 // index or base register are also part of the address. e.g.
486 // foo(%rip)(%rcx,%rax,4) is not legal
496 case MachineOperand::MO_ExternalSymbol: {
497 bool isCallOp = Modifier && !strcmp(Modifier, "call");
498 bool needCloseParen = false;
499 std::string Name(TAI->getGlobalPrefix());
500 Name += MO.getSymbolName();
501 // Print function stub suffix unless it's Mac OS X 10.5 and up.
502 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
503 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
504 FnStubs.insert(Name);
505 printSuffixedName(Name, "$stub");
510 else if (Name[0] == '$') {
511 // The name begins with a dollar-sign. In order to avoid having it look
512 // like an integer immediate to the assembler, enclose it in parens.
514 needCloseParen = true;
519 if (shouldPrintPLT(TM, Subtarget)) {
520 std::string GOTName(TAI->getGlobalPrefix());
521 GOTName+="_GLOBAL_OFFSET_TABLE_";
523 // HACK! Emit extra offset to PC during printing GOT offset to
524 // compensate for the size of popl instruction. The resulting code
528 // popl %some_register
529 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
531 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
540 if (!isCallOp && Subtarget->isPICStyleRIPRel())
546 O << "<unknown operand type>"; return;
550 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
551 unsigned char value = MI->getOperand(Op).getImm();
552 assert(value <= 7 && "Invalid ssecc argument!");
554 case 0: O << "eq"; break;
555 case 1: O << "lt"; break;
556 case 2: O << "le"; break;
557 case 3: O << "unord"; break;
558 case 4: O << "neq"; break;
559 case 5: O << "nlt"; break;
560 case 6: O << "nle"; break;
561 case 7: O << "ord"; break;
565 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
566 const char *Modifier){
567 assert(isMem(MI, Op) && "Invalid memory reference!");
568 MachineOperand BaseReg = MI->getOperand(Op);
569 MachineOperand IndexReg = MI->getOperand(Op+2);
570 const MachineOperand &DispSpec = MI->getOperand(Op+3);
572 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
573 if (DispSpec.isGlobal() ||
576 printOperand(MI, Op+3, "mem", NotRIPRel);
578 int DispVal = DispSpec.getImm();
579 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
583 if (IndexReg.getReg() || BaseReg.getReg()) {
584 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
585 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
587 // There are cases where we can end up with ESP/RSP in the indexreg slot.
588 // If this happens, swap the base/index register to support assemblers that
589 // don't work when the index is *SP.
590 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
591 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
592 std::swap(BaseReg, IndexReg);
593 std::swap(BaseRegOperand, IndexRegOperand);
597 if (BaseReg.getReg())
598 printOperand(MI, Op+BaseRegOperand, Modifier);
600 if (IndexReg.getReg()) {
602 printOperand(MI, Op+IndexRegOperand, Modifier);
604 O << ',' << ScaleVal;
610 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
611 const MachineBasicBlock *MBB) const {
612 if (!TAI->getSetDirective())
615 // We don't need .set machinery if we have GOT-style relocations
616 if (Subtarget->isPICStyleGOT())
619 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
620 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
621 printBasicBlockLabel(MBB, false, false, false);
622 if (Subtarget->isPICStyleRIPRel())
623 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
624 << '_' << uid << '\n';
626 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
629 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
630 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
631 O << label << '\n' << label << ':';
635 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
636 const MachineBasicBlock *MBB,
639 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
640 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
642 O << JTEntryDirective << ' ';
644 if (TM.getRelocationModel() == Reloc::PIC_) {
645 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
646 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
647 << '_' << uid << "_set_" << MBB->getNumber();
648 } else if (Subtarget->isPICStyleGOT()) {
649 printBasicBlockLabel(MBB, false, false, false);
652 assert(0 && "Don't know how to print MBB label for this PIC mode");
654 printBasicBlockLabel(MBB, false, false, false);
657 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
659 unsigned Reg = MO.getReg();
661 default: return true; // Unknown mode.
662 case 'b': // Print QImode register
663 Reg = getX86SubSuperRegister(Reg, MVT::i8);
665 case 'h': // Print QImode high register
666 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
668 case 'w': // Print HImode register
669 Reg = getX86SubSuperRegister(Reg, MVT::i16);
671 case 'k': // Print SImode register
672 Reg = getX86SubSuperRegister(Reg, MVT::i32);
674 case 'q': // Print DImode register
675 Reg = getX86SubSuperRegister(Reg, MVT::i64);
679 O << '%'<< TRI->getAsmName(Reg);
683 /// PrintAsmOperand - Print out an operand for an inline asm expression.
685 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
687 const char *ExtraCode) {
688 // Does this asm operand have a single letter operand modifier?
689 if (ExtraCode && ExtraCode[0]) {
690 if (ExtraCode[1] != 0) return true; // Unknown modifier.
692 switch (ExtraCode[0]) {
693 default: return true; // Unknown modifier.
694 case 'c': // Don't print "$" before a global var name or constant.
695 printOperand(MI, OpNo, "mem");
697 case 'b': // Print QImode register
698 case 'h': // Print QImode high register
699 case 'w': // Print HImode register
700 case 'k': // Print SImode register
701 case 'q': // Print DImode register
702 if (MI->getOperand(OpNo).isReg())
703 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
704 printOperand(MI, OpNo);
707 case 'P': // Don't print @PLT, but do print as memory.
708 printOperand(MI, OpNo, "mem");
713 printOperand(MI, OpNo);
717 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
720 const char *ExtraCode) {
721 if (ExtraCode && ExtraCode[0]) {
722 if (ExtraCode[1] != 0) return true; // Unknown modifier.
724 switch (ExtraCode[0]) {
725 default: return true; // Unknown modifier.
726 case 'b': // Print QImode register
727 case 'h': // Print QImode high register
728 case 'w': // Print HImode register
729 case 'k': // Print SImode register
730 case 'q': // Print SImode register
731 // These only apply to registers, ignore on mem.
733 case 'P': // Don't print @PLT, but do print as memory.
734 printOperand(MI, OpNo, "mem");
738 printMemReference(MI, OpNo);
742 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
743 /// AT&T syntax to the current output stream.
745 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
748 // Call the autogenerated instruction printer routines.
749 printInstruction(MI);
753 bool X86ATTAsmPrinter::doInitialization(Module &M) {
755 bool Result = AsmPrinter::doInitialization(M);
757 if (TAI->doesSupportDebugInformation()) {
758 // Let PassManager know we need debug information and relay
759 // the MachineModuleInfo address on to DwarfWriter.
760 // AsmPrinter::doInitialization did this analysis.
761 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
762 DW = getAnalysisIfAvailable<DwarfWriter>();
763 DW->BeginModule(&M, MMI, O, this, TAI);
766 // Darwin wants symbols to be quoted if they have complex names.
767 if (Subtarget->isTargetDarwin())
768 Mang->setUseQuotes(true);
774 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
775 const TargetData *TD = TM.getTargetData();
777 if (!GVar->hasInitializer())
778 return; // External global require no code
780 // Check to see if this is a special global used by LLVM, if so, emit it.
781 if (EmitSpecialLLVMGlobal(GVar)) {
782 if (Subtarget->isTargetDarwin() &&
783 TM.getRelocationModel() == Reloc::Static) {
784 if (GVar->getName() == "llvm.global_ctors")
785 O << ".reference .constructors_used\n";
786 else if (GVar->getName() == "llvm.global_dtors")
787 O << ".reference .destructors_used\n";
792 std::string name = Mang->getValueName(GVar);
793 Constant *C = GVar->getInitializer();
794 const Type *Type = C->getType();
795 unsigned Size = TD->getTypePaddedSize(Type);
796 unsigned Align = TD->getPreferredAlignmentLog(GVar);
798 printVisibility(name, GVar->getVisibility());
800 if (Subtarget->isTargetELF())
801 O << "\t.type\t" << name << ",@object\n";
803 SwitchToSection(TAI->SectionForGlobal(GVar));
805 if (C->isNullValue() && !GVar->hasSection() &&
806 !(Subtarget->isTargetDarwin() &&
807 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
808 // FIXME: This seems to be pretty darwin-specific
809 if (GVar->hasExternalLinkage()) {
810 if (const char *Directive = TAI->getZeroFillDirective()) {
811 O << "\t.globl " << name << '\n';
812 O << Directive << "__DATA, __common, " << name << ", "
813 << Size << ", " << Align << '\n';
818 if (!GVar->isThreadLocal() &&
819 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
820 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
822 if (TAI->getLCOMMDirective() != NULL) {
823 if (GVar->hasLocalLinkage()) {
824 O << TAI->getLCOMMDirective() << name << ',' << Size;
825 if (Subtarget->isTargetDarwin())
827 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
828 O << "\t.globl " << name << '\n'
829 << TAI->getWeakDefDirective() << name << '\n';
830 EmitAlignment(Align, GVar);
831 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
832 PrintUnmangledNameSafely(GVar, O);
834 EmitGlobalConstant(C);
837 O << TAI->getCOMMDirective() << name << ',' << Size;
838 if (TAI->getCOMMDirectiveTakesAlignment())
839 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
842 if (!Subtarget->isTargetCygMing()) {
843 if (GVar->hasLocalLinkage())
844 O << "\t.local\t" << name << '\n';
846 O << TAI->getCOMMDirective() << name << ',' << Size;
847 if (TAI->getCOMMDirectiveTakesAlignment())
848 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
850 O << "\t\t" << TAI->getCommentString() << ' ';
851 PrintUnmangledNameSafely(GVar, O);
857 switch (GVar->getLinkage()) {
858 case GlobalValue::CommonLinkage:
859 case GlobalValue::LinkOnceAnyLinkage:
860 case GlobalValue::LinkOnceODRLinkage:
861 case GlobalValue::WeakAnyLinkage:
862 case GlobalValue::WeakODRLinkage:
863 if (Subtarget->isTargetDarwin()) {
864 O << "\t.globl " << name << '\n'
865 << TAI->getWeakDefDirective() << name << '\n';
866 } else if (Subtarget->isTargetCygMing()) {
867 O << "\t.globl\t" << name << "\n"
868 "\t.linkonce same_size\n";
870 O << "\t.weak\t" << name << '\n';
873 case GlobalValue::DLLExportLinkage:
874 case GlobalValue::AppendingLinkage:
875 // FIXME: appending linkage variables should go into a section of
876 // their name or something. For now, just emit them as external.
877 case GlobalValue::ExternalLinkage:
878 // If external or appending, declare as a global symbol
879 O << "\t.globl " << name << '\n';
881 case GlobalValue::PrivateLinkage:
882 case GlobalValue::InternalLinkage:
885 assert(0 && "Unknown linkage type!");
888 EmitAlignment(Align, GVar);
889 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
890 PrintUnmangledNameSafely(GVar, O);
892 if (TAI->hasDotTypeDotSizeDirective())
893 O << "\t.size\t" << name << ", " << Size << '\n';
895 EmitGlobalConstant(C);
898 /// printGVStub - Print stub for a global value.
900 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
901 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
902 O << ":\n\t.indirect_symbol ";
903 if (Prefix) O << Prefix;
904 O << GV << "\n\t.long\t0\n";
907 /// printHiddenGVStub - Print stub for a hidden global value.
909 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
911 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
912 if (Prefix) O << Prefix;
913 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
917 bool X86ATTAsmPrinter::doFinalization(Module &M) {
918 // Print out module-level global variables here.
919 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
921 printModuleLevelGV(I);
923 if (I->hasDLLExportLinkage())
924 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
926 // If the global is a extern weak symbol, remember to emit the weak
928 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
929 // not used. But currently it's the only way to deal with extern weak
930 // initializers hidden deep inside constant expressions.
931 if (I->hasExternalWeakLinkage())
932 ExtWeakSymbols.insert(I);
935 for (Module::const_iterator I = M.begin(), E = M.end();
937 // If the global is a extern weak symbol, remember to emit the weak
939 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
940 // not used. But currently it's the only way to deal with extern weak
941 // initializers hidden deep inside constant expressions.
942 if (I->hasExternalWeakLinkage())
943 ExtWeakSymbols.insert(I);
946 // Output linker support code for dllexported globals
947 if (!DLLExportedGVs.empty())
948 SwitchToDataSection(".section .drectve");
950 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
951 e = DLLExportedGVs.end();
953 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
955 if (!DLLExportedFns.empty()) {
956 SwitchToDataSection(".section .drectve");
959 for (StringSet<>::iterator i = DLLExportedFns.begin(),
960 e = DLLExportedFns.end();
962 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
964 if (Subtarget->isTargetDarwin()) {
965 SwitchToDataSection("");
967 // Output stubs for dynamically-linked functions
968 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
970 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
971 "self_modifying_code+pure_instructions,5", 0);
972 const char *p = i->getKeyData();
973 printSuffixedName(p, "$stub");
975 "\t.indirect_symbol " << p << "\n"
976 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
981 // Print global value stubs.
982 bool InStubSection = false;
983 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
984 // Add the (possibly multiple) personalities to the set of global values.
985 // Only referenced functions get into the Personalities list.
986 const std::vector<Function *>& Personalities = MMI->getPersonalities();
987 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
988 E = Personalities.end(); I != E; ++I) {
991 if (!InStubSection) {
993 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
994 InStubSection = true;
996 printGVStub((*I)->getNameStart(), "_");
1000 // Output stubs for external and common global variables.
1001 if (!InStubSection && !GVStubs.empty())
1002 SwitchToDataSection(
1003 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1004 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1006 printGVStub(i->getKeyData());
1008 if (!HiddenGVStubs.empty()) {
1009 SwitchToSection(TAI->getDataSection());
1010 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1012 printHiddenGVStub(i->getKeyData());
1015 // Emit final debug information.
1016 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1019 // Funny Darwin hack: This flag tells the linker that no global symbols
1020 // contain code that falls through to other global symbols (e.g. the obvious
1021 // implementation of multiple entry points). If this doesn't occur, the
1022 // linker can safely perform dead code stripping. Since LLVM never
1023 // generates code that does this, it is always safe to set.
1024 O << "\t.subsections_via_symbols\n";
1025 } else if (Subtarget->isTargetCygMing()) {
1026 // Emit type information for external functions
1027 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1029 O << "\t.def\t " << i->getKeyData()
1030 << ";\t.scl\t" << COFF::C_EXT
1031 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1035 // Emit final debug information.
1036 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1038 } else if (Subtarget->isTargetELF()) {
1039 // Emit final debug information.
1040 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1044 return AsmPrinter::doFinalization(M);
1047 // Include the auto-generated portion of the assembly writer.
1048 #include "X86GenAsmWriter.inc"