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");
157 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
158 unsigned FnAlign = MF.getAlignment();
159 const Function *F = MF.getFunction();
161 decorateName(CurrentFnName, F);
163 SwitchToSection(TAI->SectionForGlobal(F));
164 switch (F->getLinkage()) {
165 default: assert(0 && "Unknown linkage type!");
166 case Function::InternalLinkage: // Symbols default to internal.
167 case Function::PrivateLinkage:
168 EmitAlignment(FnAlign, F);
170 case Function::DLLExportLinkage:
171 case Function::ExternalLinkage:
172 EmitAlignment(FnAlign, F);
173 O << "\t.globl\t" << CurrentFnName << '\n';
175 case Function::LinkOnceAnyLinkage:
176 case Function::LinkOnceODRLinkage:
177 case Function::WeakAnyLinkage:
178 case Function::WeakODRLinkage:
179 EmitAlignment(FnAlign, F);
180 if (Subtarget->isTargetDarwin()) {
181 O << "\t.globl\t" << CurrentFnName << '\n';
182 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
183 } else if (Subtarget->isTargetCygMing()) {
184 O << "\t.globl\t" << CurrentFnName << "\n"
185 "\t.linkonce discard\n";
187 O << "\t.weak\t" << CurrentFnName << '\n';
192 printVisibility(CurrentFnName, F->getVisibility());
194 if (Subtarget->isTargetELF())
195 O << "\t.type\t" << CurrentFnName << ",@function\n";
196 else if (Subtarget->isTargetCygMing()) {
197 O << "\t.def\t " << CurrentFnName
199 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
200 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
204 O << CurrentFnName << ":\n";
205 // Add some workaround for linkonce linkage on Cygwin\MinGW
206 if (Subtarget->isTargetCygMing() &&
207 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
208 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
211 /// runOnMachineFunction - This uses the printMachineInstruction()
212 /// method to print assembly for each instruction.
214 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
215 const Function *F = MF.getFunction();
217 unsigned CC = F->getCallingConv();
219 SetupMachineFunction(MF);
222 // Populate function information map. Actually, We don't want to populate
223 // non-stdcall or non-fastcall functions' information right now.
224 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
225 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
227 // Print out constants referenced by the function
228 EmitConstantPool(MF.getConstantPool());
230 if (F->hasDLLExportLinkage())
231 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
233 // Print the 'header' of function
234 emitFunctionHeader(MF);
236 // Emit pre-function debug and/or EH information.
237 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
238 DW->BeginFunction(&MF);
240 // Print out code for the function.
241 bool hasAnyRealCode = false;
242 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
244 // Print a label for the basic block.
245 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
246 // This is an entry block or a block that's only reachable via a
247 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
249 printBasicBlockLabel(I, true, true, VerboseAsm);
252 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
254 // Print the assembly for the instruction.
256 hasAnyRealCode = true;
257 printMachineInstruction(II);
261 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
262 // If the function is empty, then we need to emit *something*. Otherwise,
263 // the function's label might be associated with something that it wasn't
264 // meant to be associated with. We emit a noop in this situation.
265 // We are assuming inline asms are code.
269 if (TAI->hasDotTypeDotSizeDirective())
270 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
272 // Emit post-function debug information.
273 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
274 DW->EndFunction(&MF);
276 // Print out jump tables referenced by the function.
277 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
281 // We didn't modify anything.
285 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
286 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_;
289 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
290 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
293 /// print_pcrel_imm - This is used to print an immediate value that ends up
294 /// being encoded as a pc-relative value. These print slightly differently, for
295 /// example, a $ is not emitted.
296 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
297 const MachineOperand &MO = MI->getOperand(OpNo);
298 switch (MO.getType()) {
299 default: assert(0 && "Unknown pcrel immediate operand");
300 case MachineOperand::MO_Immediate:
303 case MachineOperand::MO_MachineBasicBlock:
304 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
307 case MachineOperand::MO_GlobalAddress: {
308 const GlobalValue *GV = MO.getGlobal();
309 std::string Name = Mang->getValueName(GV);
310 decorateName(Name, GV);
312 bool needCloseParen = false;
313 if (Name[0] == '$') {
314 // The name begins with a dollar-sign. In order to avoid having it look
315 // like an integer immediate to the assembler, enclose it in parens.
317 needCloseParen = true;
320 if (shouldPrintStub(TM, Subtarget)) {
321 // DARWIN/X86-32 in != static mode.
323 // Link-once, declaration, or Weakly-linked global variables need
324 // non-lazily-resolved stubs
325 if (GV->isDeclaration() || GV->isWeakForLinker()) {
326 // Dynamically-resolved functions need a stub for the function.
327 if (isa<Function>(GV)) {
328 // Function stubs are no longer needed for Mac OS X 10.5 and up.
329 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
332 FnStubs.insert(Name);
333 printSuffixedName(Name, "$stub");
335 } else if (GV->hasHiddenVisibility()) {
336 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
337 // Definition is not definitely in the current translation unit.
340 HiddenGVStubs.insert(Name);
341 printSuffixedName(Name, "$non_lazy_ptr");
344 GVStubs.insert(Name);
345 printSuffixedName(Name, "$non_lazy_ptr");
348 if (GV->hasDLLImportLinkage())
353 if (GV->hasDLLImportLinkage())
357 if (shouldPrintPLT(TM, Subtarget)) {
358 // Assemble call via PLT for externally visible symbols
359 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
360 !GV->hasLocalLinkage())
363 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
364 // Save function name for later type emission
365 FnStubs.insert(Name);
368 printOffset(MO.getOffset());
375 case MachineOperand::MO_ExternalSymbol: {
376 bool needCloseParen = false;
377 std::string Name(TAI->getGlobalPrefix());
378 Name += MO.getSymbolName();
379 // Print function stub suffix unless it's Mac OS X 10.5 and up.
380 if (shouldPrintStub(TM, Subtarget) &&
381 // DARWIN/X86-32 in != static mode.
382 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
384 FnStubs.insert(Name);
385 printSuffixedName(Name, "$stub");
389 if (Name[0] == '$') {
390 // The name begins with a dollar-sign. In order to avoid having it look
391 // like an integer immediate to the assembler, enclose it in parens.
393 needCloseParen = true;
398 if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
400 PrintPICBaseSymbol();
404 if (shouldPrintPLT(TM, Subtarget))
415 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
416 const char *Modifier) {
417 const MachineOperand &MO = MI->getOperand(OpNo);
418 switch (MO.getType()) {
419 default: assert(0 && "unknown operand type!");
420 case MachineOperand::MO_Register: {
421 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
422 "Virtual registers should not make it this far!");
424 unsigned Reg = MO.getReg();
425 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
426 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
427 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
428 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
429 Reg = getX86SubSuperRegister(Reg, VT);
431 O << TRI->getAsmName(Reg);
435 case MachineOperand::MO_Immediate:
436 if (!Modifier || (strcmp(Modifier, "debug") &&
437 strcmp(Modifier, "mem") &&
438 strcmp(Modifier, "asmcall")))
442 case MachineOperand::MO_JumpTableIndex: {
443 bool isMemOp = Modifier &&
444 (!strcmp(Modifier, "mem") || !strcmp(Modifier, "asmcall"));
445 if (!isMemOp) O << '$';
446 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
450 case MachineOperand::MO_ConstantPoolIndex: {
451 bool isMemOp = Modifier &&
452 (!strcmp(Modifier, "mem") || !strcmp(Modifier, "asmcall"));
453 if (!isMemOp) O << '$';
454 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
457 printOffset(MO.getOffset());
460 case MachineOperand::MO_GlobalAddress: {
461 bool isMemOp = Modifier &&
462 (!strcmp(Modifier, "mem") || !strcmp(Modifier, "asmcall"));
463 bool isAsmCallOp = Modifier && !strcmp(Modifier, "asmcall");
465 const GlobalValue *GV = MO.getGlobal();
466 std::string Name = Mang->getValueName(GV);
467 decorateName(Name, GV);
469 bool needCloseParen = false;
472 else if (Name[0] == '$') {
473 // The name begins with a dollar-sign. In order to avoid having it look
474 // like an integer immediate to the assembler, enclose it in parens.
476 needCloseParen = true;
479 if (shouldPrintStub(TM, Subtarget)) {
480 // DARWIN/X86-32 in != static mode.
482 // Link-once, declaration, or Weakly-linked global variables need
483 // non-lazily-resolved stubs
484 if (GV->isDeclaration() || GV->isWeakForLinker()) {
485 // Dynamically-resolved functions need a stub for the function.
486 if (isa<Function>(GV) && isAsmCallOp) {
487 // Function stubs are no longer needed for Mac OS X 10.5 and up.
488 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
491 FnStubs.insert(Name);
492 printSuffixedName(Name, "$stub");
493 assert(MO.getTargetFlags() == 0);
495 } else if (GV->hasHiddenVisibility()) {
496 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
497 // Definition is not definitely in the current translation unit.
500 HiddenGVStubs.insert(Name);
501 printSuffixedName(Name, "$non_lazy_ptr");
502 assert(MO.getTargetFlags() == 0);
505 GVStubs.insert(Name);
506 printSuffixedName(Name, "$non_lazy_ptr");
507 assert(MO.getTargetFlags() == 0);
513 if (TM.getRelocationModel() == Reloc::PIC_ && !isAsmCallOp) {
515 PrintPICBaseSymbol();
518 if (GV->hasDLLImportLinkage()) {
520 assert(MO.getTargetFlags() == 0);
525 printOffset(MO.getOffset());
532 case MachineOperand::MO_ExternalSymbol:
533 /// NOTE: MO_ExternalSymbol in a non-pcrel_imm context is *only* generated
534 /// by _GLOBAL_OFFSET_TABLE_ on X86-32. All others are call operands, which
536 assert(!Subtarget->is64Bit() && !Subtarget->isPICStyleRIPRel());
537 // These are never used as memory operands.
539 (!strcmp(Modifier, "mem") || !strcmp(Modifier, "asmcall"))));
542 O << TAI->getGlobalPrefix();
543 O << MO.getSymbolName();
547 switch (MO.getTargetFlags()) {
549 assert(0 && "Unknown target flag on GV operand");
550 case X86II::MO_NO_FLAG:
552 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
554 PrintPICBaseSymbol();
557 case X86II::MO_PIC_BASE_OFFSET:
559 PrintPICBaseSymbol();
561 case X86II::MO_TLSGD: O << "@TLSGD"; break;
562 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
563 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
564 case X86II::MO_TPOFF: O << "@TPOFF"; break;
565 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
566 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
567 case X86II::MO_GOT: O << "@GOT"; break;
568 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
572 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
573 unsigned char value = MI->getOperand(Op).getImm();
574 assert(value <= 7 && "Invalid ssecc argument!");
576 case 0: O << "eq"; break;
577 case 1: O << "lt"; break;
578 case 2: O << "le"; break;
579 case 3: O << "unord"; break;
580 case 4: O << "neq"; break;
581 case 5: O << "nlt"; break;
582 case 6: O << "nle"; break;
583 case 7: O << "ord"; break;
587 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
588 const char *Modifier) {
589 const MachineOperand &BaseReg = MI->getOperand(Op);
590 const MachineOperand &IndexReg = MI->getOperand(Op+2);
591 const MachineOperand &DispSpec = MI->getOperand(Op+3);
593 if (DispSpec.isGlobal() ||
596 DispSpec.isSymbol()) {
597 printOperand(MI, Op+3, "mem");
599 int DispVal = DispSpec.getImm();
600 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
604 // If we really don't want to print out (rip), don't.
605 bool HasBaseReg = BaseReg.getReg() != 0;
606 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
607 BaseReg.getReg() == X86::RIP)
610 if (IndexReg.getReg() || HasBaseReg) {
611 assert(IndexReg.getReg() != X86::ESP &&
612 "X86 doesn't allow scaling by ESP");
616 printOperand(MI, Op, Modifier);
618 if (IndexReg.getReg()) {
620 printOperand(MI, Op+2, Modifier);
621 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
623 O << ',' << ScaleVal;
629 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
630 const char *Modifier) {
631 assert(isMem(MI, Op) && "Invalid memory reference!");
632 const MachineOperand &Segment = MI->getOperand(Op+4);
633 if (Segment.getReg()) {
634 printOperand(MI, Op+4, Modifier);
637 printLeaMemReference(MI, Op, Modifier);
640 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
641 const MachineBasicBlock *MBB) const {
642 if (!TAI->getSetDirective())
645 // We don't need .set machinery if we have GOT-style relocations
646 if (Subtarget->isPICStyleGOT())
649 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
650 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
651 printBasicBlockLabel(MBB, false, false, false);
652 if (Subtarget->isPICStyleRIPRel())
653 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
654 << '_' << uid << '\n';
657 PrintPICBaseSymbol();
663 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
664 PrintPICBaseSymbol();
666 PrintPICBaseSymbol();
671 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
672 const MachineBasicBlock *MBB,
675 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
676 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
678 O << JTEntryDirective << ' ';
680 if (TM.getRelocationModel() == Reloc::PIC_) {
681 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
682 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
683 << '_' << uid << "_set_" << MBB->getNumber();
684 } else if (Subtarget->isPICStyleGOT()) {
685 printBasicBlockLabel(MBB, false, false, false);
688 assert(0 && "Don't know how to print MBB label for this PIC mode");
690 printBasicBlockLabel(MBB, false, false, false);
693 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
694 unsigned Reg = MO.getReg();
696 default: return true; // Unknown mode.
697 case 'b': // Print QImode register
698 Reg = getX86SubSuperRegister(Reg, MVT::i8);
700 case 'h': // Print QImode high register
701 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
703 case 'w': // Print HImode register
704 Reg = getX86SubSuperRegister(Reg, MVT::i16);
706 case 'k': // Print SImode register
707 Reg = getX86SubSuperRegister(Reg, MVT::i32);
709 case 'q': // Print DImode register
710 Reg = getX86SubSuperRegister(Reg, MVT::i64);
714 O << '%'<< TRI->getAsmName(Reg);
718 /// PrintAsmOperand - Print out an operand for an inline asm expression.
720 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
722 const char *ExtraCode) {
723 // Does this asm operand have a single letter operand modifier?
724 if (ExtraCode && ExtraCode[0]) {
725 if (ExtraCode[1] != 0) return true; // Unknown modifier.
727 switch (ExtraCode[0]) {
728 default: return true; // Unknown modifier.
729 case 'c': // Don't print "$" before a global var name or constant.
730 printOperand(MI, OpNo, "mem");
732 case 'b': // Print QImode register
733 case 'h': // Print QImode high register
734 case 'w': // Print HImode register
735 case 'k': // Print SImode register
736 case 'q': // Print DImode register
737 if (MI->getOperand(OpNo).isReg())
738 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
739 printOperand(MI, OpNo);
742 case 'P': // This is the operand of a call, treat specially.
743 printOperand(MI, OpNo, "asmcall");
746 case 'n': { // Negate the immediate or print a '-' before the operand.
747 // Note: this is a temporary solution. It should be handled target
748 // independently as part of the 'MC' work.
749 const MachineOperand &MO = MI->getOperand(OpNo);
759 printOperand(MI, OpNo);
763 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
766 const char *ExtraCode) {
767 if (ExtraCode && ExtraCode[0]) {
768 if (ExtraCode[1] != 0) return true; // Unknown modifier.
770 switch (ExtraCode[0]) {
771 default: return true; // Unknown modifier.
772 case 'b': // Print QImode register
773 case 'h': // Print QImode high register
774 case 'w': // Print HImode register
775 case 'k': // Print SImode register
776 case 'q': // Print SImode register
777 // These only apply to registers, ignore on mem.
779 case 'P': // Don't print @PLT, but do print as memory.
780 printMemReference(MI, OpNo, "no-rip");
784 printMemReference(MI, OpNo);
788 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
789 // Convert registers in the addr mode according to subreg64.
790 for (unsigned i = 0; i != 4; ++i) {
791 if (!MI->getOperand(i).isReg()) continue;
793 unsigned Reg = MI->getOperand(i).getReg();
794 if (Reg == 0) continue;
796 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
800 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
801 /// AT&T syntax to the current output stream.
803 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
807 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
811 } else if (MI->isLabel()) {
814 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
817 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
818 printImplicitDef(MI);
825 TmpInst.setOpcode(MI->getOpcode());
827 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
828 const MachineOperand &MO = MI->getOperand(i);
832 MCOp.MakeReg(MO.getReg());
833 } else if (MO.isImm()) {
834 MCOp.MakeImm(MO.getImm());
835 } else if (MO.isMBB()) {
836 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
838 assert(0 && "Unimp");
841 TmpInst.addOperand(MCOp);
844 switch (TmpInst.getOpcode()) {
846 // Handle the 'subreg rewriting' for the lea64_32mem operand.
847 lower_lea64_32mem(&TmpInst, 1);
851 // FIXME: Convert TmpInst.
852 printInstruction(&TmpInst);
856 // Call the autogenerated instruction printer routines.
857 printInstruction(MI);
861 bool X86ATTAsmPrinter::doInitialization(Module &M) {
863 Context = new MCContext();
864 // FIXME: Send this to "O" instead of outs(). For now, we force it to
865 // stdout to make it easy to compare.
866 Streamer = createAsmStreamer(*Context, outs());
869 return AsmPrinter::doInitialization(M);
872 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
873 const TargetData *TD = TM.getTargetData();
875 if (!GVar->hasInitializer())
876 return; // External global require no code
878 // Check to see if this is a special global used by LLVM, if so, emit it.
879 if (EmitSpecialLLVMGlobal(GVar)) {
880 if (Subtarget->isTargetDarwin() &&
881 TM.getRelocationModel() == Reloc::Static) {
882 if (GVar->getName() == "llvm.global_ctors")
883 O << ".reference .constructors_used\n";
884 else if (GVar->getName() == "llvm.global_dtors")
885 O << ".reference .destructors_used\n";
890 std::string name = Mang->getValueName(GVar);
891 Constant *C = GVar->getInitializer();
892 if (isa<MDNode>(C) || isa<MDString>(C))
894 const Type *Type = C->getType();
895 unsigned Size = TD->getTypeAllocSize(Type);
896 unsigned Align = TD->getPreferredAlignmentLog(GVar);
898 printVisibility(name, GVar->getVisibility());
900 if (Subtarget->isTargetELF())
901 O << "\t.type\t" << name << ",@object\n";
903 SwitchToSection(TAI->SectionForGlobal(GVar));
905 if (C->isNullValue() && !GVar->hasSection() &&
906 !(Subtarget->isTargetDarwin() &&
907 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
908 // FIXME: This seems to be pretty darwin-specific
909 if (GVar->hasExternalLinkage()) {
910 if (const char *Directive = TAI->getZeroFillDirective()) {
911 O << "\t.globl " << name << '\n';
912 O << Directive << "__DATA, __common, " << name << ", "
913 << Size << ", " << Align << '\n';
918 if (!GVar->isThreadLocal() &&
919 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
920 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
922 if (TAI->getLCOMMDirective() != NULL) {
923 if (GVar->hasLocalLinkage()) {
924 O << TAI->getLCOMMDirective() << name << ',' << Size;
925 if (Subtarget->isTargetDarwin())
927 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
928 O << "\t.globl " << name << '\n'
929 << TAI->getWeakDefDirective() << name << '\n';
930 EmitAlignment(Align, GVar);
933 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
934 PrintUnmangledNameSafely(GVar, O);
937 EmitGlobalConstant(C);
940 O << TAI->getCOMMDirective() << name << ',' << Size;
941 if (TAI->getCOMMDirectiveTakesAlignment())
942 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
945 if (!Subtarget->isTargetCygMing()) {
946 if (GVar->hasLocalLinkage())
947 O << "\t.local\t" << name << '\n';
949 O << TAI->getCOMMDirective() << name << ',' << Size;
950 if (TAI->getCOMMDirectiveTakesAlignment())
951 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
954 O << "\t\t" << TAI->getCommentString() << ' ';
955 PrintUnmangledNameSafely(GVar, O);
962 switch (GVar->getLinkage()) {
963 case GlobalValue::CommonLinkage:
964 case GlobalValue::LinkOnceAnyLinkage:
965 case GlobalValue::LinkOnceODRLinkage:
966 case GlobalValue::WeakAnyLinkage:
967 case GlobalValue::WeakODRLinkage:
968 if (Subtarget->isTargetDarwin()) {
969 O << "\t.globl " << name << '\n'
970 << TAI->getWeakDefDirective() << name << '\n';
971 } else if (Subtarget->isTargetCygMing()) {
972 O << "\t.globl\t" << name << "\n"
973 "\t.linkonce same_size\n";
975 O << "\t.weak\t" << name << '\n';
978 case GlobalValue::DLLExportLinkage:
979 case GlobalValue::AppendingLinkage:
980 // FIXME: appending linkage variables should go into a section of
981 // their name or something. For now, just emit them as external.
982 case GlobalValue::ExternalLinkage:
983 // If external or appending, declare as a global symbol
984 O << "\t.globl " << name << '\n';
986 case GlobalValue::PrivateLinkage:
987 case GlobalValue::InternalLinkage:
990 assert(0 && "Unknown linkage type!");
993 EmitAlignment(Align, GVar);
996 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
997 PrintUnmangledNameSafely(GVar, O);
1000 if (TAI->hasDotTypeDotSizeDirective())
1001 O << "\t.size\t" << name << ", " << Size << '\n';
1003 EmitGlobalConstant(C);
1006 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1007 // Print out module-level global variables here.
1008 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1010 printModuleLevelGV(I);
1012 if (I->hasDLLExportLinkage())
1013 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1016 if (Subtarget->isTargetDarwin()) {
1017 SwitchToDataSection("");
1019 // Add the (possibly multiple) personalities to the set of global value
1020 // stubs. Only referenced functions get into the Personalities list.
1021 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1022 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1023 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1024 if (Personalities[i] == 0)
1026 std::string Name = Mang->getValueName(Personalities[i]);
1027 decorateName(Name, Personalities[i]);
1028 GVStubs.insert(Name);
1032 // Output stubs for dynamically-linked functions
1033 if (!FnStubs.empty()) {
1034 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1036 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1037 "self_modifying_code+pure_instructions,5", 0);
1038 const char *Name = I->getKeyData();
1039 printSuffixedName(Name, "$stub");
1041 "\t.indirect_symbol " << Name << "\n"
1042 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1047 // Output stubs for external and common global variables.
1048 if (!GVStubs.empty()) {
1049 SwitchToDataSection(
1050 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1051 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1053 const char *Name = I->getKeyData();
1054 printSuffixedName(Name, "$non_lazy_ptr");
1055 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1059 if (!HiddenGVStubs.empty()) {
1060 SwitchToSection(TAI->getDataSection());
1062 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1063 E = HiddenGVStubs.end(); I != E; ++I) {
1064 const char *Name = I->getKeyData();
1065 printSuffixedName(Name, "$non_lazy_ptr");
1066 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1070 // Funny Darwin hack: This flag tells the linker that no global symbols
1071 // contain code that falls through to other global symbols (e.g. the obvious
1072 // implementation of multiple entry points). If this doesn't occur, the
1073 // linker can safely perform dead code stripping. Since LLVM never
1074 // generates code that does this, it is always safe to set.
1075 O << "\t.subsections_via_symbols\n";
1076 } else if (Subtarget->isTargetCygMing()) {
1077 // Emit type information for external functions
1078 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1080 O << "\t.def\t " << i->getKeyData()
1081 << ";\t.scl\t" << COFF::C_EXT
1082 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1088 // Output linker support code for dllexported globals on windows.
1089 if (!DLLExportedGVs.empty()) {
1090 SwitchToDataSection(".section .drectve");
1092 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1093 e = DLLExportedGVs.end(); i != e; ++i)
1094 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1097 if (!DLLExportedFns.empty()) {
1098 SwitchToDataSection(".section .drectve");
1100 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1101 e = DLLExportedFns.end();
1103 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1106 // Do common shutdown.
1107 bool Changed = AsmPrinter::doFinalization(M);
1109 if (NewAsmPrinter) {
1121 // Include the auto-generated portion of the assembly writer.
1122 #include "X86GenAsmWriter.inc"