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