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