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 (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
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 /// decorateName - Query FunctionInfoMap and use this information for various
107 void X86ATTAsmPrinter::decorateName(std::string &Name,
108 const GlobalValue *GV) {
109 const Function *F = dyn_cast<Function>(GV);
112 // Save function name for later type emission.
113 if (Subtarget->isTargetCygMing() && F->isDeclaration())
114 CygMingStubs.insert(Name);
116 // We don't want to decorate non-stdcall or non-fastcall functions right now
117 unsigned CC = F->getCallingConv();
118 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
121 // Decorate names only when we're targeting Cygwin/Mingw32 targets
122 if (!Subtarget->isTargetCygMing())
125 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
127 const X86MachineFunctionInfo *Info;
128 if (info_item == FunctionInfoMap.end()) {
129 // Calculate apropriate function info and populate map
130 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
131 Info = &FunctionInfoMap[F];
133 Info = &info_item->second;
136 const FunctionType *FT = F->getFunctionType();
137 switch (Info->getDecorationStyle()) {
141 // "Pure" variadic functions do not receive @0 suffix.
142 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
143 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
144 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
147 // "Pure" variadic functions do not receive @0 suffix.
148 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
149 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
150 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
152 if (Name[0] == '_') {
159 llvm_unreachable("Unsupported DecorationStyle");
163 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
164 unsigned FnAlign = MF.getAlignment();
165 const Function *F = MF.getFunction();
167 decorateName(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 EmitAlignment(FnAlign, F);
176 case Function::DLLExportLinkage:
177 case Function::ExternalLinkage:
178 EmitAlignment(FnAlign, F);
179 O << "\t.globl\t" << CurrentFnName << '\n';
181 case Function::LinkOnceAnyLinkage:
182 case Function::LinkOnceODRLinkage:
183 case Function::WeakAnyLinkage:
184 case Function::WeakODRLinkage:
185 EmitAlignment(FnAlign, F);
186 if (Subtarget->isTargetDarwin()) {
187 O << "\t.globl\t" << CurrentFnName << '\n';
188 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
189 } else if (Subtarget->isTargetCygMing()) {
190 O << "\t.globl\t" << CurrentFnName << "\n"
191 "\t.linkonce discard\n";
193 O << "\t.weak\t" << CurrentFnName << '\n';
198 printVisibility(CurrentFnName, F->getVisibility());
200 if (Subtarget->isTargetELF())
201 O << "\t.type\t" << CurrentFnName << ",@function\n";
202 else if (Subtarget->isTargetCygMing()) {
203 O << "\t.def\t " << CurrentFnName
205 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
206 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
210 O << CurrentFnName << ":\n";
211 // Add some workaround for linkonce linkage on Cygwin\MinGW
212 if (Subtarget->isTargetCygMing() &&
213 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
214 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
217 /// runOnMachineFunction - This uses the printMachineInstruction()
218 /// method to print assembly for each instruction.
220 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
221 const Function *F = MF.getFunction();
223 unsigned CC = F->getCallingConv();
225 SetupMachineFunction(MF);
228 // Populate function information map. Actually, We don't want to populate
229 // non-stdcall or non-fastcall functions' information right now.
230 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
231 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
233 // Print out constants referenced by the function
234 EmitConstantPool(MF.getConstantPool());
236 if (F->hasDLLExportLinkage())
237 DLLExportedFns.insert(Mang->getMangledName(F));
239 // Print the 'header' of function
240 emitFunctionHeader(MF);
242 // Emit pre-function debug and/or EH information.
243 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
244 DW->BeginFunction(&MF);
246 // Print out code for the function.
247 bool hasAnyRealCode = false;
248 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
250 // Print a label for the basic block.
251 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
252 // This is an entry block or a block that's only reachable via a
253 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
255 printBasicBlockLabel(I, true, true, VerboseAsm);
258 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
260 // Print the assembly for the instruction.
262 hasAnyRealCode = true;
263 printMachineInstruction(II);
267 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
268 // If the function is empty, then we need to emit *something*. Otherwise,
269 // the function's label might be associated with something that it wasn't
270 // meant to be associated with. We emit a noop in this situation.
271 // We are assuming inline asms are code.
275 if (TAI->hasDotTypeDotSizeDirective())
276 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
278 // Emit post-function debug information.
279 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
280 DW->EndFunction(&MF);
282 // Print out jump tables referenced by the function.
283 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
287 // We didn't modify anything.
291 /// printSymbolOperand - Print a raw symbol reference operand. This handles
292 /// jump tables, constant pools, global address and external symbols, all of
293 /// which print to a label with various suffixes for relocation types etc.
294 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
295 switch (MO.getType()) {
296 default: llvm_unreachable("unknown symbol type!");
297 case MachineOperand::MO_JumpTableIndex:
298 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
301 case MachineOperand::MO_ConstantPoolIndex:
302 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
304 printOffset(MO.getOffset());
306 case MachineOperand::MO_GlobalAddress: {
307 const GlobalValue *GV = MO.getGlobal();
309 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 = Mang->makeNameProper(MO.getSymbolName());
346 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
347 FnStubs[Name+"$stub"] = Name;
351 // If the name begins with a dollar-sign, enclose it in parens. We do this
352 // to avoid having it look like an integer immediate to the assembler.
354 O << '(' << Name << ')';
361 switch (MO.getTargetFlags()) {
363 llvm_unreachable("Unknown target flag on GV operand");
364 case X86II::MO_NO_FLAG: // No flag.
366 case X86II::MO_DARWIN_NONLAZY:
367 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
368 case X86II::MO_DLLIMPORT:
369 case X86II::MO_DARWIN_STUB:
370 // These affect the name of the symbol, not any suffix.
372 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
374 PrintPICBaseSymbol();
377 case X86II::MO_PIC_BASE_OFFSET:
378 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
379 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
381 PrintPICBaseSymbol();
383 case X86II::MO_TLSGD: O << "@TLSGD"; break;
384 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
385 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
386 case X86II::MO_TPOFF: O << "@TPOFF"; break;
387 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
388 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
389 case X86II::MO_GOT: O << "@GOT"; break;
390 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
391 case X86II::MO_PLT: O << "@PLT"; break;
395 /// print_pcrel_imm - This is used to print an immediate value that ends up
396 /// being encoded as a pc-relative value. These print slightly differently, for
397 /// example, a $ is not emitted.
398 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
399 const MachineOperand &MO = MI->getOperand(OpNo);
400 switch (MO.getType()) {
401 default: llvm_unreachable("Unknown pcrel immediate operand");
402 case MachineOperand::MO_Immediate:
405 case MachineOperand::MO_MachineBasicBlock:
406 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
408 case MachineOperand::MO_GlobalAddress:
409 case MachineOperand::MO_ExternalSymbol:
410 printSymbolOperand(MO);
417 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
418 const char *Modifier) {
419 const MachineOperand &MO = MI->getOperand(OpNo);
420 switch (MO.getType()) {
421 default: llvm_unreachable("unknown operand type!");
422 case MachineOperand::MO_Register: {
423 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
424 "Virtual registers should not make it this far!");
426 unsigned Reg = MO.getReg();
427 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
428 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
429 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
430 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
431 Reg = getX86SubSuperRegister(Reg, VT);
433 O << TRI->getAsmName(Reg);
437 case MachineOperand::MO_Immediate:
438 O << '$' << MO.getImm();
441 case MachineOperand::MO_JumpTableIndex:
442 case MachineOperand::MO_ConstantPoolIndex:
443 case MachineOperand::MO_GlobalAddress:
444 case MachineOperand::MO_ExternalSymbol: {
446 printSymbolOperand(MO);
452 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
453 unsigned char value = MI->getOperand(Op).getImm();
454 assert(value <= 7 && "Invalid ssecc argument!");
456 case 0: O << "eq"; break;
457 case 1: O << "lt"; break;
458 case 2: O << "le"; break;
459 case 3: O << "unord"; break;
460 case 4: O << "neq"; break;
461 case 5: O << "nlt"; break;
462 case 6: O << "nle"; break;
463 case 7: O << "ord"; break;
467 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
468 const char *Modifier) {
469 const MachineOperand &BaseReg = MI->getOperand(Op);
470 const MachineOperand &IndexReg = MI->getOperand(Op+2);
471 const MachineOperand &DispSpec = MI->getOperand(Op+3);
473 // If we really don't want to print out (rip), don't.
474 bool HasBaseReg = BaseReg.getReg() != 0;
475 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
476 BaseReg.getReg() == X86::RIP)
479 // HasParenPart - True if we will print out the () part of the mem ref.
480 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
482 if (DispSpec.isImm()) {
483 int DispVal = DispSpec.getImm();
484 if (DispVal || !HasParenPart)
487 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
488 DispSpec.isJTI() || DispSpec.isSymbol());
489 printSymbolOperand(MI->getOperand(Op+3));
493 assert(IndexReg.getReg() != X86::ESP &&
494 "X86 doesn't allow scaling by ESP");
498 printOperand(MI, Op, Modifier);
500 if (IndexReg.getReg()) {
502 printOperand(MI, Op+2, Modifier);
503 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
505 O << ',' << ScaleVal;
511 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
512 const char *Modifier) {
513 assert(isMem(MI, Op) && "Invalid memory reference!");
514 const MachineOperand &Segment = MI->getOperand(Op+4);
515 if (Segment.getReg()) {
516 printOperand(MI, Op+4, Modifier);
519 printLeaMemReference(MI, Op, Modifier);
522 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
523 const MachineBasicBlock *MBB) const {
524 if (!TAI->getSetDirective())
527 // We don't need .set machinery if we have GOT-style relocations
528 if (Subtarget->isPICStyleGOT())
531 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
532 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
533 printBasicBlockLabel(MBB, false, false, false);
534 if (Subtarget->isPICStyleRIPRel())
535 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
536 << '_' << uid << '\n';
539 PrintPICBaseSymbol();
545 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
546 PrintPICBaseSymbol();
548 PrintPICBaseSymbol();
553 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
554 const MachineBasicBlock *MBB,
555 unsigned uid) const {
556 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
557 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
559 O << JTEntryDirective << ' ';
561 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
562 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
563 << '_' << uid << "_set_" << MBB->getNumber();
564 } else if (Subtarget->isPICStyleGOT()) {
565 printBasicBlockLabel(MBB, false, false, false);
568 printBasicBlockLabel(MBB, false, false, false);
571 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
572 unsigned Reg = MO.getReg();
574 default: return true; // Unknown mode.
575 case 'b': // Print QImode register
576 Reg = getX86SubSuperRegister(Reg, MVT::i8);
578 case 'h': // Print QImode high register
579 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
581 case 'w': // Print HImode register
582 Reg = getX86SubSuperRegister(Reg, MVT::i16);
584 case 'k': // Print SImode register
585 Reg = getX86SubSuperRegister(Reg, MVT::i32);
587 case 'q': // Print DImode register
588 Reg = getX86SubSuperRegister(Reg, MVT::i64);
592 O << '%'<< TRI->getAsmName(Reg);
596 /// PrintAsmOperand - Print out an operand for an inline asm expression.
598 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
600 const char *ExtraCode) {
601 // Does this asm operand have a single letter operand modifier?
602 if (ExtraCode && ExtraCode[0]) {
603 if (ExtraCode[1] != 0) return true; // Unknown modifier.
605 const MachineOperand &MO = MI->getOperand(OpNo);
607 switch (ExtraCode[0]) {
608 default: return true; // Unknown modifier.
609 case 'c': // Don't print "$" before a global var name or constant.
612 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
613 printSymbolOperand(MO);
615 printOperand(MI, OpNo);
618 case 'A': // Print '*' before a register (it must be a register)
621 printOperand(MI, OpNo);
626 case 'b': // Print QImode register
627 case 'h': // Print QImode high register
628 case 'w': // Print HImode register
629 case 'k': // Print SImode register
630 case 'q': // Print DImode register
632 return printAsmMRegister(MO, ExtraCode[0]);
633 printOperand(MI, OpNo);
636 case 'P': // This is the operand of a call, treat specially.
637 print_pcrel_imm(MI, OpNo);
640 case 'n': // Negate the immediate or print a '-' before the operand.
641 // Note: this is a temporary solution. It should be handled target
642 // independently as part of the 'MC' work.
651 printOperand(MI, OpNo);
655 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
658 const char *ExtraCode) {
659 if (ExtraCode && ExtraCode[0]) {
660 if (ExtraCode[1] != 0) return true; // Unknown modifier.
662 switch (ExtraCode[0]) {
663 default: return true; // Unknown modifier.
664 case 'b': // Print QImode register
665 case 'h': // Print QImode high register
666 case 'w': // Print HImode register
667 case 'k': // Print SImode register
668 case 'q': // Print SImode register
669 // These only apply to registers, ignore on mem.
671 case 'P': // Don't print @PLT, but do print as memory.
672 printMemReference(MI, OpNo, "no-rip");
676 printMemReference(MI, OpNo);
680 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
681 // Convert registers in the addr mode according to subreg64.
682 for (unsigned i = 0; i != 4; ++i) {
683 if (!MI->getOperand(i).isReg()) continue;
685 unsigned Reg = MI->getOperand(i).getReg();
686 if (Reg == 0) continue;
688 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
692 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
693 /// AT&T syntax to the current output stream.
695 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
699 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
703 } else if (MI->isLabel()) {
706 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
709 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
710 printImplicitDef(MI);
717 TmpInst.setOpcode(MI->getOpcode());
719 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
720 const MachineOperand &MO = MI->getOperand(i);
724 MCOp.MakeReg(MO.getReg());
725 } else if (MO.isImm()) {
726 MCOp.MakeImm(MO.getImm());
727 } else if (MO.isMBB()) {
728 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
730 llvm_unreachable("Unimp");
733 TmpInst.addOperand(MCOp);
736 switch (TmpInst.getOpcode()) {
738 // Handle the 'subreg rewriting' for the lea64_32mem operand.
739 lower_lea64_32mem(&TmpInst, 1);
743 // FIXME: Convert TmpInst.
744 printInstruction(&TmpInst);
748 // Call the autogenerated instruction printer routines.
749 printInstruction(MI);
753 bool X86ATTAsmPrinter::doInitialization(Module &M) {
755 Context = new MCContext();
756 // FIXME: Send this to "O" instead of outs(). For now, we force it to
757 // stdout to make it easy to compare.
758 Streamer = createAsmStreamer(*Context, outs());
761 return AsmPrinter::doInitialization(M);
764 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
765 const TargetData *TD = TM.getTargetData();
767 if (!GVar->hasInitializer())
768 return; // External global require no code
770 // Check to see if this is a special global used by LLVM, if so, emit it.
771 if (EmitSpecialLLVMGlobal(GVar)) {
772 if (Subtarget->isTargetDarwin() &&
773 TM.getRelocationModel() == Reloc::Static) {
774 if (GVar->getName() == "llvm.global_ctors")
775 O << ".reference .constructors_used\n";
776 else if (GVar->getName() == "llvm.global_dtors")
777 O << ".reference .destructors_used\n";
782 std::string name = Mang->getMangledName(GVar);
783 Constant *C = GVar->getInitializer();
784 if (isa<MDNode>(C) || isa<MDString>(C))
786 const Type *Type = C->getType();
787 unsigned Size = TD->getTypeAllocSize(Type);
788 unsigned Align = TD->getPreferredAlignmentLog(GVar);
790 printVisibility(name, GVar->getVisibility());
792 if (Subtarget->isTargetELF())
793 O << "\t.type\t" << name << ",@object\n";
795 SwitchToSection(TAI->SectionForGlobal(GVar));
797 if (C->isNullValue() && !GVar->hasSection() &&
798 !(Subtarget->isTargetDarwin() &&
799 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
800 // FIXME: This seems to be pretty darwin-specific
801 if (GVar->hasExternalLinkage()) {
802 if (const char *Directive = TAI->getZeroFillDirective()) {
803 O << "\t.globl " << name << '\n';
804 O << Directive << "__DATA, __common, " << name << ", "
805 << Size << ", " << Align << '\n';
810 if (!GVar->isThreadLocal() &&
811 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
812 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
814 if (TAI->getLCOMMDirective() != NULL) {
815 if (GVar->hasLocalLinkage()) {
816 O << TAI->getLCOMMDirective() << name << ',' << Size;
817 if (Subtarget->isTargetDarwin())
819 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
820 O << "\t.globl " << name << '\n'
821 << TAI->getWeakDefDirective() << name << '\n';
822 EmitAlignment(Align, GVar);
825 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
826 PrintUnmangledNameSafely(GVar, O);
829 EmitGlobalConstant(C);
832 O << TAI->getCOMMDirective() << name << ',' << Size;
833 if (TAI->getCOMMDirectiveTakesAlignment())
834 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
837 if (!Subtarget->isTargetCygMing()) {
838 if (GVar->hasLocalLinkage())
839 O << "\t.local\t" << name << '\n';
841 O << TAI->getCOMMDirective() << name << ',' << Size;
842 if (TAI->getCOMMDirectiveTakesAlignment())
843 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
846 O << "\t\t" << TAI->getCommentString() << ' ';
847 PrintUnmangledNameSafely(GVar, O);
854 switch (GVar->getLinkage()) {
855 case GlobalValue::CommonLinkage:
856 case GlobalValue::LinkOnceAnyLinkage:
857 case GlobalValue::LinkOnceODRLinkage:
858 case GlobalValue::WeakAnyLinkage:
859 case GlobalValue::WeakODRLinkage:
860 if (Subtarget->isTargetDarwin()) {
861 O << "\t.globl " << name << '\n'
862 << TAI->getWeakDefDirective() << name << '\n';
863 } else if (Subtarget->isTargetCygMing()) {
864 O << "\t.globl\t" << name << "\n"
865 "\t.linkonce same_size\n";
867 O << "\t.weak\t" << name << '\n';
870 case GlobalValue::DLLExportLinkage:
871 case GlobalValue::AppendingLinkage:
872 // FIXME: appending linkage variables should go into a section of
873 // their name or something. For now, just emit them as external.
874 case GlobalValue::ExternalLinkage:
875 // If external or appending, declare as a global symbol
876 O << "\t.globl " << name << '\n';
878 case GlobalValue::PrivateLinkage:
879 case GlobalValue::InternalLinkage:
882 llvm_unreachable("Unknown linkage type!");
885 EmitAlignment(Align, GVar);
888 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
889 PrintUnmangledNameSafely(GVar, O);
892 if (TAI->hasDotTypeDotSizeDirective())
893 O << "\t.size\t" << name << ", " << Size << '\n';
895 EmitGlobalConstant(C);
898 bool X86ATTAsmPrinter::doFinalization(Module &M) {
899 // Print out module-level global variables here.
900 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
902 printModuleLevelGV(I);
904 if (I->hasDLLExportLinkage())
905 DLLExportedGVs.insert(Mang->getMangledName(I));
908 if (Subtarget->isTargetDarwin()) {
909 SwitchToDataSection("");
911 // Add the (possibly multiple) personalities to the set of global value
912 // stubs. Only referenced functions get into the Personalities list.
913 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
914 const std::vector<Function*> &Personalities = MMI->getPersonalities();
915 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
916 if (Personalities[i])
917 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
918 true /*private label*/)] =
919 Mang->getMangledName(Personalities[i]);
923 // Output stubs for dynamically-linked functions
924 if (!FnStubs.empty()) {
925 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
926 "self_modifying_code+pure_instructions,5", 0);
927 for (StringMap<std::string>::iterator I = FnStubs.begin(),
928 E = FnStubs.end(); I != E; ++I)
929 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
930 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
934 // Output stubs for external and common global variables.
935 if (!GVStubs.empty()) {
937 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
938 for (StringMap<std::string>::iterator I = GVStubs.begin(),
939 E = GVStubs.end(); I != E; ++I)
940 O << I->getKeyData() << ":\n\t.indirect_symbol "
941 << I->second << "\n\t.long\t0\n";
944 if (!HiddenGVStubs.empty()) {
945 SwitchToSection(TAI->getDataSection());
947 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
948 E = HiddenGVStubs.end(); I != E; ++I)
949 O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
950 << I->second << '\n';
953 // Funny Darwin hack: This flag tells the linker that no global symbols
954 // contain code that falls through to other global symbols (e.g. the obvious
955 // implementation of multiple entry points). If this doesn't occur, the
956 // linker can safely perform dead code stripping. Since LLVM never
957 // generates code that does this, it is always safe to set.
958 O << "\t.subsections_via_symbols\n";
959 } else if (Subtarget->isTargetCygMing()) {
960 // Emit type information for external functions
961 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
963 O << "\t.def\t " << i->getKeyData()
964 << ";\t.scl\t" << COFF::C_EXT
965 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
971 // Output linker support code for dllexported globals on windows.
972 if (!DLLExportedGVs.empty()) {
973 SwitchToDataSection(".section .drectve");
975 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
976 e = DLLExportedGVs.end(); i != e; ++i)
977 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
980 if (!DLLExportedFns.empty()) {
981 SwitchToDataSection(".section .drectve");
983 for (StringSet<>::iterator i = DLLExportedFns.begin(),
984 e = DLLExportedFns.end();
986 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
989 // Do common shutdown.
990 bool Changed = AsmPrinter::doFinalization(M);
1004 // Include the auto-generated portion of the assembly writer.
1005 #include "X86GenAsmWriter.inc"