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