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 "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Type.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/Statistic.h"
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44 //===----------------------------------------------------------------------===//
45 // Primitive Helper Functions.
46 //===----------------------------------------------------------------------===//
48 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
49 // FIXME: the actual label generated doesn't matter here! Just mangle in
50 // something unique (the function number) with Private prefix.
51 if (Subtarget->isTargetDarwin())
52 O << "\"L" << getFunctionNumber() << "$pb\"";
54 assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
55 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
59 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
60 const TargetData *TD) {
61 X86MachineFunctionInfo Info;
64 switch (F->getCallingConv()) {
65 case CallingConv::X86_StdCall:
66 Info.setDecorationStyle(StdCall);
68 case CallingConv::X86_FastCall:
69 Info.setDecorationStyle(FastCall);
76 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
77 AI != AE; ++AI, ++argNum) {
78 const Type* Ty = AI->getType();
80 // 'Dereference' type in case of byval parameter attribute
81 if (F->paramHasAttr(argNum, Attribute::ByVal))
82 Ty = cast<PointerType>(Ty)->getElementType();
84 // Size should be aligned to DWORD boundary
85 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
88 // We're not supporting tooooo huge arguments :)
89 Info.setBytesToPopOnReturn((unsigned int)Size);
93 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
94 /// various name decorations for Cygwin and MingW.
95 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl<char> &Name,
96 const GlobalValue *GV) {
97 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
99 const Function *F = dyn_cast<Function>(GV);
102 // Save function name for later type emission.
103 if (F->isDeclaration())
104 CygMingStubs.insert(StringRef(Name.data(), Name.size()));
106 // We don't want to decorate non-stdcall or non-fastcall functions right now
107 CallingConv::ID CC = F->getCallingConv();
108 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
112 const X86MachineFunctionInfo *Info;
114 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
115 if (info_item == FunctionInfoMap.end()) {
116 // Calculate apropriate function info and populate map
117 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
118 Info = &FunctionInfoMap[F];
120 Info = &info_item->second;
123 if (Info->getDecorationStyle() == None) return;
124 const FunctionType *FT = F->getFunctionType();
126 // "Pure" variadic functions do not receive @0 suffix.
127 if (!FT->isVarArg() || FT->getNumParams() == 0 ||
128 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
129 raw_svector_ostream(Name) << '@' << Info->getBytesToPopOnReturn();
131 if (Info->getDecorationStyle() == FastCall) {
135 Name.insert(Name.begin(), '@');
139 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
140 /// various name decorations for Cygwin and MingW.
141 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
142 const GlobalValue *GV) {
143 SmallString<128> NameStr(Name.begin(), Name.end());
144 DecorateCygMingName(NameStr, GV);
145 Name.assign(NameStr.begin(), NameStr.end());
148 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
149 unsigned FnAlign = MF.getAlignment();
150 const Function *F = MF.getFunction();
152 if (Subtarget->isTargetCygMing())
153 DecorateCygMingName(CurrentFnName, F);
155 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
156 EmitAlignment(FnAlign, F);
158 switch (F->getLinkage()) {
159 default: llvm_unreachable("Unknown linkage type!");
160 case Function::InternalLinkage: // Symbols default to internal.
161 case Function::PrivateLinkage:
163 case Function::DLLExportLinkage:
164 case Function::ExternalLinkage:
165 O << "\t.globl\t" << CurrentFnName << '\n';
167 case Function::LinkerPrivateLinkage:
168 case Function::LinkOnceAnyLinkage:
169 case Function::LinkOnceODRLinkage:
170 case Function::WeakAnyLinkage:
171 case Function::WeakODRLinkage:
172 if (Subtarget->isTargetDarwin()) {
173 O << "\t.globl\t" << CurrentFnName << '\n';
174 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
175 } else if (Subtarget->isTargetCygMing()) {
176 O << "\t.globl\t" << CurrentFnName << "\n"
177 "\t.linkonce discard\n";
179 O << "\t.weak\t" << CurrentFnName << '\n';
184 printVisibility(CurrentFnName, F->getVisibility());
186 if (Subtarget->isTargetELF())
187 O << "\t.type\t" << CurrentFnName << ",@function\n";
188 else if (Subtarget->isTargetCygMing()) {
189 O << "\t.def\t " << CurrentFnName
191 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
192 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
196 O << CurrentFnName << ':';
198 O.PadToColumn(MAI->getCommentColumn());
199 O << MAI->getCommentString() << ' ';
200 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
204 // Add some workaround for linkonce linkage on Cygwin\MinGW
205 if (Subtarget->isTargetCygMing() &&
206 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
207 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
210 /// runOnMachineFunction - This uses the printMachineInstruction()
211 /// method to print assembly for each instruction.
213 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
214 const Function *F = MF.getFunction();
216 CallingConv::ID CC = F->getCallingConv();
218 SetupMachineFunction(MF);
221 // Populate function information map. Actually, We don't want to populate
222 // non-stdcall or non-fastcall functions' information right now.
223 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
224 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
226 // Print out constants referenced by the function
227 EmitConstantPool(MF.getConstantPool());
229 if (F->hasDLLExportLinkage())
230 DLLExportedFns.insert(Mang->getMangledName(F));
232 // Print the 'header' of function
233 emitFunctionHeader(MF);
235 // Emit pre-function debug and/or EH information.
236 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
237 DW->BeginFunction(&MF);
239 // Print out code for the function.
240 bool hasAnyRealCode = false;
241 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
243 // Print a label for the basic block.
244 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
245 // This is an entry block or a block that's only reachable via a
246 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
248 printBasicBlockLabel(I, true, true, VerboseAsm);
251 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
253 // Print the assembly for the instruction.
255 hasAnyRealCode = true;
256 printMachineInstruction(II);
260 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
261 // If the function is empty, then we need to emit *something*. Otherwise,
262 // the function's label might be associated with something that it wasn't
263 // meant to be associated with. We emit a noop in this situation.
264 // We are assuming inline asms are code.
268 if (MAI->hasDotTypeDotSizeDirective())
269 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
271 // Emit post-function debug information.
272 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
273 DW->EndFunction(&MF);
275 // Print out jump tables referenced by the function.
276 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
278 // We didn't modify anything.
282 /// printSymbolOperand - Print a raw symbol reference operand. This handles
283 /// jump tables, constant pools, global address and external symbols, all of
284 /// which print to a label with various suffixes for relocation types etc.
285 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
286 switch (MO.getType()) {
287 default: llvm_unreachable("unknown symbol type!");
288 case MachineOperand::MO_JumpTableIndex:
289 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
292 case MachineOperand::MO_ConstantPoolIndex:
293 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
295 printOffset(MO.getOffset());
297 case MachineOperand::MO_GlobalAddress: {
298 const GlobalValue *GV = MO.getGlobal();
300 const char *Suffix = "";
301 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
303 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
304 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
305 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
306 Suffix = "$non_lazy_ptr";
308 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
309 if (Subtarget->isTargetCygMing())
310 DecorateCygMingName(Name, GV);
312 // Handle dllimport linkage.
313 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
314 Name = "__imp_" + Name;
316 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
317 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
318 SmallString<128> NameStr;
319 Mang->getNameWithPrefix(NameStr, GV, true);
320 NameStr += "$non_lazy_ptr";
321 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
322 MCSymbol *&StubSym = GVStubs[Sym];
325 Mang->getNameWithPrefix(NameStr, GV, false);
326 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
328 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
329 SmallString<128> NameStr;
330 Mang->getNameWithPrefix(NameStr, GV, true);
331 NameStr += "$non_lazy_ptr";
332 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
333 MCSymbol *&StubSym = HiddenGVStubs[Sym];
336 Mang->getNameWithPrefix(NameStr, GV, false);
337 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
339 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
340 SmallString<128> NameStr;
341 Mang->getNameWithPrefix(NameStr, GV, true);
343 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
344 MCSymbol *&StubSym = FnStubs[Sym];
347 Mang->getNameWithPrefix(NameStr, GV, false);
348 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
352 // If the name begins with a dollar-sign, enclose it in parens. We do this
353 // to avoid having it look like an integer immediate to the assembler.
355 O << '(' << Name << ')';
359 printOffset(MO.getOffset());
362 case MachineOperand::MO_ExternalSymbol: {
363 std::string Name = Mang->makeNameProper(MO.getSymbolName());
364 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
366 MCSymbol *&StubSym = FnStubs[OutContext.GetOrCreateSymbol(Name)];
368 Name.erase(Name.end()-5, Name.end());
369 StubSym = OutContext.GetOrCreateSymbol(Name);
373 // If the name begins with a dollar-sign, enclose it in parens. We do this
374 // to avoid having it look like an integer immediate to the assembler.
376 O << '(' << Name << ')';
383 switch (MO.getTargetFlags()) {
385 llvm_unreachable("Unknown target flag on GV operand");
386 case X86II::MO_NO_FLAG: // No flag.
388 case X86II::MO_DARWIN_NONLAZY:
389 case X86II::MO_DLLIMPORT:
390 case X86II::MO_DARWIN_STUB:
391 // These affect the name of the symbol, not any suffix.
393 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
395 PrintPICBaseSymbol();
398 case X86II::MO_PIC_BASE_OFFSET:
399 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
400 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
402 PrintPICBaseSymbol();
404 case X86II::MO_TLSGD: O << "@TLSGD"; break;
405 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
406 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
407 case X86II::MO_TPOFF: O << "@TPOFF"; break;
408 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
409 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
410 case X86II::MO_GOT: O << "@GOT"; break;
411 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
412 case X86II::MO_PLT: O << "@PLT"; break;
416 /// print_pcrel_imm - This is used to print an immediate value that ends up
417 /// being encoded as a pc-relative value. These print slightly differently, for
418 /// example, a $ is not emitted.
419 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
420 const MachineOperand &MO = MI->getOperand(OpNo);
421 switch (MO.getType()) {
422 default: llvm_unreachable("Unknown pcrel immediate operand");
423 case MachineOperand::MO_Immediate:
426 case MachineOperand::MO_MachineBasicBlock:
427 printBasicBlockLabel(MO.getMBB(), false, false, false);
429 case MachineOperand::MO_GlobalAddress:
430 case MachineOperand::MO_ExternalSymbol:
431 printSymbolOperand(MO);
437 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
438 const char *Modifier) {
439 const MachineOperand &MO = MI->getOperand(OpNo);
440 switch (MO.getType()) {
441 default: llvm_unreachable("unknown operand type!");
442 case MachineOperand::MO_Register: {
443 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
444 "Virtual registers should not make it this far!");
446 unsigned Reg = MO.getReg();
447 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
448 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
449 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
450 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
451 Reg = getX86SubSuperRegister(Reg, VT);
453 O << TRI->getAsmName(Reg);
457 case MachineOperand::MO_Immediate:
458 O << '$' << MO.getImm();
461 case MachineOperand::MO_JumpTableIndex:
462 case MachineOperand::MO_ConstantPoolIndex:
463 case MachineOperand::MO_GlobalAddress:
464 case MachineOperand::MO_ExternalSymbol: {
466 printSymbolOperand(MO);
472 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
473 unsigned char value = MI->getOperand(Op).getImm();
474 assert(value <= 7 && "Invalid ssecc argument!");
476 case 0: O << "eq"; break;
477 case 1: O << "lt"; break;
478 case 2: O << "le"; break;
479 case 3: O << "unord"; break;
480 case 4: O << "neq"; break;
481 case 5: O << "nlt"; break;
482 case 6: O << "nle"; break;
483 case 7: O << "ord"; break;
487 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
488 const char *Modifier) {
489 const MachineOperand &BaseReg = MI->getOperand(Op);
490 const MachineOperand &IndexReg = MI->getOperand(Op+2);
491 const MachineOperand &DispSpec = MI->getOperand(Op+3);
493 // If we really don't want to print out (rip), don't.
494 bool HasBaseReg = BaseReg.getReg() != 0;
495 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
496 BaseReg.getReg() == X86::RIP)
499 // HasParenPart - True if we will print out the () part of the mem ref.
500 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
502 if (DispSpec.isImm()) {
503 int DispVal = DispSpec.getImm();
504 if (DispVal || !HasParenPart)
507 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
508 DispSpec.isJTI() || DispSpec.isSymbol());
509 printSymbolOperand(MI->getOperand(Op+3));
513 assert(IndexReg.getReg() != X86::ESP &&
514 "X86 doesn't allow scaling by ESP");
518 printOperand(MI, Op, Modifier);
520 if (IndexReg.getReg()) {
522 printOperand(MI, Op+2, Modifier);
523 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
525 O << ',' << ScaleVal;
531 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
532 const char *Modifier) {
533 assert(isMem(MI, Op) && "Invalid memory reference!");
534 const MachineOperand &Segment = MI->getOperand(Op+4);
535 if (Segment.getReg()) {
536 printOperand(MI, Op+4, Modifier);
539 printLeaMemReference(MI, Op, Modifier);
542 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
543 const MachineBasicBlock *MBB) const {
544 if (!MAI->getSetDirective())
547 // We don't need .set machinery if we have GOT-style relocations
548 if (Subtarget->isPICStyleGOT())
551 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
552 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
553 printBasicBlockLabel(MBB, false, false, false);
554 if (Subtarget->isPICStyleRIPRel())
555 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
556 << '_' << uid << '\n';
559 PrintPICBaseSymbol();
565 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
566 PrintPICBaseSymbol();
568 PrintPICBaseSymbol();
572 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
573 const MachineBasicBlock *MBB,
574 unsigned uid) const {
575 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
576 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
578 O << JTEntryDirective << ' ';
580 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
581 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
582 << '_' << uid << "_set_" << MBB->getNumber();
583 } else if (Subtarget->isPICStyleGOT()) {
584 printBasicBlockLabel(MBB, false, false, false);
587 printBasicBlockLabel(MBB, false, false, false);
590 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
591 unsigned Reg = MO.getReg();
593 default: return true; // Unknown mode.
594 case 'b': // Print QImode register
595 Reg = getX86SubSuperRegister(Reg, MVT::i8);
597 case 'h': // Print QImode high register
598 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
600 case 'w': // Print HImode register
601 Reg = getX86SubSuperRegister(Reg, MVT::i16);
603 case 'k': // Print SImode register
604 Reg = getX86SubSuperRegister(Reg, MVT::i32);
606 case 'q': // Print DImode register
607 Reg = getX86SubSuperRegister(Reg, MVT::i64);
611 O << '%'<< TRI->getAsmName(Reg);
615 /// PrintAsmOperand - Print out an operand for an inline asm expression.
617 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
619 const char *ExtraCode) {
620 // Does this asm operand have a single letter operand modifier?
621 if (ExtraCode && ExtraCode[0]) {
622 if (ExtraCode[1] != 0) return true; // Unknown modifier.
624 const MachineOperand &MO = MI->getOperand(OpNo);
626 switch (ExtraCode[0]) {
627 default: return true; // Unknown modifier.
628 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
633 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
634 printSymbolOperand(MO);
639 printOperand(MI, OpNo);
645 case 'c': // Don't print "$" before a global var name or constant.
648 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
649 printSymbolOperand(MO);
651 printOperand(MI, OpNo);
654 case 'A': // Print '*' before a register (it must be a register)
657 printOperand(MI, OpNo);
662 case 'b': // Print QImode register
663 case 'h': // Print QImode high register
664 case 'w': // Print HImode register
665 case 'k': // Print SImode register
666 case 'q': // Print DImode register
668 return printAsmMRegister(MO, ExtraCode[0]);
669 printOperand(MI, OpNo);
672 case 'P': // This is the operand of a call, treat specially.
673 print_pcrel_imm(MI, OpNo);
676 case 'n': // Negate the immediate or print a '-' before the operand.
677 // Note: this is a temporary solution. It should be handled target
678 // independently as part of the 'MC' work.
687 printOperand(MI, OpNo);
691 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
694 const char *ExtraCode) {
695 if (ExtraCode && ExtraCode[0]) {
696 if (ExtraCode[1] != 0) return true; // Unknown modifier.
698 switch (ExtraCode[0]) {
699 default: return true; // Unknown modifier.
700 case 'b': // Print QImode register
701 case 'h': // Print QImode high register
702 case 'w': // Print HImode register
703 case 'k': // Print SImode register
704 case 'q': // Print SImode register
705 // These only apply to registers, ignore on mem.
707 case 'P': // Don't print @PLT, but do print as memory.
708 printMemReference(MI, OpNo, "no-rip");
712 printMemReference(MI, OpNo);
718 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
719 /// AT&T syntax to the current output stream.
721 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
724 processDebugLoc(MI->getDebugLoc());
726 printInstructionThroughMCStreamer(MI);
728 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
733 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
734 const TargetData *TD = TM.getTargetData();
736 if (!GVar->hasInitializer())
737 return; // External global require no code
739 // Check to see if this is a special global used by LLVM, if so, emit it.
740 if (EmitSpecialLLVMGlobal(GVar)) {
741 if (Subtarget->isTargetDarwin() &&
742 TM.getRelocationModel() == Reloc::Static) {
743 if (GVar->getName() == "llvm.global_ctors")
744 O << ".reference .constructors_used\n";
745 else if (GVar->getName() == "llvm.global_dtors")
746 O << ".reference .destructors_used\n";
751 std::string name = Mang->getMangledName(GVar);
752 Constant *C = GVar->getInitializer();
753 const Type *Type = C->getType();
754 unsigned Size = TD->getTypeAllocSize(Type);
755 unsigned Align = TD->getPreferredAlignmentLog(GVar);
757 printVisibility(name, GVar->getVisibility());
759 if (Subtarget->isTargetELF())
760 O << "\t.type\t" << name << ",@object\n";
763 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
764 const MCSection *TheSection =
765 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
766 OutStreamer.SwitchSection(TheSection);
768 // FIXME: get this stuff from section kind flags.
769 if (C->isNullValue() && !GVar->hasSection() &&
770 // Don't put things that should go in the cstring section into "comm".
771 !TheSection->getKind().isMergeableCString()) {
772 if (GVar->hasExternalLinkage()) {
773 if (const char *Directive = MAI->getZeroFillDirective()) {
774 O << "\t.globl " << name << '\n';
775 O << Directive << "__DATA, __common, " << name << ", "
776 << Size << ", " << Align << '\n';
781 if (!GVar->isThreadLocal() &&
782 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
783 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
785 if (MAI->getLCOMMDirective() != NULL) {
786 if (GVar->hasLocalLinkage()) {
787 O << MAI->getLCOMMDirective() << name << ',' << Size;
788 if (Subtarget->isTargetDarwin())
790 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
791 O << "\t.globl " << name << '\n'
792 << MAI->getWeakDefDirective() << name << '\n';
793 EmitAlignment(Align, GVar);
796 O.PadToColumn(MAI->getCommentColumn());
797 O << MAI->getCommentString() << ' ';
798 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
801 EmitGlobalConstant(C);
804 O << MAI->getCOMMDirective() << name << ',' << Size;
805 if (MAI->getCOMMDirectiveTakesAlignment())
806 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
809 if (!Subtarget->isTargetCygMing()) {
810 if (GVar->hasLocalLinkage())
811 O << "\t.local\t" << name << '\n';
813 O << MAI->getCOMMDirective() << name << ',' << Size;
814 if (MAI->getCOMMDirectiveTakesAlignment())
815 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
818 O.PadToColumn(MAI->getCommentColumn());
819 O << MAI->getCommentString() << ' ';
820 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
827 switch (GVar->getLinkage()) {
828 case GlobalValue::CommonLinkage:
829 case GlobalValue::LinkOnceAnyLinkage:
830 case GlobalValue::LinkOnceODRLinkage:
831 case GlobalValue::WeakAnyLinkage:
832 case GlobalValue::WeakODRLinkage:
833 case GlobalValue::LinkerPrivateLinkage:
834 if (Subtarget->isTargetDarwin()) {
835 O << "\t.globl " << name << '\n'
836 << MAI->getWeakDefDirective() << name << '\n';
837 } else if (Subtarget->isTargetCygMing()) {
838 O << "\t.globl\t" << name << "\n"
839 "\t.linkonce same_size\n";
841 O << "\t.weak\t" << name << '\n';
844 case GlobalValue::DLLExportLinkage:
845 case GlobalValue::AppendingLinkage:
846 // FIXME: appending linkage variables should go into a section of
847 // their name or something. For now, just emit them as external.
848 case GlobalValue::ExternalLinkage:
849 // If external or appending, declare as a global symbol
850 O << "\t.globl " << name << '\n';
852 case GlobalValue::PrivateLinkage:
853 case GlobalValue::InternalLinkage:
856 llvm_unreachable("Unknown linkage type!");
859 EmitAlignment(Align, GVar);
862 O.PadToColumn(MAI->getCommentColumn());
863 O << MAI->getCommentString() << ' ';
864 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
868 EmitGlobalConstant(C);
870 if (MAI->hasDotTypeDotSizeDirective())
871 O << "\t.size\t" << name << ", " << Size << '\n';
874 static int SortSymbolPair(const void *LHS, const void *RHS) {
875 MCSymbol *LHSS = ((const std::pair<MCSymbol*, MCSymbol*>*)LHS)->first;
876 MCSymbol *RHSS = ((const std::pair<MCSymbol*, MCSymbol*>*)RHS)->first;
877 return LHSS->getName().compare(RHSS->getName());
880 /// GetSortedStubs - Return the entries from a DenseMap in a deterministic
882 static std::vector<std::pair<MCSymbol*, MCSymbol*> >
883 GetSortedStubs(const DenseMap<MCSymbol*, MCSymbol*> &Map) {
884 assert(!Map.empty());
885 std::vector<std::pair<MCSymbol*, MCSymbol*> > List(Map.begin(), Map.end());
886 qsort(&List[0], List.size(), sizeof(List[0]), SortSymbolPair);
890 bool X86ATTAsmPrinter::doFinalization(Module &M) {
891 // Print out module-level global variables here.
892 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
894 if (I->hasDLLExportLinkage())
895 DLLExportedGVs.insert(Mang->getMangledName(I));
898 if (Subtarget->isTargetDarwin()) {
899 // All darwin targets use mach-o.
900 TargetLoweringObjectFileMachO &TLOFMacho =
901 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
903 // Add the (possibly multiple) personalities to the set of global value
904 // stubs. Only referenced functions get into the Personalities list.
905 if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
906 const std::vector<Function*> &Personalities = MMI->getPersonalities();
907 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
908 if (Personalities[i] == 0)
911 SmallString<128> Name;
912 Mang->getNameWithPrefix(Name, Personalities[i], true /*private label*/);
913 Name += "$non_lazy_ptr";
914 MCSymbol *NLPName = OutContext.GetOrCreateSymbol(Name.str());
916 MCSymbol *&StubName = GVStubs[NLPName];
917 if (StubName != 0) continue;
921 Mang->getNameWithPrefix(Name, Personalities[i], false);
922 StubName = OutContext.GetOrCreateSymbol(Name.str());
926 // Output stubs for dynamically-linked functions
927 if (!FnStubs.empty()) {
928 const MCSection *TheSection =
929 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
930 MCSectionMachO::S_SYMBOL_STUBS |
931 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
932 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
933 5, SectionKind::getMetadata());
934 OutStreamer.SwitchSection(TheSection);
936 std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
937 = GetSortedStubs(FnStubs);
938 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
939 Stubs[i].first->print(O, MAI);
940 O << ":\n" << "\t.indirect_symbol ";
941 // Get the MCSymbol without the $stub suffix.
942 Stubs[i].second->print(O, MAI);
943 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
948 // Output stubs for external and common global variables.
949 if (!GVStubs.empty()) {
950 const MCSection *TheSection =
951 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
952 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
953 SectionKind::getMetadata());
954 OutStreamer.SwitchSection(TheSection);
956 std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
957 = GetSortedStubs(GVStubs);
958 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
959 Stubs[i].first->print(O, MAI);
960 O << ":\n\t.indirect_symbol ";
961 Stubs[i].second->print(O, MAI);
962 O << "\n\t.long\t0\n";
966 if (!HiddenGVStubs.empty()) {
967 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
970 std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
971 = GetSortedStubs(HiddenGVStubs);
972 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
973 Stubs[i].first->print(O, MAI);
974 O << ":\n" << MAI->getData32bitsDirective();
975 Stubs[i].second->print(O, MAI);
980 // Funny Darwin hack: This flag tells the linker that no global symbols
981 // contain code that falls through to other global symbols (e.g. the obvious
982 // implementation of multiple entry points). If this doesn't occur, the
983 // linker can safely perform dead code stripping. Since LLVM never
984 // generates code that does this, it is always safe to set.
985 O << "\t.subsections_via_symbols\n";
986 } else if (Subtarget->isTargetCygMing()) {
987 // Emit type information for external functions
988 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
990 O << "\t.def\t " << i->getKeyData()
991 << ";\t.scl\t" << COFF::C_EXT
992 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
998 // Output linker support code for dllexported globals on windows.
999 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
1000 // dllexport symbols only exist on coff targets.
1001 TargetLoweringObjectFileCOFF &TLOFMacho =
1002 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
1004 OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
1005 SectionKind::getMetadata()));
1007 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1008 e = DLLExportedGVs.end(); i != e; ++i)
1009 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1011 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1012 e = DLLExportedFns.end();
1014 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1017 // Do common shutdown.
1018 return AsmPrinter::doFinalization(M);