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