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