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