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