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/MDNode.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/CodeGen/DwarfWriter.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/TargetOptions.h"
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
47 //===----------------------------------------------------------------------===//
48 // Primitive Helper Functions.
49 //===----------------------------------------------------------------------===//
51 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
52 if (Subtarget->isTargetDarwin())
53 O << "\"L" << getFunctionNumber() << "$pb\"";
54 else if (Subtarget->isTargetELF())
55 O << ".Lllvm$" << getFunctionNumber() << "." "$piclabel";
57 assert(0 && "Don't know how to print PIC label!\n");
60 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
61 /// Don't print things like \\n or \\0.
62 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
63 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
69 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
70 const TargetData *TD) {
71 X86MachineFunctionInfo Info;
74 switch (F->getCallingConv()) {
75 case CallingConv::X86_StdCall:
76 Info.setDecorationStyle(StdCall);
78 case CallingConv::X86_FastCall:
79 Info.setDecorationStyle(FastCall);
86 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
87 AI != AE; ++AI, ++argNum) {
88 const Type* Ty = AI->getType();
90 // 'Dereference' type in case of byval parameter attribute
91 if (F->paramHasAttr(argNum, Attribute::ByVal))
92 Ty = cast<PointerType>(Ty)->getElementType();
94 // Size should be aligned to DWORD boundary
95 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
98 // We're not supporting tooooo huge arguments :)
99 Info.setBytesToPopOnReturn((unsigned int)Size);
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");
159 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
160 const Function *F = MF.getFunction();
162 decorateName(CurrentFnName, F);
164 SwitchToSection(TAI->SectionForGlobal(F));
166 // FIXME: A function's alignment should be part of MachineFunction. There
167 // shouldn't be a policy decision here.
168 unsigned FnAlign = 4;
169 if (F->hasFnAttr(Attribute::OptimizeForSize))
172 switch (F->getLinkage()) {
173 default: assert(0 && "Unknown linkage type!");
174 case Function::InternalLinkage: // Symbols default to internal.
175 case Function::PrivateLinkage:
176 EmitAlignment(FnAlign, F);
178 case Function::DLLExportLinkage:
179 case Function::ExternalLinkage:
180 EmitAlignment(FnAlign, F);
181 O << "\t.globl\t" << CurrentFnName << '\n';
183 case Function::LinkOnceAnyLinkage:
184 case Function::LinkOnceODRLinkage:
185 case Function::WeakAnyLinkage:
186 case Function::WeakODRLinkage:
187 EmitAlignment(FnAlign, F);
188 if (Subtarget->isTargetDarwin()) {
189 O << "\t.globl\t" << CurrentFnName << '\n';
190 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
191 } else if (Subtarget->isTargetCygMing()) {
192 O << "\t.globl\t" << CurrentFnName << "\n"
193 "\t.linkonce discard\n";
195 O << "\t.weak\t" << CurrentFnName << '\n';
200 printVisibility(CurrentFnName, F->getVisibility());
202 if (Subtarget->isTargetELF())
203 O << "\t.type\t" << CurrentFnName << ",@function\n";
204 else if (Subtarget->isTargetCygMing()) {
205 O << "\t.def\t " << CurrentFnName
207 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
208 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
212 O << CurrentFnName << ":\n";
213 // Add some workaround for linkonce linkage on Cygwin\MinGW
214 if (Subtarget->isTargetCygMing() &&
215 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
216 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
219 /// runOnMachineFunction - This uses the printMachineInstruction()
220 /// method to print assembly for each instruction.
222 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
223 const Function *F = MF.getFunction();
225 unsigned CC = F->getCallingConv();
227 SetupMachineFunction(MF);
230 // Populate function information map. Actually, We don't want to populate
231 // non-stdcall or non-fastcall functions' information right now.
232 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
233 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
235 // Print out constants referenced by the function
236 EmitConstantPool(MF.getConstantPool());
238 if (F->hasDLLExportLinkage())
239 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
241 // Print the 'header' of function
242 emitFunctionHeader(MF);
244 // Emit pre-function debug and/or EH information.
245 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
246 DW->BeginFunction(&MF);
248 // Print out code for the function.
249 bool hasAnyRealCode = false;
250 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
252 // Print a label for the basic block.
253 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
254 // This is an entry block or a block that's only reachable via a
255 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
257 printBasicBlockLabel(I, true, true, VerboseAsm);
260 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
262 // Print the assembly for the instruction.
264 hasAnyRealCode = true;
265 printMachineInstruction(II);
269 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
270 // If the function is empty, then we need to emit *something*. Otherwise,
271 // the function's label might be associated with something that it wasn't
272 // meant to be associated with. We emit a noop in this situation.
273 // We are assuming inline asms are code.
277 if (TAI->hasDotTypeDotSizeDirective())
278 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
280 // Emit post-function debug information.
281 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
282 DW->EndFunction(&MF);
284 // Print out jump tables referenced by the function.
285 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
289 // We didn't modify anything.
293 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
294 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_;
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 // DARWIN/X86-32 in != static mode.
331 // Link-once, declaration, or Weakly-linked global variables need
332 // non-lazily-resolved stubs
333 if (GV->isDeclaration() || GV->isWeakForLinker()) {
334 // Dynamically-resolved functions need a stub for the function.
335 if (isa<Function>(GV)) {
336 // Function stubs are no longer needed for Mac OS X 10.5 and up.
337 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
340 FnStubs.insert(Name);
341 printSuffixedName(Name, "$stub");
343 } else if (GV->hasHiddenVisibility()) {
344 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
345 // Definition is not definitely in the current translation unit.
348 HiddenGVStubs.insert(Name);
349 printSuffixedName(Name, "$non_lazy_ptr");
352 GVStubs.insert(Name);
353 printSuffixedName(Name, "$non_lazy_ptr");
356 if (GV->hasDLLImportLinkage())
361 if (GV->hasDLLImportLinkage())
365 if (shouldPrintPLT(TM, Subtarget)) {
366 // Assemble call via PLT for externally visible symbols
367 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
368 !GV->hasLocalLinkage())
371 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
372 // Save function name for later type emission
373 FnStubs.insert(Name);
376 printOffset(MO.getOffset());
383 case MachineOperand::MO_ExternalSymbol: {
384 bool needCloseParen = false;
385 std::string Name(TAI->getGlobalPrefix());
386 Name += MO.getSymbolName();
387 // Print function stub suffix unless it's Mac OS X 10.5 and up.
388 if (shouldPrintStub(TM, Subtarget) &&
389 // DARWIN/X86-32 in != static mode.
390 !(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 (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
408 PrintPICBaseSymbol();
412 if (shouldPrintPLT(TM, Subtarget))
423 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
424 const char *Modifier) {
425 const MachineOperand &MO = MI->getOperand(OpNo);
426 switch (MO.getType()) {
427 case MachineOperand::MO_Register: {
428 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
429 "Virtual registers should not make it this far!");
431 unsigned Reg = MO.getReg();
432 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
433 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
434 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
435 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
436 Reg = getX86SubSuperRegister(Reg, VT);
438 O << TRI->getAsmName(Reg);
442 case MachineOperand::MO_Immediate:
443 if (!Modifier || (strcmp(Modifier, "debug") &&
444 strcmp(Modifier, "mem")))
448 case MachineOperand::MO_JumpTableIndex: {
449 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
450 if (!isMemOp) O << '$';
451 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
454 switch (MO.getTargetFlags()) {
456 assert(0 && "Unknown target flag on jump table operand");
457 case X86II::MO_NO_FLAG:
458 // FIXME: REMOVE EVENTUALLY.
459 if (TM.getRelocationModel() == Reloc::PIC_) {
460 assert(!Subtarget->isPICStyleStub() &&
461 !Subtarget->isPICStyleGOT() &&
462 "Should have operand flag!");
466 case X86II::MO_PIC_BASE_OFFSET:
468 PrintPICBaseSymbol();
470 case X86II::MO_GOTOFF:
477 case MachineOperand::MO_ConstantPoolIndex: {
478 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
479 if (!isMemOp) O << '$';
480 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
483 printOffset(MO.getOffset());
485 switch (MO.getTargetFlags()) {
487 assert(0 && "Unknown target flag on constant pool operand");
488 case X86II::MO_NO_FLAG:
489 // FIXME: REMOVE EVENTUALLY.
490 if (TM.getRelocationModel() == Reloc::PIC_) {
491 assert(!Subtarget->isPICStyleStub() &&
492 !Subtarget->isPICStyleGOT() &&
493 "Should have operand flag!");
497 case X86II::MO_PIC_BASE_OFFSET:
499 PrintPICBaseSymbol();
501 case X86II::MO_GOTOFF:
508 case MachineOperand::MO_GlobalAddress: {
509 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
510 bool needCloseParen = false;
512 const GlobalValue *GV = MO.getGlobal();
513 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
515 // If GV is an alias then use the aliasee for determining
517 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
518 GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
521 bool isThreadLocal = GVar && GVar->isThreadLocal();
523 std::string Name = Mang->getValueName(GV);
524 decorateName(Name, GV);
528 else if (Name[0] == '$') {
529 // The name begins with a dollar-sign. In order to avoid having it look
530 // like an integer immediate to the assembler, enclose it in parens.
532 needCloseParen = true;
535 if (shouldPrintStub(TM, Subtarget)) {
536 // DARWIN/X86-32 in != static mode.
538 // Link-once, declaration, or Weakly-linked global variables need
539 // non-lazily-resolved stubs
540 if (GV->isDeclaration() || GV->isWeakForLinker()) {
541 // Dynamically-resolved functions need a stub for the function.
542 if (GV->hasHiddenVisibility()) {
543 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
544 // Definition is not definitely in the current translation unit.
547 HiddenGVStubs.insert(Name);
548 printSuffixedName(Name, "$non_lazy_ptr");
551 GVStubs.insert(Name);
552 printSuffixedName(Name, "$non_lazy_ptr");
555 if (GV->hasDLLImportLinkage())
560 if (TM.getRelocationModel() == Reloc::PIC_) {
562 PrintPICBaseSymbol();
565 if (GV->hasDLLImportLinkage())
570 printOffset(MO.getOffset());
575 switch (MO.getTargetFlags()) {
577 assert(0 && "Unknown target flag on GV operand");
578 case X86II::MO_NO_FLAG:
579 // FIXME: RIP THIS CHECKING CODE OUT EVENTUALLY.
581 assert(0 && "Not lowered right");
583 case X86II::MO_TLSGD: O << "@TLSGD"; break;
584 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
585 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
586 case X86II::MO_TPOFF: O << "@TPOFF"; break;
587 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
588 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
589 case X86II::MO_GOT: O << "@GOT"; break;
590 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
594 case MachineOperand::MO_ExternalSymbol: {
595 /// NOTE: MO_ExternalSymbol in a non-pcrel_imm context is *only* generated
596 /// by _GLOBAL_OFFSET_TABLE_ on X86-32. All others are call operands, which
598 assert(!Subtarget->is64Bit() && !Subtarget->isPICStyleRIPRel());
599 // These are never used as memory operands.
600 assert(!(Modifier && !strcmp(Modifier, "mem")));
603 O << TAI->getGlobalPrefix();
604 O << MO.getSymbolName();
606 if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
608 PrintPICBaseSymbol();
611 assert(MO.getTargetFlags() == X86II::MO_NO_FLAG &&
612 "Unknown operand flag for external symbol");
617 O << "<unknown operand type>"; return;
621 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
622 unsigned char value = MI->getOperand(Op).getImm();
623 assert(value <= 7 && "Invalid ssecc argument!");
625 case 0: O << "eq"; break;
626 case 1: O << "lt"; break;
627 case 2: O << "le"; break;
628 case 3: O << "unord"; break;
629 case 4: O << "neq"; break;
630 case 5: O << "nlt"; break;
631 case 6: O << "nle"; break;
632 case 7: O << "ord"; break;
636 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
637 const char *Modifier) {
638 MachineOperand BaseReg = MI->getOperand(Op);
639 MachineOperand IndexReg = MI->getOperand(Op+2);
640 const MachineOperand &DispSpec = MI->getOperand(Op+3);
642 if (DispSpec.isGlobal() ||
645 DispSpec.isSymbol()) {
646 printOperand(MI, Op+3, "mem");
648 int DispVal = DispSpec.getImm();
649 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
653 if ((IndexReg.getReg() || BaseReg.getReg()) &&
654 (Modifier == 0 || strcmp(Modifier, "no-rip"))) {
655 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
656 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
658 // There are cases where we can end up with ESP/RSP in the indexreg slot.
659 // If this happens, swap the base/index register to support assemblers that
660 // don't work when the index is *SP.
661 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
662 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
663 std::swap(BaseReg, IndexReg);
664 std::swap(BaseRegOperand, IndexRegOperand);
668 if (BaseReg.getReg())
669 printOperand(MI, Op+BaseRegOperand, Modifier);
671 if (IndexReg.getReg()) {
673 printOperand(MI, Op+IndexRegOperand, Modifier);
675 O << ',' << ScaleVal;
681 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
682 const char *Modifier) {
683 assert(isMem(MI, Op) && "Invalid memory reference!");
684 MachineOperand Segment = MI->getOperand(Op+4);
685 if (Segment.getReg()) {
686 printOperand(MI, Op+4, Modifier);
689 printLeaMemReference(MI, Op, Modifier);
692 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
693 const MachineBasicBlock *MBB) const {
694 if (!TAI->getSetDirective())
697 // We don't need .set machinery if we have GOT-style relocations
698 if (Subtarget->isPICStyleGOT())
701 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
702 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
703 printBasicBlockLabel(MBB, false, false, false);
704 if (Subtarget->isPICStyleRIPRel())
705 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
706 << '_' << uid << '\n';
709 PrintPICBaseSymbol();
715 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
716 PrintPICBaseSymbol();
718 PrintPICBaseSymbol();
723 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
724 const MachineBasicBlock *MBB,
727 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
728 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
730 O << JTEntryDirective << ' ';
732 if (TM.getRelocationModel() == Reloc::PIC_) {
733 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
734 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
735 << '_' << uid << "_set_" << MBB->getNumber();
736 } else if (Subtarget->isPICStyleGOT()) {
737 printBasicBlockLabel(MBB, false, false, false);
740 assert(0 && "Don't know how to print MBB label for this PIC mode");
742 printBasicBlockLabel(MBB, false, false, false);
745 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
746 unsigned Reg = MO.getReg();
748 default: return true; // Unknown mode.
749 case 'b': // Print QImode register
750 Reg = getX86SubSuperRegister(Reg, MVT::i8);
752 case 'h': // Print QImode high register
753 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
755 case 'w': // Print HImode register
756 Reg = getX86SubSuperRegister(Reg, MVT::i16);
758 case 'k': // Print SImode register
759 Reg = getX86SubSuperRegister(Reg, MVT::i32);
761 case 'q': // Print DImode register
762 Reg = getX86SubSuperRegister(Reg, MVT::i64);
766 O << '%'<< TRI->getAsmName(Reg);
770 /// PrintAsmOperand - Print out an operand for an inline asm expression.
772 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
774 const char *ExtraCode) {
775 // Does this asm operand have a single letter operand modifier?
776 if (ExtraCode && ExtraCode[0]) {
777 if (ExtraCode[1] != 0) return true; // Unknown modifier.
779 switch (ExtraCode[0]) {
780 default: return true; // Unknown modifier.
781 case 'c': // Don't print "$" before a global var name or constant.
782 printOperand(MI, OpNo, "mem");
784 case 'b': // Print QImode register
785 case 'h': // Print QImode high register
786 case 'w': // Print HImode register
787 case 'k': // Print SImode register
788 case 'q': // Print DImode register
789 if (MI->getOperand(OpNo).isReg())
790 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
791 printOperand(MI, OpNo);
794 case 'P': // Don't print @PLT, but do print as memory.
795 printOperand(MI, OpNo, "mem");
798 case 'n': { // Negate the immediate or print a '-' before the operand.
799 // Note: this is a temporary solution. It should be handled target
800 // independently as part of the 'MC' work.
801 const MachineOperand &MO = MI->getOperand(OpNo);
811 printOperand(MI, OpNo);
815 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
818 const char *ExtraCode) {
819 if (ExtraCode && ExtraCode[0]) {
820 if (ExtraCode[1] != 0) return true; // Unknown modifier.
822 switch (ExtraCode[0]) {
823 default: return true; // Unknown modifier.
824 case 'b': // Print QImode register
825 case 'h': // Print QImode high register
826 case 'w': // Print HImode register
827 case 'k': // Print SImode register
828 case 'q': // Print SImode register
829 // These only apply to registers, ignore on mem.
831 case 'P': // Don't print @PLT, but do print as memory.
832 printMemReference(MI, OpNo, "no-rip");
836 printMemReference(MI, OpNo);
840 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
841 // Convert registers in the addr mode according to subreg64.
842 for (unsigned i = 0; i != 4; ++i) {
843 if (!MI->getOperand(i).isReg()) continue;
845 unsigned Reg = MI->getOperand(i).getReg();
846 if (Reg == 0) continue;
848 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
852 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
853 /// AT&T syntax to the current output stream.
855 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
859 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
863 } else if (MI->isLabel()) {
866 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
869 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
870 printImplicitDef(MI);
877 TmpInst.setOpcode(MI->getOpcode());
879 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
880 const MachineOperand &MO = MI->getOperand(i);
884 MCOp.MakeReg(MO.getReg());
885 } else if (MO.isImm()) {
886 MCOp.MakeImm(MO.getImm());
887 } else if (MO.isMBB()) {
888 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
890 assert(0 && "Unimp");
893 TmpInst.addOperand(MCOp);
896 switch (TmpInst.getOpcode()) {
898 // Handle the 'subreg rewriting' for the lea64_32mem operand.
899 lower_lea64_32mem(&TmpInst, 1);
903 // FIXME: Convert TmpInst.
904 printInstruction(&TmpInst);
908 // Call the autogenerated instruction printer routines.
909 printInstruction(MI);
913 bool X86ATTAsmPrinter::doInitialization(Module &M) {
915 Context = new MCContext();
916 // FIXME: Send this to "O" instead of outs(). For now, we force it to
917 // stdout to make it easy to compare.
918 Streamer = createAsmStreamer(*Context, outs());
921 return AsmPrinter::doInitialization(M);
924 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
925 const TargetData *TD = TM.getTargetData();
927 if (!GVar->hasInitializer())
928 return; // External global require no code
930 // Check to see if this is a special global used by LLVM, if so, emit it.
931 if (EmitSpecialLLVMGlobal(GVar)) {
932 if (Subtarget->isTargetDarwin() &&
933 TM.getRelocationModel() == Reloc::Static) {
934 if (GVar->getName() == "llvm.global_ctors")
935 O << ".reference .constructors_used\n";
936 else if (GVar->getName() == "llvm.global_dtors")
937 O << ".reference .destructors_used\n";
942 std::string name = Mang->getValueName(GVar);
943 Constant *C = GVar->getInitializer();
944 if (isa<MDNode>(C) || isa<MDString>(C))
946 const Type *Type = C->getType();
947 unsigned Size = TD->getTypeAllocSize(Type);
948 unsigned Align = TD->getPreferredAlignmentLog(GVar);
950 printVisibility(name, GVar->getVisibility());
952 if (Subtarget->isTargetELF())
953 O << "\t.type\t" << name << ",@object\n";
955 SwitchToSection(TAI->SectionForGlobal(GVar));
957 if (C->isNullValue() && !GVar->hasSection() &&
958 !(Subtarget->isTargetDarwin() &&
959 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
960 // FIXME: This seems to be pretty darwin-specific
961 if (GVar->hasExternalLinkage()) {
962 if (const char *Directive = TAI->getZeroFillDirective()) {
963 O << "\t.globl " << name << '\n';
964 O << Directive << "__DATA, __common, " << name << ", "
965 << Size << ", " << Align << '\n';
970 if (!GVar->isThreadLocal() &&
971 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
972 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
974 if (TAI->getLCOMMDirective() != NULL) {
975 if (GVar->hasLocalLinkage()) {
976 O << TAI->getLCOMMDirective() << name << ',' << Size;
977 if (Subtarget->isTargetDarwin())
979 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
980 O << "\t.globl " << name << '\n'
981 << TAI->getWeakDefDirective() << name << '\n';
982 EmitAlignment(Align, GVar);
985 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
986 PrintUnmangledNameSafely(GVar, O);
989 EmitGlobalConstant(C);
992 O << TAI->getCOMMDirective() << name << ',' << Size;
993 if (TAI->getCOMMDirectiveTakesAlignment())
994 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
997 if (!Subtarget->isTargetCygMing()) {
998 if (GVar->hasLocalLinkage())
999 O << "\t.local\t" << name << '\n';
1001 O << TAI->getCOMMDirective() << name << ',' << Size;
1002 if (TAI->getCOMMDirectiveTakesAlignment())
1003 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1006 O << "\t\t" << TAI->getCommentString() << ' ';
1007 PrintUnmangledNameSafely(GVar, O);
1014 switch (GVar->getLinkage()) {
1015 case GlobalValue::CommonLinkage:
1016 case GlobalValue::LinkOnceAnyLinkage:
1017 case GlobalValue::LinkOnceODRLinkage:
1018 case GlobalValue::WeakAnyLinkage:
1019 case GlobalValue::WeakODRLinkage:
1020 if (Subtarget->isTargetDarwin()) {
1021 O << "\t.globl " << name << '\n'
1022 << TAI->getWeakDefDirective() << name << '\n';
1023 } else if (Subtarget->isTargetCygMing()) {
1024 O << "\t.globl\t" << name << "\n"
1025 "\t.linkonce same_size\n";
1027 O << "\t.weak\t" << name << '\n';
1030 case GlobalValue::DLLExportLinkage:
1031 case GlobalValue::AppendingLinkage:
1032 // FIXME: appending linkage variables should go into a section of
1033 // their name or something. For now, just emit them as external.
1034 case GlobalValue::ExternalLinkage:
1035 // If external or appending, declare as a global symbol
1036 O << "\t.globl " << name << '\n';
1038 case GlobalValue::PrivateLinkage:
1039 case GlobalValue::InternalLinkage:
1042 assert(0 && "Unknown linkage type!");
1045 EmitAlignment(Align, GVar);
1048 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1049 PrintUnmangledNameSafely(GVar, O);
1052 if (TAI->hasDotTypeDotSizeDirective())
1053 O << "\t.size\t" << name << ", " << Size << '\n';
1055 EmitGlobalConstant(C);
1058 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1059 // Print out module-level global variables here.
1060 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1062 printModuleLevelGV(I);
1064 if (I->hasDLLExportLinkage())
1065 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1068 if (Subtarget->isTargetDarwin()) {
1069 SwitchToDataSection("");
1071 // Add the (possibly multiple) personalities to the set of global value
1072 // stubs. Only referenced functions get into the Personalities list.
1073 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1074 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1075 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1076 if (Personalities[i] == 0)
1078 std::string Name = Mang->getValueName(Personalities[i]);
1079 decorateName(Name, Personalities[i]);
1080 GVStubs.insert(Name);
1084 // Output stubs for dynamically-linked functions
1085 if (!FnStubs.empty()) {
1086 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1088 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1089 "self_modifying_code+pure_instructions,5", 0);
1090 const char *Name = I->getKeyData();
1091 printSuffixedName(Name, "$stub");
1093 "\t.indirect_symbol " << Name << "\n"
1094 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1099 // Output stubs for external and common global variables.
1100 if (!GVStubs.empty()) {
1101 SwitchToDataSection(
1102 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1103 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1105 const char *Name = I->getKeyData();
1106 printSuffixedName(Name, "$non_lazy_ptr");
1107 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1111 if (!HiddenGVStubs.empty()) {
1112 SwitchToSection(TAI->getDataSection());
1114 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1115 E = HiddenGVStubs.end(); I != E; ++I) {
1116 const char *Name = I->getKeyData();
1117 printSuffixedName(Name, "$non_lazy_ptr");
1118 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1122 // Funny Darwin hack: This flag tells the linker that no global symbols
1123 // contain code that falls through to other global symbols (e.g. the obvious
1124 // implementation of multiple entry points). If this doesn't occur, the
1125 // linker can safely perform dead code stripping. Since LLVM never
1126 // generates code that does this, it is always safe to set.
1127 O << "\t.subsections_via_symbols\n";
1128 } else if (Subtarget->isTargetCygMing()) {
1129 // Emit type information for external functions
1130 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1132 O << "\t.def\t " << i->getKeyData()
1133 << ";\t.scl\t" << COFF::C_EXT
1134 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1140 // Output linker support code for dllexported globals on windows.
1141 if (!DLLExportedGVs.empty()) {
1142 SwitchToDataSection(".section .drectve");
1144 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1145 e = DLLExportedGVs.end(); i != e; ++i)
1146 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1149 if (!DLLExportedFns.empty()) {
1150 SwitchToDataSection(".section .drectve");
1152 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1153 e = DLLExportedFns.end();
1155 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1158 // Do common shutdown.
1159 bool Changed = AsmPrinter::doFinalization(M);
1161 if (NewAsmPrinter) {
1173 // Include the auto-generated portion of the assembly writer.
1174 #include "X86GenAsmWriter.inc"