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/MachineJumpTableInfo.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetOptions.h"
36 STATISTIC(EmittedInsts, "Number of machine instrs printed");
38 static std::string getPICLabelString(unsigned FnNum,
39 const TargetAsmInfo *TAI,
40 const X86Subtarget* Subtarget) {
42 if (Subtarget->isTargetDarwin())
43 label = "\"L" + utostr_32(FnNum) + "$pb\"";
44 else if (Subtarget->isTargetELF())
45 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
47 assert(0 && "Don't know how to print PIC label!\n");
52 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
53 const TargetData *TD) {
54 X86MachineFunctionInfo Info;
57 switch (F->getCallingConv()) {
58 case CallingConv::X86_StdCall:
59 Info.setDecorationStyle(StdCall);
61 case CallingConv::X86_FastCall:
62 Info.setDecorationStyle(FastCall);
69 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
70 AI != AE; ++AI, ++argNum) {
71 const Type* Ty = AI->getType();
73 // 'Dereference' type in case of byval parameter attribute
74 if (F->paramHasAttr(argNum, Attribute::ByVal))
75 Ty = cast<PointerType>(Ty)->getElementType();
77 // Size should be aligned to DWORD boundary
78 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
81 // We're not supporting tooooo huge arguments :)
82 Info.setBytesToPopOnReturn((unsigned int)Size);
86 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
87 /// Don't print things like \n or \0.
88 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
89 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
95 /// decorateName - Query FunctionInfoMap and use this information for various
97 void X86ATTAsmPrinter::decorateName(std::string &Name,
98 const GlobalValue *GV) {
99 const Function *F = dyn_cast<Function>(GV);
102 // We don't want to decorate non-stdcall or non-fastcall functions right now
103 unsigned CC = F->getCallingConv();
104 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
107 // Decorate names only when we're targeting Cygwin/Mingw32 targets
108 if (!Subtarget->isTargetCygMing())
111 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
113 const X86MachineFunctionInfo *Info;
114 if (info_item == FunctionInfoMap.end()) {
115 // Calculate apropriate function info and populate map
116 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
117 Info = &FunctionInfoMap[F];
119 Info = &info_item->second;
122 const FunctionType *FT = F->getFunctionType();
123 switch (Info->getDecorationStyle()) {
127 // "Pure" variadic functions do not receive @0 suffix.
128 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
129 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
130 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
133 // "Pure" variadic functions do not receive @0 suffix.
134 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
135 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
136 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
138 if (Name[0] == '_') {
145 assert(0 && "Unsupported DecorationStyle");
149 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
150 const Function *F = MF.getFunction();
152 decorateName(CurrentFnName, F);
154 SwitchToSection(TAI->SectionForGlobal(F));
156 unsigned FnAlign = 4;
157 if (F->hasFnAttr(Attribute::OptimizeForSize))
159 switch (F->getLinkage()) {
160 default: assert(0 && "Unknown linkage type!");
161 case Function::InternalLinkage: // Symbols default to internal.
162 EmitAlignment(FnAlign, F);
164 case Function::DLLExportLinkage:
165 case Function::ExternalLinkage:
166 EmitAlignment(FnAlign, F);
167 O << "\t.globl\t" << CurrentFnName << '\n';
169 case Function::LinkOnceLinkage:
170 case Function::WeakLinkage:
171 EmitAlignment(FnAlign, F);
172 if (Subtarget->isTargetDarwin()) {
173 O << "\t.globl\t" << CurrentFnName << '\n';
174 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
175 } else if (Subtarget->isTargetCygMing()) {
176 O << "\t.globl\t" << CurrentFnName << "\n"
177 "\t.linkonce discard\n";
179 O << "\t.weak\t" << CurrentFnName << '\n';
184 printVisibility(CurrentFnName, F->getVisibility());
186 if (Subtarget->isTargetELF())
187 O << "\t.type\t" << CurrentFnName << ",@function\n";
188 else if (Subtarget->isTargetCygMing()) {
189 O << "\t.def\t " << CurrentFnName
191 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
192 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
196 O << CurrentFnName << ":\n";
197 // Add some workaround for linkonce linkage on Cygwin\MinGW
198 if (Subtarget->isTargetCygMing() &&
199 (F->getLinkage() == Function::LinkOnceLinkage ||
200 F->getLinkage() == Function::WeakLinkage))
201 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
204 /// runOnMachineFunction - This uses the printMachineInstruction()
205 /// method to print assembly for each instruction.
207 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
208 const Function *F = MF.getFunction();
209 unsigned CC = F->getCallingConv();
211 SetupMachineFunction(MF);
214 // Populate function information map. Actually, We don't want to populate
215 // non-stdcall or non-fastcall functions' information right now.
216 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
217 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
219 // Print out constants referenced by the function
220 EmitConstantPool(MF.getConstantPool());
222 if (F->hasDLLExportLinkage())
223 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
225 // Print the 'header' of function
226 emitFunctionHeader(MF);
228 // Emit pre-function debug and/or EH information.
229 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
230 DW.BeginFunction(&MF);
232 // Print out code for the function.
233 bool hasAnyRealCode = false;
234 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
236 // Print a label for the basic block.
237 if (!I->pred_empty()) {
238 printBasicBlockLabel(I, true, true);
241 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
243 // Print the assembly for the instruction.
245 hasAnyRealCode = true;
246 printMachineInstruction(II);
250 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
251 // If the function is empty, then we need to emit *something*. Otherwise,
252 // the function's label might be associated with something that it wasn't
253 // meant to be associated with. We emit a noop in this situation.
254 // We are assuming inline asms are code.
258 if (TAI->hasDotTypeDotSizeDirective())
259 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
261 // Emit post-function debug information.
262 if (TAI->doesSupportDebugInformation())
265 // Print out jump tables referenced by the function.
266 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
270 // We didn't modify anything.
274 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
275 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
278 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
279 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
280 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
283 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
284 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
287 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
288 const char *Modifier, bool NotRIPRel) {
289 const MachineOperand &MO = MI->getOperand(OpNo);
290 switch (MO.getType()) {
291 case MachineOperand::MO_Register: {
292 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
293 "Virtual registers should not make it this far!");
295 unsigned Reg = MO.getReg();
296 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
297 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
298 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
299 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
300 Reg = getX86SubSuperRegister(Reg, VT);
302 O << TRI->getAsmName(Reg);
306 case MachineOperand::MO_Immediate:
308 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
312 case MachineOperand::MO_MachineBasicBlock:
313 printBasicBlockLabel(MO.getMBB());
315 case MachineOperand::MO_JumpTableIndex: {
316 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
317 if (!isMemOp) O << '$';
318 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
321 if (TM.getRelocationModel() == Reloc::PIC_) {
322 if (Subtarget->isPICStyleStub())
323 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
325 else if (Subtarget->isPICStyleGOT())
329 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
333 case MachineOperand::MO_ConstantPoolIndex: {
334 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
335 if (!isMemOp) O << '$';
336 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
339 if (TM.getRelocationModel() == Reloc::PIC_) {
340 if (Subtarget->isPICStyleStub())
341 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
343 else if (Subtarget->isPICStyleGOT())
347 printOffset(MO.getOffset());
349 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
353 case MachineOperand::MO_GlobalAddress: {
354 bool isCallOp = Modifier && !strcmp(Modifier, "call");
355 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
356 bool needCloseParen = false;
358 const GlobalValue *GV = MO.getGlobal();
359 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
361 // If GV is an alias then use the aliasee for determining
363 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
364 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
367 bool isThreadLocal = GVar && GVar->isThreadLocal();
369 std::string Name = Mang->getValueName(GV);
370 decorateName(Name, GV);
372 if (!isMemOp && !isCallOp)
374 else if (Name[0] == '$') {
375 // The name begins with a dollar-sign. In order to avoid having it look
376 // like an integer immediate to the assembler, enclose it in parens.
378 needCloseParen = true;
381 if (shouldPrintStub(TM, Subtarget)) {
382 // Link-once, declaration, or Weakly-linked global variables need
383 // non-lazily-resolved stubs
384 if (GV->isDeclaration() || GV->mayBeOverridden()) {
385 // Dynamically-resolved functions need a stub for the function.
386 if (isCallOp && isa<Function>(GV)) {
387 // Function stubs are no longer needed for Mac OS X 10.5 and up.
388 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
391 FnStubs.insert(Name);
392 printSuffixedName(Name, "$stub");
395 GVStubs.insert(Name);
396 printSuffixedName(Name, "$non_lazy_ptr");
399 if (GV->hasDLLImportLinkage())
404 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
405 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
407 if (GV->hasDLLImportLinkage()) {
413 if (shouldPrintPLT(TM, Subtarget)) {
414 // Assemble call via PLT for externally visible symbols
415 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
416 !GV->hasInternalLinkage())
419 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
420 // Save function name for later type emission
421 FnStubs.insert(Name);
425 if (GV->hasExternalWeakLinkage())
426 ExtWeakSymbols.insert(GV);
428 printOffset(MO.getOffset());
431 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
432 O << "@TLSGD"; // general dynamic TLS model
434 if (GV->isDeclaration())
435 O << "@INDNTPOFF"; // initial exec TLS model
437 O << "@NTPOFF"; // local exec TLS model
438 } else if (isMemOp) {
439 if (shouldPrintGOT(TM, Subtarget)) {
440 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
444 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
445 TM.getRelocationModel() != Reloc::Static) {
446 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
449 if (needCloseParen) {
450 needCloseParen = false;
454 // Use rip when possible to reduce code size, except when
455 // index or base register are also part of the address. e.g.
456 // foo(%rip)(%rcx,%rax,4) is not legal
466 case MachineOperand::MO_ExternalSymbol: {
467 bool isCallOp = Modifier && !strcmp(Modifier, "call");
468 bool needCloseParen = false;
469 std::string Name(TAI->getGlobalPrefix());
470 Name += MO.getSymbolName();
471 // Print function stub suffix unless it's Mac OS X 10.5 and up.
472 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
473 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
474 FnStubs.insert(Name);
475 printSuffixedName(Name, "$stub");
480 else if (Name[0] == '$') {
481 // The name begins with a dollar-sign. In order to avoid having it look
482 // like an integer immediate to the assembler, enclose it in parens.
484 needCloseParen = true;
489 if (shouldPrintPLT(TM, Subtarget)) {
490 std::string GOTName(TAI->getGlobalPrefix());
491 GOTName+="_GLOBAL_OFFSET_TABLE_";
493 // HACK! Emit extra offset to PC during printing GOT offset to
494 // compensate for the size of popl instruction. The resulting code
498 // popl %some_register
499 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
501 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
510 if (!isCallOp && Subtarget->isPICStyleRIPRel())
516 O << "<unknown operand type>"; return;
520 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
521 unsigned char value = MI->getOperand(Op).getImm();
522 assert(value <= 7 && "Invalid ssecc argument!");
524 case 0: O << "eq"; break;
525 case 1: O << "lt"; break;
526 case 2: O << "le"; break;
527 case 3: O << "unord"; break;
528 case 4: O << "neq"; break;
529 case 5: O << "nlt"; break;
530 case 6: O << "nle"; break;
531 case 7: O << "ord"; break;
535 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
536 const char *Modifier){
537 assert(isMem(MI, Op) && "Invalid memory reference!");
538 MachineOperand BaseReg = MI->getOperand(Op);
539 MachineOperand IndexReg = MI->getOperand(Op+2);
540 const MachineOperand &DispSpec = MI->getOperand(Op+3);
542 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
543 if (DispSpec.isGlobal() ||
546 printOperand(MI, Op+3, "mem", NotRIPRel);
548 int DispVal = DispSpec.getImm();
549 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
553 if (IndexReg.getReg() || BaseReg.getReg()) {
554 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
555 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
557 // There are cases where we can end up with ESP/RSP in the indexreg slot.
558 // If this happens, swap the base/index register to support assemblers that
559 // don't work when the index is *SP.
560 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
561 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
562 std::swap(BaseReg, IndexReg);
563 std::swap(BaseRegOperand, IndexRegOperand);
567 if (BaseReg.getReg())
568 printOperand(MI, Op+BaseRegOperand, Modifier);
570 if (IndexReg.getReg()) {
572 printOperand(MI, Op+IndexRegOperand, Modifier);
574 O << ',' << ScaleVal;
580 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
581 const MachineBasicBlock *MBB) const {
582 if (!TAI->getSetDirective())
585 // We don't need .set machinery if we have GOT-style relocations
586 if (Subtarget->isPICStyleGOT())
589 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
590 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
591 printBasicBlockLabel(MBB, false, false, false);
592 if (Subtarget->isPICStyleRIPRel())
593 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
594 << '_' << uid << '\n';
596 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
599 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
600 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
601 O << label << '\n' << label << ':';
605 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
606 const MachineBasicBlock *MBB,
609 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
610 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
612 O << JTEntryDirective << ' ';
614 if (TM.getRelocationModel() == Reloc::PIC_) {
615 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
616 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
617 << '_' << uid << "_set_" << MBB->getNumber();
618 } else if (Subtarget->isPICStyleGOT()) {
619 printBasicBlockLabel(MBB, false, false, false);
622 assert(0 && "Don't know how to print MBB label for this PIC mode");
624 printBasicBlockLabel(MBB, false, false, false);
627 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
629 unsigned Reg = MO.getReg();
631 default: return true; // Unknown mode.
632 case 'b': // Print QImode register
633 Reg = getX86SubSuperRegister(Reg, MVT::i8);
635 case 'h': // Print QImode high register
636 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
638 case 'w': // Print HImode register
639 Reg = getX86SubSuperRegister(Reg, MVT::i16);
641 case 'k': // Print SImode register
642 Reg = getX86SubSuperRegister(Reg, MVT::i32);
644 case 'q': // Print DImode register
645 Reg = getX86SubSuperRegister(Reg, MVT::i64);
649 O << '%'<< TRI->getAsmName(Reg);
653 /// PrintAsmOperand - Print out an operand for an inline asm expression.
655 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
657 const char *ExtraCode) {
658 // Does this asm operand have a single letter operand modifier?
659 if (ExtraCode && ExtraCode[0]) {
660 if (ExtraCode[1] != 0) return true; // Unknown modifier.
662 switch (ExtraCode[0]) {
663 default: return true; // Unknown modifier.
664 case 'c': // Don't print "$" before a global var name or constant.
665 printOperand(MI, OpNo, "mem");
667 case 'b': // Print QImode register
668 case 'h': // Print QImode high register
669 case 'w': // Print HImode register
670 case 'k': // Print SImode register
671 case 'q': // Print DImode register
672 if (MI->getOperand(OpNo).isReg())
673 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
674 printOperand(MI, OpNo);
677 case 'P': // Don't print @PLT, but do print as memory.
678 printOperand(MI, OpNo, "mem");
683 printOperand(MI, OpNo);
687 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
690 const char *ExtraCode) {
691 if (ExtraCode && ExtraCode[0]) {
692 if (ExtraCode[1] != 0) return true; // Unknown modifier.
694 switch (ExtraCode[0]) {
695 default: return true; // Unknown modifier.
696 case 'b': // Print QImode register
697 case 'h': // Print QImode high register
698 case 'w': // Print HImode register
699 case 'k': // Print SImode register
700 case 'q': // Print SImode register
701 // These only apply to registers, ignore on mem.
705 printMemReference(MI, OpNo);
709 /// printMachineInstruction -- Print out a single X86 LLVM instruction
710 /// MI in AT&T syntax to the current output stream.
712 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
715 // Call the autogenerated instruction printer routines.
716 printInstruction(MI);
720 bool X86ATTAsmPrinter::doInitialization(Module &M) {
721 if (TAI->doesSupportDebugInformation()) {
722 // Emit initial debug information.
726 bool Result = AsmPrinter::doInitialization(M);
728 if (TAI->doesSupportDebugInformation()) {
729 // Let PassManager know we need debug information and relay
730 // the MachineModuleInfo address on to DwarfWriter.
731 // AsmPrinter::doInitialization did this analysis.
732 MMI = getAnalysisToUpdate<MachineModuleInfo>();
733 DW.SetModuleInfo(MMI);
736 // Darwin wants symbols to be quoted if they have complex names.
737 if (Subtarget->isTargetDarwin())
738 Mang->setUseQuotes(true);
744 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
745 const TargetData *TD = TM.getTargetData();
747 if (!GVar->hasInitializer())
748 return; // External global require no code
750 // Check to see if this is a special global used by LLVM, if so, emit it.
751 if (EmitSpecialLLVMGlobal(GVar)) {
752 if (Subtarget->isTargetDarwin() &&
753 TM.getRelocationModel() == Reloc::Static) {
754 if (GVar->getName() == "llvm.global_ctors")
755 O << ".reference .constructors_used\n";
756 else if (GVar->getName() == "llvm.global_dtors")
757 O << ".reference .destructors_used\n";
762 std::string name = Mang->getValueName(GVar);
763 Constant *C = GVar->getInitializer();
764 const Type *Type = C->getType();
765 unsigned Size = TD->getABITypeSize(Type);
766 unsigned Align = TD->getPreferredAlignmentLog(GVar);
768 printVisibility(name, GVar->getVisibility());
770 if (Subtarget->isTargetELF())
771 O << "\t.type\t" << name << ",@object\n";
773 SwitchToSection(TAI->SectionForGlobal(GVar));
775 if (C->isNullValue() && !GVar->hasSection()) {
776 // FIXME: This seems to be pretty darwin-specific
777 if (GVar->hasExternalLinkage()) {
778 if (const char *Directive = TAI->getZeroFillDirective()) {
779 O << "\t.globl " << name << '\n';
780 O << Directive << "__DATA, __common, " << name << ", "
781 << Size << ", " << Align << '\n';
786 if (!GVar->isThreadLocal() &&
787 (GVar->hasInternalLinkage() || GVar->mayBeOverridden())) {
788 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
790 if (TAI->getLCOMMDirective() != NULL) {
791 if (GVar->hasInternalLinkage()) {
792 O << TAI->getLCOMMDirective() << name << ',' << Size;
793 if (Subtarget->isTargetDarwin())
795 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
796 O << "\t.globl " << name << '\n'
797 << TAI->getWeakDefDirective() << name << '\n';
798 EmitAlignment(Align, GVar);
799 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
800 PrintUnmangledNameSafely(GVar, O);
802 EmitGlobalConstant(C);
805 O << TAI->getCOMMDirective() << name << ',' << Size;
806 if (TAI->getCOMMDirectiveTakesAlignment())
807 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
810 if (!Subtarget->isTargetCygMing()) {
811 if (GVar->hasInternalLinkage())
812 O << "\t.local\t" << name << '\n';
814 O << TAI->getCOMMDirective() << name << ',' << Size;
815 if (TAI->getCOMMDirectiveTakesAlignment())
816 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
818 O << "\t\t" << TAI->getCommentString() << ' ';
819 PrintUnmangledNameSafely(GVar, O);
825 switch (GVar->getLinkage()) {
826 case GlobalValue::CommonLinkage:
827 case GlobalValue::LinkOnceLinkage:
828 case GlobalValue::WeakLinkage:
829 if (Subtarget->isTargetDarwin()) {
830 O << "\t.globl " << name << '\n'
831 << TAI->getWeakDefDirective() << name << '\n';
832 } else if (Subtarget->isTargetCygMing()) {
833 O << "\t.globl\t" << name << "\n"
834 "\t.linkonce same_size\n";
836 O << "\t.weak\t" << name << '\n';
839 case GlobalValue::DLLExportLinkage:
840 case GlobalValue::AppendingLinkage:
841 // FIXME: appending linkage variables should go into a section of
842 // their name or something. For now, just emit them as external.
843 case GlobalValue::ExternalLinkage:
844 // If external or appending, declare as a global symbol
845 O << "\t.globl " << name << '\n';
847 case GlobalValue::InternalLinkage:
850 assert(0 && "Unknown linkage type!");
853 EmitAlignment(Align, GVar);
854 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
855 PrintUnmangledNameSafely(GVar, O);
857 if (TAI->hasDotTypeDotSizeDirective())
858 O << "\t.size\t" << name << ", " << Size << '\n';
860 // If the initializer is a extern weak symbol, remember to emit the weak
862 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
863 if (GV->hasExternalWeakLinkage())
864 ExtWeakSymbols.insert(GV);
866 EmitGlobalConstant(C);
869 /// printGVStub - Print stub for a global value.
871 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
872 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
873 O << ":\n\t.indirect_symbol ";
874 if (Prefix) O << Prefix;
875 O << GV << "\n\t.long\t0\n";
879 bool X86ATTAsmPrinter::doFinalization(Module &M) {
880 // Print out module-level global variables here.
881 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
883 printModuleLevelGV(I);
885 if (I->hasDLLExportLinkage())
886 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
889 // Output linker support code for dllexported globals
890 if (!DLLExportedGVs.empty())
891 SwitchToDataSection(".section .drectve");
893 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
894 e = DLLExportedGVs.end();
896 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
898 if (!DLLExportedFns.empty()) {
899 SwitchToDataSection(".section .drectve");
902 for (StringSet<>::iterator i = DLLExportedFns.begin(),
903 e = DLLExportedFns.end();
905 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
907 if (Subtarget->isTargetDarwin()) {
908 SwitchToDataSection("");
910 // Output stubs for dynamically-linked functions
912 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
914 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
915 "self_modifying_code+pure_instructions,5", 0);
916 const char *p = i->getKeyData();
917 printSuffixedName(p, "$stub");
919 "\t.indirect_symbol " << p << "\n"
920 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
925 // Print global value stubs.
926 bool InStubSection = false;
927 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
928 // Add the (possibly multiple) personalities to the set of global values.
929 // Only referenced functions get into the Personalities list.
930 const std::vector<Function *>& Personalities = MMI->getPersonalities();
931 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
932 E = Personalities.end(); I != E; ++I) {
935 if (!InStubSection) {
937 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
938 InStubSection = true;
940 printGVStub((*I)->getNameStart(), "_");
944 // Output stubs for external and common global variables.
945 if (!InStubSection && !GVStubs.empty())
947 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
948 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
950 printGVStub(i->getKeyData());
952 // Emit final debug information.
955 // Funny Darwin hack: This flag tells the linker that no global symbols
956 // contain code that falls through to other global symbols (e.g. the obvious
957 // implementation of multiple entry points). If this doesn't occur, the
958 // linker can safely perform dead code stripping. Since LLVM never
959 // generates code that does this, it is always safe to set.
960 O << "\t.subsections_via_symbols\n";
961 } else if (Subtarget->isTargetCygMing()) {
962 // Emit type information for external functions
963 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
965 O << "\t.def\t " << i->getKeyData()
966 << ";\t.scl\t" << COFF::C_EXT
967 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
971 // Emit final debug information.
973 } else if (Subtarget->isTargetELF()) {
974 // Emit final debug information.
978 return AsmPrinter::doFinalization(M);
981 // Include the auto-generated portion of the assembly writer.
982 #include "X86GenAsmWriter.inc"