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