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