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/Mangler.h"
38 #include "llvm/Support/raw_ostream.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, raw_ostream &OS) {
64 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
70 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
71 const TargetData *TD) {
72 X86MachineFunctionInfo Info;
75 switch (F->getCallingConv()) {
76 case CallingConv::X86_StdCall:
77 Info.setDecorationStyle(StdCall);
79 case CallingConv::X86_FastCall:
80 Info.setDecorationStyle(FastCall);
87 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
88 AI != AE; ++AI, ++argNum) {
89 const Type* Ty = AI->getType();
91 // 'Dereference' type in case of byval parameter attribute
92 if (F->paramHasAttr(argNum, Attribute::ByVal))
93 Ty = cast<PointerType>(Ty)->getElementType();
95 // Size should be aligned to DWORD boundary
96 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
99 // We're not supporting tooooo huge arguments :)
100 Info.setBytesToPopOnReturn((unsigned int)Size);
104 /// decorateName - Query FunctionInfoMap and use this information for various
106 void X86ATTAsmPrinter::decorateName(std::string &Name,
107 const GlobalValue *GV) {
108 const Function *F = dyn_cast<Function>(GV);
111 // Save function name for later type emission.
112 if (Subtarget->isTargetCygMing() && F->isDeclaration())
113 CygMingStubs.insert(Name);
115 // We don't want to decorate non-stdcall or non-fastcall functions right now
116 unsigned CC = F->getCallingConv();
117 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
120 // Decorate names only when we're targeting Cygwin/Mingw32 targets
121 if (!Subtarget->isTargetCygMing())
124 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
126 const X86MachineFunctionInfo *Info;
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 decorateName(CurrentFnName, F);
168 SwitchToSection(TAI->SectionForGlobal(F));
169 switch (F->getLinkage()) {
170 default: llvm_unreachable("Unknown linkage type!");
171 case Function::InternalLinkage: // Symbols default to internal.
172 case Function::PrivateLinkage:
173 EmitAlignment(FnAlign, F);
175 case Function::DLLExportLinkage:
176 case Function::ExternalLinkage:
177 EmitAlignment(FnAlign, F);
178 O << "\t.globl\t" << CurrentFnName << '\n';
180 case Function::LinkOnceAnyLinkage:
181 case Function::LinkOnceODRLinkage:
182 case Function::WeakAnyLinkage:
183 case Function::WeakODRLinkage:
184 EmitAlignment(FnAlign, F);
185 if (Subtarget->isTargetDarwin()) {
186 O << "\t.globl\t" << CurrentFnName << '\n';
187 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
188 } else if (Subtarget->isTargetCygMing()) {
189 O << "\t.globl\t" << CurrentFnName << "\n"
190 "\t.linkonce discard\n";
192 O << "\t.weak\t" << CurrentFnName << '\n';
197 printVisibility(CurrentFnName, F->getVisibility());
199 if (Subtarget->isTargetELF())
200 O << "\t.type\t" << CurrentFnName << ",@function\n";
201 else if (Subtarget->isTargetCygMing()) {
202 O << "\t.def\t " << CurrentFnName
204 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
205 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
209 O << CurrentFnName << ":\n";
210 // Add some workaround for linkonce linkage on Cygwin\MinGW
211 if (Subtarget->isTargetCygMing() &&
212 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
213 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
216 /// runOnMachineFunction - This uses the printMachineInstruction()
217 /// method to print assembly for each instruction.
219 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
220 const Function *F = MF.getFunction();
222 unsigned CC = F->getCallingConv();
224 SetupMachineFunction(MF);
227 // Populate function information map. Actually, We don't want to populate
228 // non-stdcall or non-fastcall functions' information right now.
229 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
230 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
232 // Print out constants referenced by the function
233 EmitConstantPool(MF.getConstantPool());
235 if (F->hasDLLExportLinkage())
236 DLLExportedFns.insert(Mang->getMangledName(F));
238 // Print the 'header' of function
239 emitFunctionHeader(MF);
241 // Emit pre-function debug and/or EH information.
242 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
243 DW->BeginFunction(&MF);
245 // Print out code for the function.
246 bool hasAnyRealCode = false;
247 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
249 // Print a label for the basic block.
250 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
251 // This is an entry block or a block that's only reachable via a
252 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
254 printBasicBlockLabel(I, true, true, VerboseAsm);
257 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
259 // Print the assembly for the instruction.
261 hasAnyRealCode = true;
262 printMachineInstruction(II);
266 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
267 // If the function is empty, then we need to emit *something*. Otherwise,
268 // the function's label might be associated with something that it wasn't
269 // meant to be associated with. We emit a noop in this situation.
270 // We are assuming inline asms are code.
274 if (TAI->hasDotTypeDotSizeDirective())
275 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
277 // Emit post-function debug information.
278 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
279 DW->EndFunction(&MF);
281 // Print out jump tables referenced by the function.
282 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
286 // We didn't modify anything.
290 /// printSymbolOperand - Print a raw symbol reference operand. This handles
291 /// jump tables, constant pools, global address and external symbols, all of
292 /// which print to a label with various suffixes for relocation types etc.
293 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
294 switch (MO.getType()) {
295 default: llvm_unreachable("unknown symbol type!");
296 case MachineOperand::MO_JumpTableIndex:
297 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
300 case MachineOperand::MO_ConstantPoolIndex:
301 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
303 printOffset(MO.getOffset());
305 case MachineOperand::MO_GlobalAddress: {
306 const GlobalValue *GV = MO.getGlobal();
308 const char *Suffix = "";
310 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
312 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
313 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
314 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
315 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
316 Suffix = "$non_lazy_ptr";
318 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
319 decorateName(Name, GV);
321 // Handle dllimport linkage.
322 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
323 Name = "__imp_" + Name;
325 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
326 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
327 GVStubs[Name] = Mang->getMangledName(GV);
328 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
329 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
330 HiddenGVStubs[Name] = Mang->getMangledName(GV);
331 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
332 FnStubs[Name] = Mang->getMangledName(GV);
334 // If the name begins with a dollar-sign, enclose it in parens. We do this
335 // to avoid having it look like an integer immediate to the assembler.
337 O << '(' << Name << ')';
341 printOffset(MO.getOffset());
344 case MachineOperand::MO_ExternalSymbol: {
345 std::string Name(TAI->getGlobalPrefix());
346 Name += 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 printSymbolOperand(MO);
413 case MachineOperand::MO_ExternalSymbol:
414 printSymbolOperand(MO);
421 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
422 const char *Modifier) {
423 const MachineOperand &MO = MI->getOperand(OpNo);
424 switch (MO.getType()) {
425 default: llvm_unreachable("unknown operand type!");
426 case MachineOperand::MO_Register: {
427 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
428 "Virtual registers should not make it this far!");
430 unsigned Reg = MO.getReg();
431 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
432 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
433 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
434 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
435 Reg = getX86SubSuperRegister(Reg, VT);
437 O << TRI->getAsmName(Reg);
441 case MachineOperand::MO_Immediate:
442 O << '$' << MO.getImm();
445 case MachineOperand::MO_JumpTableIndex:
446 case MachineOperand::MO_ConstantPoolIndex:
447 case MachineOperand::MO_GlobalAddress:
448 case MachineOperand::MO_ExternalSymbol: {
450 printSymbolOperand(MO);
456 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
457 unsigned char value = MI->getOperand(Op).getImm();
458 assert(value <= 7 && "Invalid ssecc argument!");
460 case 0: O << "eq"; break;
461 case 1: O << "lt"; break;
462 case 2: O << "le"; break;
463 case 3: O << "unord"; break;
464 case 4: O << "neq"; break;
465 case 5: O << "nlt"; break;
466 case 6: O << "nle"; break;
467 case 7: O << "ord"; break;
471 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
472 const char *Modifier) {
473 const MachineOperand &BaseReg = MI->getOperand(Op);
474 const MachineOperand &IndexReg = MI->getOperand(Op+2);
475 const MachineOperand &DispSpec = MI->getOperand(Op+3);
477 // If we really don't want to print out (rip), don't.
478 bool HasBaseReg = BaseReg.getReg() != 0;
479 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
480 BaseReg.getReg() == X86::RIP)
483 // HasParenPart - True if we will print out the () part of the mem ref.
484 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
486 if (DispSpec.isImm()) {
487 int DispVal = DispSpec.getImm();
488 if (DispVal || !HasParenPart)
491 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
492 DispSpec.isJTI() || DispSpec.isSymbol());
493 printSymbolOperand(MI->getOperand(Op+3));
497 assert(IndexReg.getReg() != X86::ESP &&
498 "X86 doesn't allow scaling by ESP");
502 printOperand(MI, Op, Modifier);
504 if (IndexReg.getReg()) {
506 printOperand(MI, Op+2, Modifier);
507 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
509 O << ',' << ScaleVal;
515 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
516 const char *Modifier) {
517 assert(isMem(MI, Op) && "Invalid memory reference!");
518 const MachineOperand &Segment = MI->getOperand(Op+4);
519 if (Segment.getReg()) {
520 printOperand(MI, Op+4, Modifier);
523 printLeaMemReference(MI, Op, Modifier);
526 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
527 const MachineBasicBlock *MBB) const {
528 if (!TAI->getSetDirective())
531 // We don't need .set machinery if we have GOT-style relocations
532 if (Subtarget->isPICStyleGOT())
535 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
536 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
537 printBasicBlockLabel(MBB, false, false, false);
538 if (Subtarget->isPICStyleRIPRel())
539 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
540 << '_' << uid << '\n';
543 PrintPICBaseSymbol();
549 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
550 PrintPICBaseSymbol();
552 PrintPICBaseSymbol();
557 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
558 const MachineBasicBlock *MBB,
559 unsigned uid) const {
560 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
561 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
563 O << JTEntryDirective << ' ';
565 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
566 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
567 << '_' << uid << "_set_" << MBB->getNumber();
568 } else if (Subtarget->isPICStyleGOT()) {
569 printBasicBlockLabel(MBB, false, false, false);
572 printBasicBlockLabel(MBB, false, false, false);
575 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
576 unsigned Reg = MO.getReg();
578 default: return true; // Unknown mode.
579 case 'b': // Print QImode register
580 Reg = getX86SubSuperRegister(Reg, MVT::i8);
582 case 'h': // Print QImode high register
583 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
585 case 'w': // Print HImode register
586 Reg = getX86SubSuperRegister(Reg, MVT::i16);
588 case 'k': // Print SImode register
589 Reg = getX86SubSuperRegister(Reg, MVT::i32);
591 case 'q': // Print DImode register
592 Reg = getX86SubSuperRegister(Reg, MVT::i64);
596 O << '%'<< TRI->getAsmName(Reg);
600 /// PrintAsmOperand - Print out an operand for an inline asm expression.
602 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
604 const char *ExtraCode) {
605 // Does this asm operand have a single letter operand modifier?
606 if (ExtraCode && ExtraCode[0]) {
607 if (ExtraCode[1] != 0) return true; // Unknown modifier.
609 const MachineOperand &MO = MI->getOperand(OpNo);
611 switch (ExtraCode[0]) {
612 default: return true; // Unknown modifier.
613 case 'c': // Don't print "$" before a global var name or constant.
616 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
617 printSymbolOperand(MO);
619 printOperand(MI, OpNo);
622 case 'A': // Print '*' before a register (it must be a register)
625 printOperand(MI, OpNo);
630 case 'b': // Print QImode register
631 case 'h': // Print QImode high register
632 case 'w': // Print HImode register
633 case 'k': // Print SImode register
634 case 'q': // Print DImode register
636 return printAsmMRegister(MO, ExtraCode[0]);
637 printOperand(MI, OpNo);
640 case 'P': // This is the operand of a call, treat specially.
641 print_pcrel_imm(MI, OpNo);
644 case 'n': // Negate the immediate or print a '-' before the operand.
645 // Note: this is a temporary solution. It should be handled target
646 // independently as part of the 'MC' work.
655 printOperand(MI, OpNo);
659 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
662 const char *ExtraCode) {
663 if (ExtraCode && ExtraCode[0]) {
664 if (ExtraCode[1] != 0) return true; // Unknown modifier.
666 switch (ExtraCode[0]) {
667 default: return true; // Unknown modifier.
668 case 'b': // Print QImode register
669 case 'h': // Print QImode high register
670 case 'w': // Print HImode register
671 case 'k': // Print SImode register
672 case 'q': // Print SImode register
673 // These only apply to registers, ignore on mem.
675 case 'P': // Don't print @PLT, but do print as memory.
676 printMemReference(MI, OpNo, "no-rip");
680 printMemReference(MI, OpNo);
684 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
685 // Convert registers in the addr mode according to subreg64.
686 for (unsigned i = 0; i != 4; ++i) {
687 if (!MI->getOperand(i).isReg()) continue;
689 unsigned Reg = MI->getOperand(i).getReg();
690 if (Reg == 0) continue;
692 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
696 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
697 /// AT&T syntax to the current output stream.
699 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
703 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
707 } else if (MI->isLabel()) {
710 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
713 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
714 printImplicitDef(MI);
721 TmpInst.setOpcode(MI->getOpcode());
723 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
724 const MachineOperand &MO = MI->getOperand(i);
728 MCOp.MakeReg(MO.getReg());
729 } else if (MO.isImm()) {
730 MCOp.MakeImm(MO.getImm());
731 } else if (MO.isMBB()) {
732 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
734 llvm_unreachable("Unimp");
737 TmpInst.addOperand(MCOp);
740 switch (TmpInst.getOpcode()) {
742 // Handle the 'subreg rewriting' for the lea64_32mem operand.
743 lower_lea64_32mem(&TmpInst, 1);
747 // FIXME: Convert TmpInst.
748 printInstruction(&TmpInst);
752 // Call the autogenerated instruction printer routines.
753 printInstruction(MI);
757 bool X86ATTAsmPrinter::doInitialization(Module &M) {
759 Context = new MCContext();
760 // FIXME: Send this to "O" instead of outs(). For now, we force it to
761 // stdout to make it easy to compare.
762 Streamer = createAsmStreamer(*Context, outs());
765 return AsmPrinter::doInitialization(M);
768 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
769 const TargetData *TD = TM.getTargetData();
771 if (!GVar->hasInitializer())
772 return; // External global require no code
774 // Check to see if this is a special global used by LLVM, if so, emit it.
775 if (EmitSpecialLLVMGlobal(GVar)) {
776 if (Subtarget->isTargetDarwin() &&
777 TM.getRelocationModel() == Reloc::Static) {
778 if (GVar->getName() == "llvm.global_ctors")
779 O << ".reference .constructors_used\n";
780 else if (GVar->getName() == "llvm.global_dtors")
781 O << ".reference .destructors_used\n";
786 std::string name = Mang->getMangledName(GVar);
787 Constant *C = GVar->getInitializer();
788 if (isa<MDNode>(C) || isa<MDString>(C))
790 const Type *Type = C->getType();
791 unsigned Size = TD->getTypeAllocSize(Type);
792 unsigned Align = TD->getPreferredAlignmentLog(GVar);
794 printVisibility(name, GVar->getVisibility());
796 if (Subtarget->isTargetELF())
797 O << "\t.type\t" << name << ",@object\n";
799 SwitchToSection(TAI->SectionForGlobal(GVar));
801 if (C->isNullValue() && !GVar->hasSection() &&
802 !(Subtarget->isTargetDarwin() &&
803 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
804 // FIXME: This seems to be pretty darwin-specific
805 if (GVar->hasExternalLinkage()) {
806 if (const char *Directive = TAI->getZeroFillDirective()) {
807 O << "\t.globl " << name << '\n';
808 O << Directive << "__DATA, __common, " << name << ", "
809 << Size << ", " << Align << '\n';
814 if (!GVar->isThreadLocal() &&
815 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
816 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
818 if (TAI->getLCOMMDirective() != NULL) {
819 if (GVar->hasLocalLinkage()) {
820 O << TAI->getLCOMMDirective() << name << ',' << Size;
821 if (Subtarget->isTargetDarwin())
823 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
824 O << "\t.globl " << name << '\n'
825 << TAI->getWeakDefDirective() << name << '\n';
826 EmitAlignment(Align, GVar);
829 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
830 PrintUnmangledNameSafely(GVar, O);
833 EmitGlobalConstant(C);
836 O << TAI->getCOMMDirective() << name << ',' << Size;
837 if (TAI->getCOMMDirectiveTakesAlignment())
838 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
841 if (!Subtarget->isTargetCygMing()) {
842 if (GVar->hasLocalLinkage())
843 O << "\t.local\t" << name << '\n';
845 O << TAI->getCOMMDirective() << name << ',' << Size;
846 if (TAI->getCOMMDirectiveTakesAlignment())
847 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
850 O << "\t\t" << TAI->getCommentString() << ' ';
851 PrintUnmangledNameSafely(GVar, O);
858 switch (GVar->getLinkage()) {
859 case GlobalValue::CommonLinkage:
860 case GlobalValue::LinkOnceAnyLinkage:
861 case GlobalValue::LinkOnceODRLinkage:
862 case GlobalValue::WeakAnyLinkage:
863 case GlobalValue::WeakODRLinkage:
864 if (Subtarget->isTargetDarwin()) {
865 O << "\t.globl " << name << '\n'
866 << TAI->getWeakDefDirective() << name << '\n';
867 } else if (Subtarget->isTargetCygMing()) {
868 O << "\t.globl\t" << name << "\n"
869 "\t.linkonce same_size\n";
871 O << "\t.weak\t" << name << '\n';
874 case GlobalValue::DLLExportLinkage:
875 case GlobalValue::AppendingLinkage:
876 // FIXME: appending linkage variables should go into a section of
877 // their name or something. For now, just emit them as external.
878 case GlobalValue::ExternalLinkage:
879 // If external or appending, declare as a global symbol
880 O << "\t.globl " << name << '\n';
882 case GlobalValue::PrivateLinkage:
883 case GlobalValue::InternalLinkage:
886 llvm_unreachable("Unknown linkage type!");
889 EmitAlignment(Align, GVar);
892 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
893 PrintUnmangledNameSafely(GVar, O);
896 if (TAI->hasDotTypeDotSizeDirective())
897 O << "\t.size\t" << name << ", " << Size << '\n';
899 EmitGlobalConstant(C);
902 bool X86ATTAsmPrinter::doFinalization(Module &M) {
903 // Print out module-level global variables here.
904 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
906 printModuleLevelGV(I);
908 if (I->hasDLLExportLinkage())
909 DLLExportedGVs.insert(Mang->getMangledName(I));
912 if (Subtarget->isTargetDarwin()) {
913 SwitchToDataSection("");
915 // Add the (possibly multiple) personalities to the set of global value
916 // stubs. Only referenced functions get into the Personalities list.
917 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
918 const std::vector<Function*> &Personalities = MMI->getPersonalities();
919 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
920 if (Personalities[i])
921 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
922 true /*private label*/)] =
923 Mang->getMangledName(Personalities[i]);
927 // Output stubs for dynamically-linked functions
928 if (!FnStubs.empty()) {
929 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
930 "self_modifying_code+pure_instructions,5", 0);
931 for (StringMap<std::string>::iterator I = FnStubs.begin(),
932 E = FnStubs.end(); I != E; ++I)
933 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
934 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
938 // Output stubs for external and common global variables.
939 if (!GVStubs.empty()) {
941 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
942 for (StringMap<std::string>::iterator I = GVStubs.begin(),
943 E = GVStubs.end(); I != E; ++I)
944 O << I->getKeyData() << ":\n\t.indirect_symbol "
945 << I->second << "\n\t.long\t0\n";
948 if (!HiddenGVStubs.empty()) {
949 SwitchToSection(TAI->getDataSection());
951 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
952 E = HiddenGVStubs.end(); I != E; ++I)
953 O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
954 << I->second << '\n';
957 // Funny Darwin hack: This flag tells the linker that no global symbols
958 // contain code that falls through to other global symbols (e.g. the obvious
959 // implementation of multiple entry points). If this doesn't occur, the
960 // linker can safely perform dead code stripping. Since LLVM never
961 // generates code that does this, it is always safe to set.
962 O << "\t.subsections_via_symbols\n";
963 } else if (Subtarget->isTargetCygMing()) {
964 // Emit type information for external functions
965 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
967 O << "\t.def\t " << i->getKeyData()
968 << ";\t.scl\t" << COFF::C_EXT
969 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
975 // Output linker support code for dllexported globals on windows.
976 if (!DLLExportedGVs.empty()) {
977 SwitchToDataSection(".section .drectve");
979 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
980 e = DLLExportedGVs.end(); i != e; ++i)
981 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
984 if (!DLLExportedFns.empty()) {
985 SwitchToDataSection(".section .drectve");
987 for (StringSet<>::iterator i = DLLExportedFns.begin(),
988 e = DLLExportedFns.end();
990 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
993 // Do common shutdown.
994 bool Changed = AsmPrinter::doFinalization(M);
1008 // Include the auto-generated portion of the assembly writer.
1009 #include "X86GenAsmWriter.inc"