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/ErrorHandling.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/Mangler.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Target/TargetOptions.h"
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
48 //===----------------------------------------------------------------------===//
49 // Primitive Helper Functions.
50 //===----------------------------------------------------------------------===//
52 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
53 if (Subtarget->isTargetDarwin())
54 O << "\"L" << getFunctionNumber() << "$pb\"";
55 else if (Subtarget->isTargetELF())
56 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
58 llvm_unreachable("Don't know how to print PIC label!");
61 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
62 /// Don't print things like \\n or \\0.
63 static void PrintUnmangledNameSafely(const Value *V,
64 formatted_raw_ostream &OS) {
65 for (StringRef::iterator it = V->getName().begin(),
66 ie = V->getName().end(); it != ie; ++it)
71 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
72 const TargetData *TD) {
73 X86MachineFunctionInfo Info;
76 switch (F->getCallingConv()) {
77 case CallingConv::X86_StdCall:
78 Info.setDecorationStyle(StdCall);
80 case CallingConv::X86_FastCall:
81 Info.setDecorationStyle(FastCall);
88 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
89 AI != AE; ++AI, ++argNum) {
90 const Type* Ty = AI->getType();
92 // 'Dereference' type in case of byval parameter attribute
93 if (F->paramHasAttr(argNum, Attribute::ByVal))
94 Ty = cast<PointerType>(Ty)->getElementType();
96 // Size should be aligned to DWORD boundary
97 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
100 // We're not supporting tooooo huge arguments :)
101 Info.setBytesToPopOnReturn((unsigned int)Size);
105 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
106 /// various name decorations for Cygwin and MingW.
107 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
108 const GlobalValue *GV) {
109 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
111 const Function *F = dyn_cast<Function>(GV);
114 // Save function name for later type emission.
115 if (F->isDeclaration())
116 CygMingStubs.insert(Name);
118 // We don't want to decorate non-stdcall or non-fastcall functions right now
119 unsigned CC = F->getCallingConv();
120 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
124 const X86MachineFunctionInfo *Info;
126 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
127 if (info_item == FunctionInfoMap.end()) {
128 // Calculate apropriate function info and populate map
129 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
130 Info = &FunctionInfoMap[F];
132 Info = &info_item->second;
135 const FunctionType *FT = F->getFunctionType();
136 switch (Info->getDecorationStyle()) {
140 // "Pure" variadic functions do not receive @0 suffix.
141 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
142 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
143 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
146 // "Pure" variadic functions do not receive @0 suffix.
147 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
148 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
149 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
151 if (Name[0] == '_') {
158 llvm_unreachable("Unsupported DecorationStyle");
162 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
163 unsigned FnAlign = MF.getAlignment();
164 const Function *F = MF.getFunction();
166 if (Subtarget->isTargetCygMing())
167 DecorateCygMingName(CurrentFnName, F);
169 SwitchToSection(TAI->SectionForGlobal(F));
170 switch (F->getLinkage()) {
171 default: llvm_unreachable("Unknown linkage type!");
172 case Function::InternalLinkage: // Symbols default to internal.
173 case Function::PrivateLinkage:
174 case Function::LinkerPrivateLinkage:
175 EmitAlignment(FnAlign, F);
177 case Function::DLLExportLinkage:
178 case Function::ExternalLinkage:
179 EmitAlignment(FnAlign, F);
180 O << "\t.globl\t" << CurrentFnName << '\n';
182 case Function::LinkOnceAnyLinkage:
183 case Function::LinkOnceODRLinkage:
184 case Function::WeakAnyLinkage:
185 case Function::WeakODRLinkage:
186 EmitAlignment(FnAlign, F);
187 if (Subtarget->isTargetDarwin()) {
188 O << "\t.globl\t" << CurrentFnName << '\n';
189 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
190 } else if (Subtarget->isTargetCygMing()) {
191 O << "\t.globl\t" << CurrentFnName << "\n"
192 "\t.linkonce discard\n";
194 O << "\t.weak\t" << CurrentFnName << '\n';
199 printVisibility(CurrentFnName, F->getVisibility());
201 if (Subtarget->isTargetELF())
202 O << "\t.type\t" << CurrentFnName << ",@function\n";
203 else if (Subtarget->isTargetCygMing()) {
204 O << "\t.def\t " << CurrentFnName
206 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
207 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
211 O << CurrentFnName << ":\n";
212 // Add some workaround for linkonce linkage on Cygwin\MinGW
213 if (Subtarget->isTargetCygMing() &&
214 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
215 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
218 /// runOnMachineFunction - This uses the printMachineInstruction()
219 /// method to print assembly for each instruction.
221 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
222 const Function *F = MF.getFunction();
224 unsigned CC = F->getCallingConv();
226 SetupMachineFunction(MF);
229 // Populate function information map. Actually, We don't want to populate
230 // non-stdcall or non-fastcall functions' information right now.
231 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
232 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
234 // Print out constants referenced by the function
235 EmitConstantPool(MF.getConstantPool());
237 if (F->hasDLLExportLinkage())
238 DLLExportedFns.insert(Mang->getMangledName(F));
240 // Print the 'header' of function
241 emitFunctionHeader(MF);
243 // Emit pre-function debug and/or EH information.
244 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
245 DW->BeginFunction(&MF);
247 // Print out code for the function.
248 bool hasAnyRealCode = false;
249 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
251 // Print a label for the basic block.
252 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
253 // This is an entry block or a block that's only reachable via a
254 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
256 printBasicBlockLabel(I, true, true, VerboseAsm);
259 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
261 // Print the assembly for the instruction.
263 hasAnyRealCode = true;
264 printMachineInstruction(II);
268 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
269 // If the function is empty, then we need to emit *something*. Otherwise,
270 // the function's label might be associated with something that it wasn't
271 // meant to be associated with. We emit a noop in this situation.
272 // We are assuming inline asms are code.
276 if (TAI->hasDotTypeDotSizeDirective())
277 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
279 // Emit post-function debug information.
280 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
281 DW->EndFunction(&MF);
283 // Print out jump tables referenced by the function.
284 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
288 // We didn't modify anything.
292 /// printSymbolOperand - Print a raw symbol reference operand. This handles
293 /// jump tables, constant pools, global address and external symbols, all of
294 /// which print to a label with various suffixes for relocation types etc.
295 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
296 switch (MO.getType()) {
297 default: llvm_unreachable("unknown symbol type!");
298 case MachineOperand::MO_JumpTableIndex:
299 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
302 case MachineOperand::MO_ConstantPoolIndex:
303 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
305 printOffset(MO.getOffset());
307 case MachineOperand::MO_GlobalAddress: {
308 const GlobalValue *GV = MO.getGlobal();
310 const char *Suffix = "";
311 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
313 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
314 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
315 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
316 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
317 Suffix = "$non_lazy_ptr";
319 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
320 if (Subtarget->isTargetCygMing())
321 DecorateCygMingName(Name, GV);
323 // Handle dllimport linkage.
324 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
325 Name = "__imp_" + Name;
327 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
328 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
329 GVStubs[Name] = Mang->getMangledName(GV);
330 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
331 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
332 HiddenGVStubs[Name] = Mang->getMangledName(GV);
333 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
334 FnStubs[Name] = Mang->getMangledName(GV);
336 // If the name begins with a dollar-sign, enclose it in parens. We do this
337 // to avoid having it look like an integer immediate to the assembler.
339 O << '(' << Name << ')';
343 printOffset(MO.getOffset());
346 case MachineOperand::MO_ExternalSymbol: {
347 std::string Name = Mang->makeNameProper(MO.getSymbolName());
348 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
349 FnStubs[Name+"$stub"] = Name;
353 // If the name begins with a dollar-sign, enclose it in parens. We do this
354 // to avoid having it look like an integer immediate to the assembler.
356 O << '(' << Name << ')';
363 switch (MO.getTargetFlags()) {
365 llvm_unreachable("Unknown target flag on GV operand");
366 case X86II::MO_NO_FLAG: // No flag.
368 case X86II::MO_DARWIN_NONLAZY:
369 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
370 case X86II::MO_DLLIMPORT:
371 case X86II::MO_DARWIN_STUB:
372 // These affect the name of the symbol, not any suffix.
374 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
376 PrintPICBaseSymbol();
379 case X86II::MO_PIC_BASE_OFFSET:
380 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
381 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
383 PrintPICBaseSymbol();
385 case X86II::MO_TLSGD: O << "@TLSGD"; break;
386 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
387 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
388 case X86II::MO_TPOFF: O << "@TPOFF"; break;
389 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
390 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
391 case X86II::MO_GOT: O << "@GOT"; break;
392 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
393 case X86II::MO_PLT: O << "@PLT"; break;
397 /// print_pcrel_imm - This is used to print an immediate value that ends up
398 /// being encoded as a pc-relative value. These print slightly differently, for
399 /// example, a $ is not emitted.
400 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
401 const MachineOperand &MO = MI->getOperand(OpNo);
402 switch (MO.getType()) {
403 default: llvm_unreachable("Unknown pcrel immediate operand");
404 case MachineOperand::MO_Immediate:
407 case MachineOperand::MO_MachineBasicBlock:
408 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
410 case MachineOperand::MO_GlobalAddress:
411 case MachineOperand::MO_ExternalSymbol:
412 printSymbolOperand(MO);
419 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
420 const char *Modifier) {
421 const MachineOperand &MO = MI->getOperand(OpNo);
422 switch (MO.getType()) {
423 default: llvm_unreachable("unknown operand type!");
424 case MachineOperand::MO_Register: {
425 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
426 "Virtual registers should not make it this far!");
428 unsigned Reg = MO.getReg();
429 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
430 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
431 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
432 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
433 Reg = getX86SubSuperRegister(Reg, VT);
435 O << TRI->getAsmName(Reg);
439 case MachineOperand::MO_Immediate:
440 O << '$' << MO.getImm();
443 case MachineOperand::MO_JumpTableIndex:
444 case MachineOperand::MO_ConstantPoolIndex:
445 case MachineOperand::MO_GlobalAddress:
446 case MachineOperand::MO_ExternalSymbol: {
448 printSymbolOperand(MO);
454 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
455 unsigned char value = MI->getOperand(Op).getImm();
456 assert(value <= 7 && "Invalid ssecc argument!");
458 case 0: O << "eq"; break;
459 case 1: O << "lt"; break;
460 case 2: O << "le"; break;
461 case 3: O << "unord"; break;
462 case 4: O << "neq"; break;
463 case 5: O << "nlt"; break;
464 case 6: O << "nle"; break;
465 case 7: O << "ord"; break;
469 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
470 const char *Modifier) {
471 const MachineOperand &BaseReg = MI->getOperand(Op);
472 const MachineOperand &IndexReg = MI->getOperand(Op+2);
473 const MachineOperand &DispSpec = MI->getOperand(Op+3);
475 // If we really don't want to print out (rip), don't.
476 bool HasBaseReg = BaseReg.getReg() != 0;
477 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
478 BaseReg.getReg() == X86::RIP)
481 // HasParenPart - True if we will print out the () part of the mem ref.
482 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
484 if (DispSpec.isImm()) {
485 int DispVal = DispSpec.getImm();
486 if (DispVal || !HasParenPart)
489 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
490 DispSpec.isJTI() || DispSpec.isSymbol());
491 printSymbolOperand(MI->getOperand(Op+3));
495 assert(IndexReg.getReg() != X86::ESP &&
496 "X86 doesn't allow scaling by ESP");
500 printOperand(MI, Op, Modifier);
502 if (IndexReg.getReg()) {
504 printOperand(MI, Op+2, Modifier);
505 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
507 O << ',' << ScaleVal;
513 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
514 const char *Modifier) {
515 assert(isMem(MI, Op) && "Invalid memory reference!");
516 const MachineOperand &Segment = MI->getOperand(Op+4);
517 if (Segment.getReg()) {
518 printOperand(MI, Op+4, Modifier);
521 printLeaMemReference(MI, Op, Modifier);
524 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
525 const MachineBasicBlock *MBB) const {
526 if (!TAI->getSetDirective())
529 // We don't need .set machinery if we have GOT-style relocations
530 if (Subtarget->isPICStyleGOT())
533 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
534 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
535 printBasicBlockLabel(MBB, false, false, false);
536 if (Subtarget->isPICStyleRIPRel())
537 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
538 << '_' << uid << '\n';
541 PrintPICBaseSymbol();
547 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
548 PrintPICBaseSymbol();
550 PrintPICBaseSymbol();
555 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
556 const MachineBasicBlock *MBB,
557 unsigned uid) const {
558 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
559 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
561 O << JTEntryDirective << ' ';
563 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
564 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
565 << '_' << uid << "_set_" << MBB->getNumber();
566 } else if (Subtarget->isPICStyleGOT()) {
567 printBasicBlockLabel(MBB, false, false, false);
570 printBasicBlockLabel(MBB, false, false, false);
573 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
574 unsigned Reg = MO.getReg();
576 default: return true; // Unknown mode.
577 case 'b': // Print QImode register
578 Reg = getX86SubSuperRegister(Reg, MVT::i8);
580 case 'h': // Print QImode high register
581 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
583 case 'w': // Print HImode register
584 Reg = getX86SubSuperRegister(Reg, MVT::i16);
586 case 'k': // Print SImode register
587 Reg = getX86SubSuperRegister(Reg, MVT::i32);
589 case 'q': // Print DImode register
590 Reg = getX86SubSuperRegister(Reg, MVT::i64);
594 O << '%'<< TRI->getAsmName(Reg);
598 /// PrintAsmOperand - Print out an operand for an inline asm expression.
600 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
602 const char *ExtraCode) {
603 // Does this asm operand have a single letter operand modifier?
604 if (ExtraCode && ExtraCode[0]) {
605 if (ExtraCode[1] != 0) return true; // Unknown modifier.
607 const MachineOperand &MO = MI->getOperand(OpNo);
609 switch (ExtraCode[0]) {
610 default: return true; // Unknown modifier.
611 case 'c': // Don't print "$" before a global var name or constant.
614 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
615 printSymbolOperand(MO);
617 printOperand(MI, OpNo);
620 case 'A': // Print '*' before a register (it must be a register)
623 printOperand(MI, OpNo);
628 case 'b': // Print QImode register
629 case 'h': // Print QImode high register
630 case 'w': // Print HImode register
631 case 'k': // Print SImode register
632 case 'q': // Print DImode register
634 return printAsmMRegister(MO, ExtraCode[0]);
635 printOperand(MI, OpNo);
638 case 'P': // This is the operand of a call, treat specially.
639 print_pcrel_imm(MI, OpNo);
642 case 'n': // Negate the immediate or print a '-' before the operand.
643 // Note: this is a temporary solution. It should be handled target
644 // independently as part of the 'MC' work.
653 printOperand(MI, OpNo);
657 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
660 const char *ExtraCode) {
661 if (ExtraCode && ExtraCode[0]) {
662 if (ExtraCode[1] != 0) return true; // Unknown modifier.
664 switch (ExtraCode[0]) {
665 default: return true; // Unknown modifier.
666 case 'b': // Print QImode register
667 case 'h': // Print QImode high register
668 case 'w': // Print HImode register
669 case 'k': // Print SImode register
670 case 'q': // Print SImode register
671 // These only apply to registers, ignore on mem.
673 case 'P': // Don't print @PLT, but do print as memory.
674 printMemReference(MI, OpNo, "no-rip");
678 printMemReference(MI, OpNo);
682 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
683 // Convert registers in the addr mode according to subreg64.
684 for (unsigned i = 0; i != 4; ++i) {
685 if (!MI->getOperand(i).isReg()) continue;
687 unsigned Reg = MI->getOperand(i).getReg();
688 if (Reg == 0) continue;
690 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
694 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
695 /// AT&T syntax to the current output stream.
697 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
701 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
705 } else if (MI->isLabel()) {
708 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
711 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
712 printImplicitDef(MI);
719 TmpInst.setOpcode(MI->getOpcode());
721 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
722 const MachineOperand &MO = MI->getOperand(i);
726 MCOp.MakeReg(MO.getReg());
727 } else if (MO.isImm()) {
728 MCOp.MakeImm(MO.getImm());
729 } else if (MO.isMBB()) {
730 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
732 llvm_unreachable("Unimp");
735 TmpInst.addOperand(MCOp);
738 switch (TmpInst.getOpcode()) {
740 // Handle the 'subreg rewriting' for the lea64_32mem operand.
741 lower_lea64_32mem(&TmpInst, 1);
745 // FIXME: Convert TmpInst.
746 printInstruction(&TmpInst);
750 // Call the autogenerated instruction printer routines.
751 printInstruction(MI);
755 bool X86ATTAsmPrinter::doInitialization(Module &M) {
757 Context = new MCContext();
758 // FIXME: Send this to "O" instead of outs(). For now, we force it to
759 // stdout to make it easy to compare.
760 Streamer = createAsmStreamer(*Context, outs());
763 return AsmPrinter::doInitialization(M);
766 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
767 const TargetData *TD = TM.getTargetData();
769 if (!GVar->hasInitializer())
770 return; // External global require no code
772 // Check to see if this is a special global used by LLVM, if so, emit it.
773 if (EmitSpecialLLVMGlobal(GVar)) {
774 if (Subtarget->isTargetDarwin() &&
775 TM.getRelocationModel() == Reloc::Static) {
776 if (GVar->getName() == "llvm.global_ctors")
777 O << ".reference .constructors_used\n";
778 else if (GVar->getName() == "llvm.global_dtors")
779 O << ".reference .destructors_used\n";
784 std::string name = Mang->getMangledName(GVar);
785 Constant *C = GVar->getInitializer();
786 if (isa<MDNode>(C) || isa<MDString>(C))
788 const Type *Type = C->getType();
789 unsigned Size = TD->getTypeAllocSize(Type);
790 unsigned Align = TD->getPreferredAlignmentLog(GVar);
792 printVisibility(name, GVar->getVisibility());
794 if (Subtarget->isTargetELF())
795 O << "\t.type\t" << name << ",@object\n";
797 const Section *TheSection = TAI->SectionForGlobal(GVar);
798 SwitchToSection(TheSection);
800 if (C->isNullValue() && !GVar->hasSection() &&
801 // Don't put things that should go in the cstring section into "comm".
802 !TheSection->hasFlag(SectionFlags::Strings)) {
803 if (GVar->hasExternalLinkage()) {
804 if (const char *Directive = TAI->getZeroFillDirective()) {
805 O << "\t.globl " << name << '\n';
806 O << Directive << "__DATA, __common, " << name << ", "
807 << Size << ", " << Align << '\n';
812 if (!GVar->isThreadLocal() &&
813 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
814 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
816 if (TAI->getLCOMMDirective() != NULL) {
817 if (GVar->hasLocalLinkage()) {
818 O << TAI->getLCOMMDirective() << name << ',' << Size;
819 if (Subtarget->isTargetDarwin())
821 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
822 O << "\t.globl " << name << '\n'
823 << TAI->getWeakDefDirective() << name << '\n';
824 EmitAlignment(Align, GVar);
827 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
828 PrintUnmangledNameSafely(GVar, O);
831 EmitGlobalConstant(C);
834 O << TAI->getCOMMDirective() << name << ',' << Size;
835 if (TAI->getCOMMDirectiveTakesAlignment())
836 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
839 if (!Subtarget->isTargetCygMing()) {
840 if (GVar->hasLocalLinkage())
841 O << "\t.local\t" << name << '\n';
843 O << TAI->getCOMMDirective() << name << ',' << Size;
844 if (TAI->getCOMMDirectiveTakesAlignment())
845 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
848 O << "\t\t" << TAI->getCommentString() << ' ';
849 PrintUnmangledNameSafely(GVar, O);
856 switch (GVar->getLinkage()) {
857 case GlobalValue::CommonLinkage:
858 case GlobalValue::LinkOnceAnyLinkage:
859 case GlobalValue::LinkOnceODRLinkage:
860 case GlobalValue::WeakAnyLinkage:
861 case GlobalValue::WeakODRLinkage:
862 if (Subtarget->isTargetDarwin()) {
863 O << "\t.globl " << name << '\n'
864 << TAI->getWeakDefDirective() << name << '\n';
865 } else if (Subtarget->isTargetCygMing()) {
866 O << "\t.globl\t" << name << "\n"
867 "\t.linkonce same_size\n";
869 O << "\t.weak\t" << name << '\n';
872 case GlobalValue::DLLExportLinkage:
873 case GlobalValue::AppendingLinkage:
874 // FIXME: appending linkage variables should go into a section of
875 // their name or something. For now, just emit them as external.
876 case GlobalValue::ExternalLinkage:
877 // If external or appending, declare as a global symbol
878 O << "\t.globl " << name << '\n';
880 case GlobalValue::PrivateLinkage:
881 case GlobalValue::LinkerPrivateLinkage:
882 case GlobalValue::InternalLinkage:
885 llvm_unreachable("Unknown linkage type!");
888 EmitAlignment(Align, GVar);
891 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
892 PrintUnmangledNameSafely(GVar, O);
895 if (TAI->hasDotTypeDotSizeDirective())
896 O << "\t.size\t" << name << ", " << Size << '\n';
898 EmitGlobalConstant(C);
901 bool X86ATTAsmPrinter::doFinalization(Module &M) {
902 // Print out module-level global variables here.
903 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
905 if (I->hasDLLExportLinkage())
906 DLLExportedGVs.insert(Mang->getMangledName(I));
909 if (Subtarget->isTargetDarwin()) {
910 SwitchToDataSection("");
912 // Add the (possibly multiple) personalities to the set of global value
913 // stubs. Only referenced functions get into the Personalities list.
914 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
915 const std::vector<Function*> &Personalities = MMI->getPersonalities();
916 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
917 if (Personalities[i])
918 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
919 true /*private label*/)] =
920 Mang->getMangledName(Personalities[i]);
924 // Output stubs for dynamically-linked functions
925 if (!FnStubs.empty()) {
926 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
927 "self_modifying_code+pure_instructions,5", 0);
928 for (StringMap<std::string>::iterator I = FnStubs.begin(),
929 E = FnStubs.end(); I != E; ++I)
930 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
931 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
935 // Output stubs for external and common global variables.
936 if (!GVStubs.empty()) {
938 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
939 for (StringMap<std::string>::iterator I = GVStubs.begin(),
940 E = GVStubs.end(); I != E; ++I)
941 O << I->getKeyData() << ":\n\t.indirect_symbol "
942 << I->second << "\n\t.long\t0\n";
945 if (!HiddenGVStubs.empty()) {
946 SwitchToSection(TAI->getDataSection());
948 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
949 E = HiddenGVStubs.end(); I != E; ++I)
950 O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
951 << I->second << '\n';
954 // Funny Darwin hack: This flag tells the linker that no global symbols
955 // contain code that falls through to other global symbols (e.g. the obvious
956 // implementation of multiple entry points). If this doesn't occur, the
957 // linker can safely perform dead code stripping. Since LLVM never
958 // generates code that does this, it is always safe to set.
959 O << "\t.subsections_via_symbols\n";
960 } else if (Subtarget->isTargetCygMing()) {
961 // Emit type information for external functions
962 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
964 O << "\t.def\t " << i->getKeyData()
965 << ";\t.scl\t" << COFF::C_EXT
966 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
972 // Output linker support code for dllexported globals on windows.
973 if (!DLLExportedGVs.empty()) {
974 SwitchToDataSection(".section .drectve");
976 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
977 e = DLLExportedGVs.end(); i != e; ++i)
978 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
981 if (!DLLExportedFns.empty()) {
982 SwitchToDataSection(".section .drectve");
984 for (StringSet<>::iterator i = DLLExportedFns.begin(),
985 e = DLLExportedFns.end();
987 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
990 // Do common shutdown.
991 bool Changed = AsmPrinter::doFinalization(M);
1005 // Include the auto-generated portion of the assembly writer.
1006 #include "X86GenAsmWriter.inc"