f1e4cb813df2201f94b55430bc36d5d9a72be5f5
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
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 implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "WinException.h"
18 #include "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/GCMetadataPrinter.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBundle.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbolELF.h"
43 #include "llvm/MC/MCValue.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Target/TargetFrameLowering.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
55 using namespace llvm;
56
57 #define DEBUG_TYPE "asm-printer"
58
59 static const char *const DWARFGroupName = "DWARF Emission";
60 static const char *const DbgTimerName = "Debug Info Emission";
61 static const char *const EHTimerName = "DWARF Exception Writer";
62 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
63
64 STATISTIC(EmittedInsts, "Number of machine instrs printed");
65
66 char AsmPrinter::ID = 0;
67
68 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
69 static gcp_map_type &getGCMap(void *&P) {
70   if (!P)
71     P = new gcp_map_type();
72   return *(gcp_map_type*)P;
73 }
74
75
76 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
77 /// value in log2 form.  This rounds up to the preferred alignment if possible
78 /// and legal.
79 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
80                                    unsigned InBits = 0) {
81   unsigned NumBits = 0;
82   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
83     NumBits = DL.getPreferredAlignmentLog(GVar);
84
85   // If InBits is specified, round it to it.
86   if (InBits > NumBits)
87     NumBits = InBits;
88
89   // If the GV has a specified alignment, take it into account.
90   if (GV->getAlignment() == 0)
91     return NumBits;
92
93   unsigned GVAlign = Log2_32(GV->getAlignment());
94
95   // If the GVAlign is larger than NumBits, or if we are required to obey
96   // NumBits because the GV has an assigned section, obey it.
97   if (GVAlign > NumBits || GV->hasSection())
98     NumBits = GVAlign;
99   return NumBits;
100 }
101
102 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
103     : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
104       OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
105       LastMI(nullptr), LastFn(0), Counter(~0U) {
106   DD = nullptr;
107   MMI = nullptr;
108   LI = nullptr;
109   MF = nullptr;
110   CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
111   CurrentFnBegin = nullptr;
112   CurrentFnEnd = nullptr;
113   GCMetadataPrinters = nullptr;
114   VerboseAsm = OutStreamer->isVerboseAsm();
115 }
116
117 AsmPrinter::~AsmPrinter() {
118   assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
119
120   if (GCMetadataPrinters) {
121     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
122
123     delete &GCMap;
124     GCMetadataPrinters = nullptr;
125   }
126 }
127
128 /// getFunctionNumber - Return a unique ID for the current function.
129 ///
130 unsigned AsmPrinter::getFunctionNumber() const {
131   return MF->getFunctionNumber();
132 }
133
134 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
135   return *TM.getObjFileLowering();
136 }
137
138 const DataLayout &AsmPrinter::getDataLayout() const {
139   return MMI->getModule()->getDataLayout();
140 }
141
142 // Do not use the cached DataLayout because some client use it without a Module
143 // (llmv-dsymutil, llvm-dwarfdump).
144 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); }
145
146 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
147   assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
148   return MF->getSubtarget<MCSubtargetInfo>();
149 }
150
151 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
152   S.EmitInstruction(Inst, getSubtargetInfo());
153 }
154
155 StringRef AsmPrinter::getTargetTriple() const {
156   return TM.getTargetTriple().str();
157 }
158
159 /// getCurrentSection() - Return the current section we are emitting to.
160 const MCSection *AsmPrinter::getCurrentSection() const {
161   return OutStreamer->getCurrentSection().first;
162 }
163
164
165
166 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
167   AU.setPreservesAll();
168   MachineFunctionPass::getAnalysisUsage(AU);
169   AU.addRequired<MachineModuleInfo>();
170   AU.addRequired<GCModuleInfo>();
171   if (isVerbose())
172     AU.addRequired<MachineLoopInfo>();
173 }
174
175 bool AsmPrinter::doInitialization(Module &M) {
176   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
177
178   // Initialize TargetLoweringObjectFile.
179   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
180     .Initialize(OutContext, TM);
181
182   OutStreamer->InitSections(false);
183
184   Mang = new Mangler();
185
186   // Emit the version-min deplyment target directive if needed.
187   //
188   // FIXME: If we end up with a collection of these sorts of Darwin-specific
189   // or ELF-specific things, it may make sense to have a platform helper class
190   // that will work with the target helper class. For now keep it here, as the
191   // alternative is duplicated code in each of the target asm printers that
192   // use the directive, where it would need the same conditionalization
193   // anyway.
194   Triple TT(getTargetTriple());
195   if (TT.isOSDarwin()) {
196     unsigned Major, Minor, Update;
197     TT.getOSVersion(Major, Minor, Update);
198     // If there is a version specified, Major will be non-zero.
199     if (Major) {
200       MCVersionMinType VersionType;
201       if (TT.isWatchOS())
202         VersionType = MCVM_WatchOSVersionMin;
203       else if (TT.isTvOS())
204         VersionType = MCVM_TvOSVersionMin;
205       else if (TT.isMacOSX())
206         VersionType = MCVM_OSXVersionMin;
207       else
208         VersionType = MCVM_IOSVersionMin;
209       OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update);
210     }
211   }
212
213   // Allow the target to emit any magic that it wants at the start of the file.
214   EmitStartOfAsmFile(M);
215
216   // Very minimal debug info. It is ignored if we emit actual debug info. If we
217   // don't, this at least helps the user find where a global came from.
218   if (MAI->hasSingleParameterDotFile()) {
219     // .file "foo.c"
220     OutStreamer->EmitFileDirective(M.getModuleIdentifier());
221   }
222
223   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
224   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
225   for (auto &I : *MI)
226     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
227       MP->beginAssembly(M, *MI, *this);
228
229   // Emit module-level inline asm if it exists.
230   if (!M.getModuleInlineAsm().empty()) {
231     // We're at the module level. Construct MCSubtarget from the default CPU
232     // and target triple.
233     std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
234         TM.getTargetTriple().str(), TM.getTargetCPU(),
235         TM.getTargetFeatureString()));
236     OutStreamer->AddComment("Start of file scope inline assembly");
237     OutStreamer->AddBlankLine();
238     EmitInlineAsm(M.getModuleInlineAsm()+"\n",
239                   OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
240     OutStreamer->AddComment("End of file scope inline assembly");
241     OutStreamer->AddBlankLine();
242   }
243
244   if (MAI->doesSupportDebugInformation()) {
245     bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
246     if (EmitCodeView && TM.getTargetTriple().isKnownWindowsMSVCEnvironment()) {
247       Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
248                                      DbgTimerName,
249                                      CodeViewLineTablesGroupName));
250     }
251     if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
252       DD = new DwarfDebug(this, &M);
253       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
254     }
255   }
256
257   EHStreamer *ES = nullptr;
258   switch (MAI->getExceptionHandlingType()) {
259   case ExceptionHandling::None:
260     break;
261   case ExceptionHandling::SjLj:
262   case ExceptionHandling::DwarfCFI:
263     ES = new DwarfCFIException(this);
264     break;
265   case ExceptionHandling::ARM:
266     ES = new ARMException(this);
267     break;
268   case ExceptionHandling::WinEH:
269     switch (MAI->getWinEHEncodingType()) {
270     default: llvm_unreachable("unsupported unwinding information encoding");
271     case WinEH::EncodingType::Invalid:
272       break;
273     case WinEH::EncodingType::X86:
274     case WinEH::EncodingType::Itanium:
275       ES = new WinException(this);
276       break;
277     }
278     break;
279   }
280   if (ES)
281     Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
282   return false;
283 }
284
285 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
286   if (!MAI.hasWeakDefCanBeHiddenDirective())
287     return false;
288
289   return canBeOmittedFromSymbolTable(GV);
290 }
291
292 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
293   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
294   switch (Linkage) {
295   case GlobalValue::CommonLinkage:
296   case GlobalValue::LinkOnceAnyLinkage:
297   case GlobalValue::LinkOnceODRLinkage:
298   case GlobalValue::WeakAnyLinkage:
299   case GlobalValue::WeakODRLinkage:
300     if (MAI->hasWeakDefDirective()) {
301       // .globl _foo
302       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
303
304       if (!canBeHidden(GV, *MAI))
305         // .weak_definition _foo
306         OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
307       else
308         OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
309     } else if (MAI->hasLinkOnceDirective()) {
310       // .globl _foo
311       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
312       //NOTE: linkonce is handled by the section the symbol was assigned to.
313     } else {
314       // .weak _foo
315       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
316     }
317     return;
318   case GlobalValue::AppendingLinkage:
319     // FIXME: appending linkage variables should go into a section of
320     // their name or something.  For now, just emit them as external.
321   case GlobalValue::ExternalLinkage:
322     // If external or appending, declare as a global symbol.
323     // .globl _foo
324     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
325     return;
326   case GlobalValue::PrivateLinkage:
327   case GlobalValue::InternalLinkage:
328     return;
329   case GlobalValue::AvailableExternallyLinkage:
330     llvm_unreachable("Should never emit this");
331   case GlobalValue::ExternalWeakLinkage:
332     llvm_unreachable("Don't know how to emit these");
333   }
334   llvm_unreachable("Unknown linkage type!");
335 }
336
337 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
338                                    const GlobalValue *GV) const {
339   TM.getNameWithPrefix(Name, GV, *Mang);
340 }
341
342 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
343   return TM.getSymbol(GV, *Mang);
344 }
345
346 static MCSymbol *getOrCreateEmuTLSControlSym(MCSymbol *GVSym, MCContext &C) {
347   return C.getOrCreateSymbol(Twine("__emutls_v.") + GVSym->getName());
348 }
349
350 static MCSymbol *getOrCreateEmuTLSInitSym(MCSymbol *GVSym, MCContext &C) {
351   return C.getOrCreateSymbol(Twine("__emutls_t.") + GVSym->getName());
352 }
353
354 /// EmitEmulatedTLSControlVariable - Emit the control variable for an emulated TLS variable.
355 void AsmPrinter::EmitEmulatedTLSControlVariable(const GlobalVariable *GV,
356                                                 MCSymbol *EmittedSym,
357                                                 bool AllZeroInitValue) {
358   // If there is init value, use .data.rel.local section;
359   // otherwise use the .data section.
360   MCSection *TLSVarSection =
361       const_cast<MCSection *>((GV->hasInitializer() && !AllZeroInitValue)
362                                   ? getObjFileLowering().getDataRelSection()
363                                   : getObjFileLowering().getDataSection());
364   OutStreamer->SwitchSection(TLSVarSection);
365   MCSymbol *GVSym = getSymbol(GV);
366   EmitLinkage(GV, EmittedSym);  // same linkage as GV
367   const DataLayout &DL = GV->getParent()->getDataLayout();
368   uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
369   unsigned AlignLog = getGVAlignmentLog2(GV, DL);
370   unsigned WordSize = DL.getPointerSize();
371   unsigned Alignment = DL.getPointerABIAlignment();
372   EmitAlignment(Log2_32(Alignment));
373   OutStreamer->EmitLabel(EmittedSym);
374   OutStreamer->EmitIntValue(Size, WordSize);
375   OutStreamer->EmitIntValue((1 << AlignLog), WordSize);
376   OutStreamer->EmitIntValue(0, WordSize);
377   if (GV->hasInitializer() && !AllZeroInitValue) {
378     OutStreamer->EmitSymbolValue(
379         getOrCreateEmuTLSInitSym(GVSym, OutContext), WordSize);
380   } else
381     OutStreamer->EmitIntValue(0, WordSize);
382   if (MAI->hasDotTypeDotSizeDirective())
383     OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedSym),
384                              MCConstantExpr::create(4 * WordSize, OutContext));
385   OutStreamer->AddBlankLine();  // End of the __emutls_v.* variable.
386 }
387
388 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
389 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
390   bool IsEmuTLSVar =
391       GV->getThreadLocalMode() != llvm::GlobalVariable::NotThreadLocal &&
392       TM.Options.EmulatedTLS;
393   assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
394          "No emulated TLS variables in the common section");
395
396   if (GV->hasInitializer()) {
397     // Check to see if this is a special global used by LLVM, if so, emit it.
398     if (EmitSpecialLLVMGlobal(GV))
399       return;
400
401     // Skip the emission of global equivalents. The symbol can be emitted later
402     // on by emitGlobalGOTEquivs in case it turns out to be needed.
403     if (GlobalGOTEquivs.count(getSymbol(GV)))
404       return;
405
406     if (isVerbose() && !IsEmuTLSVar) {
407       // When printing the control variable __emutls_v.*,
408       // we don't need to print the original TLS variable name.
409       GV->printAsOperand(OutStreamer->GetCommentOS(),
410                      /*PrintType=*/false, GV->getParent());
411       OutStreamer->GetCommentOS() << '\n';
412     }
413   }
414
415   MCSymbol *GVSym = getSymbol(GV);
416   MCSymbol *EmittedSym = IsEmuTLSVar ?
417       getOrCreateEmuTLSControlSym(GVSym, OutContext) : GVSym;
418   // getOrCreateEmuTLSControlSym only creates the symbol with name and default attributes.
419   // GV's or GVSym's attributes will be used for the EmittedSym.
420
421   EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
422
423   if (!GV->hasInitializer())   // External globals require no extra code.
424     return;
425
426   GVSym->redefineIfPossible();
427   if (GVSym->isDefined() || GVSym->isVariable())
428     report_fatal_error("symbol '" + Twine(GVSym->getName()) +
429                        "' is already defined");
430
431   if (MAI->hasDotTypeDotSizeDirective())
432     OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
433
434   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
435
436   const DataLayout &DL = GV->getParent()->getDataLayout();
437   uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
438
439   // If the alignment is specified, we *must* obey it.  Overaligning a global
440   // with a specified alignment is a prompt way to break globals emitted to
441   // sections and expected to be contiguous (e.g. ObjC metadata).
442   unsigned AlignLog = getGVAlignmentLog2(GV, DL);
443
444   bool AllZeroInitValue = false;
445   const Constant *InitValue = GV->getInitializer();
446   if (isa<ConstantAggregateZero>(InitValue))
447     AllZeroInitValue = true;
448   else {
449     const ConstantInt *InitIntValue = dyn_cast<ConstantInt>(InitValue);
450     if (InitIntValue && InitIntValue->isZero())
451       AllZeroInitValue = true;
452   }
453   if (IsEmuTLSVar)
454     EmitEmulatedTLSControlVariable(GV, EmittedSym, AllZeroInitValue);
455
456   for (const HandlerInfo &HI : Handlers) {
457     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
458     HI.Handler->setSymbolSize(GVSym, Size);
459   }
460
461   // Handle common and BSS local symbols (.lcomm).
462   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
463     assert(!(IsEmuTLSVar && GVKind.isCommon()) &&
464            "No emulated TLS variables in the common section");
465     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
466     unsigned Align = 1 << AlignLog;
467
468     // Handle common symbols.
469     if (GVKind.isCommon()) {
470       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
471         Align = 0;
472
473       // .comm _foo, 42, 4
474       OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
475       return;
476     }
477
478     // Handle local BSS symbols.
479     if (MAI->hasMachoZeroFillDirective()) {
480       MCSection *TheSection =
481           getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
482       // .zerofill __DATA, __bss, _foo, 400, 5
483       OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
484       return;
485     }
486
487     // Use .lcomm only if it supports user-specified alignment.
488     // Otherwise, while it would still be correct to use .lcomm in some
489     // cases (e.g. when Align == 1), the external assembler might enfore
490     // some -unknown- default alignment behavior, which could cause
491     // spurious differences between external and integrated assembler.
492     // Prefer to simply fall back to .local / .comm in this case.
493     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
494       // .lcomm _foo, 42
495       OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
496       return;
497     }
498
499     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
500       Align = 0;
501
502     // .local _foo
503     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
504     // .comm _foo, 42, 4
505     OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
506     return;
507   }
508
509   if (IsEmuTLSVar && AllZeroInitValue)
510     return;  // No need of initialization values.
511
512   MCSymbol *EmittedInitSym = IsEmuTLSVar ?
513       getOrCreateEmuTLSInitSym(GVSym, OutContext) : GVSym;
514   // getOrCreateEmuTLSInitSym only creates the symbol with name and default attributes.
515   // GV's or GVSym's attributes will be used for the EmittedInitSym.
516
517   MCSection *TheSection = IsEmuTLSVar ?
518       getObjFileLowering().getReadOnlySection() :
519       getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
520
521   // Handle the zerofill directive on darwin, which is a special form of BSS
522   // emission.
523   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective() && !IsEmuTLSVar) {
524     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
525
526     // .globl _foo
527     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
528     // .zerofill __DATA, __common, _foo, 400, 5
529     OutStreamer->EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
530     return;
531   }
532
533   // Handle thread local data for mach-o which requires us to output an
534   // additional structure of data and mangle the original symbol so that we
535   // can reference it later.
536   //
537   // TODO: This should become an "emit thread local global" method on TLOF.
538   // All of this macho specific stuff should be sunk down into TLOFMachO and
539   // stuff like "TLSExtraDataSection" should no longer be part of the parent
540   // TLOF class.  This will also make it more obvious that stuff like
541   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
542   // specific code.
543   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective() && !IsEmuTLSVar) {
544     // Emit the .tbss symbol
545     MCSymbol *MangSym =
546       OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
547
548     if (GVKind.isThreadBSS()) {
549       TheSection = getObjFileLowering().getTLSBSSSection();
550       OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
551     } else if (GVKind.isThreadData()) {
552       OutStreamer->SwitchSection(TheSection);
553
554       EmitAlignment(AlignLog, GV);
555       OutStreamer->EmitLabel(MangSym);
556
557       EmitGlobalConstant(GV->getParent()->getDataLayout(),
558                          GV->getInitializer());
559     }
560
561     OutStreamer->AddBlankLine();
562
563     // Emit the variable struct for the runtime.
564     MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
565
566     OutStreamer->SwitchSection(TLVSect);
567     // Emit the linkage here.
568     EmitLinkage(GV, GVSym);
569     OutStreamer->EmitLabel(GVSym);
570
571     // Three pointers in size:
572     //   - __tlv_bootstrap - used to make sure support exists
573     //   - spare pointer, used when mapped by the runtime
574     //   - pointer to mangled symbol above with initializer
575     unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
576     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
577                                 PtrSize);
578     OutStreamer->EmitIntValue(0, PtrSize);
579     OutStreamer->EmitSymbolValue(MangSym, PtrSize);
580
581     OutStreamer->AddBlankLine();
582     return;
583   }
584
585   OutStreamer->SwitchSection(TheSection);
586
587   // emutls_t.* symbols are only used in the current compilation unit.
588   if (!IsEmuTLSVar)
589     EmitLinkage(GV, EmittedInitSym);
590   EmitAlignment(AlignLog, GV);
591
592   OutStreamer->EmitLabel(EmittedInitSym);
593
594   EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
595
596   if (MAI->hasDotTypeDotSizeDirective())
597     // .size foo, 42
598     OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedInitSym),
599                              MCConstantExpr::create(Size, OutContext));
600
601   OutStreamer->AddBlankLine();
602 }
603
604 /// EmitFunctionHeader - This method emits the header for the current
605 /// function.
606 void AsmPrinter::EmitFunctionHeader() {
607   // Print out constants referenced by the function
608   EmitConstantPool();
609
610   // Print the 'header' of function.
611   const Function *F = MF->getFunction();
612
613   OutStreamer->SwitchSection(
614       getObjFileLowering().SectionForGlobal(F, *Mang, TM));
615   EmitVisibility(CurrentFnSym, F->getVisibility());
616
617   EmitLinkage(F, CurrentFnSym);
618   if (MAI->hasFunctionAlignment())
619     EmitAlignment(MF->getAlignment(), F);
620
621   if (MAI->hasDotTypeDotSizeDirective())
622     OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
623
624   if (isVerbose()) {
625     F->printAsOperand(OutStreamer->GetCommentOS(),
626                    /*PrintType=*/false, F->getParent());
627     OutStreamer->GetCommentOS() << '\n';
628   }
629
630   // Emit the prefix data.
631   if (F->hasPrefixData())
632     EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData());
633
634   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
635   // do their wild and crazy things as required.
636   EmitFunctionEntryLabel();
637
638   // If the function had address-taken blocks that got deleted, then we have
639   // references to the dangling symbols.  Emit them at the start of the function
640   // so that we don't get references to undefined symbols.
641   std::vector<MCSymbol*> DeadBlockSyms;
642   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
643   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
644     OutStreamer->AddComment("Address taken block that was later removed");
645     OutStreamer->EmitLabel(DeadBlockSyms[i]);
646   }
647
648   if (CurrentFnBegin) {
649     if (MAI->useAssignmentForEHBegin()) {
650       MCSymbol *CurPos = OutContext.createTempSymbol();
651       OutStreamer->EmitLabel(CurPos);
652       OutStreamer->EmitAssignment(CurrentFnBegin,
653                                  MCSymbolRefExpr::create(CurPos, OutContext));
654     } else {
655       OutStreamer->EmitLabel(CurrentFnBegin);
656     }
657   }
658
659   // Emit pre-function debug and/or EH information.
660   for (const HandlerInfo &HI : Handlers) {
661     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
662     HI.Handler->beginFunction(MF);
663   }
664
665   // Emit the prologue data.
666   if (F->hasPrologueData())
667     EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData());
668 }
669
670 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
671 /// function.  This can be overridden by targets as required to do custom stuff.
672 void AsmPrinter::EmitFunctionEntryLabel() {
673   CurrentFnSym->redefineIfPossible();
674
675   // The function label could have already been emitted if two symbols end up
676   // conflicting due to asm renaming.  Detect this and emit an error.
677   if (CurrentFnSym->isVariable())
678     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
679                        "' is a protected alias");
680   if (CurrentFnSym->isDefined())
681     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
682                        "' label emitted multiple times to assembly file");
683
684   return OutStreamer->EmitLabel(CurrentFnSym);
685 }
686
687 /// emitComments - Pretty-print comments for instructions.
688 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
689   const MachineFunction *MF = MI.getParent()->getParent();
690   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
691
692   // Check for spills and reloads
693   int FI;
694
695   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
696
697   // We assume a single instruction only has a spill or reload, not
698   // both.
699   const MachineMemOperand *MMO;
700   if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
701     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
702       MMO = *MI.memoperands_begin();
703       CommentOS << MMO->getSize() << "-byte Reload\n";
704     }
705   } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
706     if (FrameInfo->isSpillSlotObjectIndex(FI))
707       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
708   } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
709     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
710       MMO = *MI.memoperands_begin();
711       CommentOS << MMO->getSize() << "-byte Spill\n";
712     }
713   } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
714     if (FrameInfo->isSpillSlotObjectIndex(FI))
715       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
716   }
717
718   // Check for spill-induced copies
719   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
720     CommentOS << " Reload Reuse\n";
721 }
722
723 /// emitImplicitDef - This method emits the specified machine instruction
724 /// that is an implicit def.
725 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
726   unsigned RegNo = MI->getOperand(0).getReg();
727   OutStreamer->AddComment(Twine("implicit-def: ") +
728                           MMI->getContext().getRegisterInfo()->getName(RegNo));
729   OutStreamer->AddBlankLine();
730 }
731
732 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
733   std::string Str = "kill:";
734   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
735     const MachineOperand &Op = MI->getOperand(i);
736     assert(Op.isReg() && "KILL instruction must have only register operands");
737     Str += ' ';
738     Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
739     Str += (Op.isDef() ? "<def>" : "<kill>");
740   }
741   AP.OutStreamer->AddComment(Str);
742   AP.OutStreamer->AddBlankLine();
743 }
744
745 /// emitDebugValueComment - This method handles the target-independent form
746 /// of DBG_VALUE, returning true if it was able to do so.  A false return
747 /// means the target will need to handle MI in EmitInstruction.
748 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
749   // This code handles only the 4-operand target-independent form.
750   if (MI->getNumOperands() != 4)
751     return false;
752
753   SmallString<128> Str;
754   raw_svector_ostream OS(Str);
755   OS << "DEBUG_VALUE: ";
756
757   const DILocalVariable *V = MI->getDebugVariable();
758   if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
759     StringRef Name = SP->getDisplayName();
760     if (!Name.empty())
761       OS << Name << ":";
762   }
763   OS << V->getName();
764
765   const DIExpression *Expr = MI->getDebugExpression();
766   if (Expr->isBitPiece())
767     OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
768        << " size=" << Expr->getBitPieceSize() << "]";
769   OS << " <- ";
770
771   // The second operand is only an offset if it's an immediate.
772   bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
773   int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
774
775   // Register or immediate value. Register 0 means undef.
776   if (MI->getOperand(0).isFPImm()) {
777     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
778     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
779       OS << (double)APF.convertToFloat();
780     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
781       OS << APF.convertToDouble();
782     } else {
783       // There is no good way to print long double.  Convert a copy to
784       // double.  Ah well, it's only a comment.
785       bool ignored;
786       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
787                   &ignored);
788       OS << "(long double) " << APF.convertToDouble();
789     }
790   } else if (MI->getOperand(0).isImm()) {
791     OS << MI->getOperand(0).getImm();
792   } else if (MI->getOperand(0).isCImm()) {
793     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
794   } else {
795     unsigned Reg;
796     if (MI->getOperand(0).isReg()) {
797       Reg = MI->getOperand(0).getReg();
798     } else {
799       assert(MI->getOperand(0).isFI() && "Unknown operand type");
800       const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
801       Offset += TFI->getFrameIndexReference(*AP.MF,
802                                             MI->getOperand(0).getIndex(), Reg);
803       Deref = true;
804     }
805     if (Reg == 0) {
806       // Suppress offset, it is not meaningful here.
807       OS << "undef";
808       // NOTE: Want this comment at start of line, don't emit with AddComment.
809       AP.OutStreamer->emitRawComment(OS.str());
810       return true;
811     }
812     if (Deref)
813       OS << '[';
814     OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
815   }
816
817   if (Deref)
818     OS << '+' << Offset << ']';
819
820   // NOTE: Want this comment at start of line, don't emit with AddComment.
821   AP.OutStreamer->emitRawComment(OS.str());
822   return true;
823 }
824
825 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
826   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
827       MF->getFunction()->needsUnwindTableEntry())
828     return CFI_M_EH;
829
830   if (MMI->hasDebugInfo())
831     return CFI_M_Debug;
832
833   return CFI_M_None;
834 }
835
836 bool AsmPrinter::needsSEHMoves() {
837   return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
838 }
839
840 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
841   ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
842   if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
843       ExceptionHandlingType != ExceptionHandling::ARM)
844     return;
845
846   if (needsCFIMoves() == CFI_M_None)
847     return;
848
849   const MachineModuleInfo &MMI = MF->getMMI();
850   const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
851   unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
852   const MCCFIInstruction &CFI = Instrs[CFIIndex];
853   emitCFIInstruction(CFI);
854 }
855
856 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
857   // The operands are the MCSymbol and the frame offset of the allocation.
858   MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
859   int FrameOffset = MI.getOperand(1).getImm();
860
861   // Emit a symbol assignment.
862   OutStreamer->EmitAssignment(FrameAllocSym,
863                              MCConstantExpr::create(FrameOffset, OutContext));
864 }
865
866 /// EmitFunctionBody - This method emits the body and trailer for a
867 /// function.
868 void AsmPrinter::EmitFunctionBody() {
869   EmitFunctionHeader();
870
871   // Emit target-specific gunk before the function body.
872   EmitFunctionBodyStart();
873
874   bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
875
876   // Print out code for the function.
877   bool HasAnyRealCode = false;
878   for (auto &MBB : *MF) {
879     // Print a label for the basic block.
880     EmitBasicBlockStart(MBB);
881     for (auto &MI : MBB) {
882
883       // Print the assembly for the instruction.
884       if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
885           !MI.isDebugValue()) {
886         HasAnyRealCode = true;
887         ++EmittedInsts;
888       }
889
890       if (ShouldPrintDebugScopes) {
891         for (const HandlerInfo &HI : Handlers) {
892           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
893                              TimePassesIsEnabled);
894           HI.Handler->beginInstruction(&MI);
895         }
896       }
897
898       if (isVerbose())
899         emitComments(MI, OutStreamer->GetCommentOS());
900
901       switch (MI.getOpcode()) {
902       case TargetOpcode::CFI_INSTRUCTION:
903         emitCFIInstruction(MI);
904         break;
905
906       case TargetOpcode::LOCAL_ESCAPE:
907         emitFrameAlloc(MI);
908         break;
909
910       case TargetOpcode::EH_LABEL:
911       case TargetOpcode::GC_LABEL:
912         OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
913         break;
914       case TargetOpcode::INLINEASM:
915         EmitInlineAsm(&MI);
916         break;
917       case TargetOpcode::DBG_VALUE:
918         if (isVerbose()) {
919           if (!emitDebugValueComment(&MI, *this))
920             EmitInstruction(&MI);
921         }
922         break;
923       case TargetOpcode::IMPLICIT_DEF:
924         if (isVerbose()) emitImplicitDef(&MI);
925         break;
926       case TargetOpcode::KILL:
927         if (isVerbose()) emitKill(&MI, *this);
928         break;
929       default:
930         EmitInstruction(&MI);
931         break;
932       }
933
934       if (ShouldPrintDebugScopes) {
935         for (const HandlerInfo &HI : Handlers) {
936           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
937                              TimePassesIsEnabled);
938           HI.Handler->endInstruction();
939         }
940       }
941     }
942
943     EmitBasicBlockEnd(MBB);
944   }
945
946   // If the function is empty and the object file uses .subsections_via_symbols,
947   // then we need to emit *something* to the function body to prevent the
948   // labels from collapsing together.  Just emit a noop.
949   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
950     MCInst Noop;
951     MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
952     OutStreamer->AddComment("avoids zero-length function");
953
954     // Targets can opt-out of emitting the noop here by leaving the opcode
955     // unspecified.
956     if (Noop.getOpcode())
957       OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
958   }
959
960   const Function *F = MF->getFunction();
961   for (const auto &BB : *F) {
962     if (!BB.hasAddressTaken())
963       continue;
964     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
965     if (Sym->isDefined())
966       continue;
967     OutStreamer->AddComment("Address of block that was removed by CodeGen");
968     OutStreamer->EmitLabel(Sym);
969   }
970
971   // Emit target-specific gunk after the function body.
972   EmitFunctionBodyEnd();
973
974   if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
975       MMI->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) {
976     // Create a symbol for the end of function.
977     CurrentFnEnd = createTempSymbol("func_end");
978     OutStreamer->EmitLabel(CurrentFnEnd);
979   }
980
981   // If the target wants a .size directive for the size of the function, emit
982   // it.
983   if (MAI->hasDotTypeDotSizeDirective()) {
984     // We can get the size as difference between the function label and the
985     // temp label.
986     const MCExpr *SizeExp = MCBinaryExpr::createSub(
987         MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
988         MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
989     if (auto Sym = dyn_cast<MCSymbolELF>(CurrentFnSym))
990       OutStreamer->emitELFSize(Sym, SizeExp);
991   }
992
993   for (const HandlerInfo &HI : Handlers) {
994     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
995     HI.Handler->markFunctionEnd();
996   }
997
998   // Print out jump tables referenced by the function.
999   EmitJumpTableInfo();
1000
1001   // Emit post-function debug and/or EH information.
1002   for (const HandlerInfo &HI : Handlers) {
1003     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
1004     HI.Handler->endFunction(MF);
1005   }
1006   MMI->EndFunction();
1007
1008   OutStreamer->AddBlankLine();
1009 }
1010
1011 /// \brief Compute the number of Global Variables that uses a Constant.
1012 static unsigned getNumGlobalVariableUses(const Constant *C) {
1013   if (!C)
1014     return 0;
1015
1016   if (isa<GlobalVariable>(C))
1017     return 1;
1018
1019   unsigned NumUses = 0;
1020   for (auto *CU : C->users())
1021     NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1022
1023   return NumUses;
1024 }
1025
1026 /// \brief Only consider global GOT equivalents if at least one user is a
1027 /// cstexpr inside an initializer of another global variables. Also, don't
1028 /// handle cstexpr inside instructions. During global variable emission,
1029 /// candidates are skipped and are emitted later in case at least one cstexpr
1030 /// isn't replaced by a PC relative GOT entry access.
1031 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1032                                      unsigned &NumGOTEquivUsers) {
1033   // Global GOT equivalents are unnamed private globals with a constant
1034   // pointer initializer to another global symbol. They must point to a
1035   // GlobalVariable or Function, i.e., as GlobalValue.
1036   if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
1037       !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
1038     return false;
1039
1040   // To be a got equivalent, at least one of its users need to be a constant
1041   // expression used by another global variable.
1042   for (auto *U : GV->users())
1043     NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1044
1045   return NumGOTEquivUsers > 0;
1046 }
1047
1048 /// \brief Unnamed constant global variables solely contaning a pointer to
1049 /// another globals variable is equivalent to a GOT table entry; it contains the
1050 /// the address of another symbol. Optimize it and replace accesses to these
1051 /// "GOT equivalents" by using the GOT entry for the final global instead.
1052 /// Compute GOT equivalent candidates among all global variables to avoid
1053 /// emitting them if possible later on, after it use is replaced by a GOT entry
1054 /// access.
1055 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1056   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1057     return;
1058
1059   for (const auto &G : M.globals()) {
1060     unsigned NumGOTEquivUsers = 0;
1061     if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1062       continue;
1063
1064     const MCSymbol *GOTEquivSym = getSymbol(&G);
1065     GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1066   }
1067 }
1068
1069 /// \brief Constant expressions using GOT equivalent globals may not be eligible
1070 /// for PC relative GOT entry conversion, in such cases we need to emit such
1071 /// globals we previously omitted in EmitGlobalVariable.
1072 void AsmPrinter::emitGlobalGOTEquivs() {
1073   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1074     return;
1075
1076   SmallVector<const GlobalVariable *, 8> FailedCandidates;
1077   for (auto &I : GlobalGOTEquivs) {
1078     const GlobalVariable *GV = I.second.first;
1079     unsigned Cnt = I.second.second;
1080     if (Cnt)
1081       FailedCandidates.push_back(GV);
1082   }
1083   GlobalGOTEquivs.clear();
1084
1085   for (auto *GV : FailedCandidates)
1086     EmitGlobalVariable(GV);
1087 }
1088
1089 bool AsmPrinter::doFinalization(Module &M) {
1090   // Set the MachineFunction to nullptr so that we can catch attempted
1091   // accesses to MF specific features at the module level and so that
1092   // we can conditionalize accesses based on whether or not it is nullptr.
1093   MF = nullptr;
1094
1095   // Gather all GOT equivalent globals in the module. We really need two
1096   // passes over the globals: one to compute and another to avoid its emission
1097   // in EmitGlobalVariable, otherwise we would not be able to handle cases
1098   // where the got equivalent shows up before its use.
1099   computeGlobalGOTEquivs(M);
1100
1101   // Emit global variables.
1102   for (const auto &G : M.globals())
1103     EmitGlobalVariable(&G);
1104
1105   // Emit remaining GOT equivalent globals.
1106   emitGlobalGOTEquivs();
1107
1108   // Emit visibility info for declarations
1109   for (const Function &F : M) {
1110     if (!F.isDeclarationForLinker())
1111       continue;
1112     GlobalValue::VisibilityTypes V = F.getVisibility();
1113     if (V == GlobalValue::DefaultVisibility)
1114       continue;
1115
1116     MCSymbol *Name = getSymbol(&F);
1117     EmitVisibility(Name, V, false);
1118   }
1119
1120   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1121
1122   // Emit module flags.
1123   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1124   M.getModuleFlagsMetadata(ModuleFlags);
1125   if (!ModuleFlags.empty())
1126     TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1127
1128   if (TM.getTargetTriple().isOSBinFormatELF()) {
1129     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1130
1131     // Output stubs for external and common global variables.
1132     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1133     if (!Stubs.empty()) {
1134       OutStreamer->SwitchSection(TLOF.getDataRelSection());
1135       const DataLayout &DL = M.getDataLayout();
1136
1137       for (const auto &Stub : Stubs) {
1138         OutStreamer->EmitLabel(Stub.first);
1139         OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1140                                      DL.getPointerSize());
1141       }
1142     }
1143   }
1144
1145   // Finalize debug and EH information.
1146   for (const HandlerInfo &HI : Handlers) {
1147     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1148                        TimePassesIsEnabled);
1149     HI.Handler->endModule();
1150     delete HI.Handler;
1151   }
1152   Handlers.clear();
1153   DD = nullptr;
1154
1155   // If the target wants to know about weak references, print them all.
1156   if (MAI->getWeakRefDirective()) {
1157     // FIXME: This is not lazy, it would be nice to only print weak references
1158     // to stuff that is actually used.  Note that doing so would require targets
1159     // to notice uses in operands (due to constant exprs etc).  This should
1160     // happen with the MC stuff eventually.
1161
1162     // Print out module-level global variables here.
1163     for (const auto &G : M.globals()) {
1164       if (!G.hasExternalWeakLinkage())
1165         continue;
1166       OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1167     }
1168
1169     for (const auto &F : M) {
1170       if (!F.hasExternalWeakLinkage())
1171         continue;
1172       OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1173     }
1174   }
1175
1176   OutStreamer->AddBlankLine();
1177   for (const auto &Alias : M.aliases()) {
1178     MCSymbol *Name = getSymbol(&Alias);
1179
1180     if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1181       OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1182     else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1183       OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1184     else
1185       assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1186
1187     EmitVisibility(Name, Alias.getVisibility());
1188
1189     // Emit the directives as assignments aka .set:
1190     OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1191
1192     // If the aliasee does not correspond to a symbol in the output, i.e. the
1193     // alias is not of an object or the aliased object is private, then set the
1194     // size of the alias symbol from the type of the alias. We don't do this in
1195     // other situations as the alias and aliasee having differing types but same
1196     // size may be intentional.
1197     const GlobalObject *BaseObject = Alias.getBaseObject();
1198     if (MAI->hasDotTypeDotSizeDirective() && Alias.getValueType()->isSized() &&
1199         (!BaseObject || BaseObject->hasPrivateLinkage())) {
1200       const DataLayout &DL = M.getDataLayout();
1201       uint64_t Size = DL.getTypeAllocSize(Alias.getValueType());
1202       OutStreamer->emitELFSize(cast<MCSymbolELF>(Name),
1203                                MCConstantExpr::create(Size, OutContext));
1204     }
1205   }
1206
1207   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1208   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1209   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1210     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1211       MP->finishAssembly(M, *MI, *this);
1212
1213   // Emit llvm.ident metadata in an '.ident' directive.
1214   EmitModuleIdents(M);
1215
1216   // Emit __morestack address if needed for indirect calls.
1217   if (MMI->usesMorestackAddr()) {
1218     MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1219         getDataLayout(), SectionKind::getReadOnly(),
1220         /*C=*/nullptr);
1221     OutStreamer->SwitchSection(ReadOnlySection);
1222
1223     MCSymbol *AddrSymbol =
1224         OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1225     OutStreamer->EmitLabel(AddrSymbol);
1226
1227     unsigned PtrSize = M.getDataLayout().getPointerSize(0);
1228     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1229                                  PtrSize);
1230   }
1231
1232   // If we don't have any trampolines, then we don't require stack memory
1233   // to be executable. Some targets have a directive to declare this.
1234   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1235   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1236     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1237       OutStreamer->SwitchSection(S);
1238
1239   // Allow the target to emit any magic that it wants at the end of the file,
1240   // after everything else has gone out.
1241   EmitEndOfAsmFile(M);
1242
1243   delete Mang; Mang = nullptr;
1244   MMI = nullptr;
1245
1246   OutStreamer->Finish();
1247   OutStreamer->reset();
1248
1249   return false;
1250 }
1251
1252 MCSymbol *AsmPrinter::getCurExceptionSym() {
1253   if (!CurExceptionSym)
1254     CurExceptionSym = createTempSymbol("exception");
1255   return CurExceptionSym;
1256 }
1257
1258 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1259   this->MF = &MF;
1260   // Get the function symbol.
1261   CurrentFnSym = getSymbol(MF.getFunction());
1262   CurrentFnSymForSize = CurrentFnSym;
1263   CurrentFnBegin = nullptr;
1264   CurExceptionSym = nullptr;
1265   bool NeedsLocalForSize = MAI->needsLocalForSize();
1266   if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1267       MMI->hasEHFunclets() || NeedsLocalForSize) {
1268     CurrentFnBegin = createTempSymbol("func_begin");
1269     if (NeedsLocalForSize)
1270       CurrentFnSymForSize = CurrentFnBegin;
1271   }
1272
1273   if (isVerbose())
1274     LI = &getAnalysis<MachineLoopInfo>();
1275 }
1276
1277 namespace {
1278 // Keep track the alignment, constpool entries per Section.
1279   struct SectionCPs {
1280     MCSection *S;
1281     unsigned Alignment;
1282     SmallVector<unsigned, 4> CPEs;
1283     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1284   };
1285 }
1286
1287 /// EmitConstantPool - Print to the current output stream assembly
1288 /// representations of the constants in the constant pool MCP. This is
1289 /// used to print out constants which have been "spilled to memory" by
1290 /// the code generator.
1291 ///
1292 void AsmPrinter::EmitConstantPool() {
1293   const MachineConstantPool *MCP = MF->getConstantPool();
1294   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1295   if (CP.empty()) return;
1296
1297   // Calculate sections for constant pool entries. We collect entries to go into
1298   // the same section together to reduce amount of section switch statements.
1299   SmallVector<SectionCPs, 4> CPSections;
1300   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1301     const MachineConstantPoolEntry &CPE = CP[i];
1302     unsigned Align = CPE.getAlignment();
1303
1304     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1305
1306     const Constant *C = nullptr;
1307     if (!CPE.isMachineConstantPoolEntry())
1308       C = CPE.Val.ConstVal;
1309
1310     MCSection *S =
1311         getObjFileLowering().getSectionForConstant(getDataLayout(), Kind, C);
1312
1313     // The number of sections are small, just do a linear search from the
1314     // last section to the first.
1315     bool Found = false;
1316     unsigned SecIdx = CPSections.size();
1317     while (SecIdx != 0) {
1318       if (CPSections[--SecIdx].S == S) {
1319         Found = true;
1320         break;
1321       }
1322     }
1323     if (!Found) {
1324       SecIdx = CPSections.size();
1325       CPSections.push_back(SectionCPs(S, Align));
1326     }
1327
1328     if (Align > CPSections[SecIdx].Alignment)
1329       CPSections[SecIdx].Alignment = Align;
1330     CPSections[SecIdx].CPEs.push_back(i);
1331   }
1332
1333   // Now print stuff into the calculated sections.
1334   const MCSection *CurSection = nullptr;
1335   unsigned Offset = 0;
1336   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1337     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1338       unsigned CPI = CPSections[i].CPEs[j];
1339       MCSymbol *Sym = GetCPISymbol(CPI);
1340       if (!Sym->isUndefined())
1341         continue;
1342
1343       if (CurSection != CPSections[i].S) {
1344         OutStreamer->SwitchSection(CPSections[i].S);
1345         EmitAlignment(Log2_32(CPSections[i].Alignment));
1346         CurSection = CPSections[i].S;
1347         Offset = 0;
1348       }
1349
1350       MachineConstantPoolEntry CPE = CP[CPI];
1351
1352       // Emit inter-object padding for alignment.
1353       unsigned AlignMask = CPE.getAlignment() - 1;
1354       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1355       OutStreamer->EmitZeros(NewOffset - Offset);
1356
1357       Type *Ty = CPE.getType();
1358       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1359
1360       OutStreamer->EmitLabel(Sym);
1361       if (CPE.isMachineConstantPoolEntry())
1362         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1363       else
1364         EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1365     }
1366   }
1367 }
1368
1369 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1370 /// by the current function to the current output stream.
1371 ///
1372 void AsmPrinter::EmitJumpTableInfo() {
1373   const DataLayout &DL = MF->getDataLayout();
1374   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1375   if (!MJTI) return;
1376   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1377   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1378   if (JT.empty()) return;
1379
1380   // Pick the directive to use to print the jump table entries, and switch to
1381   // the appropriate section.
1382   const Function *F = MF->getFunction();
1383   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1384   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1385       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1386       *F);
1387   if (JTInDiffSection) {
1388     // Drop it in the readonly section.
1389     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1390     OutStreamer->SwitchSection(ReadOnlySection);
1391   }
1392
1393   EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
1394
1395   // Jump tables in code sections are marked with a data_region directive
1396   // where that's supported.
1397   if (!JTInDiffSection)
1398     OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1399
1400   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1401     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1402
1403     // If this jump table was deleted, ignore it.
1404     if (JTBBs.empty()) continue;
1405
1406     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1407     /// emit a .set directive for each unique entry.
1408     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1409         MAI->doesSetDirectiveSuppressesReloc()) {
1410       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1411       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1412       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1413       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1414         const MachineBasicBlock *MBB = JTBBs[ii];
1415         if (!EmittedSets.insert(MBB).second)
1416           continue;
1417
1418         // .set LJTSet, LBB32-base
1419         const MCExpr *LHS =
1420           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1421         OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1422                                     MCBinaryExpr::createSub(LHS, Base,
1423                                                             OutContext));
1424       }
1425     }
1426
1427     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1428     // before each jump table.  The first label is never referenced, but tells
1429     // the assembler and linker the extents of the jump table object.  The
1430     // second label is actually referenced by the code.
1431     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1432       // FIXME: This doesn't have to have any specific name, just any randomly
1433       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1434       OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1435
1436     OutStreamer->EmitLabel(GetJTISymbol(JTI));
1437
1438     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1439       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1440   }
1441   if (!JTInDiffSection)
1442     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1443 }
1444
1445 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1446 /// current stream.
1447 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1448                                     const MachineBasicBlock *MBB,
1449                                     unsigned UID) const {
1450   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1451   const MCExpr *Value = nullptr;
1452   switch (MJTI->getEntryKind()) {
1453   case MachineJumpTableInfo::EK_Inline:
1454     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1455   case MachineJumpTableInfo::EK_Custom32:
1456     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1457         MJTI, MBB, UID, OutContext);
1458     break;
1459   case MachineJumpTableInfo::EK_BlockAddress:
1460     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1461     //     .word LBB123
1462     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1463     break;
1464   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1465     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1466     // with a relocation as gp-relative, e.g.:
1467     //     .gprel32 LBB123
1468     MCSymbol *MBBSym = MBB->getSymbol();
1469     OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1470     return;
1471   }
1472
1473   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1474     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1475     // with a relocation as gp-relative, e.g.:
1476     //     .gpdword LBB123
1477     MCSymbol *MBBSym = MBB->getSymbol();
1478     OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1479     return;
1480   }
1481
1482   case MachineJumpTableInfo::EK_LabelDifference32: {
1483     // Each entry is the address of the block minus the address of the jump
1484     // table. This is used for PIC jump tables where gprel32 is not supported.
1485     // e.g.:
1486     //      .word LBB123 - LJTI1_2
1487     // If the .set directive avoids relocations, this is emitted as:
1488     //      .set L4_5_set_123, LBB123 - LJTI1_2
1489     //      .word L4_5_set_123
1490     if (MAI->doesSetDirectiveSuppressesReloc()) {
1491       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1492                                       OutContext);
1493       break;
1494     }
1495     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1496     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1497     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1498     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1499     break;
1500   }
1501   }
1502
1503   assert(Value && "Unknown entry kind!");
1504
1505   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1506   OutStreamer->EmitValue(Value, EntrySize);
1507 }
1508
1509
1510 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1511 /// special global used by LLVM.  If so, emit it and return true, otherwise
1512 /// do nothing and return false.
1513 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1514   if (GV->getName() == "llvm.used") {
1515     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1516       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1517     return true;
1518   }
1519
1520   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1521   if (StringRef(GV->getSection()) == "llvm.metadata" ||
1522       GV->hasAvailableExternallyLinkage())
1523     return true;
1524
1525   if (!GV->hasAppendingLinkage()) return false;
1526
1527   assert(GV->hasInitializer() && "Not a special LLVM global!");
1528
1529   if (GV->getName() == "llvm.global_ctors") {
1530     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1531                        /* isCtor */ true);
1532
1533     if (TM.getRelocationModel() == Reloc::Static &&
1534         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1535       StringRef Sym(".constructors_used");
1536       OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1537                                        MCSA_Reference);
1538     }
1539     return true;
1540   }
1541
1542   if (GV->getName() == "llvm.global_dtors") {
1543     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1544                        /* isCtor */ false);
1545
1546     if (TM.getRelocationModel() == Reloc::Static &&
1547         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1548       StringRef Sym(".destructors_used");
1549       OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1550                                        MCSA_Reference);
1551     }
1552     return true;
1553   }
1554
1555   return false;
1556 }
1557
1558 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1559 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1560 /// is true, as being used with this directive.
1561 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1562   // Should be an array of 'i8*'.
1563   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1564     const GlobalValue *GV =
1565       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1566     if (GV)
1567       OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1568   }
1569 }
1570
1571 namespace {
1572 struct Structor {
1573   Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1574   int Priority;
1575   llvm::Constant *Func;
1576   llvm::GlobalValue *ComdatKey;
1577 };
1578 } // end namespace
1579
1580 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1581 /// priority.
1582 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1583                                     bool isCtor) {
1584   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1585   // init priority.
1586   if (!isa<ConstantArray>(List)) return;
1587
1588   // Sanity check the structors list.
1589   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1590   if (!InitList) return; // Not an array!
1591   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1592   // FIXME: Only allow the 3-field form in LLVM 4.0.
1593   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1594     return; // Not an array of two or three elements!
1595   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1596       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1597   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1598     return; // Not (int, ptr, ptr).
1599
1600   // Gather the structors in a form that's convenient for sorting by priority.
1601   SmallVector<Structor, 8> Structors;
1602   for (Value *O : InitList->operands()) {
1603     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1604     if (!CS) continue; // Malformed.
1605     if (CS->getOperand(1)->isNullValue())
1606       break;  // Found a null terminator, skip the rest.
1607     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1608     if (!Priority) continue; // Malformed.
1609     Structors.push_back(Structor());
1610     Structor &S = Structors.back();
1611     S.Priority = Priority->getLimitedValue(65535);
1612     S.Func = CS->getOperand(1);
1613     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1614       S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1615   }
1616
1617   // Emit the function pointers in the target-specific order
1618   unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1619   std::stable_sort(Structors.begin(), Structors.end(),
1620                    [](const Structor &L,
1621                       const Structor &R) { return L.Priority < R.Priority; });
1622   for (Structor &S : Structors) {
1623     const TargetLoweringObjectFile &Obj = getObjFileLowering();
1624     const MCSymbol *KeySym = nullptr;
1625     if (GlobalValue *GV = S.ComdatKey) {
1626       if (GV->hasAvailableExternallyLinkage())
1627         // If the associated variable is available_externally, some other TU
1628         // will provide its dynamic initializer.
1629         continue;
1630
1631       KeySym = getSymbol(GV);
1632     }
1633     MCSection *OutputSection =
1634         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1635                 : Obj.getStaticDtorSection(S.Priority, KeySym));
1636     OutStreamer->SwitchSection(OutputSection);
1637     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1638       EmitAlignment(Align);
1639     EmitXXStructor(DL, S.Func);
1640   }
1641 }
1642
1643 void AsmPrinter::EmitModuleIdents(Module &M) {
1644   if (!MAI->hasIdentDirective())
1645     return;
1646
1647   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1648     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1649       const MDNode *N = NMD->getOperand(i);
1650       assert(N->getNumOperands() == 1 &&
1651              "llvm.ident metadata entry can have only one operand");
1652       const MDString *S = cast<MDString>(N->getOperand(0));
1653       OutStreamer->EmitIdent(S->getString());
1654     }
1655   }
1656 }
1657
1658 //===--------------------------------------------------------------------===//
1659 // Emission and print routines
1660 //
1661
1662 /// EmitInt8 - Emit a byte directive and value.
1663 ///
1664 void AsmPrinter::EmitInt8(int Value) const {
1665   OutStreamer->EmitIntValue(Value, 1);
1666 }
1667
1668 /// EmitInt16 - Emit a short directive and value.
1669 ///
1670 void AsmPrinter::EmitInt16(int Value) const {
1671   OutStreamer->EmitIntValue(Value, 2);
1672 }
1673
1674 /// EmitInt32 - Emit a long directive and value.
1675 ///
1676 void AsmPrinter::EmitInt32(int Value) const {
1677   OutStreamer->EmitIntValue(Value, 4);
1678 }
1679
1680 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1681 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1682 /// .set if it avoids relocations.
1683 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1684                                      unsigned Size) const {
1685   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1686 }
1687
1688 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1689 /// where the size in bytes of the directive is specified by Size and Label
1690 /// specifies the label.  This implicitly uses .set if it is available.
1691 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1692                                      unsigned Size,
1693                                      bool IsSectionRelative) const {
1694   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1695     OutStreamer->EmitCOFFSecRel32(Label);
1696     return;
1697   }
1698
1699   // Emit Label+Offset (or just Label if Offset is zero)
1700   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1701   if (Offset)
1702     Expr = MCBinaryExpr::createAdd(
1703         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1704
1705   OutStreamer->EmitValue(Expr, Size);
1706 }
1707
1708 //===----------------------------------------------------------------------===//
1709
1710 // EmitAlignment - Emit an alignment directive to the specified power of
1711 // two boundary.  For example, if you pass in 3 here, you will get an 8
1712 // byte alignment.  If a global value is specified, and if that global has
1713 // an explicit alignment requested, it will override the alignment request
1714 // if required for correctness.
1715 //
1716 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1717   if (GV)
1718     NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
1719
1720   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1721
1722   assert(NumBits <
1723              static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1724          "undefined behavior");
1725   if (getCurrentSection()->getKind().isText())
1726     OutStreamer->EmitCodeAlignment(1u << NumBits);
1727   else
1728     OutStreamer->EmitValueToAlignment(1u << NumBits);
1729 }
1730
1731 //===----------------------------------------------------------------------===//
1732 // Constant emission.
1733 //===----------------------------------------------------------------------===//
1734
1735 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1736   MCContext &Ctx = OutContext;
1737
1738   if (CV->isNullValue() || isa<UndefValue>(CV))
1739     return MCConstantExpr::create(0, Ctx);
1740
1741   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1742     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1743
1744   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1745     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1746
1747   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1748     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1749
1750   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1751   if (!CE) {
1752     llvm_unreachable("Unknown constant value to lower!");
1753   }
1754
1755   if (const MCExpr *RelocExpr
1756       = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1757     return RelocExpr;
1758
1759   switch (CE->getOpcode()) {
1760   default:
1761     // If the code isn't optimized, there may be outstanding folding
1762     // opportunities. Attempt to fold the expression using DataLayout as a
1763     // last resort before giving up.
1764     if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
1765       if (C != CE)
1766         return lowerConstant(C);
1767
1768     // Otherwise report the problem to the user.
1769     {
1770       std::string S;
1771       raw_string_ostream OS(S);
1772       OS << "Unsupported expression in static initializer: ";
1773       CE->printAsOperand(OS, /*PrintType=*/false,
1774                      !MF ? nullptr : MF->getFunction()->getParent());
1775       report_fatal_error(OS.str());
1776     }
1777   case Instruction::GetElementPtr: {
1778     // Generate a symbolic expression for the byte address
1779     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
1780     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
1781
1782     const MCExpr *Base = lowerConstant(CE->getOperand(0));
1783     if (!OffsetAI)
1784       return Base;
1785
1786     int64_t Offset = OffsetAI.getSExtValue();
1787     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1788                                    Ctx);
1789   }
1790
1791   case Instruction::Trunc:
1792     // We emit the value and depend on the assembler to truncate the generated
1793     // expression properly.  This is important for differences between
1794     // blockaddress labels.  Since the two labels are in the same function, it
1795     // is reasonable to treat their delta as a 32-bit value.
1796     // FALL THROUGH.
1797   case Instruction::BitCast:
1798     return lowerConstant(CE->getOperand(0));
1799
1800   case Instruction::IntToPtr: {
1801     const DataLayout &DL = getDataLayout();
1802
1803     // Handle casts to pointers by changing them into casts to the appropriate
1804     // integer type.  This promotes constant folding and simplifies this code.
1805     Constant *Op = CE->getOperand(0);
1806     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1807                                       false/*ZExt*/);
1808     return lowerConstant(Op);
1809   }
1810
1811   case Instruction::PtrToInt: {
1812     const DataLayout &DL = getDataLayout();
1813
1814     // Support only foldable casts to/from pointers that can be eliminated by
1815     // changing the pointer to the appropriately sized integer type.
1816     Constant *Op = CE->getOperand(0);
1817     Type *Ty = CE->getType();
1818
1819     const MCExpr *OpExpr = lowerConstant(Op);
1820
1821     // We can emit the pointer value into this slot if the slot is an
1822     // integer slot equal to the size of the pointer.
1823     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1824       return OpExpr;
1825
1826     // Otherwise the pointer is smaller than the resultant integer, mask off
1827     // the high bits so we are sure to get a proper truncation if the input is
1828     // a constant expr.
1829     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1830     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1831     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1832   }
1833
1834   // The MC library also has a right-shift operator, but it isn't consistently
1835   // signed or unsigned between different targets.
1836   case Instruction::Add:
1837   case Instruction::Sub:
1838   case Instruction::Mul:
1839   case Instruction::SDiv:
1840   case Instruction::SRem:
1841   case Instruction::Shl:
1842   case Instruction::And:
1843   case Instruction::Or:
1844   case Instruction::Xor: {
1845     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1846     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1847     switch (CE->getOpcode()) {
1848     default: llvm_unreachable("Unknown binary operator constant cast expr");
1849     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1850     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1851     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1852     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1853     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1854     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1855     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1856     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1857     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1858     }
1859   }
1860   }
1861 }
1862
1863 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
1864                                    AsmPrinter &AP,
1865                                    const Constant *BaseCV = nullptr,
1866                                    uint64_t Offset = 0);
1867
1868 /// isRepeatedByteSequence - Determine whether the given value is
1869 /// composed of a repeated sequence of identical bytes and return the
1870 /// byte value.  If it is not a repeated sequence, return -1.
1871 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1872   StringRef Data = V->getRawDataValues();
1873   assert(!Data.empty() && "Empty aggregates should be CAZ node");
1874   char C = Data[0];
1875   for (unsigned i = 1, e = Data.size(); i != e; ++i)
1876     if (Data[i] != C) return -1;
1877   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1878 }
1879
1880
1881 /// isRepeatedByteSequence - Determine whether the given value is
1882 /// composed of a repeated sequence of identical bytes and return the
1883 /// byte value.  If it is not a repeated sequence, return -1.
1884 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
1885   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1886     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
1887     assert(Size % 8 == 0);
1888
1889     // Extend the element to take zero padding into account.
1890     APInt Value = CI->getValue().zextOrSelf(Size);
1891     if (!Value.isSplat(8))
1892       return -1;
1893
1894     return Value.zextOrTrunc(8).getZExtValue();
1895   }
1896   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1897     // Make sure all array elements are sequences of the same repeated
1898     // byte.
1899     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1900     Constant *Op0 = CA->getOperand(0);
1901     int Byte = isRepeatedByteSequence(Op0, DL);
1902     if (Byte == -1)
1903       return -1;
1904
1905     // All array elements must be equal.
1906     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
1907       if (CA->getOperand(i) != Op0)
1908         return -1;
1909     return Byte;
1910   }
1911
1912   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1913     return isRepeatedByteSequence(CDS);
1914
1915   return -1;
1916 }
1917
1918 static void emitGlobalConstantDataSequential(const DataLayout &DL,
1919                                              const ConstantDataSequential *CDS,
1920                                              AsmPrinter &AP) {
1921
1922   // See if we can aggregate this into a .fill, if so, emit it as such.
1923   int Value = isRepeatedByteSequence(CDS, DL);
1924   if (Value != -1) {
1925     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
1926     // Don't emit a 1-byte object as a .fill.
1927     if (Bytes > 1)
1928       return AP.OutStreamer->EmitFill(Bytes, Value);
1929   }
1930
1931   // If this can be emitted with .ascii/.asciz, emit it as such.
1932   if (CDS->isString())
1933     return AP.OutStreamer->EmitBytes(CDS->getAsString());
1934
1935   // Otherwise, emit the values in successive locations.
1936   unsigned ElementByteSize = CDS->getElementByteSize();
1937   if (isa<IntegerType>(CDS->getElementType())) {
1938     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1939       if (AP.isVerbose())
1940         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1941                                                  CDS->getElementAsInteger(i));
1942       AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1943                                    ElementByteSize);
1944     }
1945   } else if (ElementByteSize == 4) {
1946     // FP Constants are printed as integer constants to avoid losing
1947     // precision.
1948     assert(CDS->getElementType()->isFloatTy());
1949     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1950       union {
1951         float F;
1952         uint32_t I;
1953       };
1954
1955       F = CDS->getElementAsFloat(i);
1956       if (AP.isVerbose())
1957         AP.OutStreamer->GetCommentOS() << "float " << F << '\n';
1958       AP.OutStreamer->EmitIntValue(I, 4);
1959     }
1960   } else {
1961     assert(CDS->getElementType()->isDoubleTy());
1962     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1963       union {
1964         double F;
1965         uint64_t I;
1966       };
1967
1968       F = CDS->getElementAsDouble(i);
1969       if (AP.isVerbose())
1970         AP.OutStreamer->GetCommentOS() << "double " << F << '\n';
1971       AP.OutStreamer->EmitIntValue(I, 8);
1972     }
1973   }
1974
1975   unsigned Size = DL.getTypeAllocSize(CDS->getType());
1976   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1977                         CDS->getNumElements();
1978   if (unsigned Padding = Size - EmittedSize)
1979     AP.OutStreamer->EmitZeros(Padding);
1980
1981 }
1982
1983 static void emitGlobalConstantArray(const DataLayout &DL,
1984                                     const ConstantArray *CA, AsmPrinter &AP,
1985                                     const Constant *BaseCV, uint64_t Offset) {
1986   // See if we can aggregate some values.  Make sure it can be
1987   // represented as a series of bytes of the constant value.
1988   int Value = isRepeatedByteSequence(CA, DL);
1989
1990   if (Value != -1) {
1991     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1992     AP.OutStreamer->EmitFill(Bytes, Value);
1993   }
1994   else {
1995     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1996       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
1997       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1998     }
1999   }
2000 }
2001
2002 static void emitGlobalConstantVector(const DataLayout &DL,
2003                                      const ConstantVector *CV, AsmPrinter &AP) {
2004   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2005     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2006
2007   unsigned Size = DL.getTypeAllocSize(CV->getType());
2008   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2009                          CV->getType()->getNumElements();
2010   if (unsigned Padding = Size - EmittedSize)
2011     AP.OutStreamer->EmitZeros(Padding);
2012 }
2013
2014 static void emitGlobalConstantStruct(const DataLayout &DL,
2015                                      const ConstantStruct *CS, AsmPrinter &AP,
2016                                      const Constant *BaseCV, uint64_t Offset) {
2017   // Print the fields in successive locations. Pad to align if needed!
2018   unsigned Size = DL.getTypeAllocSize(CS->getType());
2019   const StructLayout *Layout = DL.getStructLayout(CS->getType());
2020   uint64_t SizeSoFar = 0;
2021   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2022     const Constant *Field = CS->getOperand(i);
2023
2024     // Print the actual field value.
2025     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2026
2027     // Check if padding is needed and insert one or more 0s.
2028     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2029     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2030                         - Layout->getElementOffset(i)) - FieldSize;
2031     SizeSoFar += FieldSize + PadSize;
2032
2033     // Insert padding - this may include padding to increase the size of the
2034     // current field up to the ABI size (if the struct is not packed) as well
2035     // as padding to ensure that the next field starts at the right offset.
2036     AP.OutStreamer->EmitZeros(PadSize);
2037   }
2038   assert(SizeSoFar == Layout->getSizeInBytes() &&
2039          "Layout of constant struct may be incorrect!");
2040 }
2041
2042 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2043   APInt API = CFP->getValueAPF().bitcastToAPInt();
2044
2045   // First print a comment with what we think the original floating-point value
2046   // should have been.
2047   if (AP.isVerbose()) {
2048     SmallString<8> StrVal;
2049     CFP->getValueAPF().toString(StrVal);
2050
2051     if (CFP->getType())
2052       CFP->getType()->print(AP.OutStreamer->GetCommentOS());
2053     else
2054       AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2055     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2056   }
2057
2058   // Now iterate through the APInt chunks, emitting them in endian-correct
2059   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2060   // floats).
2061   unsigned NumBytes = API.getBitWidth() / 8;
2062   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2063   const uint64_t *p = API.getRawData();
2064
2065   // PPC's long double has odd notions of endianness compared to how LLVM
2066   // handles it: p[0] goes first for *big* endian on PPC.
2067   if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
2068     int Chunk = API.getNumWords() - 1;
2069
2070     if (TrailingBytes)
2071       AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2072
2073     for (; Chunk >= 0; --Chunk)
2074       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2075   } else {
2076     unsigned Chunk;
2077     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2078       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2079
2080     if (TrailingBytes)
2081       AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2082   }
2083
2084   // Emit the tail padding for the long double.
2085   const DataLayout &DL = AP.getDataLayout();
2086   AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2087                             DL.getTypeStoreSize(CFP->getType()));
2088 }
2089
2090 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2091   const DataLayout &DL = AP.getDataLayout();
2092   unsigned BitWidth = CI->getBitWidth();
2093
2094   // Copy the value as we may massage the layout for constants whose bit width
2095   // is not a multiple of 64-bits.
2096   APInt Realigned(CI->getValue());
2097   uint64_t ExtraBits = 0;
2098   unsigned ExtraBitsSize = BitWidth & 63;
2099
2100   if (ExtraBitsSize) {
2101     // The bit width of the data is not a multiple of 64-bits.
2102     // The extra bits are expected to be at the end of the chunk of the memory.
2103     // Little endian:
2104     // * Nothing to be done, just record the extra bits to emit.
2105     // Big endian:
2106     // * Record the extra bits to emit.
2107     // * Realign the raw data to emit the chunks of 64-bits.
2108     if (DL.isBigEndian()) {
2109       // Basically the structure of the raw data is a chunk of 64-bits cells:
2110       //    0        1         BitWidth / 64
2111       // [chunk1][chunk2] ... [chunkN].
2112       // The most significant chunk is chunkN and it should be emitted first.
2113       // However, due to the alignment issue chunkN contains useless bits.
2114       // Realign the chunks so that they contain only useless information:
2115       // ExtraBits     0       1       (BitWidth / 64) - 1
2116       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2117       ExtraBits = Realigned.getRawData()[0] &
2118         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2119       Realigned = Realigned.lshr(ExtraBitsSize);
2120     } else
2121       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2122   }
2123
2124   // We don't expect assemblers to support integer data directives
2125   // for more than 64 bits, so we emit the data in at most 64-bit
2126   // quantities at a time.
2127   const uint64_t *RawData = Realigned.getRawData();
2128   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2129     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2130     AP.OutStreamer->EmitIntValue(Val, 8);
2131   }
2132
2133   if (ExtraBitsSize) {
2134     // Emit the extra bits after the 64-bits chunks.
2135
2136     // Emit a directive that fills the expected size.
2137     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2138     Size -= (BitWidth / 64) * 8;
2139     assert(Size && Size * 8 >= ExtraBitsSize &&
2140            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2141            == ExtraBits && "Directive too small for extra bits.");
2142     AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2143   }
2144 }
2145
2146 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2147 /// equivalent global, by a target specific GOT pc relative access to the
2148 /// final symbol.
2149 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2150                                          const Constant *BaseCst,
2151                                          uint64_t Offset) {
2152   // The global @foo below illustrates a global that uses a got equivalent.
2153   //
2154   //  @bar = global i32 42
2155   //  @gotequiv = private unnamed_addr constant i32* @bar
2156   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2157   //                             i64 ptrtoint (i32* @foo to i64))
2158   //                        to i32)
2159   //
2160   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2161   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2162   // form:
2163   //
2164   //  foo = cstexpr, where
2165   //    cstexpr := <gotequiv> - "." + <cst>
2166   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2167   //
2168   // After canonicalization by evaluateAsRelocatable `ME` turns into:
2169   //
2170   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2171   //    gotpcrelcst := <offset from @foo base> + <cst>
2172   //
2173   MCValue MV;
2174   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2175     return;
2176   const MCSymbolRefExpr *SymA = MV.getSymA();
2177   if (!SymA)
2178     return;
2179
2180   // Check that GOT equivalent symbol is cached.
2181   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2182   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2183     return;
2184
2185   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2186   if (!BaseGV)
2187     return;
2188
2189   // Check for a valid base symbol
2190   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2191   const MCSymbolRefExpr *SymB = MV.getSymB();
2192
2193   if (!SymB || BaseSym != &SymB->getSymbol())
2194     return;
2195
2196   // Make sure to match:
2197   //
2198   //    gotpcrelcst := <offset from @foo base> + <cst>
2199   //
2200   // If gotpcrelcst is positive it means that we can safely fold the pc rel
2201   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2202   // if the target knows how to encode it.
2203   //
2204   int64_t GOTPCRelCst = Offset + MV.getConstant();
2205   if (GOTPCRelCst < 0)
2206     return;
2207   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2208     return;
2209
2210   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2211   //
2212   //  bar:
2213   //    .long 42
2214   //  gotequiv:
2215   //    .quad bar
2216   //  foo:
2217   //    .long gotequiv - "." + <cst>
2218   //
2219   // is replaced by the target specific equivalent to:
2220   //
2221   //  bar:
2222   //    .long 42
2223   //  foo:
2224   //    .long bar@GOTPCREL+<gotpcrelcst>
2225   //
2226   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2227   const GlobalVariable *GV = Result.first;
2228   int NumUses = (int)Result.second;
2229   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2230   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2231   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2232       FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2233
2234   // Update GOT equivalent usage information
2235   --NumUses;
2236   if (NumUses >= 0)
2237     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2238 }
2239
2240 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2241                                    AsmPrinter &AP, const Constant *BaseCV,
2242                                    uint64_t Offset) {
2243   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2244
2245   // Globals with sub-elements such as combinations of arrays and structs
2246   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2247   // constant symbol base and the current position with BaseCV and Offset.
2248   if (!BaseCV && CV->hasOneUse())
2249     BaseCV = dyn_cast<Constant>(CV->user_back());
2250
2251   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2252     return AP.OutStreamer->EmitZeros(Size);
2253
2254   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2255     switch (Size) {
2256     case 1:
2257     case 2:
2258     case 4:
2259     case 8:
2260       if (AP.isVerbose())
2261         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2262                                                  CI->getZExtValue());
2263       AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2264       return;
2265     default:
2266       emitGlobalConstantLargeInt(CI, AP);
2267       return;
2268     }
2269   }
2270
2271   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2272     return emitGlobalConstantFP(CFP, AP);
2273
2274   if (isa<ConstantPointerNull>(CV)) {
2275     AP.OutStreamer->EmitIntValue(0, Size);
2276     return;
2277   }
2278
2279   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2280     return emitGlobalConstantDataSequential(DL, CDS, AP);
2281
2282   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2283     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2284
2285   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2286     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2287
2288   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2289     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2290     // vectors).
2291     if (CE->getOpcode() == Instruction::BitCast)
2292       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2293
2294     if (Size > 8) {
2295       // If the constant expression's size is greater than 64-bits, then we have
2296       // to emit the value in chunks. Try to constant fold the value and emit it
2297       // that way.
2298       Constant *New = ConstantFoldConstantExpression(CE, DL);
2299       if (New && New != CE)
2300         return emitGlobalConstantImpl(DL, New, AP);
2301     }
2302   }
2303
2304   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2305     return emitGlobalConstantVector(DL, V, AP);
2306
2307   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2308   // thread the streamer with EmitValue.
2309   const MCExpr *ME = AP.lowerConstant(CV);
2310
2311   // Since lowerConstant already folded and got rid of all IR pointer and
2312   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2313   // directly.
2314   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2315     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2316
2317   AP.OutStreamer->EmitValue(ME, Size);
2318 }
2319
2320 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2321 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2322   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2323   if (Size)
2324     emitGlobalConstantImpl(DL, CV, *this);
2325   else if (MAI->hasSubsectionsViaSymbols()) {
2326     // If the global has zero size, emit a single byte so that two labels don't
2327     // look like they are at the same location.
2328     OutStreamer->EmitIntValue(0, 1);
2329   }
2330 }
2331
2332 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2333   // Target doesn't support this yet!
2334   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2335 }
2336
2337 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2338   if (Offset > 0)
2339     OS << '+' << Offset;
2340   else if (Offset < 0)
2341     OS << Offset;
2342 }
2343
2344 //===----------------------------------------------------------------------===//
2345 // Symbol Lowering Routines.
2346 //===----------------------------------------------------------------------===//
2347
2348 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2349   return OutContext.createTempSymbol(Name, true);
2350 }
2351
2352 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2353   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2354 }
2355
2356 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2357   return MMI->getAddrLabelSymbol(BB);
2358 }
2359
2360 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2361 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2362   const DataLayout &DL = getDataLayout();
2363   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2364                                       "CPI" + Twine(getFunctionNumber()) + "_" +
2365                                       Twine(CPID));
2366 }
2367
2368 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2369 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2370   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2371 }
2372
2373 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2374 /// FIXME: privatize to AsmPrinter.
2375 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2376   const DataLayout &DL = getDataLayout();
2377   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2378                                       Twine(getFunctionNumber()) + "_" +
2379                                       Twine(UID) + "_set_" + Twine(MBBID));
2380 }
2381
2382 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2383                                                    StringRef Suffix) const {
2384   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2385                                                            TM);
2386 }
2387
2388 /// Return the MCSymbol for the specified ExternalSymbol.
2389 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2390   SmallString<60> NameStr;
2391   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2392   return OutContext.getOrCreateSymbol(NameStr);
2393 }
2394
2395
2396
2397 /// PrintParentLoopComment - Print comments about parent loops of this one.
2398 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2399                                    unsigned FunctionNumber) {
2400   if (!Loop) return;
2401   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2402   OS.indent(Loop->getLoopDepth()*2)
2403     << "Parent Loop BB" << FunctionNumber << "_"
2404     << Loop->getHeader()->getNumber()
2405     << " Depth=" << Loop->getLoopDepth() << '\n';
2406 }
2407
2408
2409 /// PrintChildLoopComment - Print comments about child loops within
2410 /// the loop for this basic block, with nesting.
2411 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2412                                   unsigned FunctionNumber) {
2413   // Add child loop information
2414   for (const MachineLoop *CL : *Loop) {
2415     OS.indent(CL->getLoopDepth()*2)
2416       << "Child Loop BB" << FunctionNumber << "_"
2417       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2418       << '\n';
2419     PrintChildLoopComment(OS, CL, FunctionNumber);
2420   }
2421 }
2422
2423 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2424 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2425                                        const MachineLoopInfo *LI,
2426                                        const AsmPrinter &AP) {
2427   // Add loop depth information
2428   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2429   if (!Loop) return;
2430
2431   MachineBasicBlock *Header = Loop->getHeader();
2432   assert(Header && "No header for loop");
2433
2434   // If this block is not a loop header, just print out what is the loop header
2435   // and return.
2436   if (Header != &MBB) {
2437     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
2438                                Twine(AP.getFunctionNumber())+"_" +
2439                                Twine(Loop->getHeader()->getNumber())+
2440                                " Depth="+Twine(Loop->getLoopDepth()));
2441     return;
2442   }
2443
2444   // Otherwise, it is a loop header.  Print out information about child and
2445   // parent loops.
2446   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2447
2448   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2449
2450   OS << "=>";
2451   OS.indent(Loop->getLoopDepth()*2-2);
2452
2453   OS << "This ";
2454   if (Loop->empty())
2455     OS << "Inner ";
2456   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2457
2458   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2459 }
2460
2461
2462 /// EmitBasicBlockStart - This method prints the label for the specified
2463 /// MachineBasicBlock, an alignment (if present) and a comment describing
2464 /// it if appropriate.
2465 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2466   // End the previous funclet and start a new one.
2467   if (MBB.isEHFuncletEntry()) {
2468     for (const HandlerInfo &HI : Handlers) {
2469       HI.Handler->endFunclet();
2470       HI.Handler->beginFunclet(MBB);
2471     }
2472   }
2473
2474   // Emit an alignment directive for this block, if needed.
2475   if (unsigned Align = MBB.getAlignment())
2476     EmitAlignment(Align);
2477
2478   // If the block has its address taken, emit any labels that were used to
2479   // reference the block.  It is possible that there is more than one label
2480   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2481   // the references were generated.
2482   if (MBB.hasAddressTaken()) {
2483     const BasicBlock *BB = MBB.getBasicBlock();
2484     if (isVerbose())
2485       OutStreamer->AddComment("Block address taken");
2486
2487     // MBBs can have their address taken as part of CodeGen without having
2488     // their corresponding BB's address taken in IR
2489     if (BB->hasAddressTaken())
2490       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2491         OutStreamer->EmitLabel(Sym);
2492   }
2493
2494   // Print some verbose block comments.
2495   if (isVerbose()) {
2496     if (const BasicBlock *BB = MBB.getBasicBlock())
2497       if (BB->hasName())
2498         OutStreamer->AddComment("%" + BB->getName());
2499     emitBasicBlockLoopComments(MBB, LI, *this);
2500   }
2501
2502   // Print the main label for the block.
2503   if (MBB.pred_empty() ||
2504       (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) {
2505     if (isVerbose()) {
2506       // NOTE: Want this comment at start of line, don't emit with AddComment.
2507       OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2508     }
2509   } else {
2510     OutStreamer->EmitLabel(MBB.getSymbol());
2511   }
2512 }
2513
2514 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2515                                 bool IsDefinition) const {
2516   MCSymbolAttr Attr = MCSA_Invalid;
2517
2518   switch (Visibility) {
2519   default: break;
2520   case GlobalValue::HiddenVisibility:
2521     if (IsDefinition)
2522       Attr = MAI->getHiddenVisibilityAttr();
2523     else
2524       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2525     break;
2526   case GlobalValue::ProtectedVisibility:
2527     Attr = MAI->getProtectedVisibilityAttr();
2528     break;
2529   }
2530
2531   if (Attr != MCSA_Invalid)
2532     OutStreamer->EmitSymbolAttribute(Sym, Attr);
2533 }
2534
2535 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2536 /// exactly one predecessor and the control transfer mechanism between
2537 /// the predecessor and this block is a fall-through.
2538 bool AsmPrinter::
2539 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2540   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2541   // then nothing falls through to it.
2542   if (MBB->isEHPad() || MBB->pred_empty())
2543     return false;
2544
2545   // If there isn't exactly one predecessor, it can't be a fall through.
2546   if (MBB->pred_size() > 1)
2547     return false;
2548
2549   // The predecessor has to be immediately before this block.
2550   MachineBasicBlock *Pred = *MBB->pred_begin();
2551   if (!Pred->isLayoutSuccessor(MBB))
2552     return false;
2553
2554   // If the block is completely empty, then it definitely does fall through.
2555   if (Pred->empty())
2556     return true;
2557
2558   // Check the terminators in the previous blocks
2559   for (const auto &MI : Pred->terminators()) {
2560     // If it is not a simple branch, we are in a table somewhere.
2561     if (!MI.isBranch() || MI.isIndirectBranch())
2562       return false;
2563
2564     // If we are the operands of one of the branches, this is not a fall
2565     // through. Note that targets with delay slots will usually bundle
2566     // terminators with the delay slot instruction.
2567     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2568       if (OP->isJTI())
2569         return false;
2570       if (OP->isMBB() && OP->getMBB() == MBB)
2571         return false;
2572     }
2573   }
2574
2575   return true;
2576 }
2577
2578
2579
2580 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2581   if (!S.usesMetadata())
2582     return nullptr;
2583
2584   assert(!S.useStatepoints() && "statepoints do not currently support custom"
2585          " stackmap formats, please see the documentation for a description of"
2586          " the default format.  If you really need a custom serialized format,"
2587          " please file a bug");
2588
2589   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2590   gcp_map_type::iterator GCPI = GCMap.find(&S);
2591   if (GCPI != GCMap.end())
2592     return GCPI->second.get();
2593
2594   const char *Name = S.getName().c_str();
2595
2596   for (GCMetadataPrinterRegistry::iterator
2597          I = GCMetadataPrinterRegistry::begin(),
2598          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2599     if (strcmp(Name, I->getName()) == 0) {
2600       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2601       GMP->S = &S;
2602       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2603       return IterBool.first->second.get();
2604     }
2605
2606   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2607 }
2608
2609 /// Pin vtable to this file.
2610 AsmPrinterHandler::~AsmPrinterHandler() {}
2611
2612 void AsmPrinterHandler::markFunctionEnd() {}