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 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
50 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
51 if (Subtarget->isTargetDarwin())
52 O << "\"L" << getFunctionNumber() << "$pb\"";
53 else if (Subtarget->isTargetELF())
54 O << ".Lllvm$" << getFunctionNumber() << "." "$piclabel";
56 assert(0 && "Don't know how to print PIC label!\n");
59 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
60 /// Don't print things like \\n or \\0.
61 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
62 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
68 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
69 const TargetData *TD) {
70 X86MachineFunctionInfo Info;
73 switch (F->getCallingConv()) {
74 case CallingConv::X86_StdCall:
75 Info.setDecorationStyle(StdCall);
77 case CallingConv::X86_FastCall:
78 Info.setDecorationStyle(FastCall);
85 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
86 AI != AE; ++AI, ++argNum) {
87 const Type* Ty = AI->getType();
89 // 'Dereference' type in case of byval parameter attribute
90 if (F->paramHasAttr(argNum, Attribute::ByVal))
91 Ty = cast<PointerType>(Ty)->getElementType();
93 // Size should be aligned to DWORD boundary
94 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
97 // We're not supporting tooooo huge arguments :)
98 Info.setBytesToPopOnReturn((unsigned int)Size);
102 /// decorateName - Query FunctionInfoMap and use this information for various
104 void X86ATTAsmPrinter::decorateName(std::string &Name,
105 const GlobalValue *GV) {
106 const Function *F = dyn_cast<Function>(GV);
109 // We don't want to decorate non-stdcall or non-fastcall functions right now
110 unsigned CC = F->getCallingConv();
111 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
114 // Decorate names only when we're targeting Cygwin/Mingw32 targets
115 if (!Subtarget->isTargetCygMing())
118 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
120 const X86MachineFunctionInfo *Info;
121 if (info_item == FunctionInfoMap.end()) {
122 // Calculate apropriate function info and populate map
123 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
124 Info = &FunctionInfoMap[F];
126 Info = &info_item->second;
129 const FunctionType *FT = F->getFunctionType();
130 switch (Info->getDecorationStyle()) {
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());
140 // "Pure" variadic functions do not receive @0 suffix.
141 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
142 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
143 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
145 if (Name[0] == '_') {
152 assert(0 && "Unsupported DecorationStyle");
158 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
159 const Function *F = MF.getFunction();
161 decorateName(CurrentFnName, F);
163 SwitchToSection(TAI->SectionForGlobal(F));
165 // FIXME: A function's alignment should be part of MachineFunction. There
166 // shouldn't be a policy decision here.
167 unsigned FnAlign = 4;
168 if (F->hasFnAttr(Attribute::OptimizeForSize))
171 switch (F->getLinkage()) {
172 default: assert(0 && "Unknown linkage type!");
173 case Function::InternalLinkage: // Symbols default to internal.
174 case Function::PrivateLinkage:
175 EmitAlignment(FnAlign, F);
177 case Function::DLLExportLinkage:
178 case Function::ExternalLinkage:
179 EmitAlignment(FnAlign, F);
180 O << "\t.globl\t" << CurrentFnName << '\n';
182 case Function::LinkOnceAnyLinkage:
183 case Function::LinkOnceODRLinkage:
184 case Function::WeakAnyLinkage:
185 case Function::WeakODRLinkage:
186 EmitAlignment(FnAlign, F);
187 if (Subtarget->isTargetDarwin()) {
188 O << "\t.globl\t" << CurrentFnName << '\n';
189 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
190 } else if (Subtarget->isTargetCygMing()) {
191 O << "\t.globl\t" << CurrentFnName << "\n"
192 "\t.linkonce discard\n";
194 O << "\t.weak\t" << CurrentFnName << '\n';
199 printVisibility(CurrentFnName, F->getVisibility());
201 if (Subtarget->isTargetELF())
202 O << "\t.type\t" << CurrentFnName << ",@function\n";
203 else if (Subtarget->isTargetCygMing()) {
204 O << "\t.def\t " << CurrentFnName
206 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
207 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
211 O << CurrentFnName << ":\n";
212 // Add some workaround for linkonce linkage on Cygwin\MinGW
213 if (Subtarget->isTargetCygMing() &&
214 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
215 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
218 /// runOnMachineFunction - This uses the printMachineInstruction()
219 /// method to print assembly for each instruction.
221 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
222 const Function *F = MF.getFunction();
224 unsigned CC = F->getCallingConv();
226 SetupMachineFunction(MF);
229 // Populate function information map. Actually, We don't want to populate
230 // non-stdcall or non-fastcall functions' information right now.
231 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
232 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
234 // Print out constants referenced by the function
235 EmitConstantPool(MF.getConstantPool());
237 if (F->hasDLLExportLinkage())
238 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
240 // Print the 'header' of function
241 emitFunctionHeader(MF);
243 // Emit pre-function debug and/or EH information.
244 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
245 DW->BeginFunction(&MF);
247 // Print out code for the function.
248 bool hasAnyRealCode = false;
249 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
251 // Print a label for the basic block.
252 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
253 // This is an entry block or a block that's only reachable via a
254 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
256 printBasicBlockLabel(I, true, true, VerboseAsm);
259 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
261 // Print the assembly for the instruction.
263 hasAnyRealCode = true;
264 printMachineInstruction(II);
268 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
269 // If the function is empty, then we need to emit *something*. Otherwise,
270 // the function's label might be associated with something that it wasn't
271 // meant to be associated with. We emit a noop in this situation.
272 // We are assuming inline asms are code.
276 if (TAI->hasDotTypeDotSizeDirective())
277 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
279 // Emit post-function debug information.
280 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
281 DW->EndFunction(&MF);
283 // Print out jump tables referenced by the function.
284 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
288 // We didn't modify anything.
292 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
293 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
296 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
297 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
298 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
301 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
302 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
305 /// print_pcrel_imm - This is used to print an immediate value that ends up
306 /// being encoded as a pc-relative value. These print slightly differently, for
307 /// example, a $ is not emitted.
308 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
309 const MachineOperand &MO = MI->getOperand(OpNo);
310 switch (MO.getType()) {
311 default: assert(0 && "Unknown pcrel immediate operand");
312 case MachineOperand::MO_Immediate:
315 case MachineOperand::MO_MachineBasicBlock:
316 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
319 case MachineOperand::MO_GlobalAddress: {
320 const GlobalValue *GV = MO.getGlobal();
321 std::string Name = Mang->getValueName(GV);
322 decorateName(Name, GV);
324 bool needCloseParen = false;
325 if (Name[0] == '$') {
326 // The name begins with a dollar-sign. In order to avoid having it look
327 // like an integer immediate to the assembler, enclose it in parens.
329 needCloseParen = true;
332 if (shouldPrintStub(TM, Subtarget)) {
333 // Link-once, declaration, or Weakly-linked global variables need
334 // non-lazily-resolved stubs
335 if (GV->isDeclaration() || GV->isWeakForLinker()) {
336 // Dynamically-resolved functions need a stub for the function.
337 if (isa<Function>(GV)) {
338 // Function stubs are no longer needed for Mac OS X 10.5 and up.
339 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
342 FnStubs.insert(Name);
343 printSuffixedName(Name, "$stub");
345 } else if (GV->hasHiddenVisibility()) {
346 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
347 // Definition is not definitely in the current translation unit.
350 HiddenGVStubs.insert(Name);
351 printSuffixedName(Name, "$non_lazy_ptr");
354 GVStubs.insert(Name);
355 printSuffixedName(Name, "$non_lazy_ptr");
358 if (GV->hasDLLImportLinkage())
363 if (GV->hasDLLImportLinkage()) {
368 if (shouldPrintPLT(TM, Subtarget)) {
369 // Assemble call via PLT for externally visible symbols
370 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
371 !GV->hasLocalLinkage())
374 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
375 // Save function name for later type emission
376 FnStubs.insert(Name);
379 printOffset(MO.getOffset());
386 case MachineOperand::MO_ExternalSymbol: {
387 bool needCloseParen = false;
388 std::string Name(TAI->getGlobalPrefix());
389 Name += MO.getSymbolName();
390 // Print function stub suffix unless it's Mac OS X 10.5 and up.
391 if (shouldPrintStub(TM, Subtarget) &&
392 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
393 FnStubs.insert(Name);
394 printSuffixedName(Name, "$stub");
398 if (Name[0] == '$') {
399 // The name begins with a dollar-sign. In order to avoid having it look
400 // like an integer immediate to the assembler, enclose it in parens.
402 needCloseParen = true;
407 if (shouldPrintPLT(TM, Subtarget)) {
408 std::string GOTName(TAI->getGlobalPrefix());
409 GOTName+="_GLOBAL_OFFSET_TABLE_";
410 if (Name == GOTName) {
411 // HACK! Emit extra offset to PC during printing GOT offset to
412 // compensate for the size of popl instruction. The resulting code
416 // popl %some_register
417 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
419 PrintPICBaseSymbol();
434 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
435 const char *Modifier, bool NotRIPRel) {
436 const MachineOperand &MO = MI->getOperand(OpNo);
437 switch (MO.getType()) {
438 case MachineOperand::MO_Register: {
439 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
440 "Virtual registers should not make it this far!");
442 unsigned Reg = MO.getReg();
443 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
444 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
445 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
446 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
447 Reg = getX86SubSuperRegister(Reg, VT);
449 O << TRI->getAsmName(Reg);
453 case MachineOperand::MO_Immediate:
454 if (!Modifier || (strcmp(Modifier, "debug") &&
455 strcmp(Modifier, "mem")))
459 case MachineOperand::MO_JumpTableIndex: {
460 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
461 if (!isMemOp) O << '$';
462 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
465 if (TM.getRelocationModel() == Reloc::PIC_) {
466 if (Subtarget->isPICStyleStub()) {
468 PrintPICBaseSymbol();
469 } else if (Subtarget->isPICStyleGOT()) {
474 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
478 case MachineOperand::MO_ConstantPoolIndex: {
479 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
480 if (!isMemOp) O << '$';
481 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
484 if (TM.getRelocationModel() == Reloc::PIC_) {
485 if (Subtarget->isPICStyleStub()) {
487 PrintPICBaseSymbol();
488 } else if (Subtarget->isPICStyleGOT())
492 printOffset(MO.getOffset());
494 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
498 case MachineOperand::MO_GlobalAddress: {
499 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
500 bool needCloseParen = false;
502 const GlobalValue *GV = MO.getGlobal();
503 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
505 // If GV is an alias then use the aliasee for determining
507 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
508 GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
511 bool isThreadLocal = GVar && GVar->isThreadLocal();
513 std::string Name = Mang->getValueName(GV);
514 decorateName(Name, GV);
518 else if (Name[0] == '$') {
519 // The name begins with a dollar-sign. In order to avoid having it look
520 // like an integer immediate to the assembler, enclose it in parens.
522 needCloseParen = true;
525 if (shouldPrintStub(TM, Subtarget)) {
526 // Link-once, declaration, or Weakly-linked global variables need
527 // non-lazily-resolved stubs
528 if (GV->isDeclaration() || GV->isWeakForLinker()) {
529 // Dynamically-resolved functions need a stub for the function.
530 if (GV->hasHiddenVisibility()) {
531 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
532 // Definition is not definitely in the current translation unit.
535 HiddenGVStubs.insert(Name);
536 printSuffixedName(Name, "$non_lazy_ptr");
539 GVStubs.insert(Name);
540 printSuffixedName(Name, "$non_lazy_ptr");
543 if (GV->hasDLLImportLinkage())
548 if (TM.getRelocationModel() == Reloc::PIC_) {
550 PrintPICBaseSymbol();
553 if (GV->hasDLLImportLinkage())
558 printOffset(MO.getOffset());
563 bool isRIPRelative = false;
565 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
567 case TLSModel::GeneralDynamic:
570 case TLSModel::LocalDynamic:
571 // O << "@TLSLD"; // local dynamic not implemented
574 case TLSModel::InitialExec:
575 if (Subtarget->is64Bit()) {
578 isRIPRelative = true;
583 case TLSModel::LocalExec:
584 if (Subtarget->is64Bit())
590 assert (0 && "Unknown TLS model");
592 } else if (isMemOp) {
593 if (shouldPrintGOT(TM, Subtarget)) {
594 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
598 } else if (Subtarget->isPICStyleRIPRel() &&
600 if (TM.getRelocationModel() != Reloc::Static) {
601 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
605 isRIPRelative = true;
609 // Use rip when possible to reduce code size, except when
610 // index or base register are also part of the address. e.g.
611 // foo(%rip)(%rcx,%rax,4) is not legal.
617 case MachineOperand::MO_ExternalSymbol: {
618 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
619 bool needCloseParen = false;
620 std::string Name(TAI->getGlobalPrefix());
621 Name += MO.getSymbolName();
623 // Print function stub suffix unless it's Mac OS X 10.5 and up.
626 else if (Name[0] == '$') {
627 // The name begins with a dollar-sign. In order to avoid having it look
628 // like an integer immediate to the assembler, enclose it in parens.
630 needCloseParen = true;
635 if (shouldPrintPLT(TM, Subtarget)) {
636 std::string GOTName(TAI->getGlobalPrefix());
637 GOTName+="_GLOBAL_OFFSET_TABLE_";
638 if (Name == GOTName) {
639 // HACK! Emit extra offset to PC during printing GOT offset to
640 // compensate for the size of popl instruction. The resulting code
644 // popl %some_register
645 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
647 PrintPICBaseSymbol();
655 if (Subtarget->isPICStyleRIPRel())
660 O << "<unknown operand type>"; return;
664 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
665 unsigned char value = MI->getOperand(Op).getImm();
666 assert(value <= 7 && "Invalid ssecc argument!");
668 case 0: O << "eq"; break;
669 case 1: O << "lt"; break;
670 case 2: O << "le"; break;
671 case 3: O << "unord"; break;
672 case 4: O << "neq"; break;
673 case 5: O << "nlt"; break;
674 case 6: O << "nle"; break;
675 case 7: O << "ord"; break;
679 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
680 const char *Modifier,
682 MachineOperand BaseReg = MI->getOperand(Op);
683 MachineOperand IndexReg = MI->getOperand(Op+2);
684 const MachineOperand &DispSpec = MI->getOperand(Op+3);
686 NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
687 if (DispSpec.isGlobal() ||
690 DispSpec.isSymbol()) {
691 printOperand(MI, Op+3, "mem", NotRIPRel);
693 int DispVal = DispSpec.getImm();
694 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
698 if (IndexReg.getReg() || BaseReg.getReg()) {
699 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
700 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
702 // There are cases where we can end up with ESP/RSP in the indexreg slot.
703 // If this happens, swap the base/index register to support assemblers that
704 // don't work when the index is *SP.
705 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
706 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
707 std::swap(BaseReg, IndexReg);
708 std::swap(BaseRegOperand, IndexRegOperand);
712 if (BaseReg.getReg())
713 printOperand(MI, Op+BaseRegOperand, Modifier);
715 if (IndexReg.getReg()) {
717 printOperand(MI, Op+IndexRegOperand, Modifier);
719 O << ',' << ScaleVal;
725 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
726 const char *Modifier, bool NotRIPRel){
727 assert(isMem(MI, Op) && "Invalid memory reference!");
728 MachineOperand Segment = MI->getOperand(Op+4);
729 if (Segment.getReg()) {
730 printOperand(MI, Op+4, Modifier);
733 printLeaMemReference(MI, Op, Modifier, NotRIPRel);
736 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
737 const MachineBasicBlock *MBB) const {
738 if (!TAI->getSetDirective())
741 // We don't need .set machinery if we have GOT-style relocations
742 if (Subtarget->isPICStyleGOT())
745 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
746 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
747 printBasicBlockLabel(MBB, false, false, false);
748 if (Subtarget->isPICStyleRIPRel())
749 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
750 << '_' << uid << '\n';
753 PrintPICBaseSymbol();
759 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
760 PrintPICBaseSymbol();
762 PrintPICBaseSymbol();
767 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
768 const MachineBasicBlock *MBB,
771 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
772 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
774 O << JTEntryDirective << ' ';
776 if (TM.getRelocationModel() == Reloc::PIC_) {
777 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
778 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
779 << '_' << uid << "_set_" << MBB->getNumber();
780 } else if (Subtarget->isPICStyleGOT()) {
781 printBasicBlockLabel(MBB, false, false, false);
784 assert(0 && "Don't know how to print MBB label for this PIC mode");
786 printBasicBlockLabel(MBB, false, false, false);
789 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
790 unsigned Reg = MO.getReg();
792 default: return true; // Unknown mode.
793 case 'b': // Print QImode register
794 Reg = getX86SubSuperRegister(Reg, MVT::i8);
796 case 'h': // Print QImode high register
797 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
799 case 'w': // Print HImode register
800 Reg = getX86SubSuperRegister(Reg, MVT::i16);
802 case 'k': // Print SImode register
803 Reg = getX86SubSuperRegister(Reg, MVT::i32);
805 case 'q': // Print DImode register
806 Reg = getX86SubSuperRegister(Reg, MVT::i64);
810 O << '%'<< TRI->getAsmName(Reg);
814 /// PrintAsmOperand - Print out an operand for an inline asm expression.
816 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
818 const char *ExtraCode) {
819 // Does this asm operand have a single letter operand modifier?
820 if (ExtraCode && ExtraCode[0]) {
821 if (ExtraCode[1] != 0) return true; // Unknown modifier.
823 switch (ExtraCode[0]) {
824 default: return true; // Unknown modifier.
825 case 'c': // Don't print "$" before a global var name or constant.
826 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
828 case 'b': // Print QImode register
829 case 'h': // Print QImode high register
830 case 'w': // Print HImode register
831 case 'k': // Print SImode register
832 case 'q': // Print DImode register
833 if (MI->getOperand(OpNo).isReg())
834 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
835 printOperand(MI, OpNo);
838 case 'P': // Don't print @PLT, but do print as memory.
839 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
844 printOperand(MI, OpNo);
848 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
851 const char *ExtraCode) {
852 if (ExtraCode && ExtraCode[0]) {
853 if (ExtraCode[1] != 0) return true; // Unknown modifier.
855 switch (ExtraCode[0]) {
856 default: return true; // Unknown modifier.
857 case 'b': // Print QImode register
858 case 'h': // Print QImode high register
859 case 'w': // Print HImode register
860 case 'k': // Print SImode register
861 case 'q': // Print SImode register
862 // These only apply to registers, ignore on mem.
864 case 'P': // Don't print @PLT, but do print as memory.
865 printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
869 printMemReference(MI, OpNo);
873 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
874 // Convert registers in the addr mode according to subreg64.
875 for (unsigned i = 0; i != 4; ++i) {
876 if (!MI->getOperand(i).isReg()) continue;
878 unsigned Reg = MI->getOperand(i).getReg();
879 if (Reg == 0) continue;
881 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
885 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
886 /// AT&T syntax to the current output stream.
888 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
892 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
896 } else if (MI->isLabel()) {
899 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
902 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
903 printImplicitDef(MI);
910 TmpInst.setOpcode(MI->getOpcode());
912 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
913 const MachineOperand &MO = MI->getOperand(i);
917 MCOp.MakeReg(MO.getReg());
918 } else if (MO.isImm()) {
919 MCOp.MakeImm(MO.getImm());
920 } else if (MO.isMBB()) {
921 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
923 assert(0 && "Unimp");
926 TmpInst.addOperand(MCOp);
929 switch (TmpInst.getOpcode()) {
931 // Handle the 'subreg rewriting' for the lea64_32mem operand.
932 lower_lea64_32mem(&TmpInst, 1);
936 // FIXME: Convert TmpInst.
937 printInstruction(&TmpInst);
941 // Call the autogenerated instruction printer routines.
942 printInstruction(MI);
946 bool X86ATTAsmPrinter::doInitialization(Module &M) {
948 Context = new MCContext();
949 // FIXME: Send this to "O" instead of outs(). For now, we force it to
950 // stdout to make it easy to compare.
951 Streamer = createAsmStreamer(*Context, outs());
954 return AsmPrinter::doInitialization(M);
957 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
958 const TargetData *TD = TM.getTargetData();
960 if (!GVar->hasInitializer())
961 return; // External global require no code
963 // Check to see if this is a special global used by LLVM, if so, emit it.
964 if (EmitSpecialLLVMGlobal(GVar)) {
965 if (Subtarget->isTargetDarwin() &&
966 TM.getRelocationModel() == Reloc::Static) {
967 if (GVar->getName() == "llvm.global_ctors")
968 O << ".reference .constructors_used\n";
969 else if (GVar->getName() == "llvm.global_dtors")
970 O << ".reference .destructors_used\n";
975 std::string name = Mang->getValueName(GVar);
976 Constant *C = GVar->getInitializer();
977 const Type *Type = C->getType();
978 unsigned Size = TD->getTypeAllocSize(Type);
979 unsigned Align = TD->getPreferredAlignmentLog(GVar);
981 printVisibility(name, GVar->getVisibility());
983 if (Subtarget->isTargetELF())
984 O << "\t.type\t" << name << ",@object\n";
986 SwitchToSection(TAI->SectionForGlobal(GVar));
988 if (C->isNullValue() && !GVar->hasSection() &&
989 !(Subtarget->isTargetDarwin() &&
990 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
991 // FIXME: This seems to be pretty darwin-specific
992 if (GVar->hasExternalLinkage()) {
993 if (const char *Directive = TAI->getZeroFillDirective()) {
994 O << "\t.globl " << name << '\n';
995 O << Directive << "__DATA, __common, " << name << ", "
996 << Size << ", " << Align << '\n';
1001 if (!GVar->isThreadLocal() &&
1002 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
1003 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
1005 if (TAI->getLCOMMDirective() != NULL) {
1006 if (GVar->hasLocalLinkage()) {
1007 O << TAI->getLCOMMDirective() << name << ',' << Size;
1008 if (Subtarget->isTargetDarwin())
1010 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1011 O << "\t.globl " << name << '\n'
1012 << TAI->getWeakDefDirective() << name << '\n';
1013 EmitAlignment(Align, GVar);
1016 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1017 PrintUnmangledNameSafely(GVar, O);
1020 EmitGlobalConstant(C);
1023 O << TAI->getCOMMDirective() << name << ',' << Size;
1024 if (TAI->getCOMMDirectiveTakesAlignment())
1025 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1028 if (!Subtarget->isTargetCygMing()) {
1029 if (GVar->hasLocalLinkage())
1030 O << "\t.local\t" << name << '\n';
1032 O << TAI->getCOMMDirective() << name << ',' << Size;
1033 if (TAI->getCOMMDirectiveTakesAlignment())
1034 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1037 O << "\t\t" << TAI->getCommentString() << ' ';
1038 PrintUnmangledNameSafely(GVar, O);
1045 switch (GVar->getLinkage()) {
1046 case GlobalValue::CommonLinkage:
1047 case GlobalValue::LinkOnceAnyLinkage:
1048 case GlobalValue::LinkOnceODRLinkage:
1049 case GlobalValue::WeakAnyLinkage:
1050 case GlobalValue::WeakODRLinkage:
1051 if (Subtarget->isTargetDarwin()) {
1052 O << "\t.globl " << name << '\n'
1053 << TAI->getWeakDefDirective() << name << '\n';
1054 } else if (Subtarget->isTargetCygMing()) {
1055 O << "\t.globl\t" << name << "\n"
1056 "\t.linkonce same_size\n";
1058 O << "\t.weak\t" << name << '\n';
1061 case GlobalValue::DLLExportLinkage:
1062 case GlobalValue::AppendingLinkage:
1063 // FIXME: appending linkage variables should go into a section of
1064 // their name or something. For now, just emit them as external.
1065 case GlobalValue::ExternalLinkage:
1066 // If external or appending, declare as a global symbol
1067 O << "\t.globl " << name << '\n';
1069 case GlobalValue::PrivateLinkage:
1070 case GlobalValue::InternalLinkage:
1073 assert(0 && "Unknown linkage type!");
1076 EmitAlignment(Align, GVar);
1079 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1080 PrintUnmangledNameSafely(GVar, O);
1083 if (TAI->hasDotTypeDotSizeDirective())
1084 O << "\t.size\t" << name << ", " << Size << '\n';
1086 EmitGlobalConstant(C);
1089 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1090 // Print out module-level global variables here.
1091 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1093 printModuleLevelGV(I);
1095 if (I->hasDLLExportLinkage())
1096 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1099 if (Subtarget->isTargetDarwin()) {
1100 SwitchToDataSection("");
1102 // Add the (possibly multiple) personalities to the set of global value
1103 // stubs. Only referenced functions get into the Personalities list.
1104 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1105 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1106 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1107 if (Personalities[i] == 0)
1109 std::string Name = Mang->getValueName(Personalities[i]);
1110 decorateName(Name, Personalities[i]);
1111 GVStubs.insert(Name);
1115 // Output stubs for dynamically-linked functions
1116 if (!FnStubs.empty()) {
1117 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1119 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1120 "self_modifying_code+pure_instructions,5", 0);
1121 const char *Name = I->getKeyData();
1122 printSuffixedName(Name, "$stub");
1124 "\t.indirect_symbol " << Name << "\n"
1125 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1130 // Output stubs for external and common global variables.
1131 if (!GVStubs.empty()) {
1132 SwitchToDataSection(
1133 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1134 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1136 const char *Name = I->getKeyData();
1137 printSuffixedName(Name, "$non_lazy_ptr");
1138 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1142 if (!HiddenGVStubs.empty()) {
1143 SwitchToSection(TAI->getDataSection());
1145 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1146 E = HiddenGVStubs.end(); I != E; ++I) {
1147 const char *Name = I->getKeyData();
1148 printSuffixedName(Name, "$non_lazy_ptr");
1149 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1153 // Funny Darwin hack: This flag tells the linker that no global symbols
1154 // contain code that falls through to other global symbols (e.g. the obvious
1155 // implementation of multiple entry points). If this doesn't occur, the
1156 // linker can safely perform dead code stripping. Since LLVM never
1157 // generates code that does this, it is always safe to set.
1158 O << "\t.subsections_via_symbols\n";
1159 } else if (Subtarget->isTargetCygMing()) {
1160 // Emit type information for external functions
1161 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1163 O << "\t.def\t " << i->getKeyData()
1164 << ";\t.scl\t" << COFF::C_EXT
1165 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1171 // Output linker support code for dllexported globals on windows.
1172 if (!DLLExportedGVs.empty()) {
1173 SwitchToDataSection(".section .drectve");
1175 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1176 e = DLLExportedGVs.end(); i != e; ++i)
1177 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1180 if (!DLLExportedFns.empty()) {
1181 SwitchToDataSection(".section .drectve");
1183 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1184 e = DLLExportedFns.end();
1186 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1189 // Do common shutdown.
1190 bool Changed = AsmPrinter::doFinalization(M);
1192 if (NewAsmPrinter) {
1204 // Include the auto-generated portion of the assembly writer.
1205 #include "X86GenAsmWriter.inc"