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, ParamAttr::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 // Substitute old hook with new one temporary
150 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
151 return TAI->SectionForGlobal(&F);
154 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
155 const Function *F = MF.getFunction();
156 std::string SectionName = TAI->SectionForGlobal(F);
158 decorateName(CurrentFnName, F);
160 SwitchToTextSection(SectionName.c_str());
162 unsigned FnAlign = OptimizeForSize ? 1 : 4;
163 if (FnAlign == 4 && (F->getNotes() & FN_NOTE_OptimizeForSize))
165 switch (F->getLinkage()) {
166 default: assert(0 && "Unknown linkage type!");
167 case Function::InternalLinkage: // Symbols default to internal.
168 EmitAlignment(FnAlign, F);
170 case Function::DLLExportLinkage:
171 case Function::ExternalLinkage:
172 EmitAlignment(FnAlign, F);
173 O << "\t.globl\t" << CurrentFnName << '\n';
175 case Function::LinkOnceLinkage:
176 case Function::WeakLinkage:
177 EmitAlignment(FnAlign, F);
178 if (Subtarget->isTargetDarwin()) {
179 O << "\t.globl\t" << CurrentFnName << '\n';
180 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
181 } else if (Subtarget->isTargetCygMing()) {
182 O << "\t.globl\t" << CurrentFnName << "\n"
183 "\t.linkonce discard\n";
185 O << "\t.weak\t" << CurrentFnName << '\n';
190 printVisibility(CurrentFnName, F->getVisibility());
192 if (Subtarget->isTargetELF())
193 O << "\t.type\t" << CurrentFnName << ",@function\n";
194 else if (Subtarget->isTargetCygMing()) {
195 O << "\t.def\t " << CurrentFnName
197 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
198 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
202 O << CurrentFnName << ":\n";
203 // Add some workaround for linkonce linkage on Cygwin\MinGW
204 if (Subtarget->isTargetCygMing() &&
205 (F->getLinkage() == Function::LinkOnceLinkage ||
206 F->getLinkage() == Function::WeakLinkage))
207 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
210 /// runOnMachineFunction - This uses the printMachineInstruction()
211 /// method to print assembly for each instruction.
213 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
214 const Function *F = MF.getFunction();
215 unsigned CC = F->getCallingConv();
217 SetupMachineFunction(MF);
220 // Populate function information map. Actually, We don't want to populate
221 // non-stdcall or non-fastcall functions' information right now.
222 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
223 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
225 // Print out constants referenced by the function
226 EmitConstantPool(MF.getConstantPool());
228 if (F->hasDLLExportLinkage())
229 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
231 // Print the 'header' of function
232 emitFunctionHeader(MF);
234 // Emit pre-function debug and/or EH information.
235 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
236 DW.BeginFunction(&MF);
238 // Print out code for the function.
239 bool hasAnyRealCode = false;
240 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
242 // Print a label for the basic block.
243 if (!I->pred_empty()) {
244 printBasicBlockLabel(I, true, true);
247 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
249 // Print the assembly for the instruction.
251 hasAnyRealCode = true;
252 printMachineInstruction(II);
256 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
257 // If the function is empty, then we need to emit *something*. Otherwise,
258 // the function's label might be associated with something that it wasn't
259 // meant to be associated with. We emit a noop in this situation.
260 // We are assuming inline asms are code.
264 if (TAI->hasDotTypeDotSizeDirective())
265 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
267 // Emit post-function debug information.
268 if (TAI->doesSupportDebugInformation())
271 // Print out jump tables referenced by the function.
272 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:
312 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
316 case MachineOperand::MO_MachineBasicBlock:
317 printBasicBlockLabel(MO.getMBB());
319 case MachineOperand::MO_JumpTableIndex: {
320 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
321 if (!isMemOp) O << '$';
322 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
325 if (TM.getRelocationModel() == Reloc::PIC_) {
326 if (Subtarget->isPICStyleStub())
327 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
329 else if (Subtarget->isPICStyleGOT())
333 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
337 case MachineOperand::MO_ConstantPoolIndex: {
338 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
339 if (!isMemOp) O << '$';
340 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
343 if (TM.getRelocationModel() == Reloc::PIC_) {
344 if (Subtarget->isPICStyleStub())
345 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
347 else if (Subtarget->isPICStyleGOT())
351 int Offset = MO.getOffset();
357 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
361 case MachineOperand::MO_GlobalAddress: {
362 bool isCallOp = Modifier && !strcmp(Modifier, "call");
363 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
364 bool needCloseParen = false;
366 const GlobalValue *GV = MO.getGlobal();
367 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
369 // If GV is an alias then use the aliasee for determining
371 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
372 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
375 bool isThreadLocal = GVar && GVar->isThreadLocal();
377 std::string Name = Mang->getValueName(GV);
378 decorateName(Name, GV);
380 if (!isMemOp && !isCallOp)
382 else if (Name[0] == '$') {
383 // The name begins with a dollar-sign. In order to avoid having it look
384 // like an integer immediate to the assembler, enclose it in parens.
386 needCloseParen = true;
389 if (shouldPrintStub(TM, Subtarget)) {
390 // Link-once, declaration, or Weakly-linked global variables need
391 // non-lazily-resolved stubs
392 if (GV->isDeclaration() || GV->isWeakForLinker()) {
393 // Dynamically-resolved functions need a stub for the function.
394 if (isCallOp && isa<Function>(GV)) {
395 // Function stubs are no longer needed for Mac OS X 10.5 and up.
396 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
399 FnStubs.insert(Name);
400 printSuffixedName(Name, "$stub");
403 GVStubs.insert(Name);
404 printSuffixedName(Name, "$non_lazy_ptr");
407 if (GV->hasDLLImportLinkage())
412 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
413 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
415 if (GV->hasDLLImportLinkage()) {
421 if (shouldPrintPLT(TM, Subtarget)) {
422 // Assemble call via PLT for externally visible symbols
423 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
424 !GV->hasInternalLinkage())
427 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
428 // Save function name for later type emission
429 FnStubs.insert(Name);
433 if (GV->hasExternalWeakLinkage())
434 ExtWeakSymbols.insert(GV);
436 int Offset = MO.getOffset();
443 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
444 O << "@TLSGD"; // general dynamic TLS model
446 if (GV->isDeclaration())
447 O << "@INDNTPOFF"; // initial exec TLS model
449 O << "@NTPOFF"; // local exec TLS model
450 } else if (isMemOp) {
451 if (shouldPrintGOT(TM, Subtarget)) {
452 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
456 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
457 TM.getRelocationModel() != Reloc::Static) {
458 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
461 if (needCloseParen) {
462 needCloseParen = false;
466 // Use rip when possible to reduce code size, except when
467 // index or base register are also part of the address. e.g.
468 // foo(%rip)(%rcx,%rax,4) is not legal
478 case MachineOperand::MO_ExternalSymbol: {
479 bool isCallOp = Modifier && !strcmp(Modifier, "call");
480 bool needCloseParen = false;
481 std::string Name(TAI->getGlobalPrefix());
482 Name += MO.getSymbolName();
483 // Print function stub suffix unless it's Mac OS X 10.5 and up.
484 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
485 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
486 FnStubs.insert(Name);
487 printSuffixedName(Name, "$stub");
492 else if (Name[0] == '$') {
493 // The name begins with a dollar-sign. In order to avoid having it look
494 // like an integer immediate to the assembler, enclose it in parens.
496 needCloseParen = true;
501 if (shouldPrintPLT(TM, Subtarget)) {
502 std::string GOTName(TAI->getGlobalPrefix());
503 GOTName+="_GLOBAL_OFFSET_TABLE_";
505 // HACK! Emit extra offset to PC during printing GOT offset to
506 // compensate for the size of popl instruction. The resulting code
510 // popl %some_register
511 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
513 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
522 if (!isCallOp && Subtarget->isPICStyleRIPRel())
528 O << "<unknown operand type>"; return;
532 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
533 unsigned char value = MI->getOperand(Op).getImm();
534 assert(value <= 7 && "Invalid ssecc argument!");
536 case 0: O << "eq"; break;
537 case 1: O << "lt"; break;
538 case 2: O << "le"; break;
539 case 3: O << "unord"; break;
540 case 4: O << "neq"; break;
541 case 5: O << "nlt"; break;
542 case 6: O << "nle"; break;
543 case 7: O << "ord"; break;
547 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
548 const char *Modifier){
549 assert(isMem(MI, Op) && "Invalid memory reference!");
550 MachineOperand BaseReg = MI->getOperand(Op);
551 MachineOperand IndexReg = MI->getOperand(Op+2);
552 const MachineOperand &DispSpec = MI->getOperand(Op+3);
554 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
555 if (DispSpec.isGlobalAddress() ||
556 DispSpec.isConstantPoolIndex() ||
557 DispSpec.isJumpTableIndex()) {
558 printOperand(MI, Op+3, "mem", NotRIPRel);
560 int DispVal = DispSpec.getImm();
561 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
565 if (IndexReg.getReg() || BaseReg.getReg()) {
566 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
567 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
569 // There are cases where we can end up with ESP/RSP in the indexreg slot.
570 // If this happens, swap the base/index register to support assemblers that
571 // don't work when the index is *SP.
572 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
573 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
574 std::swap(BaseReg, IndexReg);
575 std::swap(BaseRegOperand, IndexRegOperand);
579 if (BaseReg.getReg())
580 printOperand(MI, Op+BaseRegOperand, Modifier);
582 if (IndexReg.getReg()) {
584 printOperand(MI, Op+IndexRegOperand, Modifier);
586 O << ',' << ScaleVal;
592 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
593 const MachineBasicBlock *MBB) const {
594 if (!TAI->getSetDirective())
597 // We don't need .set machinery if we have GOT-style relocations
598 if (Subtarget->isPICStyleGOT())
601 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
602 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
603 printBasicBlockLabel(MBB, false, false, false);
604 if (Subtarget->isPICStyleRIPRel())
605 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
606 << '_' << uid << '\n';
608 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
611 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
612 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
613 O << label << '\n' << label << ':';
617 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
618 const MachineBasicBlock *MBB,
621 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
622 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
624 O << JTEntryDirective << ' ';
626 if (TM.getRelocationModel() == Reloc::PIC_) {
627 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
628 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
629 << '_' << uid << "_set_" << MBB->getNumber();
630 } else if (Subtarget->isPICStyleGOT()) {
631 printBasicBlockLabel(MBB, false, false, false);
634 assert(0 && "Don't know how to print MBB label for this PIC mode");
636 printBasicBlockLabel(MBB, false, false, false);
639 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
641 unsigned Reg = MO.getReg();
643 default: return true; // Unknown mode.
644 case 'b': // Print QImode register
645 Reg = getX86SubSuperRegister(Reg, MVT::i8);
647 case 'h': // Print QImode high register
648 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
650 case 'w': // Print HImode register
651 Reg = getX86SubSuperRegister(Reg, MVT::i16);
653 case 'k': // Print SImode register
654 Reg = getX86SubSuperRegister(Reg, MVT::i32);
656 case 'q': // Print DImode register
657 Reg = getX86SubSuperRegister(Reg, MVT::i64);
661 O << '%'<< TRI->getAsmName(Reg);
665 /// PrintAsmOperand - Print out an operand for an inline asm expression.
667 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
669 const char *ExtraCode) {
670 // Does this asm operand have a single letter operand modifier?
671 if (ExtraCode && ExtraCode[0]) {
672 if (ExtraCode[1] != 0) return true; // Unknown modifier.
674 switch (ExtraCode[0]) {
675 default: return true; // Unknown modifier.
676 case 'c': // Don't print "$" before a global var name or constant.
677 printOperand(MI, OpNo, "mem");
679 case 'b': // Print QImode register
680 case 'h': // Print QImode high register
681 case 'w': // Print HImode register
682 case 'k': // Print SImode register
683 case 'q': // Print DImode register
684 if (MI->getOperand(OpNo).isRegister())
685 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
686 printOperand(MI, OpNo);
689 case 'P': // Don't print @PLT, but do print as memory.
690 printOperand(MI, OpNo, "mem");
695 printOperand(MI, OpNo);
699 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
702 const char *ExtraCode) {
703 if (ExtraCode && ExtraCode[0]) {
704 if (ExtraCode[1] != 0) return true; // Unknown modifier.
706 switch (ExtraCode[0]) {
707 default: return true; // Unknown modifier.
708 case 'b': // Print QImode register
709 case 'h': // Print QImode high register
710 case 'w': // Print HImode register
711 case 'k': // Print SImode register
712 case 'q': // Print SImode register
713 // These only apply to registers, ignore on mem.
717 printMemReference(MI, OpNo);
721 /// printMachineInstruction -- Print out a single X86 LLVM instruction
722 /// MI in AT&T syntax to the current output stream.
724 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
727 // Call the autogenerated instruction printer routines.
728 printInstruction(MI);
732 bool X86ATTAsmPrinter::doInitialization(Module &M) {
733 if (TAI->doesSupportDebugInformation()) {
734 // Emit initial debug information.
738 bool Result = AsmPrinter::doInitialization(M);
740 if (TAI->doesSupportDebugInformation()) {
741 // Let PassManager know we need debug information and relay
742 // the MachineModuleInfo address on to DwarfWriter.
743 // AsmPrinter::doInitialization did this analysis.
744 MMI = getAnalysisToUpdate<MachineModuleInfo>();
745 DW.SetModuleInfo(MMI);
748 // Darwin wants symbols to be quoted if they have complex names.
749 if (Subtarget->isTargetDarwin())
750 Mang->setUseQuotes(true);
756 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
757 const TargetData *TD = TM.getTargetData();
759 if (!GVar->hasInitializer())
760 return; // External global require no code
762 // Check to see if this is a special global used by LLVM, if so, emit it.
763 if (EmitSpecialLLVMGlobal(GVar)) {
764 if (Subtarget->isTargetDarwin() &&
765 TM.getRelocationModel() == Reloc::Static) {
766 if (GVar->getName() == "llvm.global_ctors")
767 O << ".reference .constructors_used\n";
768 else if (GVar->getName() == "llvm.global_dtors")
769 O << ".reference .destructors_used\n";
774 std::string SectionName = TAI->SectionForGlobal(GVar);
775 std::string name = Mang->getValueName(GVar);
776 Constant *C = GVar->getInitializer();
777 const Type *Type = C->getType();
778 unsigned Size = TD->getABITypeSize(Type);
779 unsigned Align = TD->getPreferredAlignmentLog(GVar);
781 printVisibility(name, GVar->getVisibility());
783 if (Subtarget->isTargetELF())
784 O << "\t.type\t" << name << ",@object\n";
786 SwitchToDataSection(SectionName.c_str());
788 if (C->isNullValue() && !GVar->hasSection()) {
789 // FIXME: This seems to be pretty darwin-specific
790 if (GVar->hasExternalLinkage()) {
791 if (const char *Directive = TAI->getZeroFillDirective()) {
792 O << "\t.globl " << name << '\n';
793 O << Directive << "__DATA, __common, " << name << ", "
794 << Size << ", " << Align << '\n';
799 if (!GVar->isThreadLocal() &&
800 (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
801 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
803 if (TAI->getLCOMMDirective() != NULL) {
804 if (GVar->hasInternalLinkage()) {
805 O << TAI->getLCOMMDirective() << name << ',' << Size;
806 if (Subtarget->isTargetDarwin())
808 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
809 O << "\t.globl " << name << '\n'
810 << TAI->getWeakDefDirective() << name << '\n';
811 EmitAlignment(Align, GVar);
812 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
813 PrintUnmangledNameSafely(GVar, O);
815 EmitGlobalConstant(C);
818 O << TAI->getCOMMDirective() << name << ',' << Size;
819 if (TAI->getCOMMDirectiveTakesAlignment())
820 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
823 if (!Subtarget->isTargetCygMing()) {
824 if (GVar->hasInternalLinkage())
825 O << "\t.local\t" << name << '\n';
827 O << TAI->getCOMMDirective() << name << ',' << Size;
828 if (TAI->getCOMMDirectiveTakesAlignment())
829 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
831 O << "\t\t" << TAI->getCommentString() << ' ';
832 PrintUnmangledNameSafely(GVar, O);
838 switch (GVar->getLinkage()) {
839 case GlobalValue::CommonLinkage:
840 case GlobalValue::LinkOnceLinkage:
841 case GlobalValue::WeakLinkage:
842 if (Subtarget->isTargetDarwin()) {
843 O << "\t.globl " << name << '\n'
844 << TAI->getWeakDefDirective() << name << '\n';
845 } else if (Subtarget->isTargetCygMing()) {
846 O << "\t.globl\t" << name << "\n"
847 "\t.linkonce same_size\n";
849 O << "\t.weak\t" << name << '\n';
852 case GlobalValue::DLLExportLinkage:
853 case GlobalValue::AppendingLinkage:
854 // FIXME: appending linkage variables should go into a section of
855 // their name or something. For now, just emit them as external.
856 case GlobalValue::ExternalLinkage:
857 // If external or appending, declare as a global symbol
858 O << "\t.globl " << name << '\n';
860 case GlobalValue::InternalLinkage:
863 assert(0 && "Unknown linkage type!");
866 EmitAlignment(Align, GVar);
867 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
868 PrintUnmangledNameSafely(GVar, O);
870 if (TAI->hasDotTypeDotSizeDirective())
871 O << "\t.size\t" << name << ", " << Size << '\n';
873 // If the initializer is a extern weak symbol, remember to emit the weak
875 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
876 if (GV->hasExternalWeakLinkage())
877 ExtWeakSymbols.insert(GV);
879 EmitGlobalConstant(C);
882 /// printGVStub - Print stub for a global value.
884 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
885 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
886 O << ":\n\t.indirect_symbol ";
887 if (Prefix) O << Prefix;
888 O << GV << "\n\t.long\t0\n";
892 bool X86ATTAsmPrinter::doFinalization(Module &M) {
893 // Print out module-level global variables here.
894 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
896 printModuleLevelGV(I);
898 if (I->hasDLLExportLinkage())
899 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
902 // Output linker support code for dllexported globals
903 if (!DLLExportedGVs.empty())
904 SwitchToDataSection(".section .drectve");
906 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
907 e = DLLExportedGVs.end();
909 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
911 if (!DLLExportedFns.empty()) {
912 SwitchToDataSection(".section .drectve");
915 for (StringSet<>::iterator i = DLLExportedFns.begin(),
916 e = DLLExportedFns.end();
918 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
920 if (Subtarget->isTargetDarwin()) {
921 SwitchToDataSection("");
923 // Output stubs for dynamically-linked functions
925 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
927 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
928 "self_modifying_code+pure_instructions,5", 0);
929 const char *p = i->getKeyData();
930 printSuffixedName(p, "$stub");
932 "\t.indirect_symbol " << p << "\n"
933 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
938 // Print global value stubs.
939 bool InStubSection = false;
940 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
941 // Add the (possibly multiple) personalities to the set of global values.
942 // Only referenced functions get into the Personalities list.
943 const std::vector<Function *>& Personalities = MMI->getPersonalities();
944 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
945 E = Personalities.end(); I != E; ++I) {
948 if (!InStubSection) {
950 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
951 InStubSection = true;
953 printGVStub((*I)->getNameStart(), "_");
957 // Output stubs for external and common global variables.
958 if (!InStubSection && !GVStubs.empty())
960 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
961 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
963 printGVStub(i->getKeyData());
965 // Emit final debug information.
968 // Funny Darwin hack: This flag tells the linker that no global symbols
969 // contain code that falls through to other global symbols (e.g. the obvious
970 // implementation of multiple entry points). If this doesn't occur, the
971 // linker can safely perform dead code stripping. Since LLVM never
972 // generates code that does this, it is always safe to set.
973 O << "\t.subsections_via_symbols\n";
974 } else if (Subtarget->isTargetCygMing()) {
975 // Emit type information for external functions
976 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
978 O << "\t.def\t " << i->getKeyData()
979 << ";\t.scl\t" << COFF::C_EXT
980 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
984 // Emit final debug information.
986 } else if (Subtarget->isTargetELF()) {
987 // Emit final debug information.
991 return AsmPrinter::doFinalization(M);
994 // Include the auto-generated portion of the assembly writer.
995 #include "X86GenAsmWriter.inc"