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