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