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/Target/TargetAsmInfo.h"
32 #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, ParamAttr::ByVal))
76 Ty = cast<PointerType>(Ty)->getElementType();
78 // Size should be aligned to DWORD boundary
79 Size += ((TD->getABITypeSize(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, std::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 // Substitute old hook with new one temporary
151 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
152 return TAI->SectionForGlobal(&F);
155 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
156 const Function *F = MF.getFunction();
158 decorateName(CurrentFnName, F);
160 SwitchToTextSection(TAI->SectionForGlobal(F).c_str(), F);
162 unsigned FnAlign = OptimizeForSize ? 1 : 4;
163 switch (F->getLinkage()) {
164 default: assert(0 && "Unknown linkage type!");
165 case Function::InternalLinkage: // Symbols default to internal.
166 EmitAlignment(FnAlign, F);
168 case Function::DLLExportLinkage:
169 case Function::ExternalLinkage:
170 EmitAlignment(FnAlign, F);
171 O << "\t.globl\t" << CurrentFnName << '\n';
173 case Function::LinkOnceLinkage:
174 case Function::WeakLinkage:
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';
187 if (F->hasHiddenVisibility()) {
188 if (const char *Directive = TAI->getHiddenDirective())
189 O << Directive << CurrentFnName << '\n';
190 } else if (F->hasProtectedVisibility()) {
191 if (const char *Directive = TAI->getProtectedDirective())
192 O << Directive << CurrentFnName << '\n';
195 if (Subtarget->isTargetELF())
196 O << "\t.type\t" << CurrentFnName << ",@function\n";
197 else if (Subtarget->isTargetCygMing()) {
198 O << "\t.def\t " << CurrentFnName
200 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
201 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
205 O << CurrentFnName << ":\n";
206 // Add some workaround for linkonce linkage on Cygwin\MinGW
207 if (Subtarget->isTargetCygMing() &&
208 (F->getLinkage() == Function::LinkOnceLinkage ||
209 F->getLinkage() == Function::WeakLinkage))
210 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
213 /// runOnMachineFunction - This uses the printMachineInstruction()
214 /// method to print assembly for each instruction.
216 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
217 const Function *F = MF.getFunction();
218 unsigned CC = F->getCallingConv();
220 if (TAI->doesSupportDebugInformation()) {
221 // Let PassManager know we need debug information and relay
222 // the MachineModuleInfo address on to DwarfWriter.
223 MMI = &getAnalysis<MachineModuleInfo>();
224 DW.SetModuleInfo(MMI);
227 SetupMachineFunction(MF);
230 // Populate function information map. Actually, We don't want to populate
231 // non-stdcall or non-fastcall functions' information right now.
232 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
233 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
235 // Print out constants referenced by the function
236 EmitConstantPool(MF.getConstantPool());
238 if (F->hasDLLExportLinkage())
239 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
241 // Print the 'header' of function
242 emitFunctionHeader(MF);
244 // Emit pre-function debug and/or EH information.
245 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
246 DW.BeginFunction(&MF);
248 // Print out code for the function.
249 bool hasAnyRealCode = false;
250 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
252 // Print a label for the basic block.
253 if (!I->pred_empty()) {
254 printBasicBlockLabel(I, true, true);
257 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
259 // Print the assembly for the instruction.
261 hasAnyRealCode = true;
262 printMachineInstruction(II);
266 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
267 // If the function is empty, then we need to emit *something*. Otherwise,
268 // the function's label might be associated with something that it wasn't
269 // meant to be associated with. We emit a noop in this situation.
270 // We are assuming inline asms are code.
274 if (TAI->hasDotTypeDotSizeDirective())
275 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
277 // Emit post-function debug information.
278 if (TAI->doesSupportDebugInformation())
281 // Print out jump tables referenced by the function.
282 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
284 // We didn't modify anything.
288 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
289 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
292 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
293 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
294 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
297 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
298 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
301 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
302 const char *Modifier, bool NotRIPRel) {
303 const MachineOperand &MO = MI->getOperand(OpNo);
304 switch (MO.getType()) {
305 case MachineOperand::MO_Register: {
306 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
307 "Virtual registers should not make it this far!");
309 unsigned Reg = MO.getReg();
310 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
311 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
312 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
313 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
314 Reg = getX86SubSuperRegister(Reg, VT);
316 O << TRI->getAsmName(Reg);
320 case MachineOperand::MO_Immediate:
322 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
326 case MachineOperand::MO_MachineBasicBlock:
327 printBasicBlockLabel(MO.getMBB());
329 case MachineOperand::MO_JumpTableIndex: {
330 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
331 if (!isMemOp) O << '$';
332 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
335 if (TM.getRelocationModel() == Reloc::PIC_) {
336 if (Subtarget->isPICStyleStub())
337 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
339 else if (Subtarget->isPICStyleGOT())
343 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
347 case MachineOperand::MO_ConstantPoolIndex: {
348 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
349 if (!isMemOp) O << '$';
350 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
353 if (TM.getRelocationModel() == Reloc::PIC_) {
354 if (Subtarget->isPICStyleStub())
355 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
357 else if (Subtarget->isPICStyleGOT())
361 int Offset = MO.getOffset();
367 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
371 case MachineOperand::MO_GlobalAddress: {
372 bool isCallOp = Modifier && !strcmp(Modifier, "call");
373 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
374 bool needCloseParen = false;
376 const GlobalValue *GV = MO.getGlobal();
377 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
379 // If GV is an alias then use the aliasee for determining
381 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
382 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
385 bool isThreadLocal = GVar && GVar->isThreadLocal();
387 std::string Name = Mang->getValueName(GV);
388 decorateName(Name, GV);
390 if (!isMemOp && !isCallOp)
392 else if (Name[0] == '$') {
393 // The name begins with a dollar-sign. In order to avoid having it look
394 // like an integer immediate to the assembler, enclose it in parens.
396 needCloseParen = true;
399 if (shouldPrintStub(TM, Subtarget)) {
400 // Link-once, declaration, or Weakly-linked global variables need
401 // non-lazily-resolved stubs
402 if (GV->isDeclaration() ||
403 GV->hasWeakLinkage() ||
404 GV->hasLinkOnceLinkage() ||
405 GV->hasCommonLinkage()) {
406 // Dynamically-resolved functions need a stub for the function.
407 if (isCallOp && isa<Function>(GV)) {
408 FnStubs.insert(Name);
409 printSuffixedName(Name, "$stub");
411 GVStubs.insert(Name);
412 printSuffixedName(Name, "$non_lazy_ptr");
415 if (GV->hasDLLImportLinkage())
420 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
421 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
423 if (GV->hasDLLImportLinkage()) {
429 if (shouldPrintPLT(TM, Subtarget)) {
430 // Assemble call via PLT for externally visible symbols
431 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
432 !GV->hasInternalLinkage())
435 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
436 // Save function name for later type emission
437 FnStubs.insert(Name);
441 if (GV->hasExternalWeakLinkage())
442 ExtWeakSymbols.insert(GV);
444 int Offset = MO.getOffset();
451 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
452 O << "@TLSGD"; // general dynamic TLS model
454 if (GV->isDeclaration())
455 O << "@INDNTPOFF"; // initial exec TLS model
457 O << "@NTPOFF"; // local exec TLS model
458 } else if (isMemOp) {
459 if (shouldPrintGOT(TM, Subtarget)) {
460 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
464 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
465 TM.getRelocationModel() != Reloc::Static) {
466 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
469 if (needCloseParen) {
470 needCloseParen = false;
474 // Use rip when possible to reduce code size, except when
475 // index or base register are also part of the address. e.g.
476 // foo(%rip)(%rcx,%rax,4) is not legal
486 case MachineOperand::MO_ExternalSymbol: {
487 bool isCallOp = Modifier && !strcmp(Modifier, "call");
488 bool needCloseParen = false;
489 std::string Name(TAI->getGlobalPrefix());
490 Name += MO.getSymbolName();
491 if (isCallOp && shouldPrintStub(TM, Subtarget)) {
492 FnStubs.insert(Name);
493 printSuffixedName(Name, "$stub");
498 else if (Name[0] == '$') {
499 // The name begins with a dollar-sign. In order to avoid having it look
500 // like an integer immediate to the assembler, enclose it in parens.
502 needCloseParen = true;
507 if (shouldPrintPLT(TM, Subtarget)) {
508 std::string GOTName(TAI->getGlobalPrefix());
509 GOTName+="_GLOBAL_OFFSET_TABLE_";
511 // HACK! Emit extra offset to PC during printing GOT offset to
512 // compensate for the size of popl instruction. The resulting code
516 // popl %some_register
517 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
519 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
528 if (!isCallOp && Subtarget->isPICStyleRIPRel())
534 O << "<unknown operand type>"; return;
538 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
539 unsigned char value = MI->getOperand(Op).getImm();
540 assert(value <= 7 && "Invalid ssecc argument!");
542 case 0: O << "eq"; break;
543 case 1: O << "lt"; break;
544 case 2: O << "le"; break;
545 case 3: O << "unord"; break;
546 case 4: O << "neq"; break;
547 case 5: O << "nlt"; break;
548 case 6: O << "nle"; break;
549 case 7: O << "ord"; break;
553 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
554 const char *Modifier){
555 assert(isMem(MI, Op) && "Invalid memory reference!");
556 MachineOperand BaseReg = MI->getOperand(Op);
557 MachineOperand IndexReg = MI->getOperand(Op+2);
558 const MachineOperand &DispSpec = MI->getOperand(Op+3);
560 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
561 if (DispSpec.isGlobalAddress() ||
562 DispSpec.isConstantPoolIndex() ||
563 DispSpec.isJumpTableIndex()) {
564 printOperand(MI, Op+3, "mem", NotRIPRel);
566 int DispVal = DispSpec.getImm();
567 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
571 if (IndexReg.getReg() || BaseReg.getReg()) {
572 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
573 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
575 // There are cases where we can end up with ESP/RSP in the indexreg slot.
576 // If this happens, swap the base/index register to support assemblers that
577 // don't work when the index is *SP.
578 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
579 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
580 std::swap(BaseReg, IndexReg);
581 std::swap(BaseRegOperand, IndexRegOperand);
585 if (BaseReg.getReg())
586 printOperand(MI, Op+BaseRegOperand, Modifier);
588 if (IndexReg.getReg()) {
590 printOperand(MI, Op+IndexRegOperand, Modifier);
592 O << ',' << ScaleVal;
598 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
599 const MachineBasicBlock *MBB) const {
600 if (!TAI->getSetDirective())
603 // We don't need .set machinery if we have GOT-style relocations
604 if (Subtarget->isPICStyleGOT())
607 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
608 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
609 printBasicBlockLabel(MBB, false, false, false);
610 if (Subtarget->isPICStyleRIPRel())
611 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
612 << '_' << uid << '\n';
614 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
617 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
618 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
619 O << label << '\n' << label << ':';
623 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
624 const MachineBasicBlock *MBB,
627 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
628 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
630 O << JTEntryDirective << ' ';
632 if (TM.getRelocationModel() == Reloc::PIC_) {
633 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
634 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
635 << '_' << uid << "_set_" << MBB->getNumber();
636 } else if (Subtarget->isPICStyleGOT()) {
637 printBasicBlockLabel(MBB, false, false, false);
640 assert(0 && "Don't know how to print MBB label for this PIC mode");
642 printBasicBlockLabel(MBB, false, false, false);
645 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
647 unsigned Reg = MO.getReg();
649 default: return true; // Unknown mode.
650 case 'b': // Print QImode register
651 Reg = getX86SubSuperRegister(Reg, MVT::i8);
653 case 'h': // Print QImode high register
654 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
656 case 'w': // Print HImode register
657 Reg = getX86SubSuperRegister(Reg, MVT::i16);
659 case 'k': // Print SImode register
660 Reg = getX86SubSuperRegister(Reg, MVT::i32);
662 case 'q': // Print DImode register
663 Reg = getX86SubSuperRegister(Reg, MVT::i64);
667 O << '%'<< TRI->getAsmName(Reg);
671 /// PrintAsmOperand - Print out an operand for an inline asm expression.
673 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
675 const char *ExtraCode) {
676 // Does this asm operand have a single letter operand modifier?
677 if (ExtraCode && ExtraCode[0]) {
678 if (ExtraCode[1] != 0) return true; // Unknown modifier.
680 switch (ExtraCode[0]) {
681 default: return true; // Unknown modifier.
682 case 'c': // Don't print "$" before a global var name or constant.
683 printOperand(MI, OpNo, "mem");
685 case 'b': // Print QImode register
686 case 'h': // Print QImode high register
687 case 'w': // Print HImode register
688 case 'k': // Print SImode register
689 case 'q': // Print DImode register
690 if (MI->getOperand(OpNo).isRegister())
691 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
692 printOperand(MI, OpNo);
695 case 'P': // Don't print @PLT, but do print as memory.
696 printOperand(MI, OpNo, "mem");
701 printOperand(MI, OpNo);
705 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
708 const char *ExtraCode) {
709 if (ExtraCode && ExtraCode[0]) {
710 if (ExtraCode[1] != 0) return true; // Unknown modifier.
712 switch (ExtraCode[0]) {
713 default: return true; // Unknown modifier.
714 case 'b': // Print QImode register
715 case 'h': // Print QImode high register
716 case 'w': // Print HImode register
717 case 'k': // Print SImode register
718 case 'q': // Print SImode register
719 // These only apply to registers, ignore on mem.
723 printMemReference(MI, OpNo);
727 /// printMachineInstruction -- Print out a single X86 LLVM instruction
728 /// MI in AT&T syntax to the current output stream.
730 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
733 // Call the autogenerated instruction printer routines.
734 printInstruction(MI);
738 bool X86ATTAsmPrinter::doInitialization(Module &M) {
739 if (TAI->doesSupportDebugInformation()) {
740 // Emit initial debug information.
744 bool Result = AsmPrinter::doInitialization(M);
746 // Darwin wants symbols to be quoted if they have complex names.
747 if (Subtarget->isTargetDarwin())
748 Mang->setUseQuotes(true);
754 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
755 const TargetData *TD = TM.getTargetData();
757 if (!GVar->hasInitializer())
758 return; // External global require no code
760 std::string SectionName = TAI->SectionForGlobal(GVar);
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 name = Mang->getValueName(GVar);
775 Constant *C = GVar->getInitializer();
776 const Type *Type = C->getType();
777 unsigned Size = TD->getABITypeSize(Type);
778 unsigned Align = TD->getPreferredAlignmentLog(GVar);
780 if (GVar->hasHiddenVisibility()) {
781 if (const char *Directive = TAI->getHiddenDirective())
782 O << Directive << name << '\n';
783 } else if (GVar->hasProtectedVisibility()) {
784 if (const char *Directive = TAI->getProtectedDirective())
785 O << Directive << name << '\n';
788 if (Subtarget->isTargetELF())
789 O << "\t.type\t" << name << ",@object\n";
791 SwitchToDataSection(SectionName.c_str());
793 if (C->isNullValue() && !GVar->hasSection()) {
794 // FIXME: This seems to be pretty darwin-specific
795 if (GVar->hasExternalLinkage()) {
796 if (const char *Directive = TAI->getZeroFillDirective()) {
797 O << "\t.globl " << name << '\n';
798 O << Directive << "__DATA, __common, " << name << ", "
799 << Size << ", " << Align << '\n';
804 if (!GVar->isThreadLocal() &&
805 (GVar->hasInternalLinkage() || GVar->hasWeakLinkage() ||
806 GVar->hasLinkOnceLinkage() || GVar->hasCommonLinkage())) {
807 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
809 if (TAI->getLCOMMDirective() != NULL) {
810 if (GVar->hasInternalLinkage()) {
811 O << TAI->getLCOMMDirective() << name << ',' << Size;
812 if (Subtarget->isTargetDarwin())
814 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
815 O << "\t.globl " << name << '\n'
816 << TAI->getWeakDefDirective() << name << '\n';
817 EmitAlignment(Align, GVar);
818 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
819 PrintUnmangledNameSafely(GVar, O);
821 EmitGlobalConstant(C);
824 O << TAI->getCOMMDirective() << name << ',' << Size;
826 // Leopard and above support aligned common symbols.
827 if (Subtarget->getDarwinVers() >= 9)
831 if (!Subtarget->isTargetCygMing()) {
832 if (GVar->hasInternalLinkage())
833 O << "\t.local\t" << name << '\n';
835 O << TAI->getCOMMDirective() << name << ',' << Size;
836 if (TAI->getCOMMDirectiveTakesAlignment())
837 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
839 O << "\t\t" << TAI->getCommentString() << ' ';
840 PrintUnmangledNameSafely(GVar, O);
846 switch (GVar->getLinkage()) {
847 case GlobalValue::CommonLinkage:
848 case GlobalValue::LinkOnceLinkage:
849 case GlobalValue::WeakLinkage:
850 if (Subtarget->isTargetDarwin()) {
851 O << "\t.globl " << name << '\n'
852 << TAI->getWeakDefDirective() << name << '\n';
853 } else if (Subtarget->isTargetCygMing()) {
854 O << "\t.globl\t" << name << "\n"
855 "\t.linkonce same_size\n";
857 O << "\t.weak\t" << name << '\n';
860 case GlobalValue::DLLExportLinkage:
861 case GlobalValue::AppendingLinkage:
862 // FIXME: appending linkage variables should go into a section of
863 // their name or something. For now, just emit them as external.
864 case GlobalValue::ExternalLinkage:
865 // If external or appending, declare as a global symbol
866 O << "\t.globl " << name << '\n';
868 case GlobalValue::InternalLinkage:
871 assert(0 && "Unknown linkage type!");
874 EmitAlignment(Align, GVar);
875 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
876 PrintUnmangledNameSafely(GVar, O);
878 if (TAI->hasDotTypeDotSizeDirective())
879 O << "\t.size\t" << name << ", " << Size << '\n';
881 // If the initializer is a extern weak symbol, remember to emit the weak
883 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
884 if (GV->hasExternalWeakLinkage())
885 ExtWeakSymbols.insert(GV);
887 EmitGlobalConstant(C);
890 /// printGVStub - Print stub for a global value.
892 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
893 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
894 O << ":\n\t.indirect_symbol ";
895 if (Prefix) O << Prefix;
896 O << GV << "\n\t.long\t0\n";
900 bool X86ATTAsmPrinter::doFinalization(Module &M) {
901 // Print out module-level global variables here.
902 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
904 printModuleLevelGV(I);
906 if (I->hasDLLExportLinkage())
907 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
910 // Output linker support code for dllexported globals
911 if (!DLLExportedGVs.empty())
912 SwitchToDataSection(".section .drectve");
914 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
915 e = DLLExportedGVs.end();
917 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
919 if (!DLLExportedFns.empty()) {
920 SwitchToDataSection(".section .drectve");
923 for (StringSet<>::iterator i = DLLExportedFns.begin(),
924 e = DLLExportedFns.end();
926 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
928 if (Subtarget->isTargetDarwin()) {
929 SwitchToDataSection("");
931 // Output stubs for dynamically-linked functions
933 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
935 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
936 "self_modifying_code+pure_instructions,5", 0);
937 const char *p = i->getKeyData();
938 printSuffixedName(p, "$stub");
940 "\t.indirect_symbol " << p << "\n"
941 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
946 // Print global value stubs.
947 bool InStubSection = false;
948 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
949 // Add the (possibly multiple) personalities to the set of global values.
950 // Only referenced functions get into the Personalities list.
951 const std::vector<Function *>& Personalities = MMI->getPersonalities();
952 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
953 E = Personalities.end(); I != E; ++I) {
956 if (!InStubSection) {
958 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
959 InStubSection = true;
961 printGVStub((*I)->getNameStart(), "_");
965 // Output stubs for external and common global variables.
966 if (!InStubSection && !GVStubs.empty())
968 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
969 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
971 printGVStub(i->getKeyData());
973 // Emit final debug information.
976 // Funny Darwin hack: This flag tells the linker that no global symbols
977 // contain code that falls through to other global symbols (e.g. the obvious
978 // implementation of multiple entry points). If this doesn't occur, the
979 // linker can safely perform dead code stripping. Since LLVM never
980 // generates code that does this, it is always safe to set.
981 O << "\t.subsections_via_symbols\n";
982 } else if (Subtarget->isTargetCygMing()) {
983 // Emit type information for external functions
984 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
986 O << "\t.def\t " << i->getKeyData()
987 << ";\t.scl\t" << COFF::C_EXT
988 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
992 // Emit final debug information.
994 } else if (Subtarget->isTargetELF()) {
995 // Emit final debug information.
999 return AsmPrinter::doFinalization(M);
1002 // Include the auto-generated portion of the assembly writer.
1003 #include "X86GenAsmWriter.inc"