1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetOptions.h"
37 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39 static std::string getPICLabelString(unsigned FnNum,
40 const TargetAsmInfo *TAI,
41 const X86Subtarget* Subtarget) {
43 if (Subtarget->isTargetDarwin())
44 label = "\"L" + utostr_32(FnNum) + "$pb\"";
45 else if (Subtarget->isTargetELF())
46 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
48 assert(0 && "Don't know how to print PIC label!\n");
53 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
54 const TargetData *TD) {
55 X86MachineFunctionInfo Info;
58 switch (F->getCallingConv()) {
59 case CallingConv::X86_StdCall:
60 Info.setDecorationStyle(StdCall);
62 case CallingConv::X86_FastCall:
63 Info.setDecorationStyle(FastCall);
70 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
71 AI != AE; ++AI, ++argNum) {
72 const Type* Ty = AI->getType();
74 // 'Dereference' type in case of byval parameter attribute
75 if (F->paramHasAttr(argNum, Attribute::ByVal))
76 Ty = cast<PointerType>(Ty)->getElementType();
78 // Size should be aligned to DWORD boundary
79 Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
82 // We're not supporting tooooo huge arguments :)
83 Info.setBytesToPopOnReturn((unsigned int)Size);
87 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
88 /// Don't print things like \\n or \\0.
89 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
90 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
96 /// decorateName - Query FunctionInfoMap and use this information for various
98 void X86ATTAsmPrinter::decorateName(std::string &Name,
99 const GlobalValue *GV) {
100 const Function *F = dyn_cast<Function>(GV);
103 // We don't want to decorate non-stdcall or non-fastcall functions right now
104 unsigned CC = F->getCallingConv();
105 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
108 // Decorate names only when we're targeting Cygwin/Mingw32 targets
109 if (!Subtarget->isTargetCygMing())
112 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
114 const X86MachineFunctionInfo *Info;
115 if (info_item == FunctionInfoMap.end()) {
116 // Calculate apropriate function info and populate map
117 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
118 Info = &FunctionInfoMap[F];
120 Info = &info_item->second;
123 const FunctionType *FT = F->getFunctionType();
124 switch (Info->getDecorationStyle()) {
128 // "Pure" variadic functions do not receive @0 suffix.
129 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
130 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
131 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
134 // "Pure" variadic functions do not receive @0 suffix.
135 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
136 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
137 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
139 if (Name[0] == '_') {
146 assert(0 && "Unsupported DecorationStyle");
150 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
151 const Function *F = MF.getFunction();
153 decorateName(CurrentFnName, F);
155 SwitchToSection(TAI->SectionForGlobal(F));
157 unsigned FnAlign = 4;
158 if (F->hasFnAttr(Attribute::OptimizeForSize))
160 switch (F->getLinkage()) {
161 default: assert(0 && "Unknown linkage type!");
162 case Function::InternalLinkage: // Symbols default to internal.
163 case Function::PrivateLinkage:
164 EmitAlignment(FnAlign, F);
166 case Function::DLLExportLinkage:
167 case Function::ExternalLinkage:
168 EmitAlignment(FnAlign, F);
169 O << "\t.globl\t" << CurrentFnName << '\n';
171 case Function::LinkOnceAnyLinkage:
172 case Function::LinkOnceODRLinkage:
173 case Function::WeakAnyLinkage:
174 case Function::WeakODRLinkage:
175 EmitAlignment(FnAlign, F);
176 if (Subtarget->isTargetDarwin()) {
177 O << "\t.globl\t" << CurrentFnName << '\n';
178 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
179 } else if (Subtarget->isTargetCygMing()) {
180 O << "\t.globl\t" << CurrentFnName << "\n"
181 "\t.linkonce discard\n";
183 O << "\t.weak\t" << CurrentFnName << '\n';
188 printVisibility(CurrentFnName, F->getVisibility());
190 if (Subtarget->isTargetELF())
191 O << "\t.type\t" << CurrentFnName << ",@function\n";
192 else if (Subtarget->isTargetCygMing()) {
193 O << "\t.def\t " << CurrentFnName
195 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
196 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
200 O << CurrentFnName << ":\n";
201 // Add some workaround for linkonce linkage on Cygwin\MinGW
202 if (Subtarget->isTargetCygMing() &&
203 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
204 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
207 /// runOnMachineFunction - This uses the printMachineInstruction()
208 /// method to print assembly for each instruction.
210 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
211 const Function *F = MF.getFunction();
213 unsigned CC = F->getCallingConv();
215 SetupMachineFunction(MF);
218 // Populate function information map. Actually, We don't want to populate
219 // non-stdcall or non-fastcall functions' information right now.
220 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
221 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
223 // Print out constants referenced by the function
224 EmitConstantPool(MF.getConstantPool());
226 if (F->hasDLLExportLinkage())
227 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
229 // Print the 'header' of function
230 emitFunctionHeader(MF);
232 // Emit pre-function debug and/or EH information.
233 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
234 DW->BeginFunction(&MF);
236 // Print out code for the function.
237 bool hasAnyRealCode = false;
238 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
240 // Print a label for the basic block.
241 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
242 // This is an entry block or a block that's only reachable via a
243 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
244 assert((I->pred_empty() || (*I->pred_begin())->isLayoutSuccessor(I)) &&
245 "Fall-through predecessor not adjacent to its successor!");
247 printBasicBlockLabel(I, true, true, VerboseAsm);
250 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
252 // Print the assembly for the instruction.
254 hasAnyRealCode = true;
255 printMachineInstruction(II);
259 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
260 // If the function is empty, then we need to emit *something*. Otherwise,
261 // the function's label might be associated with something that it wasn't
262 // meant to be associated with. We emit a noop in this situation.
263 // We are assuming inline asms are code.
267 if (TAI->hasDotTypeDotSizeDirective())
268 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
270 // Emit post-function debug information.
271 if (TAI->doesSupportDebugInformation())
272 DW->EndFunction(&MF);
274 // Print out jump tables referenced by the function.
275 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
279 // We didn't modify anything.
283 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
284 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
287 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
288 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
289 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
292 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
293 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
296 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
297 const char *Modifier, bool NotRIPRel) {
298 const MachineOperand &MO = MI->getOperand(OpNo);
299 switch (MO.getType()) {
300 case MachineOperand::MO_Register: {
301 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
302 "Virtual registers should not make it this far!");
304 unsigned Reg = MO.getReg();
305 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
306 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
307 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
308 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
309 Reg = getX86SubSuperRegister(Reg, VT);
311 O << TRI->getAsmName(Reg);
315 case MachineOperand::MO_Immediate:
316 if (!Modifier || (strcmp(Modifier, "debug") &&
317 strcmp(Modifier, "mem") &&
318 strcmp(Modifier, "call")))
322 case MachineOperand::MO_MachineBasicBlock:
323 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
325 case MachineOperand::MO_JumpTableIndex: {
326 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
327 if (!isMemOp) O << '$';
328 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
331 if (TM.getRelocationModel() == Reloc::PIC_) {
332 if (Subtarget->isPICStyleStub())
333 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
335 else if (Subtarget->isPICStyleGOT())
339 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
343 case MachineOperand::MO_ConstantPoolIndex: {
344 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
345 if (!isMemOp) O << '$';
346 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
349 if (TM.getRelocationModel() == Reloc::PIC_) {
350 if (Subtarget->isPICStyleStub())
351 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
353 else if (Subtarget->isPICStyleGOT())
357 printOffset(MO.getOffset());
359 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
363 case MachineOperand::MO_GlobalAddress: {
364 bool isCallOp = Modifier && !strcmp(Modifier, "call");
365 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
366 bool needCloseParen = false;
368 const GlobalValue *GV = MO.getGlobal();
369 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
371 // If GV is an alias then use the aliasee for determining
373 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
374 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
377 bool isThreadLocal = GVar && GVar->isThreadLocal();
379 std::string Name = Mang->getValueName(GV);
380 decorateName(Name, GV);
382 if (!isMemOp && !isCallOp)
384 else if (Name[0] == '$') {
385 // The name begins with a dollar-sign. In order to avoid having it look
386 // like an integer immediate to the assembler, enclose it in parens.
388 needCloseParen = true;
391 if (shouldPrintStub(TM, Subtarget)) {
392 // Link-once, declaration, or Weakly-linked global variables need
393 // non-lazily-resolved stubs
394 if (GV->isDeclaration() || GV->isWeakForLinker()) {
395 // Dynamically-resolved functions need a stub for the function.
396 if (isCallOp && isa<Function>(GV)) {
397 // Function stubs are no longer needed for Mac OS X 10.5 and up.
398 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
401 FnStubs.insert(Name);
402 printSuffixedName(Name, "$stub");
404 } else if (GV->hasHiddenVisibility()) {
405 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
406 // Definition is not definitely in the current translation unit.
409 HiddenGVStubs.insert(Name);
410 printSuffixedName(Name, "$non_lazy_ptr");
413 GVStubs.insert(Name);
414 printSuffixedName(Name, "$non_lazy_ptr");
417 if (GV->hasDLLImportLinkage())
422 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
423 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
425 if (GV->hasDLLImportLinkage()) {
431 if (shouldPrintPLT(TM, Subtarget)) {
432 // Assemble call via PLT for externally visible symbols
433 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
434 !GV->hasLocalLinkage())
437 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
438 // Save function name for later type emission
439 FnStubs.insert(Name);
443 if (GV->hasExternalWeakLinkage())
444 ExtWeakSymbols.insert(GV);
446 printOffset(MO.getOffset());
449 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
451 case TLSModel::GeneralDynamic:
454 case TLSModel::LocalDynamic:
455 // O << "@TLSLD"; // local dynamic not implemented
458 case TLSModel::InitialExec:
459 if (Subtarget->is64Bit())
460 O << "@TLSGD"; // 64 bit intial exec not implemented
464 case TLSModel::LocalExec:
465 if (Subtarget->is64Bit())
466 O << "@TLSGD"; // 64 bit local exec not implemented
471 assert (0 && "Unknown TLS model");
473 } else if (isMemOp) {
474 if (shouldPrintGOT(TM, Subtarget)) {
475 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
479 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
480 if (TM.getRelocationModel() != Reloc::Static) {
481 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
484 if (needCloseParen) {
485 needCloseParen = false;
490 // Use rip when possible to reduce code size, except when
491 // index or base register are also part of the address. e.g.
492 // foo(%rip)(%rcx,%rax,4) is not legal
502 case MachineOperand::MO_ExternalSymbol: {
503 bool isCallOp = Modifier && !strcmp(Modifier, "call");
504 bool needCloseParen = false;
505 std::string Name(TAI->getGlobalPrefix());
506 Name += MO.getSymbolName();
507 // Print function stub suffix unless it's Mac OS X 10.5 and up.
508 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
509 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
510 FnStubs.insert(Name);
511 printSuffixedName(Name, "$stub");
516 else if (Name[0] == '$') {
517 // The name begins with a dollar-sign. In order to avoid having it look
518 // like an integer immediate to the assembler, enclose it in parens.
520 needCloseParen = true;
525 if (shouldPrintPLT(TM, Subtarget)) {
526 std::string GOTName(TAI->getGlobalPrefix());
527 GOTName+="_GLOBAL_OFFSET_TABLE_";
529 // HACK! Emit extra offset to PC during printing GOT offset to
530 // compensate for the size of popl instruction. The resulting code
534 // popl %some_register
535 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
537 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
546 if (!isCallOp && Subtarget->isPICStyleRIPRel())
552 O << "<unknown operand type>"; return;
556 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
557 unsigned char value = MI->getOperand(Op).getImm();
558 assert(value <= 7 && "Invalid ssecc argument!");
560 case 0: O << "eq"; break;
561 case 1: O << "lt"; break;
562 case 2: O << "le"; break;
563 case 3: O << "unord"; break;
564 case 4: O << "neq"; break;
565 case 5: O << "nlt"; break;
566 case 6: O << "nle"; break;
567 case 7: O << "ord"; break;
571 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
572 const char *Modifier){
573 assert(isMem(MI, Op) && "Invalid memory reference!");
574 MachineOperand BaseReg = MI->getOperand(Op);
575 MachineOperand IndexReg = MI->getOperand(Op+2);
576 const MachineOperand &DispSpec = MI->getOperand(Op+3);
578 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
579 if (DispSpec.isGlobal() ||
582 printOperand(MI, Op+3, "mem", NotRIPRel);
584 int DispVal = DispSpec.getImm();
585 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
589 if (IndexReg.getReg() || BaseReg.getReg()) {
590 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
591 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
593 // There are cases where we can end up with ESP/RSP in the indexreg slot.
594 // If this happens, swap the base/index register to support assemblers that
595 // don't work when the index is *SP.
596 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
597 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
598 std::swap(BaseReg, IndexReg);
599 std::swap(BaseRegOperand, IndexRegOperand);
603 if (BaseReg.getReg())
604 printOperand(MI, Op+BaseRegOperand, Modifier);
606 if (IndexReg.getReg()) {
608 printOperand(MI, Op+IndexRegOperand, Modifier);
610 O << ',' << ScaleVal;
616 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
617 const MachineBasicBlock *MBB) const {
618 if (!TAI->getSetDirective())
621 // We don't need .set machinery if we have GOT-style relocations
622 if (Subtarget->isPICStyleGOT())
625 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
626 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
627 printBasicBlockLabel(MBB, false, false, false);
628 if (Subtarget->isPICStyleRIPRel())
629 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
630 << '_' << uid << '\n';
632 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
635 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
636 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
637 O << label << '\n' << label << ':';
641 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
642 const MachineBasicBlock *MBB,
645 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
646 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
648 O << JTEntryDirective << ' ';
650 if (TM.getRelocationModel() == Reloc::PIC_) {
651 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
652 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
653 << '_' << uid << "_set_" << MBB->getNumber();
654 } else if (Subtarget->isPICStyleGOT()) {
655 printBasicBlockLabel(MBB, false, false, false);
658 assert(0 && "Don't know how to print MBB label for this PIC mode");
660 printBasicBlockLabel(MBB, false, false, false);
663 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
665 unsigned Reg = MO.getReg();
667 default: return true; // Unknown mode.
668 case 'b': // Print QImode register
669 Reg = getX86SubSuperRegister(Reg, MVT::i8);
671 case 'h': // Print QImode high register
672 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
674 case 'w': // Print HImode register
675 Reg = getX86SubSuperRegister(Reg, MVT::i16);
677 case 'k': // Print SImode register
678 Reg = getX86SubSuperRegister(Reg, MVT::i32);
680 case 'q': // Print DImode register
681 Reg = getX86SubSuperRegister(Reg, MVT::i64);
685 O << '%'<< TRI->getAsmName(Reg);
689 /// PrintAsmOperand - Print out an operand for an inline asm expression.
691 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
693 const char *ExtraCode) {
694 // Does this asm operand have a single letter operand modifier?
695 if (ExtraCode && ExtraCode[0]) {
696 if (ExtraCode[1] != 0) return true; // Unknown modifier.
698 switch (ExtraCode[0]) {
699 default: return true; // Unknown modifier.
700 case 'c': // Don't print "$" before a global var name or constant.
701 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
703 case 'b': // Print QImode register
704 case 'h': // Print QImode high register
705 case 'w': // Print HImode register
706 case 'k': // Print SImode register
707 case 'q': // Print DImode register
708 if (MI->getOperand(OpNo).isReg())
709 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
710 printOperand(MI, OpNo);
713 case 'P': // Don't print @PLT, but do print as memory.
714 printOperand(MI, OpNo, "mem");
719 printOperand(MI, OpNo);
723 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
726 const char *ExtraCode) {
727 if (ExtraCode && ExtraCode[0]) {
728 if (ExtraCode[1] != 0) return true; // Unknown modifier.
730 switch (ExtraCode[0]) {
731 default: return true; // Unknown modifier.
732 case 'b': // Print QImode register
733 case 'h': // Print QImode high register
734 case 'w': // Print HImode register
735 case 'k': // Print SImode register
736 case 'q': // Print SImode register
737 // These only apply to registers, ignore on mem.
739 case 'P': // Don't print @PLT, but do print as memory.
740 printOperand(MI, OpNo, "mem");
744 printMemReference(MI, OpNo);
748 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
749 /// AT&T syntax to the current output stream.
751 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
754 // Call the autogenerated instruction printer routines.
755 printInstruction(MI);
759 bool X86ATTAsmPrinter::doInitialization(Module &M) {
761 bool Result = AsmPrinter::doInitialization(M);
763 if (TAI->doesSupportDebugInformation()) {
764 // Let PassManager know we need debug information and relay
765 // the MachineModuleInfo address on to DwarfWriter.
766 // AsmPrinter::doInitialization did this analysis.
767 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
768 DW = getAnalysisIfAvailable<DwarfWriter>();
769 DW->BeginModule(&M, MMI, O, this, TAI);
772 // Darwin wants symbols to be quoted if they have complex names.
773 if (Subtarget->isTargetDarwin())
774 Mang->setUseQuotes(true);
780 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
781 const TargetData *TD = TM.getTargetData();
783 if (!GVar->hasInitializer())
784 return; // External global require no code
786 // Check to see if this is a special global used by LLVM, if so, emit it.
787 if (EmitSpecialLLVMGlobal(GVar)) {
788 if (Subtarget->isTargetDarwin() &&
789 TM.getRelocationModel() == Reloc::Static) {
790 if (GVar->getName() == "llvm.global_ctors")
791 O << ".reference .constructors_used\n";
792 else if (GVar->getName() == "llvm.global_dtors")
793 O << ".reference .destructors_used\n";
798 std::string name = Mang->getValueName(GVar);
799 Constant *C = GVar->getInitializer();
800 const Type *Type = C->getType();
801 unsigned Size = TD->getTypePaddedSize(Type);
802 unsigned Align = TD->getPreferredAlignmentLog(GVar);
804 printVisibility(name, GVar->getVisibility());
806 if (Subtarget->isTargetELF())
807 O << "\t.type\t" << name << ",@object\n";
809 SwitchToSection(TAI->SectionForGlobal(GVar));
811 if (C->isNullValue() && !GVar->hasSection() &&
812 !(Subtarget->isTargetDarwin() &&
813 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
814 // FIXME: This seems to be pretty darwin-specific
815 if (GVar->hasExternalLinkage()) {
816 if (const char *Directive = TAI->getZeroFillDirective()) {
817 O << "\t.globl " << name << '\n';
818 O << Directive << "__DATA, __common, " << name << ", "
819 << Size << ", " << Align << '\n';
824 if (!GVar->isThreadLocal() &&
825 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
826 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
828 if (TAI->getLCOMMDirective() != NULL) {
829 if (GVar->hasLocalLinkage()) {
830 O << TAI->getLCOMMDirective() << name << ',' << Size;
831 if (Subtarget->isTargetDarwin())
833 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
834 O << "\t.globl " << name << '\n'
835 << TAI->getWeakDefDirective() << name << '\n';
836 EmitAlignment(Align, GVar);
839 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
840 PrintUnmangledNameSafely(GVar, O);
843 EmitGlobalConstant(C);
846 O << TAI->getCOMMDirective() << name << ',' << Size;
847 if (TAI->getCOMMDirectiveTakesAlignment())
848 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
851 if (!Subtarget->isTargetCygMing()) {
852 if (GVar->hasLocalLinkage())
853 O << "\t.local\t" << name << '\n';
855 O << TAI->getCOMMDirective() << name << ',' << Size;
856 if (TAI->getCOMMDirectiveTakesAlignment())
857 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
860 O << "\t\t" << TAI->getCommentString() << ' ';
861 PrintUnmangledNameSafely(GVar, O);
868 switch (GVar->getLinkage()) {
869 case GlobalValue::CommonLinkage:
870 case GlobalValue::LinkOnceAnyLinkage:
871 case GlobalValue::LinkOnceODRLinkage:
872 case GlobalValue::WeakAnyLinkage:
873 case GlobalValue::WeakODRLinkage:
874 if (Subtarget->isTargetDarwin()) {
875 O << "\t.globl " << name << '\n'
876 << TAI->getWeakDefDirective() << name << '\n';
877 } else if (Subtarget->isTargetCygMing()) {
878 O << "\t.globl\t" << name << "\n"
879 "\t.linkonce same_size\n";
881 O << "\t.weak\t" << name << '\n';
884 case GlobalValue::DLLExportLinkage:
885 case GlobalValue::AppendingLinkage:
886 // FIXME: appending linkage variables should go into a section of
887 // their name or something. For now, just emit them as external.
888 case GlobalValue::ExternalLinkage:
889 // If external or appending, declare as a global symbol
890 O << "\t.globl " << name << '\n';
892 case GlobalValue::PrivateLinkage:
893 case GlobalValue::InternalLinkage:
896 assert(0 && "Unknown linkage type!");
899 EmitAlignment(Align, GVar);
902 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
903 PrintUnmangledNameSafely(GVar, O);
906 if (TAI->hasDotTypeDotSizeDirective())
907 O << "\t.size\t" << name << ", " << Size << '\n';
909 EmitGlobalConstant(C);
912 /// printGVStub - Print stub for a global value.
914 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
915 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
916 O << ":\n\t.indirect_symbol ";
917 if (Prefix) O << Prefix;
918 O << GV << "\n\t.long\t0\n";
921 /// printHiddenGVStub - Print stub for a hidden global value.
923 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
925 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
926 if (Prefix) O << Prefix;
927 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
931 bool X86ATTAsmPrinter::doFinalization(Module &M) {
932 // Print out module-level global variables here.
933 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
935 printModuleLevelGV(I);
937 if (I->hasDLLExportLinkage())
938 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
940 // If the global is a extern weak symbol, remember to emit the weak
942 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
943 // not used. But currently it's the only way to deal with extern weak
944 // initializers hidden deep inside constant expressions.
945 if (I->hasExternalWeakLinkage())
946 ExtWeakSymbols.insert(I);
949 for (Module::const_iterator I = M.begin(), E = M.end();
951 // If the global is a extern weak symbol, remember to emit the weak
953 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
954 // not used. But currently it's the only way to deal with extern weak
955 // initializers hidden deep inside constant expressions.
956 if (I->hasExternalWeakLinkage())
957 ExtWeakSymbols.insert(I);
960 // Output linker support code for dllexported globals
961 if (!DLLExportedGVs.empty())
962 SwitchToDataSection(".section .drectve");
964 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
965 e = DLLExportedGVs.end();
967 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
969 if (!DLLExportedFns.empty()) {
970 SwitchToDataSection(".section .drectve");
973 for (StringSet<>::iterator i = DLLExportedFns.begin(),
974 e = DLLExportedFns.end();
976 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
978 if (Subtarget->isTargetDarwin()) {
979 SwitchToDataSection("");
981 // Output stubs for dynamically-linked functions
982 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
984 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
985 "self_modifying_code+pure_instructions,5", 0);
986 const char *p = i->getKeyData();
987 printSuffixedName(p, "$stub");
989 "\t.indirect_symbol " << p << "\n"
990 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
995 // Print global value stubs.
996 bool InStubSection = false;
997 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
998 // Add the (possibly multiple) personalities to the set of global values.
999 // Only referenced functions get into the Personalities list.
1000 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1001 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1002 E = Personalities.end(); I != E; ++I) {
1005 if (!InStubSection) {
1006 SwitchToDataSection(
1007 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1008 InStubSection = true;
1010 printGVStub((*I)->getNameStart(), "_");
1014 // Output stubs for external and common global variables.
1015 if (!InStubSection && !GVStubs.empty())
1016 SwitchToDataSection(
1017 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1018 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1020 printGVStub(i->getKeyData());
1022 if (!HiddenGVStubs.empty()) {
1023 SwitchToSection(TAI->getDataSection());
1024 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1026 printHiddenGVStub(i->getKeyData());
1029 // Emit final debug information.
1030 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1033 // Funny Darwin hack: This flag tells the linker that no global symbols
1034 // contain code that falls through to other global symbols (e.g. the obvious
1035 // implementation of multiple entry points). If this doesn't occur, the
1036 // linker can safely perform dead code stripping. Since LLVM never
1037 // generates code that does this, it is always safe to set.
1038 O << "\t.subsections_via_symbols\n";
1039 } else if (Subtarget->isTargetCygMing()) {
1040 // Emit type information for external functions
1041 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1043 O << "\t.def\t " << i->getKeyData()
1044 << ";\t.scl\t" << COFF::C_EXT
1045 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1049 // Emit final debug information.
1050 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1052 } else if (Subtarget->isTargetELF()) {
1053 // Emit final debug information.
1054 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1058 return AsmPrinter::doFinalization(M);
1061 // Include the auto-generated portion of the assembly writer.
1062 #include "X86GenAsmWriter.inc"