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 "X86MCAsmInfo.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/Assembly/Writer.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCSectionMachO.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/CodeGen/DwarfWriter.h"
36 #include "llvm/CodeGen/MachineJumpTableInfo.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Mangler.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
46 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
51 //===----------------------------------------------------------------------===//
52 // Primitive Helper Functions.
53 //===----------------------------------------------------------------------===//
55 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
56 // FIXME: the actual label generated doesn't matter here! Just mangle in
57 // something unique (the function number) with Private prefix.
58 if (Subtarget->isTargetDarwin())
59 O << "\"L" << getFunctionNumber() << "$pb\"";
61 assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
62 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
66 MCSymbol *X86ATTAsmPrinter::GetPICBaseSymbol() {
67 // FIXME: the actual label generated doesn't matter here! Just mangle in
68 // something unique (the function number) with Private prefix.
71 if (Subtarget->isTargetDarwin()) {
72 Name = "L" + utostr(getFunctionNumber())+"$pb";
74 assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
75 Name = ".Lllvm$" + utostr(getFunctionNumber())+".$piclabel";
77 return OutContext.GetOrCreateSymbol(Name);
80 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
81 const TargetData *TD) {
82 X86MachineFunctionInfo Info;
85 switch (F->getCallingConv()) {
86 case CallingConv::X86_StdCall:
87 Info.setDecorationStyle(StdCall);
89 case CallingConv::X86_FastCall:
90 Info.setDecorationStyle(FastCall);
97 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
98 AI != AE; ++AI, ++argNum) {
99 const Type* Ty = AI->getType();
101 // 'Dereference' type in case of byval parameter attribute
102 if (F->paramHasAttr(argNum, Attribute::ByVal))
103 Ty = cast<PointerType>(Ty)->getElementType();
105 // Size should be aligned to DWORD boundary
106 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
109 // We're not supporting tooooo huge arguments :)
110 Info.setBytesToPopOnReturn((unsigned int)Size);
114 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
115 /// various name decorations for Cygwin and MingW.
116 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
117 const GlobalValue *GV) {
118 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
120 const Function *F = dyn_cast<Function>(GV);
123 // Save function name for later type emission.
124 if (F->isDeclaration())
125 CygMingStubs.insert(Name);
127 // We don't want to decorate non-stdcall or non-fastcall functions right now
128 unsigned CC = F->getCallingConv();
129 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
133 const X86MachineFunctionInfo *Info;
135 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
136 if (info_item == FunctionInfoMap.end()) {
137 // Calculate apropriate function info and populate map
138 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
139 Info = &FunctionInfoMap[F];
141 Info = &info_item->second;
144 const FunctionType *FT = F->getFunctionType();
145 switch (Info->getDecorationStyle()) {
149 // "Pure" variadic functions do not receive @0 suffix.
150 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
151 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
152 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
155 // "Pure" variadic functions do not receive @0 suffix.
156 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
157 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
158 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
160 if (Name[0] == '_') {
167 llvm_unreachable("Unsupported DecorationStyle");
171 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
172 unsigned FnAlign = MF.getAlignment();
173 const Function *F = MF.getFunction();
175 if (Subtarget->isTargetCygMing())
176 DecorateCygMingName(CurrentFnName, F);
178 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
179 EmitAlignment(FnAlign, F);
181 switch (F->getLinkage()) {
182 default: llvm_unreachable("Unknown linkage type!");
183 case Function::InternalLinkage: // Symbols default to internal.
184 case Function::PrivateLinkage:
186 case Function::DLLExportLinkage:
187 case Function::ExternalLinkage:
188 O << "\t.globl\t" << CurrentFnName << '\n';
190 case Function::LinkerPrivateLinkage:
191 case Function::LinkOnceAnyLinkage:
192 case Function::LinkOnceODRLinkage:
193 case Function::WeakAnyLinkage:
194 case Function::WeakODRLinkage:
195 if (Subtarget->isTargetDarwin()) {
196 O << "\t.globl\t" << CurrentFnName << '\n';
197 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
198 } else if (Subtarget->isTargetCygMing()) {
199 O << "\t.globl\t" << CurrentFnName << "\n"
200 "\t.linkonce discard\n";
202 O << "\t.weak\t" << CurrentFnName << '\n';
207 printVisibility(CurrentFnName, F->getVisibility());
209 if (Subtarget->isTargetELF())
210 O << "\t.type\t" << CurrentFnName << ",@function\n";
211 else if (Subtarget->isTargetCygMing()) {
212 O << "\t.def\t " << CurrentFnName
214 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
215 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
219 O << CurrentFnName << ':';
221 O.PadToColumn(MAI->getCommentColumn());
222 O << MAI->getCommentString() << ' ';
223 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
227 // Add some workaround for linkonce linkage on Cygwin\MinGW
228 if (Subtarget->isTargetCygMing() &&
229 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
230 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
233 /// runOnMachineFunction - This uses the printMachineInstruction()
234 /// method to print assembly for each instruction.
236 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
237 const Function *F = MF.getFunction();
239 unsigned CC = F->getCallingConv();
241 SetupMachineFunction(MF);
244 // Populate function information map. Actually, We don't want to populate
245 // non-stdcall or non-fastcall functions' information right now.
246 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
247 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
249 // Print out constants referenced by the function
250 EmitConstantPool(MF.getConstantPool());
252 if (F->hasDLLExportLinkage())
253 DLLExportedFns.insert(Mang->getMangledName(F));
255 // Print the 'header' of function
256 emitFunctionHeader(MF);
258 // Emit pre-function debug and/or EH information.
259 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
260 DW->BeginFunction(&MF);
262 // Print out code for the function.
263 bool hasAnyRealCode = false;
264 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
266 // Print a label for the basic block.
267 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
268 // This is an entry block or a block that's only reachable via a
269 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
271 printBasicBlockLabel(I, true, true, VerboseAsm);
274 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
276 // Print the assembly for the instruction.
278 hasAnyRealCode = true;
279 printMachineInstruction(II);
283 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
284 // If the function is empty, then we need to emit *something*. Otherwise,
285 // the function's label might be associated with something that it wasn't
286 // meant to be associated with. We emit a noop in this situation.
287 // We are assuming inline asms are code.
291 if (MAI->hasDotTypeDotSizeDirective())
292 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
294 // Emit post-function debug information.
295 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
296 DW->EndFunction(&MF);
298 // Print out jump tables referenced by the function.
299 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
301 // We didn't modify anything.
305 /// printSymbolOperand - Print a raw symbol reference operand. This handles
306 /// jump tables, constant pools, global address and external symbols, all of
307 /// which print to a label with various suffixes for relocation types etc.
308 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
309 switch (MO.getType()) {
310 default: llvm_unreachable("unknown symbol type!");
311 case MachineOperand::MO_JumpTableIndex:
312 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
315 case MachineOperand::MO_ConstantPoolIndex:
316 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
318 printOffset(MO.getOffset());
320 case MachineOperand::MO_GlobalAddress: {
321 const GlobalValue *GV = MO.getGlobal();
323 const char *Suffix = "";
324 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
326 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
327 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
328 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
329 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
330 Suffix = "$non_lazy_ptr";
332 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
333 if (Subtarget->isTargetCygMing())
334 DecorateCygMingName(Name, GV);
336 // Handle dllimport linkage.
337 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
338 Name = "__imp_" + Name;
340 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
341 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
342 GVStubs[Name] = Mang->getMangledName(GV);
343 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
344 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
345 HiddenGVStubs[Name] = Mang->getMangledName(GV);
346 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
347 FnStubs[Name] = Mang->getMangledName(GV);
349 // If the name begins with a dollar-sign, enclose it in parens. We do this
350 // to avoid having it look like an integer immediate to the assembler.
352 O << '(' << Name << ')';
356 printOffset(MO.getOffset());
359 case MachineOperand::MO_ExternalSymbol: {
360 std::string Name = Mang->makeNameProper(MO.getSymbolName());
361 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
362 FnStubs[Name+"$stub"] = Name;
366 // If the name begins with a dollar-sign, enclose it in parens. We do this
367 // to avoid having it look like an integer immediate to the assembler.
369 O << '(' << Name << ')';
376 switch (MO.getTargetFlags()) {
378 llvm_unreachable("Unknown target flag on GV operand");
379 case X86II::MO_NO_FLAG: // No flag.
381 case X86II::MO_DARWIN_NONLAZY:
382 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
383 case X86II::MO_DLLIMPORT:
384 case X86II::MO_DARWIN_STUB:
385 // These affect the name of the symbol, not any suffix.
387 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
389 PrintPICBaseSymbol();
392 case X86II::MO_PIC_BASE_OFFSET:
393 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
394 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
396 PrintPICBaseSymbol();
398 case X86II::MO_TLSGD: O << "@TLSGD"; break;
399 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
400 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
401 case X86II::MO_TPOFF: O << "@TPOFF"; break;
402 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
403 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
404 case X86II::MO_GOT: O << "@GOT"; break;
405 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
406 case X86II::MO_PLT: O << "@PLT"; break;
410 /// print_pcrel_imm - This is used to print an immediate value that ends up
411 /// being encoded as a pc-relative value. These print slightly differently, for
412 /// example, a $ is not emitted.
413 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
414 const MachineOperand &MO = MI->getOperand(OpNo);
415 switch (MO.getType()) {
416 default: llvm_unreachable("Unknown pcrel immediate operand");
417 case MachineOperand::MO_Immediate:
420 case MachineOperand::MO_MachineBasicBlock:
421 printBasicBlockLabel(MO.getMBB(), false, false, false);
423 case MachineOperand::MO_GlobalAddress:
424 case MachineOperand::MO_ExternalSymbol:
425 printSymbolOperand(MO);
432 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
433 const char *Modifier) {
434 const MachineOperand &MO = MI->getOperand(OpNo);
435 switch (MO.getType()) {
436 default: llvm_unreachable("unknown operand type!");
437 case MachineOperand::MO_Register: {
438 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
439 "Virtual registers should not make it this far!");
441 unsigned Reg = MO.getReg();
442 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
443 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
444 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
445 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
446 Reg = getX86SubSuperRegister(Reg, VT);
448 O << TRI->getAsmName(Reg);
452 case MachineOperand::MO_Immediate:
453 O << '$' << MO.getImm();
456 case MachineOperand::MO_JumpTableIndex:
457 case MachineOperand::MO_ConstantPoolIndex:
458 case MachineOperand::MO_GlobalAddress:
459 case MachineOperand::MO_ExternalSymbol: {
461 printSymbolOperand(MO);
467 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
468 unsigned char value = MI->getOperand(Op).getImm();
469 assert(value <= 7 && "Invalid ssecc argument!");
471 case 0: O << "eq"; break;
472 case 1: O << "lt"; break;
473 case 2: O << "le"; break;
474 case 3: O << "unord"; break;
475 case 4: O << "neq"; break;
476 case 5: O << "nlt"; break;
477 case 6: O << "nle"; break;
478 case 7: O << "ord"; break;
482 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
483 const char *Modifier) {
484 const MachineOperand &BaseReg = MI->getOperand(Op);
485 const MachineOperand &IndexReg = MI->getOperand(Op+2);
486 const MachineOperand &DispSpec = MI->getOperand(Op+3);
488 // If we really don't want to print out (rip), don't.
489 bool HasBaseReg = BaseReg.getReg() != 0;
490 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
491 BaseReg.getReg() == X86::RIP)
494 // HasParenPart - True if we will print out the () part of the mem ref.
495 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
497 if (DispSpec.isImm()) {
498 int DispVal = DispSpec.getImm();
499 if (DispVal || !HasParenPart)
502 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
503 DispSpec.isJTI() || DispSpec.isSymbol());
504 printSymbolOperand(MI->getOperand(Op+3));
508 assert(IndexReg.getReg() != X86::ESP &&
509 "X86 doesn't allow scaling by ESP");
513 printOperand(MI, Op, Modifier);
515 if (IndexReg.getReg()) {
517 printOperand(MI, Op+2, Modifier);
518 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
520 O << ',' << ScaleVal;
526 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
527 const char *Modifier) {
528 assert(isMem(MI, Op) && "Invalid memory reference!");
529 const MachineOperand &Segment = MI->getOperand(Op+4);
530 if (Segment.getReg()) {
531 printOperand(MI, Op+4, Modifier);
534 printLeaMemReference(MI, Op, Modifier);
537 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
538 const MachineBasicBlock *MBB) const {
539 if (!MAI->getSetDirective())
542 // We don't need .set machinery if we have GOT-style relocations
543 if (Subtarget->isPICStyleGOT())
546 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
547 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
548 printBasicBlockLabel(MBB, false, false, false);
549 if (Subtarget->isPICStyleRIPRel())
550 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
551 << '_' << uid << '\n';
554 PrintPICBaseSymbol();
560 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
561 PrintPICBaseSymbol();
563 PrintPICBaseSymbol();
568 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
569 const MachineBasicBlock *MBB,
570 unsigned uid) const {
571 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
572 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
574 O << JTEntryDirective << ' ';
576 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
577 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
578 << '_' << uid << "_set_" << MBB->getNumber();
579 } else if (Subtarget->isPICStyleGOT()) {
580 printBasicBlockLabel(MBB, false, false, false);
583 printBasicBlockLabel(MBB, false, false, false);
586 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
587 unsigned Reg = MO.getReg();
589 default: return true; // Unknown mode.
590 case 'b': // Print QImode register
591 Reg = getX86SubSuperRegister(Reg, MVT::i8);
593 case 'h': // Print QImode high register
594 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
596 case 'w': // Print HImode register
597 Reg = getX86SubSuperRegister(Reg, MVT::i16);
599 case 'k': // Print SImode register
600 Reg = getX86SubSuperRegister(Reg, MVT::i32);
602 case 'q': // Print DImode register
603 Reg = getX86SubSuperRegister(Reg, MVT::i64);
607 O << '%'<< TRI->getAsmName(Reg);
611 /// PrintAsmOperand - Print out an operand for an inline asm expression.
613 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
615 const char *ExtraCode) {
616 // Does this asm operand have a single letter operand modifier?
617 if (ExtraCode && ExtraCode[0]) {
618 if (ExtraCode[1] != 0) return true; // Unknown modifier.
620 const MachineOperand &MO = MI->getOperand(OpNo);
622 switch (ExtraCode[0]) {
623 default: return true; // Unknown modifier.
624 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
629 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
630 printSymbolOperand(MO);
635 printOperand(MI, OpNo);
641 case 'c': // Don't print "$" before a global var name or constant.
644 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
645 printSymbolOperand(MO);
647 printOperand(MI, OpNo);
650 case 'A': // Print '*' before a register (it must be a register)
653 printOperand(MI, OpNo);
658 case 'b': // Print QImode register
659 case 'h': // Print QImode high register
660 case 'w': // Print HImode register
661 case 'k': // Print SImode register
662 case 'q': // Print DImode register
664 return printAsmMRegister(MO, ExtraCode[0]);
665 printOperand(MI, OpNo);
668 case 'P': // This is the operand of a call, treat specially.
669 print_pcrel_imm(MI, OpNo);
672 case 'n': // Negate the immediate or print a '-' before the operand.
673 // Note: this is a temporary solution. It should be handled target
674 // independently as part of the 'MC' work.
683 printOperand(MI, OpNo);
687 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
690 const char *ExtraCode) {
691 if (ExtraCode && ExtraCode[0]) {
692 if (ExtraCode[1] != 0) return true; // Unknown modifier.
694 switch (ExtraCode[0]) {
695 default: return true; // Unknown modifier.
696 case 'b': // Print QImode register
697 case 'h': // Print QImode high register
698 case 'w': // Print HImode register
699 case 'k': // Print SImode register
700 case 'q': // Print SImode register
701 // These only apply to registers, ignore on mem.
703 case 'P': // Don't print @PLT, but do print as memory.
704 printMemReference(MI, OpNo, "no-rip");
708 printMemReference(MI, OpNo);
712 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
713 // Convert registers in the addr mode according to subreg64.
714 for (unsigned i = 0; i != 4; ++i) {
715 if (!MI->getOperand(i).isReg()) continue;
717 unsigned Reg = MI->getOperand(i).getReg();
718 if (Reg == 0) continue;
720 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
724 /// LowerGlobalAddressOperand - Lower an MO_GlobalAddress operand to an
726 MCOperand X86ATTAsmPrinter::LowerGlobalAddressOperand(const MachineOperand &MO){
727 const GlobalValue *GV = MO.getGlobal();
729 const char *Suffix = "";
730 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
732 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
733 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
734 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
735 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
736 Suffix = "$non_lazy_ptr";
738 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
739 if (Subtarget->isTargetCygMing())
740 DecorateCygMingName(Name, GV);
742 // Handle dllimport linkage.
743 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
744 Name = "__imp_" + Name;
746 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
747 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
748 GVStubs[Name] = Mang->getMangledName(GV);
749 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
750 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
751 HiddenGVStubs[Name] = Mang->getMangledName(GV);
752 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
753 FnStubs[Name] = Mang->getMangledName(GV);
756 // Handle target operand flags.
757 // FIXME: This should be common between external symbols, constant pool etc.
758 MCSymbol *NegatedSymbol = 0;
760 switch (MO.getTargetFlags()) {
762 llvm_unreachable("Unknown target flag on GV operand");
763 case X86II::MO_NO_FLAG: // No flag.
765 case X86II::MO_DARWIN_NONLAZY:
766 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
767 case X86II::MO_DLLIMPORT:
768 case X86II::MO_DARWIN_STUB:
769 // These affect the name of the symbol, not any suffix.
771 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
772 assert(0 && "Reloc mode unimp!");
774 //PrintPICBaseSymbol();
777 case X86II::MO_PIC_BASE_OFFSET:
778 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
779 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
780 // Subtract the pic base.
781 NegatedSymbol = GetPICBaseSymbol();
784 // FIXME: These probably should be a modifier on the symbol or something??
785 case X86II::MO_TLSGD: Name += "@TLSGD"; break;
786 case X86II::MO_GOTTPOFF: Name += "@GOTTPOFF"; break;
787 case X86II::MO_INDNTPOFF: Name += "@INDNTPOFF"; break;
788 case X86II::MO_TPOFF: Name += "@TPOFF"; break;
789 case X86II::MO_NTPOFF: Name += "@NTPOFF"; break;
790 case X86II::MO_GOTPCREL: Name += "@GOTPCREL"; break;
791 case X86II::MO_GOT: Name += "@GOT"; break;
792 case X86II::MO_GOTOFF: Name += "@GOTOFF"; break;
793 case X86II::MO_PLT: Name += "@PLT"; break;
796 // Create a symbol for the name.
797 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
798 // FIXME: We would like an efficient form for this, so we don't have to do a
799 // lot of extra uniquing.
800 const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, OutContext);
802 Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(NegatedSymbol,
806 Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(),
809 return MCOperand::CreateExpr(Expr);
812 MCOperand X86ATTAsmPrinter::
813 LowerExternalSymbolOperand(const MachineOperand &MO){
814 std::string Name = Mang->makeNameProper(MO.getSymbolName());
815 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
816 FnStubs[Name+"$stub"] = Name;
820 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
821 // FIXME: We would like an efficient form for this, so we don't have to do a
822 // lot of extra uniquing.
823 const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, OutContext);
825 Expr = MCBinaryExpr::CreateAdd(Expr,
826 MCConstantExpr::Create(MO.getOffset(),
829 return MCOperand::CreateExpr(Expr);
833 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
834 /// AT&T syntax to the current output stream.
836 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
839 if (!NewAsmPrinter) {
840 // Call the autogenerated instruction printer routines.
841 printInstruction(MI);
847 switch (MI->getOpcode()) {
848 case TargetInstrInfo::DBG_LABEL:
849 case TargetInstrInfo::EH_LABEL:
850 case TargetInstrInfo::GC_LABEL:
853 case TargetInstrInfo::INLINEASM:
857 case TargetInstrInfo::IMPLICIT_DEF:
858 printImplicitDef(MI);
860 case X86::MOVPC32r: {
861 // This is a pseudo op for a two instruction sequence with a label, which
868 MCSymbol *PICBase = GetPICBaseSymbol();
869 TmpInst.setOpcode(X86::CALLpcrel32);
870 // FIXME: We would like an efficient form for this, so we don't have to do a
871 // lot of extra uniquing.
872 TmpInst.addOperand(MCOperand::CreateExpr(MCSymbolRefExpr::Create(PICBase,
874 printInstruction(&TmpInst);
877 OutStreamer.EmitLabel(PICBase);
880 TmpInst.setOpcode(X86::POP32r);
881 TmpInst.getOperand(0) = MCOperand::CreateReg(MI->getOperand(0).getReg());
882 printInstruction(&TmpInst);
884 // Call the autogenerated instruction printer routines.
885 printInstruction(MI);
892 TmpInst.setOpcode(MI->getOpcode());
894 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
895 const MachineOperand &MO = MI->getOperand(i);
898 switch (MO.getType()) {
901 errs() << "Cannot lower operand #" << i << " of :" << *MI;
902 llvm_unreachable("Unimp");
903 case MachineOperand::MO_Register:
904 MCOp = MCOperand::CreateReg(MO.getReg());
906 case MachineOperand::MO_Immediate:
907 MCOp = MCOperand::CreateImm(MO.getImm());
909 case MachineOperand::MO_MachineBasicBlock:
910 MCOp = MCOperand::CreateMBBLabel(getFunctionNumber(),
911 MO.getMBB()->getNumber());
913 case MachineOperand::MO_GlobalAddress:
914 MCOp = LowerGlobalAddressOperand(MO);
916 case MachineOperand::MO_ExternalSymbol:
917 MCOp = LowerExternalSymbolOperand(MO);
921 TmpInst.addOperand(MCOp);
924 switch (TmpInst.getOpcode()) {
926 // Handle the 'subreg rewriting' for the lea64_32mem operand.
927 lower_lea64_32mem(&TmpInst, 1);
931 // FIXME: Convert TmpInst.
932 printInstruction(&TmpInst);
935 // Call the autogenerated instruction printer routines.
936 printInstruction(MI);
939 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
940 const TargetData *TD = TM.getTargetData();
942 if (!GVar->hasInitializer())
943 return; // External global require no code
945 // Check to see if this is a special global used by LLVM, if so, emit it.
946 if (EmitSpecialLLVMGlobal(GVar)) {
947 if (Subtarget->isTargetDarwin() &&
948 TM.getRelocationModel() == Reloc::Static) {
949 if (GVar->getName() == "llvm.global_ctors")
950 O << ".reference .constructors_used\n";
951 else if (GVar->getName() == "llvm.global_dtors")
952 O << ".reference .destructors_used\n";
957 std::string name = Mang->getMangledName(GVar);
958 Constant *C = GVar->getInitializer();
959 const Type *Type = C->getType();
960 unsigned Size = TD->getTypeAllocSize(Type);
961 unsigned Align = TD->getPreferredAlignmentLog(GVar);
963 printVisibility(name, GVar->getVisibility());
965 if (Subtarget->isTargetELF())
966 O << "\t.type\t" << name << ",@object\n";
969 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
970 const MCSection *TheSection =
971 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
972 OutStreamer.SwitchSection(TheSection);
974 // FIXME: get this stuff from section kind flags.
975 if (C->isNullValue() && !GVar->hasSection() &&
976 // Don't put things that should go in the cstring section into "comm".
977 !TheSection->getKind().isMergeableCString()) {
978 if (GVar->hasExternalLinkage()) {
979 if (const char *Directive = MAI->getZeroFillDirective()) {
980 O << "\t.globl " << name << '\n';
981 O << Directive << "__DATA, __common, " << name << ", "
982 << Size << ", " << Align << '\n';
987 if (!GVar->isThreadLocal() &&
988 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
989 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
991 if (MAI->getLCOMMDirective() != NULL) {
992 if (GVar->hasLocalLinkage()) {
993 O << MAI->getLCOMMDirective() << name << ',' << Size;
994 if (Subtarget->isTargetDarwin())
996 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
997 O << "\t.globl " << name << '\n'
998 << MAI->getWeakDefDirective() << name << '\n';
999 EmitAlignment(Align, GVar);
1002 O.PadToColumn(MAI->getCommentColumn());
1003 O << MAI->getCommentString() << ' ';
1004 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1007 EmitGlobalConstant(C);
1010 O << MAI->getCOMMDirective() << name << ',' << Size;
1011 if (MAI->getCOMMDirectiveTakesAlignment())
1012 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1015 if (!Subtarget->isTargetCygMing()) {
1016 if (GVar->hasLocalLinkage())
1017 O << "\t.local\t" << name << '\n';
1019 O << MAI->getCOMMDirective() << name << ',' << Size;
1020 if (MAI->getCOMMDirectiveTakesAlignment())
1021 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1024 O.PadToColumn(MAI->getCommentColumn());
1025 O << MAI->getCommentString() << ' ';
1026 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1033 switch (GVar->getLinkage()) {
1034 case GlobalValue::CommonLinkage:
1035 case GlobalValue::LinkOnceAnyLinkage:
1036 case GlobalValue::LinkOnceODRLinkage:
1037 case GlobalValue::WeakAnyLinkage:
1038 case GlobalValue::WeakODRLinkage:
1039 case GlobalValue::LinkerPrivateLinkage:
1040 if (Subtarget->isTargetDarwin()) {
1041 O << "\t.globl " << name << '\n'
1042 << MAI->getWeakDefDirective() << name << '\n';
1043 } else if (Subtarget->isTargetCygMing()) {
1044 O << "\t.globl\t" << name << "\n"
1045 "\t.linkonce same_size\n";
1047 O << "\t.weak\t" << name << '\n';
1050 case GlobalValue::DLLExportLinkage:
1051 case GlobalValue::AppendingLinkage:
1052 // FIXME: appending linkage variables should go into a section of
1053 // their name or something. For now, just emit them as external.
1054 case GlobalValue::ExternalLinkage:
1055 // If external or appending, declare as a global symbol
1056 O << "\t.globl " << name << '\n';
1058 case GlobalValue::PrivateLinkage:
1059 case GlobalValue::InternalLinkage:
1062 llvm_unreachable("Unknown linkage type!");
1065 EmitAlignment(Align, GVar);
1068 O.PadToColumn(MAI->getCommentColumn());
1069 O << MAI->getCommentString() << ' ';
1070 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1074 EmitGlobalConstant(C);
1076 if (MAI->hasDotTypeDotSizeDirective())
1077 O << "\t.size\t" << name << ", " << Size << '\n';
1080 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1081 // Print out module-level global variables here.
1082 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1084 if (I->hasDLLExportLinkage())
1085 DLLExportedGVs.insert(Mang->getMangledName(I));
1088 if (Subtarget->isTargetDarwin()) {
1089 // All darwin targets use mach-o.
1090 TargetLoweringObjectFileMachO &TLOFMacho =
1091 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1093 // Add the (possibly multiple) personalities to the set of global value
1094 // stubs. Only referenced functions get into the Personalities list.
1095 if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1096 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1097 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1098 if (Personalities[i])
1099 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
1100 true /*private label*/)] =
1101 Mang->getMangledName(Personalities[i]);
1105 // Output stubs for dynamically-linked functions
1106 if (!FnStubs.empty()) {
1107 const MCSection *TheSection =
1108 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
1109 MCSectionMachO::S_SYMBOL_STUBS |
1110 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
1111 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1112 5, SectionKind::getMetadata());
1113 OutStreamer.SwitchSection(TheSection);
1114 for (StringMap<std::string>::iterator I = FnStubs.begin(),
1115 E = FnStubs.end(); I != E; ++I)
1116 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
1117 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
1121 // Output stubs for external and common global variables.
1122 if (!GVStubs.empty()) {
1123 const MCSection *TheSection =
1124 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
1125 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
1126 SectionKind::getMetadata());
1127 OutStreamer.SwitchSection(TheSection);
1128 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1129 E = GVStubs.end(); I != E; ++I)
1130 O << I->getKeyData() << ":\n\t.indirect_symbol "
1131 << I->second << "\n\t.long\t0\n";
1134 if (!HiddenGVStubs.empty()) {
1135 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1137 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1138 E = HiddenGVStubs.end(); I != E; ++I)
1139 O << I->getKeyData() << ":\n" << MAI->getData32bitsDirective()
1140 << I->second << '\n';
1143 // Funny Darwin hack: This flag tells the linker that no global symbols
1144 // contain code that falls through to other global symbols (e.g. the obvious
1145 // implementation of multiple entry points). If this doesn't occur, the
1146 // linker can safely perform dead code stripping. Since LLVM never
1147 // generates code that does this, it is always safe to set.
1148 O << "\t.subsections_via_symbols\n";
1149 } else if (Subtarget->isTargetCygMing()) {
1150 // Emit type information for external functions
1151 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
1153 O << "\t.def\t " << i->getKeyData()
1154 << ";\t.scl\t" << COFF::C_EXT
1155 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1161 // Output linker support code for dllexported globals on windows.
1162 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
1163 // dllexport symbols only exist on coff targets.
1164 TargetLoweringObjectFileCOFF &TLOFMacho =
1165 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
1167 OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
1168 SectionKind::getMetadata()));
1170 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1171 e = DLLExportedGVs.end(); i != e; ++i)
1172 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1174 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1175 e = DLLExportedFns.end();
1177 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1180 // Do common shutdown.
1181 return AsmPrinter::doFinalization(M);
1184 // Include the auto-generated portion of the assembly writer.
1185 #include "X86GenAsmWriter.inc"