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