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 "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Type.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/Statistic.h"
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
44 cl::Hidden, cl::init(false));
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
50 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
51 // FIXME: the actual label generated doesn't matter here! Just mangle in
52 // something unique (the function number) with Private prefix.
53 if (Subtarget->isTargetDarwin())
54 O << "\"L" << getFunctionNumber() << "$pb\"";
56 assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
57 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
61 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
62 const TargetData *TD) {
63 X86MachineFunctionInfo Info;
66 switch (F->getCallingConv()) {
67 case CallingConv::X86_StdCall:
68 Info.setDecorationStyle(StdCall);
70 case CallingConv::X86_FastCall:
71 Info.setDecorationStyle(FastCall);
78 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
79 AI != AE; ++AI, ++argNum) {
80 const Type* Ty = AI->getType();
82 // 'Dereference' type in case of byval parameter attribute
83 if (F->paramHasAttr(argNum, Attribute::ByVal))
84 Ty = cast<PointerType>(Ty)->getElementType();
86 // Size should be aligned to DWORD boundary
87 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
90 // We're not supporting tooooo huge arguments :)
91 Info.setBytesToPopOnReturn((unsigned int)Size);
95 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
96 /// various name decorations for Cygwin and MingW.
97 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl<char> &Name,
98 const GlobalValue *GV) {
99 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
101 const Function *F = dyn_cast<Function>(GV);
104 // Save function name for later type emission.
105 if (F->isDeclaration())
106 CygMingStubs.insert(StringRef(Name.data(), Name.size()));
108 // We don't want to decorate non-stdcall or non-fastcall functions right now
109 CallingConv::ID CC = F->getCallingConv();
110 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
114 const X86MachineFunctionInfo *Info;
116 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
117 if (info_item == FunctionInfoMap.end()) {
118 // Calculate apropriate function info and populate map
119 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
120 Info = &FunctionInfoMap[F];
122 Info = &info_item->second;
125 if (Info->getDecorationStyle() == None) return;
126 const FunctionType *FT = F->getFunctionType();
128 // "Pure" variadic functions do not receive @0 suffix.
129 if (!FT->isVarArg() || FT->getNumParams() == 0 ||
130 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
131 raw_svector_ostream(Name) << '@' << Info->getBytesToPopOnReturn();
133 if (Info->getDecorationStyle() == FastCall) {
137 Name.insert(Name.begin(), '@');
141 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
142 /// various name decorations for Cygwin and MingW.
143 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
144 const GlobalValue *GV) {
145 SmallString<128> NameStr(Name.begin(), Name.end());
146 DecorateCygMingName(NameStr, GV);
147 Name.assign(NameStr.begin(), NameStr.end());
150 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
151 unsigned FnAlign = MF.getAlignment();
152 const Function *F = MF.getFunction();
154 if (Subtarget->isTargetCygMing())
155 DecorateCygMingName(CurrentFnName, F);
157 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
158 EmitAlignment(FnAlign, F);
160 switch (F->getLinkage()) {
161 default: llvm_unreachable("Unknown linkage type!");
162 case Function::InternalLinkage: // Symbols default to internal.
163 case Function::PrivateLinkage:
165 case Function::DLLExportLinkage:
166 case Function::ExternalLinkage:
167 O << "\t.globl\t" << CurrentFnName << '\n';
169 case Function::LinkerPrivateLinkage:
170 case Function::LinkOnceAnyLinkage:
171 case Function::LinkOnceODRLinkage:
172 case Function::WeakAnyLinkage:
173 case Function::WeakODRLinkage:
174 if (Subtarget->isTargetDarwin()) {
175 O << "\t.globl\t" << CurrentFnName << '\n';
176 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
177 } else if (Subtarget->isTargetCygMing()) {
178 O << "\t.globl\t" << CurrentFnName << "\n"
179 "\t.linkonce discard\n";
181 O << "\t.weak\t" << CurrentFnName << '\n';
186 printVisibility(CurrentFnName, F->getVisibility());
188 if (Subtarget->isTargetELF())
189 O << "\t.type\t" << CurrentFnName << ",@function\n";
190 else if (Subtarget->isTargetCygMing()) {
191 O << "\t.def\t " << CurrentFnName
193 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
194 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
198 O << CurrentFnName << ':';
200 O.PadToColumn(MAI->getCommentColumn());
201 O << MAI->getCommentString() << ' ';
202 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
206 // Add some workaround for linkonce linkage on Cygwin\MinGW
207 if (Subtarget->isTargetCygMing() &&
208 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
209 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
212 /// runOnMachineFunction - This uses the printMachineInstruction()
213 /// method to print assembly for each instruction.
215 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
216 const Function *F = MF.getFunction();
218 CallingConv::ID CC = F->getCallingConv();
220 SetupMachineFunction(MF);
223 // Populate function information map. Actually, We don't want to populate
224 // non-stdcall or non-fastcall functions' information right now.
225 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
226 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
228 // Print out constants referenced by the function
229 EmitConstantPool(MF.getConstantPool());
231 if (F->hasDLLExportLinkage())
232 DLLExportedFns.insert(Mang->getMangledName(F));
234 // Print the 'header' of function
235 emitFunctionHeader(MF);
237 // Emit pre-function debug and/or EH information.
238 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
239 DW->BeginFunction(&MF);
241 // Print out code for the function.
242 bool hasAnyRealCode = false;
243 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
245 // Print a label for the basic block.
246 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
247 // This is an entry block or a block that's only reachable via a
248 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
250 printBasicBlockLabel(I, true, true, VerboseAsm);
253 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
255 // Print the assembly for the instruction.
257 hasAnyRealCode = true;
258 printMachineInstruction(II);
262 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
263 // If the function is empty, then we need to emit *something*. Otherwise,
264 // the function's label might be associated with something that it wasn't
265 // meant to be associated with. We emit a noop in this situation.
266 // We are assuming inline asms are code.
270 if (MAI->hasDotTypeDotSizeDirective())
271 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
273 // Emit post-function debug information.
274 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
275 DW->EndFunction(&MF);
277 // Print out jump tables referenced by the function.
278 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
280 // We didn't modify anything.
284 /// printSymbolOperand - Print a raw symbol reference operand. This handles
285 /// jump tables, constant pools, global address and external symbols, all of
286 /// which print to a label with various suffixes for relocation types etc.
287 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
288 switch (MO.getType()) {
289 default: llvm_unreachable("unknown symbol type!");
290 case MachineOperand::MO_JumpTableIndex:
291 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
294 case MachineOperand::MO_ConstantPoolIndex:
295 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
297 printOffset(MO.getOffset());
299 case MachineOperand::MO_GlobalAddress: {
300 const GlobalValue *GV = MO.getGlobal();
302 const char *Suffix = "";
303 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
305 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
306 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
307 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
308 Suffix = "$non_lazy_ptr";
310 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
311 if (Subtarget->isTargetCygMing())
312 DecorateCygMingName(Name, GV);
314 // Handle dllimport linkage.
315 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
316 Name = "__imp_" + Name;
318 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
319 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
320 GVStubs[Name] = Mang->getMangledName(GV);
321 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
322 HiddenGVStubs[Name] = Mang->getMangledName(GV);
323 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
324 FnStubs[Name] = Mang->getMangledName(GV);
326 // If the name begins with a dollar-sign, enclose it in parens. We do this
327 // to avoid having it look like an integer immediate to the assembler.
329 O << '(' << Name << ')';
333 printOffset(MO.getOffset());
336 case MachineOperand::MO_ExternalSymbol: {
337 std::string Name = Mang->makeNameProper(MO.getSymbolName());
338 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
339 FnStubs[Name+"$stub"] = Name;
343 // If the name begins with a dollar-sign, enclose it in parens. We do this
344 // to avoid having it look like an integer immediate to the assembler.
346 O << '(' << Name << ')';
353 switch (MO.getTargetFlags()) {
355 llvm_unreachable("Unknown target flag on GV operand");
356 case X86II::MO_NO_FLAG: // No flag.
358 case X86II::MO_DARWIN_NONLAZY:
359 case X86II::MO_DLLIMPORT:
360 case X86II::MO_DARWIN_STUB:
361 // These affect the name of the symbol, not any suffix.
363 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
365 PrintPICBaseSymbol();
368 case X86II::MO_PIC_BASE_OFFSET:
369 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
370 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
372 PrintPICBaseSymbol();
374 case X86II::MO_TLSGD: O << "@TLSGD"; break;
375 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
376 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
377 case X86II::MO_TPOFF: O << "@TPOFF"; break;
378 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
379 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
380 case X86II::MO_GOT: O << "@GOT"; break;
381 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
382 case X86II::MO_PLT: O << "@PLT"; break;
386 /// print_pcrel_imm - This is used to print an immediate value that ends up
387 /// being encoded as a pc-relative value. These print slightly differently, for
388 /// example, a $ is not emitted.
389 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
390 const MachineOperand &MO = MI->getOperand(OpNo);
391 switch (MO.getType()) {
392 default: llvm_unreachable("Unknown pcrel immediate operand");
393 case MachineOperand::MO_Immediate:
396 case MachineOperand::MO_MachineBasicBlock:
397 printBasicBlockLabel(MO.getMBB(), false, false, false);
399 case MachineOperand::MO_GlobalAddress:
400 case MachineOperand::MO_ExternalSymbol:
401 printSymbolOperand(MO);
408 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
409 const char *Modifier) {
410 const MachineOperand &MO = MI->getOperand(OpNo);
411 switch (MO.getType()) {
412 default: llvm_unreachable("unknown operand type!");
413 case MachineOperand::MO_Register: {
414 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
415 "Virtual registers should not make it this far!");
417 unsigned Reg = MO.getReg();
418 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
419 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
420 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
421 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
422 Reg = getX86SubSuperRegister(Reg, VT);
424 O << TRI->getAsmName(Reg);
428 case MachineOperand::MO_Immediate:
429 O << '$' << MO.getImm();
432 case MachineOperand::MO_JumpTableIndex:
433 case MachineOperand::MO_ConstantPoolIndex:
434 case MachineOperand::MO_GlobalAddress:
435 case MachineOperand::MO_ExternalSymbol: {
437 printSymbolOperand(MO);
443 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
444 unsigned char value = MI->getOperand(Op).getImm();
445 assert(value <= 7 && "Invalid ssecc argument!");
447 case 0: O << "eq"; break;
448 case 1: O << "lt"; break;
449 case 2: O << "le"; break;
450 case 3: O << "unord"; break;
451 case 4: O << "neq"; break;
452 case 5: O << "nlt"; break;
453 case 6: O << "nle"; break;
454 case 7: O << "ord"; break;
458 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
459 const char *Modifier) {
460 const MachineOperand &BaseReg = MI->getOperand(Op);
461 const MachineOperand &IndexReg = MI->getOperand(Op+2);
462 const MachineOperand &DispSpec = MI->getOperand(Op+3);
464 // If we really don't want to print out (rip), don't.
465 bool HasBaseReg = BaseReg.getReg() != 0;
466 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
467 BaseReg.getReg() == X86::RIP)
470 // HasParenPart - True if we will print out the () part of the mem ref.
471 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
473 if (DispSpec.isImm()) {
474 int DispVal = DispSpec.getImm();
475 if (DispVal || !HasParenPart)
478 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
479 DispSpec.isJTI() || DispSpec.isSymbol());
480 printSymbolOperand(MI->getOperand(Op+3));
484 assert(IndexReg.getReg() != X86::ESP &&
485 "X86 doesn't allow scaling by ESP");
489 printOperand(MI, Op, Modifier);
491 if (IndexReg.getReg()) {
493 printOperand(MI, Op+2, Modifier);
494 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
496 O << ',' << ScaleVal;
502 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
503 const char *Modifier) {
504 assert(isMem(MI, Op) && "Invalid memory reference!");
505 const MachineOperand &Segment = MI->getOperand(Op+4);
506 if (Segment.getReg()) {
507 printOperand(MI, Op+4, Modifier);
510 printLeaMemReference(MI, Op, Modifier);
513 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
514 const MachineBasicBlock *MBB) const {
515 if (!MAI->getSetDirective())
518 // We don't need .set machinery if we have GOT-style relocations
519 if (Subtarget->isPICStyleGOT())
522 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
523 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
524 printBasicBlockLabel(MBB, false, false, false);
525 if (Subtarget->isPICStyleRIPRel())
526 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
527 << '_' << uid << '\n';
530 PrintPICBaseSymbol();
536 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
537 PrintPICBaseSymbol();
539 PrintPICBaseSymbol();
544 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
545 const MachineBasicBlock *MBB,
546 unsigned uid) const {
547 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
548 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
550 O << JTEntryDirective << ' ';
552 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
553 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
554 << '_' << uid << "_set_" << MBB->getNumber();
555 } else if (Subtarget->isPICStyleGOT()) {
556 printBasicBlockLabel(MBB, false, false, false);
559 printBasicBlockLabel(MBB, false, false, false);
562 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
563 unsigned Reg = MO.getReg();
565 default: return true; // Unknown mode.
566 case 'b': // Print QImode register
567 Reg = getX86SubSuperRegister(Reg, MVT::i8);
569 case 'h': // Print QImode high register
570 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
572 case 'w': // Print HImode register
573 Reg = getX86SubSuperRegister(Reg, MVT::i16);
575 case 'k': // Print SImode register
576 Reg = getX86SubSuperRegister(Reg, MVT::i32);
578 case 'q': // Print DImode register
579 Reg = getX86SubSuperRegister(Reg, MVT::i64);
583 O << '%'<< TRI->getAsmName(Reg);
587 /// PrintAsmOperand - Print out an operand for an inline asm expression.
589 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
591 const char *ExtraCode) {
592 // Does this asm operand have a single letter operand modifier?
593 if (ExtraCode && ExtraCode[0]) {
594 if (ExtraCode[1] != 0) return true; // Unknown modifier.
596 const MachineOperand &MO = MI->getOperand(OpNo);
598 switch (ExtraCode[0]) {
599 default: return true; // Unknown modifier.
600 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
605 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
606 printSymbolOperand(MO);
611 printOperand(MI, OpNo);
617 case 'c': // Don't print "$" before a global var name or constant.
620 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
621 printSymbolOperand(MO);
623 printOperand(MI, OpNo);
626 case 'A': // Print '*' before a register (it must be a register)
629 printOperand(MI, OpNo);
634 case 'b': // Print QImode register
635 case 'h': // Print QImode high register
636 case 'w': // Print HImode register
637 case 'k': // Print SImode register
638 case 'q': // Print DImode register
640 return printAsmMRegister(MO, ExtraCode[0]);
641 printOperand(MI, OpNo);
644 case 'P': // This is the operand of a call, treat specially.
645 print_pcrel_imm(MI, OpNo);
648 case 'n': // Negate the immediate or print a '-' before the operand.
649 // Note: this is a temporary solution. It should be handled target
650 // independently as part of the 'MC' work.
659 printOperand(MI, OpNo);
663 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
666 const char *ExtraCode) {
667 if (ExtraCode && ExtraCode[0]) {
668 if (ExtraCode[1] != 0) return true; // Unknown modifier.
670 switch (ExtraCode[0]) {
671 default: return true; // Unknown modifier.
672 case 'b': // Print QImode register
673 case 'h': // Print QImode high register
674 case 'w': // Print HImode register
675 case 'k': // Print SImode register
676 case 'q': // Print SImode register
677 // These only apply to registers, ignore on mem.
679 case 'P': // Don't print @PLT, but do print as memory.
680 printMemReference(MI, OpNo, "no-rip");
684 printMemReference(MI, OpNo);
690 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
691 /// AT&T syntax to the current output stream.
693 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
696 processDebugLoc(MI->getDebugLoc());
698 // Call the autogenerated instruction printer routines.
700 printInstructionThroughMCStreamer(MI);
702 printInstruction(MI);
704 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
709 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
710 const TargetData *TD = TM.getTargetData();
712 if (!GVar->hasInitializer())
713 return; // External global require no code
715 // Check to see if this is a special global used by LLVM, if so, emit it.
716 if (EmitSpecialLLVMGlobal(GVar)) {
717 if (Subtarget->isTargetDarwin() &&
718 TM.getRelocationModel() == Reloc::Static) {
719 if (GVar->getName() == "llvm.global_ctors")
720 O << ".reference .constructors_used\n";
721 else if (GVar->getName() == "llvm.global_dtors")
722 O << ".reference .destructors_used\n";
727 std::string name = Mang->getMangledName(GVar);
728 Constant *C = GVar->getInitializer();
729 const Type *Type = C->getType();
730 unsigned Size = TD->getTypeAllocSize(Type);
731 unsigned Align = TD->getPreferredAlignmentLog(GVar);
733 printVisibility(name, GVar->getVisibility());
735 if (Subtarget->isTargetELF())
736 O << "\t.type\t" << name << ",@object\n";
739 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
740 const MCSection *TheSection =
741 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
742 OutStreamer.SwitchSection(TheSection);
744 // FIXME: get this stuff from section kind flags.
745 if (C->isNullValue() && !GVar->hasSection() &&
746 // Don't put things that should go in the cstring section into "comm".
747 !TheSection->getKind().isMergeableCString()) {
748 if (GVar->hasExternalLinkage()) {
749 if (const char *Directive = MAI->getZeroFillDirective()) {
750 O << "\t.globl " << name << '\n';
751 O << Directive << "__DATA, __common, " << name << ", "
752 << Size << ", " << Align << '\n';
757 if (!GVar->isThreadLocal() &&
758 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
759 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
761 if (MAI->getLCOMMDirective() != NULL) {
762 if (GVar->hasLocalLinkage()) {
763 O << MAI->getLCOMMDirective() << name << ',' << Size;
764 if (Subtarget->isTargetDarwin())
766 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
767 O << "\t.globl " << name << '\n'
768 << MAI->getWeakDefDirective() << name << '\n';
769 EmitAlignment(Align, GVar);
772 O.PadToColumn(MAI->getCommentColumn());
773 O << MAI->getCommentString() << ' ';
774 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
777 EmitGlobalConstant(C);
780 O << MAI->getCOMMDirective() << name << ',' << Size;
781 if (MAI->getCOMMDirectiveTakesAlignment())
782 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
785 if (!Subtarget->isTargetCygMing()) {
786 if (GVar->hasLocalLinkage())
787 O << "\t.local\t" << name << '\n';
789 O << MAI->getCOMMDirective() << name << ',' << Size;
790 if (MAI->getCOMMDirectiveTakesAlignment())
791 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
794 O.PadToColumn(MAI->getCommentColumn());
795 O << MAI->getCommentString() << ' ';
796 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
803 switch (GVar->getLinkage()) {
804 case GlobalValue::CommonLinkage:
805 case GlobalValue::LinkOnceAnyLinkage:
806 case GlobalValue::LinkOnceODRLinkage:
807 case GlobalValue::WeakAnyLinkage:
808 case GlobalValue::WeakODRLinkage:
809 case GlobalValue::LinkerPrivateLinkage:
810 if (Subtarget->isTargetDarwin()) {
811 O << "\t.globl " << name << '\n'
812 << MAI->getWeakDefDirective() << name << '\n';
813 } else if (Subtarget->isTargetCygMing()) {
814 O << "\t.globl\t" << name << "\n"
815 "\t.linkonce same_size\n";
817 O << "\t.weak\t" << name << '\n';
820 case GlobalValue::DLLExportLinkage:
821 case GlobalValue::AppendingLinkage:
822 // FIXME: appending linkage variables should go into a section of
823 // their name or something. For now, just emit them as external.
824 case GlobalValue::ExternalLinkage:
825 // If external or appending, declare as a global symbol
826 O << "\t.globl " << name << '\n';
828 case GlobalValue::PrivateLinkage:
829 case GlobalValue::InternalLinkage:
832 llvm_unreachable("Unknown linkage type!");
835 EmitAlignment(Align, GVar);
838 O.PadToColumn(MAI->getCommentColumn());
839 O << MAI->getCommentString() << ' ';
840 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
844 EmitGlobalConstant(C);
846 if (MAI->hasDotTypeDotSizeDirective())
847 O << "\t.size\t" << name << ", " << Size << '\n';
850 bool X86ATTAsmPrinter::doFinalization(Module &M) {
851 // Print out module-level global variables here.
852 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
854 if (I->hasDLLExportLinkage())
855 DLLExportedGVs.insert(Mang->getMangledName(I));
858 if (Subtarget->isTargetDarwin()) {
859 // All darwin targets use mach-o.
860 TargetLoweringObjectFileMachO &TLOFMacho =
861 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
863 // Add the (possibly multiple) personalities to the set of global value
864 // stubs. Only referenced functions get into the Personalities list.
865 if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
866 const std::vector<Function*> &Personalities = MMI->getPersonalities();
867 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
868 if (Personalities[i])
869 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
870 true /*private label*/)] =
871 Mang->getMangledName(Personalities[i]);
875 // Output stubs for dynamically-linked functions
876 if (!FnStubs.empty()) {
877 const MCSection *TheSection =
878 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
879 MCSectionMachO::S_SYMBOL_STUBS |
880 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
881 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
882 5, SectionKind::getMetadata());
883 OutStreamer.SwitchSection(TheSection);
884 for (StringMap<std::string>::iterator I = FnStubs.begin(),
885 E = FnStubs.end(); I != E; ++I)
886 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
887 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
891 // Output stubs for external and common global variables.
892 if (!GVStubs.empty()) {
893 const MCSection *TheSection =
894 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
895 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
896 SectionKind::getMetadata());
897 OutStreamer.SwitchSection(TheSection);
898 for (StringMap<std::string>::iterator I = GVStubs.begin(),
899 E = GVStubs.end(); I != E; ++I)
900 O << I->getKeyData() << ":\n\t.indirect_symbol "
901 << I->second << "\n\t.long\t0\n";
904 if (!HiddenGVStubs.empty()) {
905 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
907 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
908 E = HiddenGVStubs.end(); I != E; ++I)
909 O << I->getKeyData() << ":\n" << MAI->getData32bitsDirective()
910 << I->second << '\n';
913 // Funny Darwin hack: This flag tells the linker that no global symbols
914 // contain code that falls through to other global symbols (e.g. the obvious
915 // implementation of multiple entry points). If this doesn't occur, the
916 // linker can safely perform dead code stripping. Since LLVM never
917 // generates code that does this, it is always safe to set.
918 O << "\t.subsections_via_symbols\n";
919 } else if (Subtarget->isTargetCygMing()) {
920 // Emit type information for external functions
921 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
923 O << "\t.def\t " << i->getKeyData()
924 << ";\t.scl\t" << COFF::C_EXT
925 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
931 // Output linker support code for dllexported globals on windows.
932 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
933 // dllexport symbols only exist on coff targets.
934 TargetLoweringObjectFileCOFF &TLOFMacho =
935 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
937 OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
938 SectionKind::getMetadata()));
940 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
941 e = DLLExportedGVs.end(); i != e; ++i)
942 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
944 for (StringSet<>::iterator i = DLLExportedFns.begin(),
945 e = DLLExportedFns.end();
947 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
950 // Do common shutdown.
951 return AsmPrinter::doFinalization(M);
954 // Include the auto-generated portion of the assembly writer.
955 #include "X86GenAsmWriter.inc"