69a69e9e84537e3e98d78d14be9011a43c16e393
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to X86 machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86AsmPrinter.h"
16 #include "InstPrinter/X86ATTInstPrinter.h"
17 #include "X86.h"
18 #include "X86COFFMachineModuleInfo.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/MCExpr.h"
34 #include "llvm/MC/MCSectionMachO.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/COFF.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetOptions.h"
43 using namespace llvm;
44
45 //===----------------------------------------------------------------------===//
46 // Primitive Helper Functions.
47 //===----------------------------------------------------------------------===//
48
49 /// runOnMachineFunction - Emit the function body.
50 ///
51 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
52   SetupMachineFunction(MF);
53
54   if (Subtarget->isTargetCOFF()) {
55     bool Intrn = MF.getFunction()->hasInternalLinkage();
56     OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
57     OutStreamer.EmitCOFFSymbolStorageClass(Intrn ? COFF::IMAGE_SYM_CLASS_STATIC
58                                               : COFF::IMAGE_SYM_CLASS_EXTERNAL);
59     OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
60                                                << COFF::SCT_COMPLEX_TYPE_SHIFT);
61     OutStreamer.EndCOFFSymbolDef();
62   }
63
64   // Have common code print out the function header with linkage info etc.
65   EmitFunctionHeader();
66
67   // Emit the rest of the function body.
68   EmitFunctionBody();
69
70   // We didn't modify anything.
71   return false;
72 }
73
74 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
75 /// jump tables, constant pools, global address and external symbols, all of
76 /// which print to a label with various suffixes for relocation types etc.
77 static void printSymbolOperand(X86AsmPrinter &P, const MachineOperand &MO,
78                                raw_ostream &O) {
79   switch (MO.getType()) {
80   default: llvm_unreachable("unknown symbol type!");
81   case MachineOperand::MO_ConstantPoolIndex:
82     O << *P.GetCPISymbol(MO.getIndex());
83     P.printOffset(MO.getOffset(), O);
84     break;
85   case MachineOperand::MO_GlobalAddress: {
86     const GlobalValue *GV = MO.getGlobal();
87
88     MCSymbol *GVSym;
89     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
90       GVSym = P.getSymbolWithGlobalValueBase(GV, "$stub");
91     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
92              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
93              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
94       GVSym = P.getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
95     else
96       GVSym = P.getSymbol(GV);
97
98     // Handle dllimport linkage.
99     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
100       GVSym =
101           P.OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
102
103     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
104         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
105       MCSymbol *Sym = P.getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
106       MachineModuleInfoImpl::StubValueTy &StubSym =
107           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
108       if (StubSym.getPointer() == 0)
109         StubSym = MachineModuleInfoImpl::
110           StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
111     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
112       MCSymbol *Sym = P.getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
113       MachineModuleInfoImpl::StubValueTy &StubSym =
114           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(
115               Sym);
116       if (StubSym.getPointer() == 0)
117         StubSym = MachineModuleInfoImpl::
118           StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
119     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
120       MCSymbol *Sym = P.getSymbolWithGlobalValueBase(GV, "$stub");
121       MachineModuleInfoImpl::StubValueTy &StubSym =
122           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
123       if (StubSym.getPointer() == 0)
124         StubSym = MachineModuleInfoImpl::
125           StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
126     }
127
128     // If the name begins with a dollar-sign, enclose it in parens.  We do this
129     // to avoid having it look like an integer immediate to the assembler.
130     if (GVSym->getName()[0] != '$')
131       O << *GVSym;
132     else
133       O << '(' << *GVSym << ')';
134     P.printOffset(MO.getOffset(), O);
135     break;
136   }
137   }
138
139   switch (MO.getTargetFlags()) {
140   default:
141     llvm_unreachable("Unknown target flag on GV operand");
142   case X86II::MO_NO_FLAG:    // No flag.
143     break;
144   case X86II::MO_DARWIN_NONLAZY:
145   case X86II::MO_DLLIMPORT:
146   case X86II::MO_DARWIN_STUB:
147     // These affect the name of the symbol, not any suffix.
148     break;
149   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
150     O << " + [.-" << *P.MF->getPICBaseSymbol() << ']';
151     break;
152   case X86II::MO_PIC_BASE_OFFSET:
153   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
154   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
155     O << '-' << *P.MF->getPICBaseSymbol();
156     break;
157   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
158   case X86II::MO_TLSLD:     O << "@TLSLD";     break;
159   case X86II::MO_TLSLDM:    O << "@TLSLDM";    break;
160   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
161   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
162   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
163   case X86II::MO_DTPOFF:    O << "@DTPOFF";    break;
164   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
165   case X86II::MO_GOTNTPOFF: O << "@GOTNTPOFF"; break;
166   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
167   case X86II::MO_GOT:       O << "@GOT";       break;
168   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
169   case X86II::MO_PLT:       O << "@PLT";       break;
170   case X86II::MO_TLVP:      O << "@TLVP";      break;
171   case X86II::MO_TLVP_PIC_BASE:
172     O << "@TLVP" << '-' << *P.MF->getPICBaseSymbol();
173     break;
174   case X86II::MO_SECREL:    O << "@SECREL32";  break;
175   }
176 }
177
178 static void printOperand(X86AsmPrinter &P, const MachineInstr *MI,
179                          unsigned OpNo, raw_ostream &O,
180                          const char *Modifier = 0, unsigned AsmVariant = 0);
181
182 /// printPCRelImm - This is used to print an immediate value that ends up
183 /// being encoded as a pc-relative value.  These print slightly differently, for
184 /// example, a $ is not emitted.
185 static void printPCRelImm(X86AsmPrinter &P, const MachineInstr *MI,
186                           unsigned OpNo, raw_ostream &O) {
187   const MachineOperand &MO = MI->getOperand(OpNo);
188   switch (MO.getType()) {
189   default: llvm_unreachable("Unknown pcrel immediate operand");
190   case MachineOperand::MO_Register:
191     // pc-relativeness was handled when computing the value in the reg.
192     printOperand(P, MI, OpNo, O);
193     return;
194   case MachineOperand::MO_Immediate:
195     O << MO.getImm();
196     return;
197   case MachineOperand::MO_GlobalAddress:
198     printSymbolOperand(P, MO, O);
199     return;
200   }
201 }
202
203 static void printOperand(X86AsmPrinter &P, const MachineInstr *MI,
204                          unsigned OpNo, raw_ostream &O, const char *Modifier,
205                          unsigned AsmVariant) {
206   const MachineOperand &MO = MI->getOperand(OpNo);
207   switch (MO.getType()) {
208   default: llvm_unreachable("unknown operand type!");
209   case MachineOperand::MO_Register: {
210     // FIXME: Enumerating AsmVariant, so we can remove magic number.
211     if (AsmVariant == 0) O << '%';
212     unsigned Reg = MO.getReg();
213     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
214       MVT::SimpleValueType VT = (strcmp(Modifier+6,"64") == 0) ?
215         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
216                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
217       Reg = getX86SubSuperRegister(Reg, VT);
218     }
219     O << X86ATTInstPrinter::getRegisterName(Reg);
220     return;
221   }
222
223   case MachineOperand::MO_Immediate:
224     if (AsmVariant == 0) O << '$';
225     O << MO.getImm();
226     return;
227
228   case MachineOperand::MO_GlobalAddress: {
229     if (AsmVariant == 0) O << '$';
230     printSymbolOperand(P, MO, O);
231     break;
232   }
233   }
234 }
235
236 static void printLeaMemReference(X86AsmPrinter &P, const MachineInstr *MI,
237                                  unsigned Op, raw_ostream &O,
238                                  const char *Modifier = NULL) {
239   const MachineOperand &BaseReg  = MI->getOperand(Op);
240   const MachineOperand &IndexReg = MI->getOperand(Op+2);
241   const MachineOperand &DispSpec = MI->getOperand(Op+3);
242
243   // If we really don't want to print out (rip), don't.
244   bool HasBaseReg = BaseReg.getReg() != 0;
245   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
246       BaseReg.getReg() == X86::RIP)
247     HasBaseReg = false;
248
249   // HasParenPart - True if we will print out the () part of the mem ref.
250   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
251
252   switch (DispSpec.getType()) {
253   default:
254     llvm_unreachable("unknown operand type!");
255   case MachineOperand::MO_Immediate: {
256     int DispVal = DispSpec.getImm();
257     if (DispVal || !HasParenPart)
258       O << DispVal;
259     break;
260   }
261   case MachineOperand::MO_GlobalAddress:
262   case MachineOperand::MO_ConstantPoolIndex:
263     printSymbolOperand(P, MI->getOperand(Op + 3), O);
264   }
265
266   if (Modifier && strcmp(Modifier, "H") == 0)
267     O << "+8";
268
269   if (HasParenPart) {
270     assert(IndexReg.getReg() != X86::ESP &&
271            "X86 doesn't allow scaling by ESP");
272
273     O << '(';
274     if (HasBaseReg)
275       printOperand(P, MI, Op, O, Modifier);
276
277     if (IndexReg.getReg()) {
278       O << ',';
279       printOperand(P, MI, Op+2, O, Modifier);
280       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
281       if (ScaleVal != 1)
282         O << ',' << ScaleVal;
283     }
284     O << ')';
285   }
286 }
287
288 static void printMemReference(X86AsmPrinter &P, const MachineInstr *MI,
289                               unsigned Op, raw_ostream &O,
290                               const char *Modifier = NULL) {
291   assert(isMem(MI, Op) && "Invalid memory reference!");
292   const MachineOperand &Segment = MI->getOperand(Op+4);
293   if (Segment.getReg()) {
294     printOperand(P, MI, Op+4, O, Modifier);
295     O << ':';
296   }
297   printLeaMemReference(P, MI, Op, O, Modifier);
298 }
299
300 static void printIntelMemReference(X86AsmPrinter &P, const MachineInstr *MI,
301                                    unsigned Op, raw_ostream &O,
302                                    const char *Modifier = NULL,
303                                    unsigned AsmVariant = 1) {
304   const MachineOperand &BaseReg  = MI->getOperand(Op);
305   unsigned ScaleVal = MI->getOperand(Op+1).getImm();
306   const MachineOperand &IndexReg = MI->getOperand(Op+2);
307   const MachineOperand &DispSpec = MI->getOperand(Op+3);
308   const MachineOperand &SegReg   = MI->getOperand(Op+4);
309
310   // If this has a segment register, print it.
311   if (SegReg.getReg()) {
312     printOperand(P, MI, Op+4, O, Modifier, AsmVariant);
313     O << ':';
314   }
315
316   O << '[';
317
318   bool NeedPlus = false;
319   if (BaseReg.getReg()) {
320     printOperand(P, MI, Op, O, Modifier, AsmVariant);
321     NeedPlus = true;
322   }
323
324   if (IndexReg.getReg()) {
325     if (NeedPlus) O << " + ";
326     if (ScaleVal != 1)
327       O << ScaleVal << '*';
328     printOperand(P, MI, Op+2, O, Modifier, AsmVariant);
329     NeedPlus = true;
330   }
331
332   if (!DispSpec.isImm()) {
333     if (NeedPlus) O << " + ";
334     printOperand(P, MI, Op+3, O, Modifier, AsmVariant);
335   } else {
336     int64_t DispVal = DispSpec.getImm();
337     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg())) {
338       if (NeedPlus) {
339         if (DispVal > 0)
340           O << " + ";
341         else {
342           O << " - ";
343           DispVal = -DispVal;
344         }
345       }
346       O << DispVal;
347     }
348   }
349   O << ']';
350 }
351
352 static bool printAsmMRegister(X86AsmPrinter &P, const MachineOperand &MO,
353                               char Mode, raw_ostream &O) {
354   unsigned Reg = MO.getReg();
355   switch (Mode) {
356   default: return true;  // Unknown mode.
357   case 'b': // Print QImode register
358     Reg = getX86SubSuperRegister(Reg, MVT::i8);
359     break;
360   case 'h': // Print QImode high register
361     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
362     break;
363   case 'w': // Print HImode register
364     Reg = getX86SubSuperRegister(Reg, MVT::i16);
365     break;
366   case 'k': // Print SImode register
367     Reg = getX86SubSuperRegister(Reg, MVT::i32);
368     break;
369   case 'q': // Print DImode register
370     // FIXME: gcc will actually print e instead of r for 32-bit.
371     Reg = getX86SubSuperRegister(Reg, MVT::i64);
372     break;
373   }
374
375   O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
376   return false;
377 }
378
379 /// PrintAsmOperand - Print out an operand for an inline asm expression.
380 ///
381 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
382                                     unsigned AsmVariant,
383                                     const char *ExtraCode, raw_ostream &O) {
384   // Does this asm operand have a single letter operand modifier?
385   if (ExtraCode && ExtraCode[0]) {
386     if (ExtraCode[1] != 0) return true; // Unknown modifier.
387
388     const MachineOperand &MO = MI->getOperand(OpNo);
389
390     switch (ExtraCode[0]) {
391     default:
392       // See if this is a generic print operand
393       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
394     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
395       switch (MO.getType()) {
396       default:
397         return true;
398       case MachineOperand::MO_Immediate:
399         O << MO.getImm();
400         return false;
401       case MachineOperand::MO_ConstantPoolIndex:
402       case MachineOperand::MO_JumpTableIndex:
403       case MachineOperand::MO_ExternalSymbol:
404         llvm_unreachable("unexpected operand type!");
405       case MachineOperand::MO_GlobalAddress:
406         printSymbolOperand(*this, MO, O);
407         if (Subtarget->isPICStyleRIPRel())
408           O << "(%rip)";
409         return false;
410       case MachineOperand::MO_Register:
411         O << '(';
412         printOperand(*this, MI, OpNo, O);
413         O << ')';
414         return false;
415       }
416
417     case 'c': // Don't print "$" before a global var name or constant.
418       switch (MO.getType()) {
419       default:
420         printOperand(*this, MI, OpNo, O);
421         break;
422       case MachineOperand::MO_Immediate:
423         O << MO.getImm();
424         break;
425       case MachineOperand::MO_ConstantPoolIndex:
426       case MachineOperand::MO_JumpTableIndex:
427       case MachineOperand::MO_ExternalSymbol:
428         llvm_unreachable("unexpected operand type!");
429       case MachineOperand::MO_GlobalAddress:
430         printSymbolOperand(*this, MO, O);
431         break;
432       }
433       return false;
434
435     case 'A': // Print '*' before a register (it must be a register)
436       if (MO.isReg()) {
437         O << '*';
438         printOperand(*this, MI, OpNo, O);
439         return false;
440       }
441       return true;
442
443     case 'b': // Print QImode register
444     case 'h': // Print QImode high register
445     case 'w': // Print HImode register
446     case 'k': // Print SImode register
447     case 'q': // Print DImode register
448       if (MO.isReg())
449         return printAsmMRegister(*this, MO, ExtraCode[0], O);
450       printOperand(*this, MI, OpNo, O);
451       return false;
452
453     case 'P': // This is the operand of a call, treat specially.
454       printPCRelImm(*this, MI, OpNo, O);
455       return false;
456
457     case 'n':  // Negate the immediate or print a '-' before the operand.
458       // Note: this is a temporary solution. It should be handled target
459       // independently as part of the 'MC' work.
460       if (MO.isImm()) {
461         O << -MO.getImm();
462         return false;
463       }
464       O << '-';
465     }
466   }
467
468   printOperand(*this, MI, OpNo, O, /*Modifier*/ 0, AsmVariant);
469   return false;
470 }
471
472 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
473                                           unsigned OpNo, unsigned AsmVariant,
474                                           const char *ExtraCode,
475                                           raw_ostream &O) {
476   if (AsmVariant) {
477     printIntelMemReference(*this, MI, OpNo, O);
478     return false;
479   }
480
481   if (ExtraCode && ExtraCode[0]) {
482     if (ExtraCode[1] != 0) return true; // Unknown modifier.
483
484     switch (ExtraCode[0]) {
485     default: return true;  // Unknown modifier.
486     case 'b': // Print QImode register
487     case 'h': // Print QImode high register
488     case 'w': // Print HImode register
489     case 'k': // Print SImode register
490     case 'q': // Print SImode register
491       // These only apply to registers, ignore on mem.
492       break;
493     case 'H':
494       printMemReference(*this, MI, OpNo, O, "H");
495       return false;
496     case 'P': // Don't print @PLT, but do print as memory.
497       printMemReference(*this, MI, OpNo, O, "no-rip");
498       return false;
499     }
500   }
501   printMemReference(*this, MI, OpNo, O);
502   return false;
503 }
504
505 void X86AsmPrinter::EmitStartOfAsmFile(Module &M) {
506   if (Subtarget->isTargetMacho())
507     OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
508
509   if (Subtarget->isTargetCOFF()) {
510     // Emit an absolute @feat.00 symbol.  This appears to be some kind of
511     // compiler features bitfield read by link.exe.
512     if (!Subtarget->is64Bit()) {
513       MCSymbol *S = MMI->getContext().GetOrCreateSymbol(StringRef("@feat.00"));
514       OutStreamer.BeginCOFFSymbolDef(S);
515       OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
516       OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
517       OutStreamer.EndCOFFSymbolDef();
518       // According to the PE-COFF spec, the LSB of this value marks the object
519       // for "registered SEH".  This means that all SEH handler entry points
520       // must be registered in .sxdata.  Use of any unregistered handlers will
521       // cause the process to terminate immediately.  LLVM does not know how to
522       // register any SEH handlers, so its object files should be safe.
523       S->setAbsolute();
524       OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
525       OutStreamer.EmitAssignment(
526           S, MCConstantExpr::Create(int64_t(1), MMI->getContext()));
527     }
528   }
529 }
530
531
532 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
533   if (Subtarget->isTargetMacho()) {
534     // All darwin targets use mach-o.
535     MachineModuleInfoMachO &MMIMacho =
536       MMI->getObjFileInfo<MachineModuleInfoMachO>();
537
538     // Output stubs for dynamically-linked functions.
539     MachineModuleInfoMachO::SymbolListTy Stubs;
540
541     Stubs = MMIMacho.GetFnStubList();
542     if (!Stubs.empty()) {
543       const MCSection *TheSection =
544         OutContext.getMachOSection("__IMPORT", "__jump_table",
545                                    MCSectionMachO::S_SYMBOL_STUBS |
546                                    MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
547                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
548                                    5, SectionKind::getMetadata());
549       OutStreamer.SwitchSection(TheSection);
550
551       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
552         // L_foo$stub:
553         OutStreamer.EmitLabel(Stubs[i].first);
554         //   .indirect_symbol _foo
555         OutStreamer.EmitSymbolAttribute(Stubs[i].second.getPointer(),
556                                         MCSA_IndirectSymbol);
557         // hlt; hlt; hlt; hlt; hlt     hlt = 0xf4.
558         const char HltInsts[] = "\xf4\xf4\xf4\xf4\xf4";
559         OutStreamer.EmitBytes(StringRef(HltInsts, 5));
560       }
561
562       Stubs.clear();
563       OutStreamer.AddBlankLine();
564     }
565
566     // Output stubs for external and common global variables.
567     Stubs = MMIMacho.GetGVStubList();
568     if (!Stubs.empty()) {
569       const MCSection *TheSection =
570         OutContext.getMachOSection("__IMPORT", "__pointers",
571                                    MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
572                                    SectionKind::getMetadata());
573       OutStreamer.SwitchSection(TheSection);
574
575       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
576         // L_foo$non_lazy_ptr:
577         OutStreamer.EmitLabel(Stubs[i].first);
578         // .indirect_symbol _foo
579         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
580         OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),
581                                         MCSA_IndirectSymbol);
582         // .long 0
583         if (MCSym.getInt())
584           // External to current translation unit.
585           OutStreamer.EmitIntValue(0, 4/*size*/);
586         else
587           // Internal to current translation unit.
588           //
589           // When we place the LSDA into the TEXT section, the type info
590           // pointers need to be indirect and pc-rel. We accomplish this by
591           // using NLPs.  However, sometimes the types are local to the file. So
592           // we need to fill in the value for the NLP in those cases.
593           OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
594                                                         OutContext), 4/*size*/);
595       }
596       Stubs.clear();
597       OutStreamer.AddBlankLine();
598     }
599
600     Stubs = MMIMacho.GetHiddenGVStubList();
601     if (!Stubs.empty()) {
602       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
603       EmitAlignment(2);
604
605       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
606         // L_foo$non_lazy_ptr:
607         OutStreamer.EmitLabel(Stubs[i].first);
608         // .long _foo
609         OutStreamer.EmitValue(MCSymbolRefExpr::
610                               Create(Stubs[i].second.getPointer(),
611                                      OutContext), 4/*size*/);
612       }
613       Stubs.clear();
614       OutStreamer.AddBlankLine();
615     }
616
617     SM.serializeToStackMapSection();
618
619     // Funny Darwin hack: This flag tells the linker that no global symbols
620     // contain code that falls through to other global symbols (e.g. the obvious
621     // implementation of multiple entry points).  If this doesn't occur, the
622     // linker can safely perform dead code stripping.  Since LLVM never
623     // generates code that does this, it is always safe to set.
624     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
625   }
626
627   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing() &&
628       MMI->usesVAFloatArgument()) {
629     StringRef SymbolName = Subtarget->is64Bit() ? "_fltused" : "__fltused";
630     MCSymbol *S = MMI->getContext().GetOrCreateSymbol(SymbolName);
631     OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
632   }
633
634   if (Subtarget->isTargetCOFF()) {
635     X86COFFMachineModuleInfo &COFFMMI =
636       MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
637
638     // Emit type information for external functions
639     typedef X86COFFMachineModuleInfo::externals_iterator externals_iterator;
640     for (externals_iterator I = COFFMMI.externals_begin(),
641                             E = COFFMMI.externals_end();
642                             I != E; ++I) {
643       OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
644       OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
645       OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
646                                                << COFF::SCT_COMPLEX_TYPE_SHIFT);
647       OutStreamer.EndCOFFSymbolDef();
648     }
649
650     // Necessary for dllexport support
651     std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
652
653     const TargetLoweringObjectFileCOFF &TLOFCOFF =
654       static_cast<const TargetLoweringObjectFileCOFF&>(getObjFileLowering());
655
656     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
657       if (I->hasDLLExportLinkage())
658         DLLExportedFns.push_back(getSymbol(I));
659
660     for (Module::const_global_iterator I = M.global_begin(),
661            E = M.global_end(); I != E; ++I)
662       if (I->hasDLLExportLinkage())
663         DLLExportedGlobals.push_back(getSymbol(I));
664
665     // Output linker support code for dllexported globals on windows.
666     if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
667       OutStreamer.SwitchSection(TLOFCOFF.getDrectveSection());
668       SmallString<128> name;
669       for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i) {
670         if (Subtarget->isTargetWindows())
671           name = " /EXPORT:";
672         else
673           name = " -export:";
674         name += DLLExportedGlobals[i]->getName();
675         if (Subtarget->isTargetWindows())
676           name += ",DATA";
677         else
678         name += ",data";
679         OutStreamer.EmitBytes(name);
680       }
681
682       for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i) {
683         if (Subtarget->isTargetWindows())
684           name = " /EXPORT:";
685         else
686           name = " -export:";
687         name += DLLExportedFns[i]->getName();
688         OutStreamer.EmitBytes(name);
689       }
690     }
691   }
692
693   if (Subtarget->isTargetELF()) {
694     const TargetLoweringObjectFileELF &TLOFELF =
695       static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
696
697     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
698
699     // Output stubs for external and common global variables.
700     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
701     if (!Stubs.empty()) {
702       OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
703       const DataLayout *TD = TM.getDataLayout();
704
705       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
706         OutStreamer.EmitLabel(Stubs[i].first);
707         OutStreamer.EmitSymbolValue(Stubs[i].second.getPointer(),
708                                     TD->getPointerSize());
709       }
710       Stubs.clear();
711     }
712   }
713 }
714
715 //===----------------------------------------------------------------------===//
716 // Target Registry Stuff
717 //===----------------------------------------------------------------------===//
718
719 // Force static initialization.
720 extern "C" void LLVMInitializeX86AsmPrinter() {
721   RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
722   RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
723 }