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/MC/MCContext.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/CodeGen/DwarfWriter.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetAsmInfo.h"
38 #include "llvm/Target/TargetOptions.h"
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
46 static std::string getPICLabelString(unsigned FnNum,
47 const TargetAsmInfo *TAI,
48 const X86Subtarget* Subtarget) {
50 if (Subtarget->isTargetDarwin())
51 label = "\"L" + utostr_32(FnNum) + "$pb\"";
52 else if (Subtarget->isTargetELF())
53 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
55 assert(0 && "Don't know how to print PIC label!\n");
60 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
61 const TargetData *TD) {
62 X86MachineFunctionInfo Info;
65 switch (F->getCallingConv()) {
66 case CallingConv::X86_StdCall:
67 Info.setDecorationStyle(StdCall);
69 case CallingConv::X86_FastCall:
70 Info.setDecorationStyle(FastCall);
77 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
78 AI != AE; ++AI, ++argNum) {
79 const Type* Ty = AI->getType();
81 // 'Dereference' type in case of byval parameter attribute
82 if (F->paramHasAttr(argNum, Attribute::ByVal))
83 Ty = cast<PointerType>(Ty)->getElementType();
85 // Size should be aligned to DWORD boundary
86 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
89 // We're not supporting tooooo huge arguments :)
90 Info.setBytesToPopOnReturn((unsigned int)Size);
94 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
95 /// Don't print things like \\n or \\0.
96 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
97 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
103 /// decorateName - Query FunctionInfoMap and use this information for various
105 void X86ATTAsmPrinter::decorateName(std::string &Name,
106 const GlobalValue *GV) {
107 const Function *F = dyn_cast<Function>(GV);
110 // We don't want to decorate non-stdcall or non-fastcall functions right now
111 unsigned CC = F->getCallingConv();
112 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
115 // Decorate names only when we're targeting Cygwin/Mingw32 targets
116 if (!Subtarget->isTargetCygMing())
119 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
121 const X86MachineFunctionInfo *Info;
122 if (info_item == FunctionInfoMap.end()) {
123 // Calculate apropriate function info and populate map
124 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
125 Info = &FunctionInfoMap[F];
127 Info = &info_item->second;
130 const FunctionType *FT = F->getFunctionType();
131 switch (Info->getDecorationStyle()) {
135 // "Pure" variadic functions do not receive @0 suffix.
136 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
137 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
138 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
141 // "Pure" variadic functions do not receive @0 suffix.
142 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
143 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
144 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
146 if (Name[0] == '_') {
153 assert(0 && "Unsupported DecorationStyle");
157 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
158 const Function *F = MF.getFunction();
160 decorateName(CurrentFnName, F);
162 SwitchToSection(TAI->SectionForGlobal(F));
164 unsigned FnAlign = 4;
165 if (F->hasFnAttr(Attribute::OptimizeForSize))
167 switch (F->getLinkage()) {
168 default: assert(0 && "Unknown linkage type!");
169 case Function::InternalLinkage: // Symbols default to internal.
170 case Function::PrivateLinkage:
171 EmitAlignment(FnAlign, F);
173 case Function::DLLExportLinkage:
174 case Function::ExternalLinkage:
175 EmitAlignment(FnAlign, F);
176 O << "\t.globl\t" << CurrentFnName << '\n';
178 case Function::LinkOnceAnyLinkage:
179 case Function::LinkOnceODRLinkage:
180 case Function::WeakAnyLinkage:
181 case Function::WeakODRLinkage:
182 EmitAlignment(FnAlign, F);
183 if (Subtarget->isTargetDarwin()) {
184 O << "\t.globl\t" << CurrentFnName << '\n';
185 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
186 } else if (Subtarget->isTargetCygMing()) {
187 O << "\t.globl\t" << CurrentFnName << "\n"
188 "\t.linkonce discard\n";
190 O << "\t.weak\t" << CurrentFnName << '\n';
195 printVisibility(CurrentFnName, F->getVisibility());
197 if (Subtarget->isTargetELF())
198 O << "\t.type\t" << CurrentFnName << ",@function\n";
199 else if (Subtarget->isTargetCygMing()) {
200 O << "\t.def\t " << CurrentFnName
202 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
203 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
207 O << CurrentFnName << ":\n";
208 // Add some workaround for linkonce linkage on Cygwin\MinGW
209 if (Subtarget->isTargetCygMing() &&
210 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
211 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
214 /// runOnMachineFunction - This uses the printMachineInstruction()
215 /// method to print assembly for each instruction.
217 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
218 const Function *F = MF.getFunction();
220 unsigned CC = F->getCallingConv();
222 SetupMachineFunction(MF);
225 // Populate function information map. Actually, We don't want to populate
226 // non-stdcall or non-fastcall functions' information right now.
227 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
228 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
230 // Print out constants referenced by the function
231 EmitConstantPool(MF.getConstantPool());
233 if (F->hasDLLExportLinkage())
234 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
236 // Print the 'header' of function
237 emitFunctionHeader(MF);
239 // Emit pre-function debug and/or EH information.
240 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
241 DW->BeginFunction(&MF);
243 // Print out code for the function.
244 bool hasAnyRealCode = false;
245 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
247 // Print a label for the basic block.
248 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
249 // This is an entry block or a block that's only reachable via a
250 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
252 printBasicBlockLabel(I, true, true, VerboseAsm);
255 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
257 // Print the assembly for the instruction.
259 hasAnyRealCode = true;
260 printMachineInstruction(II);
264 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
265 // If the function is empty, then we need to emit *something*. Otherwise,
266 // the function's label might be associated with something that it wasn't
267 // meant to be associated with. We emit a noop in this situation.
268 // We are assuming inline asms are code.
272 if (TAI->hasDotTypeDotSizeDirective())
273 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
275 // Emit post-function debug information.
276 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
277 DW->EndFunction(&MF);
279 // Print out jump tables referenced by the function.
280 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 /// print_pcrel_imm - This is used to print an immediate value that ends up
302 /// being encoded as a pc-relative value. These print slightly differently, for
303 /// example, a $ is not emitted.
304 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
305 const MachineOperand &MO = MI->getOperand(OpNo);
306 switch (MO.getType()) {
307 default: assert(0 && "Unknown pcrel immediate operand");
308 case MachineOperand::MO_Immediate:
311 case MachineOperand::MO_MachineBasicBlock:
312 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
315 case MachineOperand::MO_GlobalAddress: {
316 const GlobalValue *GV = MO.getGlobal();
317 std::string Name = Mang->getValueName(GV);
318 decorateName(Name, GV);
320 bool needCloseParen = false;
321 if (Name[0] == '$') {
322 // The name begins with a dollar-sign. In order to avoid having it look
323 // like an integer immediate to the assembler, enclose it in parens.
325 needCloseParen = true;
328 if (shouldPrintStub(TM, Subtarget)) {
329 // Link-once, declaration, or Weakly-linked global variables need
330 // non-lazily-resolved stubs
331 if (GV->isDeclaration() || GV->isWeakForLinker()) {
332 // Dynamically-resolved functions need a stub for the function.
333 if (isa<Function>(GV)) {
334 // Function stubs are no longer needed for Mac OS X 10.5 and up.
335 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
338 FnStubs.insert(Name);
339 printSuffixedName(Name, "$stub");
341 } else if (GV->hasHiddenVisibility()) {
342 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
343 // Definition is not definitely in the current translation unit.
346 HiddenGVStubs.insert(Name);
347 printSuffixedName(Name, "$non_lazy_ptr");
350 GVStubs.insert(Name);
351 printSuffixedName(Name, "$non_lazy_ptr");
354 if (GV->hasDLLImportLinkage())
359 if (GV->hasDLLImportLinkage()) {
364 if (shouldPrintPLT(TM, Subtarget)) {
365 // Assemble call via PLT for externally visible symbols
366 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
367 !GV->hasLocalLinkage())
370 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
371 // Save function name for later type emission
372 FnStubs.insert(Name);
375 if (GV->hasExternalWeakLinkage())
376 ExtWeakSymbols.insert(GV);
378 printOffset(MO.getOffset());
385 case MachineOperand::MO_ExternalSymbol: {
386 bool needCloseParen = false;
387 std::string Name(TAI->getGlobalPrefix());
388 Name += MO.getSymbolName();
389 // Print function stub suffix unless it's Mac OS X 10.5 and up.
390 if (shouldPrintStub(TM, Subtarget) &&
391 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
392 FnStubs.insert(Name);
393 printSuffixedName(Name, "$stub");
397 if (Name[0] == '$') {
398 // The name begins with a dollar-sign. In order to avoid having it look
399 // like an integer immediate to the assembler, enclose it in parens.
401 needCloseParen = true;
406 if (shouldPrintPLT(TM, Subtarget)) {
407 std::string GOTName(TAI->getGlobalPrefix());
408 GOTName+="_GLOBAL_OFFSET_TABLE_";
410 // HACK! Emit extra offset to PC during printing GOT offset to
411 // compensate for the size of popl instruction. The resulting code
415 // popl %some_register
416 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
418 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
431 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
432 const char *Modifier, bool NotRIPRel) {
433 const MachineOperand &MO = MI->getOperand(OpNo);
434 switch (MO.getType()) {
435 case MachineOperand::MO_Register: {
436 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
437 "Virtual registers should not make it this far!");
439 unsigned Reg = MO.getReg();
440 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
441 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
442 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
443 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
444 Reg = getX86SubSuperRegister(Reg, VT);
446 O << TRI->getAsmName(Reg);
450 case MachineOperand::MO_Immediate:
451 if (!Modifier || (strcmp(Modifier, "debug") &&
452 strcmp(Modifier, "mem")))
456 case MachineOperand::MO_JumpTableIndex: {
457 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
458 if (!isMemOp) O << '$';
459 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
462 if (TM.getRelocationModel() == Reloc::PIC_) {
463 if (Subtarget->isPICStyleStub())
464 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
466 else if (Subtarget->isPICStyleGOT())
470 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
474 case MachineOperand::MO_ConstantPoolIndex: {
475 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
476 if (!isMemOp) O << '$';
477 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
480 if (TM.getRelocationModel() == Reloc::PIC_) {
481 if (Subtarget->isPICStyleStub())
482 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
484 else if (Subtarget->isPICStyleGOT())
488 printOffset(MO.getOffset());
490 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
494 case MachineOperand::MO_GlobalAddress: {
495 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
496 bool needCloseParen = false;
498 const GlobalValue *GV = MO.getGlobal();
499 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
501 // If GV is an alias then use the aliasee for determining
503 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
504 GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
507 bool isThreadLocal = GVar && GVar->isThreadLocal();
509 std::string Name = Mang->getValueName(GV);
510 decorateName(Name, GV);
514 else if (Name[0] == '$') {
515 // The name begins with a dollar-sign. In order to avoid having it look
516 // like an integer immediate to the assembler, enclose it in parens.
518 needCloseParen = true;
521 if (shouldPrintStub(TM, Subtarget)) {
522 // Link-once, declaration, or Weakly-linked global variables need
523 // non-lazily-resolved stubs
524 if (GV->isDeclaration() || GV->isWeakForLinker()) {
525 // Dynamically-resolved functions need a stub for the function.
526 if (GV->hasHiddenVisibility()) {
527 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
528 // Definition is not definitely in the current translation unit.
531 HiddenGVStubs.insert(Name);
532 printSuffixedName(Name, "$non_lazy_ptr");
535 GVStubs.insert(Name);
536 printSuffixedName(Name, "$non_lazy_ptr");
539 if (GV->hasDLLImportLinkage())
544 if (TM.getRelocationModel() == Reloc::PIC_)
545 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
547 if (GV->hasDLLImportLinkage())
552 if (GV->hasExternalWeakLinkage())
553 ExtWeakSymbols.insert(GV);
555 printOffset(MO.getOffset());
560 bool isRIPRelative = false;
562 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
564 case TLSModel::GeneralDynamic:
567 case TLSModel::LocalDynamic:
568 // O << "@TLSLD"; // local dynamic not implemented
571 case TLSModel::InitialExec:
572 if (Subtarget->is64Bit()) {
575 isRIPRelative = true;
580 case TLSModel::LocalExec:
581 if (Subtarget->is64Bit())
587 assert (0 && "Unknown TLS model");
589 } else if (isMemOp) {
590 if (shouldPrintGOT(TM, Subtarget)) {
591 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
595 } else if (Subtarget->isPICStyleRIPRel() &&
597 if (TM.getRelocationModel() != Reloc::Static) {
598 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
602 isRIPRelative = true;
606 // Use rip when possible to reduce code size, except when
607 // index or base register are also part of the address. e.g.
608 // foo(%rip)(%rcx,%rax,4) is not legal.
614 case MachineOperand::MO_ExternalSymbol: {
615 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
616 bool needCloseParen = false;
617 std::string Name(TAI->getGlobalPrefix());
618 Name += MO.getSymbolName();
620 // Print function stub suffix unless it's Mac OS X 10.5 and up.
623 else if (Name[0] == '$') {
624 // The name begins with a dollar-sign. In order to avoid having it look
625 // like an integer immediate to the assembler, enclose it in parens.
627 needCloseParen = true;
632 if (shouldPrintPLT(TM, Subtarget)) {
633 std::string GOTName(TAI->getGlobalPrefix());
634 GOTName+="_GLOBAL_OFFSET_TABLE_";
636 // HACK! Emit extra offset to PC during printing GOT offset to
637 // compensate for the size of popl instruction. The resulting code
641 // popl %some_register
642 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
644 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
650 if (Subtarget->isPICStyleRIPRel())
655 O << "<unknown operand type>"; return;
659 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
660 unsigned char value = MI->getOperand(Op).getImm();
661 assert(value <= 7 && "Invalid ssecc argument!");
663 case 0: O << "eq"; break;
664 case 1: O << "lt"; break;
665 case 2: O << "le"; break;
666 case 3: O << "unord"; break;
667 case 4: O << "neq"; break;
668 case 5: O << "nlt"; break;
669 case 6: O << "nle"; break;
670 case 7: O << "ord"; break;
674 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
675 const char *Modifier,
677 MachineOperand BaseReg = MI->getOperand(Op);
678 MachineOperand IndexReg = MI->getOperand(Op+2);
679 const MachineOperand &DispSpec = MI->getOperand(Op+3);
681 NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
682 if (DispSpec.isGlobal() ||
685 DispSpec.isSymbol()) {
686 printOperand(MI, Op+3, "mem", NotRIPRel);
688 int DispVal = DispSpec.getImm();
689 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
693 if (IndexReg.getReg() || BaseReg.getReg()) {
694 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
695 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
697 // There are cases where we can end up with ESP/RSP in the indexreg slot.
698 // If this happens, swap the base/index register to support assemblers that
699 // don't work when the index is *SP.
700 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
701 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
702 std::swap(BaseReg, IndexReg);
703 std::swap(BaseRegOperand, IndexRegOperand);
707 if (BaseReg.getReg())
708 printOperand(MI, Op+BaseRegOperand, Modifier);
710 if (IndexReg.getReg()) {
712 printOperand(MI, Op+IndexRegOperand, Modifier);
714 O << ',' << ScaleVal;
720 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
721 const char *Modifier, bool NotRIPRel){
722 assert(isMem(MI, Op) && "Invalid memory reference!");
723 MachineOperand Segment = MI->getOperand(Op+4);
724 if (Segment.getReg()) {
725 printOperand(MI, Op+4, Modifier);
728 printLeaMemReference(MI, Op, Modifier, NotRIPRel);
731 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
732 const MachineBasicBlock *MBB) const {
733 if (!TAI->getSetDirective())
736 // We don't need .set machinery if we have GOT-style relocations
737 if (Subtarget->isPICStyleGOT())
740 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
741 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
742 printBasicBlockLabel(MBB, false, false, false);
743 if (Subtarget->isPICStyleRIPRel())
744 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
745 << '_' << uid << '\n';
747 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
750 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
751 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
752 O << label << '\n' << label << ':';
756 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
757 const MachineBasicBlock *MBB,
760 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
761 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
763 O << JTEntryDirective << ' ';
765 if (TM.getRelocationModel() == Reloc::PIC_) {
766 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
767 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
768 << '_' << uid << "_set_" << MBB->getNumber();
769 } else if (Subtarget->isPICStyleGOT()) {
770 printBasicBlockLabel(MBB, false, false, false);
773 assert(0 && "Don't know how to print MBB label for this PIC mode");
775 printBasicBlockLabel(MBB, false, false, false);
778 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
779 unsigned Reg = MO.getReg();
781 default: return true; // Unknown mode.
782 case 'b': // Print QImode register
783 Reg = getX86SubSuperRegister(Reg, MVT::i8);
785 case 'h': // Print QImode high register
786 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
788 case 'w': // Print HImode register
789 Reg = getX86SubSuperRegister(Reg, MVT::i16);
791 case 'k': // Print SImode register
792 Reg = getX86SubSuperRegister(Reg, MVT::i32);
794 case 'q': // Print DImode register
795 Reg = getX86SubSuperRegister(Reg, MVT::i64);
799 O << '%'<< TRI->getAsmName(Reg);
803 /// PrintAsmOperand - Print out an operand for an inline asm expression.
805 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
807 const char *ExtraCode) {
808 // Does this asm operand have a single letter operand modifier?
809 if (ExtraCode && ExtraCode[0]) {
810 if (ExtraCode[1] != 0) return true; // Unknown modifier.
812 switch (ExtraCode[0]) {
813 default: return true; // Unknown modifier.
814 case 'c': // Don't print "$" before a global var name or constant.
815 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
817 case 'b': // Print QImode register
818 case 'h': // Print QImode high register
819 case 'w': // Print HImode register
820 case 'k': // Print SImode register
821 case 'q': // Print DImode register
822 if (MI->getOperand(OpNo).isReg())
823 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
824 printOperand(MI, OpNo);
827 case 'P': // Don't print @PLT, but do print as memory.
828 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
833 printOperand(MI, OpNo);
837 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
840 const char *ExtraCode) {
841 if (ExtraCode && ExtraCode[0]) {
842 if (ExtraCode[1] != 0) return true; // Unknown modifier.
844 switch (ExtraCode[0]) {
845 default: return true; // Unknown modifier.
846 case 'b': // Print QImode register
847 case 'h': // Print QImode high register
848 case 'w': // Print HImode register
849 case 'k': // Print SImode register
850 case 'q': // Print SImode register
851 // These only apply to registers, ignore on mem.
853 case 'P': // Don't print @PLT, but do print as memory.
854 printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
858 printMemReference(MI, OpNo);
862 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
863 // Convert registers in the addr mode according to subreg64.
864 for (unsigned i = 0; i != 4; ++i) {
865 if (!MI->getOperand(i).isReg()) continue;
867 unsigned Reg = MI->getOperand(i).getReg();
868 if (Reg == 0) continue;
870 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
874 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
875 /// AT&T syntax to the current output stream.
877 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
881 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
885 } else if (MI->isLabel()) {
888 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
891 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
892 printImplicitDef(MI);
899 TmpInst.setOpcode(MI->getOpcode());
901 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
902 const MachineOperand &MO = MI->getOperand(i);
906 MCOp.MakeReg(MO.getReg());
907 } else if (MO.isImm()) {
908 MCOp.MakeImm(MO.getImm());
909 } else if (MO.isMBB()) {
910 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
912 assert(0 && "Unimp");
915 TmpInst.addOperand(MCOp);
918 switch (TmpInst.getOpcode()) {
920 // Handle the 'subreg rewriting' for the lea64_32mem operand.
921 lower_lea64_32mem(&TmpInst, 1);
925 // FIXME: Convert TmpInst.
926 printInstruction(&TmpInst);
930 // Call the autogenerated instruction printer routines.
931 printInstruction(MI);
935 bool X86ATTAsmPrinter::doInitialization(Module &M) {
936 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
937 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
940 Context = new MCContext();
941 // FIXME: Send this to "O" instead of outs(). For now, we force it to
942 // stdout to make it easy to compare.
943 Streamer = createAsmStreamer(*Context, outs());
946 return AsmPrinter::doInitialization(M);
949 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
950 const TargetData *TD = TM.getTargetData();
952 if (!GVar->hasInitializer())
953 return; // External global require no code
955 // Check to see if this is a special global used by LLVM, if so, emit it.
956 if (EmitSpecialLLVMGlobal(GVar)) {
957 if (Subtarget->isTargetDarwin() &&
958 TM.getRelocationModel() == Reloc::Static) {
959 if (GVar->getName() == "llvm.global_ctors")
960 O << ".reference .constructors_used\n";
961 else if (GVar->getName() == "llvm.global_dtors")
962 O << ".reference .destructors_used\n";
967 std::string name = Mang->getValueName(GVar);
968 Constant *C = GVar->getInitializer();
969 const Type *Type = C->getType();
970 unsigned Size = TD->getTypeAllocSize(Type);
971 unsigned Align = TD->getPreferredAlignmentLog(GVar);
973 printVisibility(name, GVar->getVisibility());
975 if (Subtarget->isTargetELF())
976 O << "\t.type\t" << name << ",@object\n";
978 SwitchToSection(TAI->SectionForGlobal(GVar));
980 if (C->isNullValue() && !GVar->hasSection() &&
981 !(Subtarget->isTargetDarwin() &&
982 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
983 // FIXME: This seems to be pretty darwin-specific
984 if (GVar->hasExternalLinkage()) {
985 if (const char *Directive = TAI->getZeroFillDirective()) {
986 O << "\t.globl " << name << '\n';
987 O << Directive << "__DATA, __common, " << name << ", "
988 << Size << ", " << Align << '\n';
993 if (!GVar->isThreadLocal() &&
994 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
995 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
997 if (TAI->getLCOMMDirective() != NULL) {
998 if (GVar->hasLocalLinkage()) {
999 O << TAI->getLCOMMDirective() << name << ',' << Size;
1000 if (Subtarget->isTargetDarwin())
1002 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1003 O << "\t.globl " << name << '\n'
1004 << TAI->getWeakDefDirective() << name << '\n';
1005 EmitAlignment(Align, GVar);
1008 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1009 PrintUnmangledNameSafely(GVar, O);
1012 EmitGlobalConstant(C);
1015 O << TAI->getCOMMDirective() << name << ',' << Size;
1016 if (TAI->getCOMMDirectiveTakesAlignment())
1017 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1020 if (!Subtarget->isTargetCygMing()) {
1021 if (GVar->hasLocalLinkage())
1022 O << "\t.local\t" << name << '\n';
1024 O << TAI->getCOMMDirective() << name << ',' << Size;
1025 if (TAI->getCOMMDirectiveTakesAlignment())
1026 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1029 O << "\t\t" << TAI->getCommentString() << ' ';
1030 PrintUnmangledNameSafely(GVar, O);
1037 switch (GVar->getLinkage()) {
1038 case GlobalValue::CommonLinkage:
1039 case GlobalValue::LinkOnceAnyLinkage:
1040 case GlobalValue::LinkOnceODRLinkage:
1041 case GlobalValue::WeakAnyLinkage:
1042 case GlobalValue::WeakODRLinkage:
1043 if (Subtarget->isTargetDarwin()) {
1044 O << "\t.globl " << name << '\n'
1045 << TAI->getWeakDefDirective() << name << '\n';
1046 } else if (Subtarget->isTargetCygMing()) {
1047 O << "\t.globl\t" << name << "\n"
1048 "\t.linkonce same_size\n";
1050 O << "\t.weak\t" << name << '\n';
1053 case GlobalValue::DLLExportLinkage:
1054 case GlobalValue::AppendingLinkage:
1055 // FIXME: appending linkage variables should go into a section of
1056 // their name or something. For now, just emit them as external.
1057 case GlobalValue::ExternalLinkage:
1058 // If external or appending, declare as a global symbol
1059 O << "\t.globl " << name << '\n';
1061 case GlobalValue::PrivateLinkage:
1062 case GlobalValue::InternalLinkage:
1065 assert(0 && "Unknown linkage type!");
1068 EmitAlignment(Align, GVar);
1071 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1072 PrintUnmangledNameSafely(GVar, O);
1075 if (TAI->hasDotTypeDotSizeDirective())
1076 O << "\t.size\t" << name << ", " << Size << '\n';
1078 EmitGlobalConstant(C);
1081 /// printGVStub - Print stub for a global value.
1083 void X86ATTAsmPrinter::printGVStub(const char *GV) {
1084 printSuffixedName(GV, "$non_lazy_ptr");
1085 O << ":\n\t.indirect_symbol " << GV << "\n\t.long\t0\n";
1088 /// printHiddenGVStub - Print stub for a hidden global value.
1090 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV) {
1092 printSuffixedName(GV, "$non_lazy_ptr");
1093 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
1097 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1098 // Print out module-level global variables here.
1099 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1101 printModuleLevelGV(I);
1103 if (I->hasDLLExportLinkage())
1104 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1106 // If the global is a extern weak symbol, remember to emit the weak
1108 // FIXME: This is rather hacky, since we'll emit references to ALL weak
1109 // stuff, not used. But currently it's the only way to deal with extern weak
1110 // initializers hidden deep inside constant expressions.
1111 if (I->hasExternalWeakLinkage())
1112 ExtWeakSymbols.insert(I);
1115 for (Module::const_iterator I = M.begin(), E = M.end();
1117 // If the global is a extern weak symbol, remember to emit the weak
1119 // FIXME: This is rather hacky, since we'll emit references to ALL weak
1120 // stuff, not used. But currently it's the only way to deal with extern weak
1121 // initializers hidden deep inside constant expressions.
1122 if (I->hasExternalWeakLinkage())
1123 ExtWeakSymbols.insert(I);
1126 // Output linker support code for dllexported globals
1127 if (!DLLExportedGVs.empty())
1128 SwitchToDataSection(".section .drectve");
1130 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1131 e = DLLExportedGVs.end();
1133 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1135 if (!DLLExportedFns.empty())
1136 SwitchToDataSection(".section .drectve");
1138 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1139 e = DLLExportedFns.end();
1141 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1143 if (Subtarget->isTargetDarwin()) {
1144 SwitchToDataSection("");
1146 // Output stubs for dynamically-linked functions
1147 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1149 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1150 "self_modifying_code+pure_instructions,5", 0);
1151 const char *p = i->getKeyData();
1152 printSuffixedName(p, "$stub");
1154 "\t.indirect_symbol " << p << "\n"
1155 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1160 // Print global value stubs.
1161 bool InStubSection = false;
1162 // Add the (possibly multiple) personalities to the set of global value
1163 // stubs. Only referenced functions get into the Personalities list.
1164 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1165 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1166 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1167 if (Personalities[i] == 0)
1169 if (!InStubSection) {
1170 SwitchToDataSection(
1171 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1172 InStubSection = true;
1174 std::string Name = Mang->getValueName(Personalities[i]);
1175 decorateName(Name, Personalities[i]);
1176 GVStubs.insert(Name);
1180 // Output stubs for external and common global variables.
1181 if (!InStubSection && !GVStubs.empty())
1182 SwitchToDataSection(
1183 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1184 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1186 printGVStub(i->getKeyData());
1188 if (!HiddenGVStubs.empty()) {
1189 SwitchToSection(TAI->getDataSection());
1190 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1192 printHiddenGVStub(i->getKeyData());
1195 // Funny Darwin hack: This flag tells the linker that no global symbols
1196 // contain code that falls through to other global symbols (e.g. the obvious
1197 // implementation of multiple entry points). If this doesn't occur, the
1198 // linker can safely perform dead code stripping. Since LLVM never
1199 // generates code that does this, it is always safe to set.
1200 O << "\t.subsections_via_symbols\n";
1201 } else if (Subtarget->isTargetCygMing()) {
1202 // Emit type information for external functions
1203 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1205 O << "\t.def\t " << i->getKeyData()
1206 << ";\t.scl\t" << COFF::C_EXT
1207 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1212 // Emit final debug information.
1213 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
1217 if (NewAsmPrinter) {
1226 return AsmPrinter::doFinalization(M);
1229 // Include the auto-generated portion of the assembly writer.
1230 #include "X86GenAsmWriter.inc"