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