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