LLVM  mainline
AsmPrinter.cpp
Go to the documentation of this file.
00001 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the AsmPrinter class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/AsmPrinter.h"
00015 #include "DwarfDebug.h"
00016 #include "DwarfException.h"
00017 #include "WinException.h"
00018 #include "CodeViewDebug.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/Analysis/ConstantFolding.h"
00022 #include "llvm/CodeGen/Analysis.h"
00023 #include "llvm/CodeGen/GCMetadataPrinter.h"
00024 #include "llvm/CodeGen/MachineConstantPool.h"
00025 #include "llvm/CodeGen/MachineFrameInfo.h"
00026 #include "llvm/CodeGen/MachineFunction.h"
00027 #include "llvm/CodeGen/MachineInstrBundle.h"
00028 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00029 #include "llvm/CodeGen/MachineLoopInfo.h"
00030 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00031 #include "llvm/IR/DataLayout.h"
00032 #include "llvm/IR/DebugInfo.h"
00033 #include "llvm/IR/Mangler.h"
00034 #include "llvm/IR/Module.h"
00035 #include "llvm/IR/Operator.h"
00036 #include "llvm/MC/MCAsmInfo.h"
00037 #include "llvm/MC/MCContext.h"
00038 #include "llvm/MC/MCExpr.h"
00039 #include "llvm/MC/MCInst.h"
00040 #include "llvm/MC/MCSection.h"
00041 #include "llvm/MC/MCStreamer.h"
00042 #include "llvm/MC/MCSymbolELF.h"
00043 #include "llvm/MC/MCValue.h"
00044 #include "llvm/Support/ErrorHandling.h"
00045 #include "llvm/Support/Format.h"
00046 #include "llvm/Support/MathExtras.h"
00047 #include "llvm/Support/TargetRegistry.h"
00048 #include "llvm/Support/Timer.h"
00049 #include "llvm/Target/TargetFrameLowering.h"
00050 #include "llvm/Target/TargetInstrInfo.h"
00051 #include "llvm/Target/TargetLowering.h"
00052 #include "llvm/Target/TargetLoweringObjectFile.h"
00053 #include "llvm/Target/TargetRegisterInfo.h"
00054 #include "llvm/Target/TargetSubtargetInfo.h"
00055 using namespace llvm;
00056 
00057 #define DEBUG_TYPE "asm-printer"
00058 
00059 static const char *const DWARFGroupName = "DWARF Emission";
00060 static const char *const DbgTimerName = "Debug Info Emission";
00061 static const char *const EHTimerName = "DWARF Exception Writer";
00062 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
00063 
00064 STATISTIC(EmittedInsts, "Number of machine instrs printed");
00065 
00066 char AsmPrinter::ID = 0;
00067 
00068 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
00069 static gcp_map_type &getGCMap(void *&P) {
00070   if (!P)
00071     P = new gcp_map_type();
00072   return *(gcp_map_type*)P;
00073 }
00074 
00075 
00076 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
00077 /// value in log2 form.  This rounds up to the preferred alignment if possible
00078 /// and legal.
00079 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
00080                                    unsigned InBits = 0) {
00081   unsigned NumBits = 0;
00082   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
00083     NumBits = DL.getPreferredAlignmentLog(GVar);
00084 
00085   // If InBits is specified, round it to it.
00086   if (InBits > NumBits)
00087     NumBits = InBits;
00088 
00089   // If the GV has a specified alignment, take it into account.
00090   if (GV->getAlignment() == 0)
00091     return NumBits;
00092 
00093   unsigned GVAlign = Log2_32(GV->getAlignment());
00094 
00095   // If the GVAlign is larger than NumBits, or if we are required to obey
00096   // NumBits because the GV has an assigned section, obey it.
00097   if (GVAlign > NumBits || GV->hasSection())
00098     NumBits = GVAlign;
00099   return NumBits;
00100 }
00101 
00102 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
00103     : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
00104       OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
00105       LastMI(nullptr), LastFn(0), Counter(~0U) {
00106   DD = nullptr;
00107   MMI = nullptr;
00108   LI = nullptr;
00109   MF = nullptr;
00110   CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
00111   CurrentFnBegin = nullptr;
00112   CurrentFnEnd = nullptr;
00113   GCMetadataPrinters = nullptr;
00114   VerboseAsm = OutStreamer->isVerboseAsm();
00115 }
00116 
00117 AsmPrinter::~AsmPrinter() {
00118   assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
00119 
00120   if (GCMetadataPrinters) {
00121     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
00122 
00123     delete &GCMap;
00124     GCMetadataPrinters = nullptr;
00125   }
00126 }
00127 
00128 /// getFunctionNumber - Return a unique ID for the current function.
00129 ///
00130 unsigned AsmPrinter::getFunctionNumber() const {
00131   return MF->getFunctionNumber();
00132 }
00133 
00134 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
00135   return *TM.getObjFileLowering();
00136 }
00137 
00138 const DataLayout &AsmPrinter::getDataLayout() const {
00139   return MMI->getModule()->getDataLayout();
00140 }
00141 
00142 // Do not use the cached DataLayout because some client use it without a Module
00143 // (llmv-dsymutil, llvm-dwarfdump).
00144 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); }
00145 
00146 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
00147   assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
00148   return MF->getSubtarget<MCSubtargetInfo>();
00149 }
00150 
00151 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
00152   S.EmitInstruction(Inst, getSubtargetInfo());
00153 }
00154 
00155 StringRef AsmPrinter::getTargetTriple() const {
00156   return TM.getTargetTriple().str();
00157 }
00158 
00159 /// getCurrentSection() - Return the current section we are emitting to.
00160 const MCSection *AsmPrinter::getCurrentSection() const {
00161   return OutStreamer->getCurrentSection().first;
00162 }
00163 
00164 
00165 
00166 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
00167   AU.setPreservesAll();
00168   MachineFunctionPass::getAnalysisUsage(AU);
00169   AU.addRequired<MachineModuleInfo>();
00170   AU.addRequired<GCModuleInfo>();
00171   if (isVerbose())
00172     AU.addRequired<MachineLoopInfo>();
00173 }
00174 
00175 bool AsmPrinter::doInitialization(Module &M) {
00176   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
00177 
00178   // Initialize TargetLoweringObjectFile.
00179   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
00180     .Initialize(OutContext, TM);
00181 
00182   OutStreamer->InitSections(false);
00183 
00184   Mang = new Mangler();
00185 
00186   // Emit the version-min deplyment target directive if needed.
00187   //
00188   // FIXME: If we end up with a collection of these sorts of Darwin-specific
00189   // or ELF-specific things, it may make sense to have a platform helper class
00190   // that will work with the target helper class. For now keep it here, as the
00191   // alternative is duplicated code in each of the target asm printers that
00192   // use the directive, where it would need the same conditionalization
00193   // anyway.
00194   Triple TT(getTargetTriple());
00195   // If there is a version specified, Major will be non-zero.
00196   if (TT.isOSDarwin() && TT.getOSMajorVersion() != 0) {
00197     unsigned Major, Minor, Update;
00198     MCVersionMinType VersionType;
00199     if (TT.isWatchOS()) {
00200       VersionType = MCVM_WatchOSVersionMin;
00201       TT.getWatchOSVersion(Major, Minor, Update);
00202     } else if (TT.isTvOS()) {
00203       VersionType = MCVM_TvOSVersionMin;
00204       TT.getiOSVersion(Major, Minor, Update);
00205     } else if (TT.isMacOSX()) {
00206       VersionType = MCVM_OSXVersionMin;
00207       if (!TT.getMacOSXVersion(Major, Minor, Update))
00208         Major = 0;
00209     } else {
00210       VersionType = MCVM_IOSVersionMin;
00211       TT.getiOSVersion(Major, Minor, Update);
00212     }
00213     if (Major != 0)
00214       OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update);
00215   }
00216 
00217   // Allow the target to emit any magic that it wants at the start of the file.
00218   EmitStartOfAsmFile(M);
00219 
00220   // Very minimal debug info. It is ignored if we emit actual debug info. If we
00221   // don't, this at least helps the user find where a global came from.
00222   if (MAI->hasSingleParameterDotFile()) {
00223     // .file "foo.c"
00224     OutStreamer->EmitFileDirective(M.getModuleIdentifier());
00225   }
00226 
00227   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
00228   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
00229   for (auto &I : *MI)
00230     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
00231       MP->beginAssembly(M, *MI, *this);
00232 
00233   // Emit module-level inline asm if it exists.
00234   if (!M.getModuleInlineAsm().empty()) {
00235     // We're at the module level. Construct MCSubtarget from the default CPU
00236     // and target triple.
00237     std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
00238         TM.getTargetTriple().str(), TM.getTargetCPU(),
00239         TM.getTargetFeatureString()));
00240     OutStreamer->AddComment("Start of file scope inline assembly");
00241     OutStreamer->AddBlankLine();
00242     EmitInlineAsm(M.getModuleInlineAsm()+"\n",
00243                   OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
00244     OutStreamer->AddComment("End of file scope inline assembly");
00245     OutStreamer->AddBlankLine();
00246   }
00247 
00248   if (MAI->doesSupportDebugInformation()) {
00249     bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
00250     if (EmitCodeView && TM.getTargetTriple().isKnownWindowsMSVCEnvironment()) {
00251       Handlers.push_back(HandlerInfo(new CodeViewDebug(this),
00252                                      DbgTimerName,
00253                                      CodeViewLineTablesGroupName));
00254     }
00255     if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
00256       DD = new DwarfDebug(this, &M);
00257       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
00258     }
00259   }
00260 
00261   EHStreamer *ES = nullptr;
00262   switch (MAI->getExceptionHandlingType()) {
00263   case ExceptionHandling::None:
00264     break;
00265   case ExceptionHandling::SjLj:
00266   case ExceptionHandling::DwarfCFI:
00267     ES = new DwarfCFIException(this);
00268     break;
00269   case ExceptionHandling::ARM:
00270     ES = new ARMException(this);
00271     break;
00272   case ExceptionHandling::WinEH:
00273     switch (MAI->getWinEHEncodingType()) {
00274     default: llvm_unreachable("unsupported unwinding information encoding");
00275     case WinEH::EncodingType::Invalid:
00276       break;
00277     case WinEH::EncodingType::X86:
00278     case WinEH::EncodingType::Itanium:
00279       ES = new WinException(this);
00280       break;
00281     }
00282     break;
00283   }
00284   if (ES)
00285     Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
00286   return false;
00287 }
00288 
00289 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
00290   if (!MAI.hasWeakDefCanBeHiddenDirective())
00291     return false;
00292 
00293   return canBeOmittedFromSymbolTable(GV);
00294 }
00295 
00296 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
00297   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
00298   switch (Linkage) {
00299   case GlobalValue::CommonLinkage:
00300   case GlobalValue::LinkOnceAnyLinkage:
00301   case GlobalValue::LinkOnceODRLinkage:
00302   case GlobalValue::WeakAnyLinkage:
00303   case GlobalValue::WeakODRLinkage:
00304     if (MAI->hasWeakDefDirective()) {
00305       // .globl _foo
00306       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
00307 
00308       if (!canBeHidden(GV, *MAI))
00309         // .weak_definition _foo
00310         OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
00311       else
00312         OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
00313     } else if (MAI->hasLinkOnceDirective()) {
00314       // .globl _foo
00315       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
00316       //NOTE: linkonce is handled by the section the symbol was assigned to.
00317     } else {
00318       // .weak _foo
00319       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
00320     }
00321     return;
00322   case GlobalValue::AppendingLinkage:
00323     // FIXME: appending linkage variables should go into a section of
00324     // their name or something.  For now, just emit them as external.
00325   case GlobalValue::ExternalLinkage:
00326     // If external or appending, declare as a global symbol.
00327     // .globl _foo
00328     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
00329     return;
00330   case GlobalValue::PrivateLinkage:
00331   case GlobalValue::InternalLinkage:
00332     return;
00333   case GlobalValue::AvailableExternallyLinkage:
00334     llvm_unreachable("Should never emit this");
00335   case GlobalValue::ExternalWeakLinkage:
00336     llvm_unreachable("Don't know how to emit these");
00337   }
00338   llvm_unreachable("Unknown linkage type!");
00339 }
00340 
00341 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
00342                                    const GlobalValue *GV) const {
00343   TM.getNameWithPrefix(Name, GV, *Mang);
00344 }
00345 
00346 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
00347   return TM.getSymbol(GV, *Mang);
00348 }
00349 
00350 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
00351 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
00352   bool IsEmuTLSVar = TM.Options.EmulatedTLS && GV->isThreadLocal();
00353   assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
00354          "No emulated TLS variables in the common section");
00355 
00356   // Never emit TLS variable xyz in emulated TLS model.
00357   // The initialization value is in __emutls_t.xyz instead of xyz.
00358   if (IsEmuTLSVar)
00359     return;
00360 
00361   if (GV->hasInitializer()) {
00362     // Check to see if this is a special global used by LLVM, if so, emit it.
00363     if (EmitSpecialLLVMGlobal(GV))
00364       return;
00365 
00366     // Skip the emission of global equivalents. The symbol can be emitted later
00367     // on by emitGlobalGOTEquivs in case it turns out to be needed.
00368     if (GlobalGOTEquivs.count(getSymbol(GV)))
00369       return;
00370 
00371     if (isVerbose()) {
00372       // When printing the control variable __emutls_v.*,
00373       // we don't need to print the original TLS variable name.
00374       GV->printAsOperand(OutStreamer->GetCommentOS(),
00375                      /*PrintType=*/false, GV->getParent());
00376       OutStreamer->GetCommentOS() << '\n';
00377     }
00378   }
00379 
00380   MCSymbol *GVSym = getSymbol(GV);
00381   MCSymbol *EmittedSym = GVSym;
00382   // getOrCreateEmuTLSControlSym only creates the symbol with name and default attributes.
00383   // GV's or GVSym's attributes will be used for the EmittedSym.
00384 
00385   EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
00386 
00387   if (!GV->hasInitializer())   // External globals require no extra code.
00388     return;
00389 
00390   GVSym->redefineIfPossible();
00391   if (GVSym->isDefined() || GVSym->isVariable())
00392     report_fatal_error("symbol '" + Twine(GVSym->getName()) +
00393                        "' is already defined");
00394 
00395   if (MAI->hasDotTypeDotSizeDirective())
00396     OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
00397 
00398   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
00399 
00400   const DataLayout &DL = GV->getParent()->getDataLayout();
00401   uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
00402 
00403   // If the alignment is specified, we *must* obey it.  Overaligning a global
00404   // with a specified alignment is a prompt way to break globals emitted to
00405   // sections and expected to be contiguous (e.g. ObjC metadata).
00406   unsigned AlignLog = getGVAlignmentLog2(GV, DL);
00407 
00408   for (const HandlerInfo &HI : Handlers) {
00409     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00410     HI.Handler->setSymbolSize(GVSym, Size);
00411   }
00412 
00413   // Handle common and BSS local symbols (.lcomm).
00414   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
00415     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
00416     unsigned Align = 1 << AlignLog;
00417 
00418     // Handle common symbols.
00419     if (GVKind.isCommon()) {
00420       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
00421         Align = 0;
00422 
00423       // .comm _foo, 42, 4
00424       OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
00425       return;
00426     }
00427 
00428     // Handle local BSS symbols.
00429     if (MAI->hasMachoZeroFillDirective()) {
00430       MCSection *TheSection =
00431           getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
00432       // .zerofill __DATA, __bss, _foo, 400, 5
00433       OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
00434       return;
00435     }
00436 
00437     // Use .lcomm only if it supports user-specified alignment.
00438     // Otherwise, while it would still be correct to use .lcomm in some
00439     // cases (e.g. when Align == 1), the external assembler might enfore
00440     // some -unknown- default alignment behavior, which could cause
00441     // spurious differences between external and integrated assembler.
00442     // Prefer to simply fall back to .local / .comm in this case.
00443     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
00444       // .lcomm _foo, 42
00445       OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
00446       return;
00447     }
00448 
00449     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
00450       Align = 0;
00451 
00452     // .local _foo
00453     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
00454     // .comm _foo, 42, 4
00455     OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
00456     return;
00457   }
00458 
00459   MCSymbol *EmittedInitSym = GVSym;
00460 
00461   MCSection *TheSection =
00462       getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
00463 
00464   // Handle the zerofill directive on darwin, which is a special form of BSS
00465   // emission.
00466   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
00467     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
00468 
00469     // .globl _foo
00470     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
00471     // .zerofill __DATA, __common, _foo, 400, 5
00472     OutStreamer->EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
00473     return;
00474   }
00475 
00476   // Handle thread local data for mach-o which requires us to output an
00477   // additional structure of data and mangle the original symbol so that we
00478   // can reference it later.
00479   //
00480   // TODO: This should become an "emit thread local global" method on TLOF.
00481   // All of this macho specific stuff should be sunk down into TLOFMachO and
00482   // stuff like "TLSExtraDataSection" should no longer be part of the parent
00483   // TLOF class.  This will also make it more obvious that stuff like
00484   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
00485   // specific code.
00486   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
00487     // Emit the .tbss symbol
00488     MCSymbol *MangSym =
00489       OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
00490 
00491     if (GVKind.isThreadBSS()) {
00492       TheSection = getObjFileLowering().getTLSBSSSection();
00493       OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
00494     } else if (GVKind.isThreadData()) {
00495       OutStreamer->SwitchSection(TheSection);
00496 
00497       EmitAlignment(AlignLog, GV);
00498       OutStreamer->EmitLabel(MangSym);
00499 
00500       EmitGlobalConstant(GV->getParent()->getDataLayout(),
00501                          GV->getInitializer());
00502     }
00503 
00504     OutStreamer->AddBlankLine();
00505 
00506     // Emit the variable struct for the runtime.
00507     MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
00508 
00509     OutStreamer->SwitchSection(TLVSect);
00510     // Emit the linkage here.
00511     EmitLinkage(GV, GVSym);
00512     OutStreamer->EmitLabel(GVSym);
00513 
00514     // Three pointers in size:
00515     //   - __tlv_bootstrap - used to make sure support exists
00516     //   - spare pointer, used when mapped by the runtime
00517     //   - pointer to mangled symbol above with initializer
00518     unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
00519     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
00520                                 PtrSize);
00521     OutStreamer->EmitIntValue(0, PtrSize);
00522     OutStreamer->EmitSymbolValue(MangSym, PtrSize);
00523 
00524     OutStreamer->AddBlankLine();
00525     return;
00526   }
00527 
00528   OutStreamer->SwitchSection(TheSection);
00529 
00530   EmitLinkage(GV, EmittedInitSym);
00531   EmitAlignment(AlignLog, GV);
00532 
00533   OutStreamer->EmitLabel(EmittedInitSym);
00534 
00535   EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
00536 
00537   if (MAI->hasDotTypeDotSizeDirective())
00538     // .size foo, 42
00539     OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedInitSym),
00540                              MCConstantExpr::create(Size, OutContext));
00541 
00542   OutStreamer->AddBlankLine();
00543 }
00544 
00545 /// EmitFunctionHeader - This method emits the header for the current
00546 /// function.
00547 void AsmPrinter::EmitFunctionHeader() {
00548   // Print out constants referenced by the function
00549   EmitConstantPool();
00550 
00551   // Print the 'header' of function.
00552   const Function *F = MF->getFunction();
00553 
00554   OutStreamer->SwitchSection(
00555       getObjFileLowering().SectionForGlobal(F, *Mang, TM));
00556   EmitVisibility(CurrentFnSym, F->getVisibility());
00557 
00558   EmitLinkage(F, CurrentFnSym);
00559   if (MAI->hasFunctionAlignment())
00560     EmitAlignment(MF->getAlignment(), F);
00561 
00562   if (MAI->hasDotTypeDotSizeDirective())
00563     OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
00564 
00565   if (isVerbose()) {
00566     F->printAsOperand(OutStreamer->GetCommentOS(),
00567                    /*PrintType=*/false, F->getParent());
00568     OutStreamer->GetCommentOS() << '\n';
00569   }
00570 
00571   // Emit the prefix data.
00572   if (F->hasPrefixData())
00573     EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData());
00574 
00575   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
00576   // do their wild and crazy things as required.
00577   EmitFunctionEntryLabel();
00578 
00579   // If the function had address-taken blocks that got deleted, then we have
00580   // references to the dangling symbols.  Emit them at the start of the function
00581   // so that we don't get references to undefined symbols.
00582   std::vector<MCSymbol*> DeadBlockSyms;
00583   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
00584   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
00585     OutStreamer->AddComment("Address taken block that was later removed");
00586     OutStreamer->EmitLabel(DeadBlockSyms[i]);
00587   }
00588 
00589   if (CurrentFnBegin) {
00590     if (MAI->useAssignmentForEHBegin()) {
00591       MCSymbol *CurPos = OutContext.createTempSymbol();
00592       OutStreamer->EmitLabel(CurPos);
00593       OutStreamer->EmitAssignment(CurrentFnBegin,
00594                                  MCSymbolRefExpr::create(CurPos, OutContext));
00595     } else {
00596       OutStreamer->EmitLabel(CurrentFnBegin);
00597     }
00598   }
00599 
00600   // Emit pre-function debug and/or EH information.
00601   for (const HandlerInfo &HI : Handlers) {
00602     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00603     HI.Handler->beginFunction(MF);
00604   }
00605 
00606   // Emit the prologue data.
00607   if (F->hasPrologueData())
00608     EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData());
00609 }
00610 
00611 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
00612 /// function.  This can be overridden by targets as required to do custom stuff.
00613 void AsmPrinter::EmitFunctionEntryLabel() {
00614   CurrentFnSym->redefineIfPossible();
00615 
00616   // The function label could have already been emitted if two symbols end up
00617   // conflicting due to asm renaming.  Detect this and emit an error.
00618   if (CurrentFnSym->isVariable())
00619     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
00620                        "' is a protected alias");
00621   if (CurrentFnSym->isDefined())
00622     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
00623                        "' label emitted multiple times to assembly file");
00624 
00625   return OutStreamer->EmitLabel(CurrentFnSym);
00626 }
00627 
00628 /// emitComments - Pretty-print comments for instructions.
00629 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
00630   const MachineFunction *MF = MI.getParent()->getParent();
00631   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00632 
00633   // Check for spills and reloads
00634   int FI;
00635 
00636   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
00637 
00638   // We assume a single instruction only has a spill or reload, not
00639   // both.
00640   const MachineMemOperand *MMO;
00641   if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
00642     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
00643       MMO = *MI.memoperands_begin();
00644       CommentOS << MMO->getSize() << "-byte Reload\n";
00645     }
00646   } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
00647     if (FrameInfo->isSpillSlotObjectIndex(FI))
00648       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
00649   } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
00650     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
00651       MMO = *MI.memoperands_begin();
00652       CommentOS << MMO->getSize() << "-byte Spill\n";
00653     }
00654   } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
00655     if (FrameInfo->isSpillSlotObjectIndex(FI))
00656       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
00657   }
00658 
00659   // Check for spill-induced copies
00660   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
00661     CommentOS << " Reload Reuse\n";
00662 }
00663 
00664 /// emitImplicitDef - This method emits the specified machine instruction
00665 /// that is an implicit def.
00666 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00667   unsigned RegNo = MI->getOperand(0).getReg();
00668 
00669   SmallString<128> Str;
00670   raw_svector_ostream OS(Str);
00671   OS << "implicit-def: "
00672      << PrintReg(RegNo, MF->getSubtarget().getRegisterInfo());
00673 
00674   OutStreamer->AddComment(OS.str());
00675   OutStreamer->AddBlankLine();
00676 }
00677 
00678 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
00679   std::string Str;
00680   raw_string_ostream OS(Str);
00681   OS << "kill:";
00682   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00683     const MachineOperand &Op = MI->getOperand(i);
00684     assert(Op.isReg() && "KILL instruction must have only register operands");
00685     OS << ' '
00686        << PrintReg(Op.getReg(),
00687                    AP.MF->getSubtarget().getRegisterInfo())
00688        << (Op.isDef() ? "<def>" : "<kill>");
00689   }
00690   AP.OutStreamer->AddComment(Str);
00691   AP.OutStreamer->AddBlankLine();
00692 }
00693 
00694 /// emitDebugValueComment - This method handles the target-independent form
00695 /// of DBG_VALUE, returning true if it was able to do so.  A false return
00696 /// means the target will need to handle MI in EmitInstruction.
00697 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
00698   // This code handles only the 4-operand target-independent form.
00699   if (MI->getNumOperands() != 4)
00700     return false;
00701 
00702   SmallString<128> Str;
00703   raw_svector_ostream OS(Str);
00704   OS << "DEBUG_VALUE: ";
00705 
00706   const DILocalVariable *V = MI->getDebugVariable();
00707   if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
00708     StringRef Name = SP->getDisplayName();
00709     if (!Name.empty())
00710       OS << Name << ":";
00711   }
00712   OS << V->getName();
00713 
00714   const DIExpression *Expr = MI->getDebugExpression();
00715   if (Expr->isBitPiece())
00716     OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
00717        << " size=" << Expr->getBitPieceSize() << "]";
00718   OS << " <- ";
00719 
00720   // The second operand is only an offset if it's an immediate.
00721   bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
00722   int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
00723 
00724   for (unsigned i = 0; i < Expr->getNumElements(); ++i) {
00725     if (Deref) {
00726       // We currently don't support extra Offsets or derefs after the first
00727       // one. Bail out early instead of emitting an incorrect comment
00728       OS << " [complex expression]";
00729       AP.OutStreamer->emitRawComment(OS.str());
00730       return true;
00731     }
00732     uint64_t Op = Expr->getElement(i);
00733     if (Op == dwarf::DW_OP_deref) {
00734       Deref = true;
00735       continue;
00736     } else if (Op == dwarf::DW_OP_bit_piece) {
00737       // There can't be any operands after this in a valid expression
00738       break;
00739     }
00740     uint64_t ExtraOffset = Expr->getElement(i++);
00741     if (Op == dwarf::DW_OP_plus)
00742       Offset += ExtraOffset;
00743     else {
00744       assert(Op == dwarf::DW_OP_minus);
00745       Offset -= ExtraOffset;
00746     }
00747   }
00748 
00749   // Register or immediate value. Register 0 means undef.
00750   if (MI->getOperand(0).isFPImm()) {
00751     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
00752     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
00753       OS << (double)APF.convertToFloat();
00754     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
00755       OS << APF.convertToDouble();
00756     } else {
00757       // There is no good way to print long double.  Convert a copy to
00758       // double.  Ah well, it's only a comment.
00759       bool ignored;
00760       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
00761                   &ignored);
00762       OS << "(long double) " << APF.convertToDouble();
00763     }
00764   } else if (MI->getOperand(0).isImm()) {
00765     OS << MI->getOperand(0).getImm();
00766   } else if (MI->getOperand(0).isCImm()) {
00767     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
00768   } else {
00769     unsigned Reg;
00770     if (MI->getOperand(0).isReg()) {
00771       Reg = MI->getOperand(0).getReg();
00772     } else {
00773       assert(MI->getOperand(0).isFI() && "Unknown operand type");
00774       const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
00775       Offset += TFI->getFrameIndexReference(*AP.MF,
00776                                             MI->getOperand(0).getIndex(), Reg);
00777       Deref = true;
00778     }
00779     if (Reg == 0) {
00780       // Suppress offset, it is not meaningful here.
00781       OS << "undef";
00782       // NOTE: Want this comment at start of line, don't emit with AddComment.
00783       AP.OutStreamer->emitRawComment(OS.str());
00784       return true;
00785     }
00786     if (Deref)
00787       OS << '[';
00788     OS << PrintReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
00789   }
00790 
00791   if (Deref)
00792     OS << '+' << Offset << ']';
00793 
00794   // NOTE: Want this comment at start of line, don't emit with AddComment.
00795   AP.OutStreamer->emitRawComment(OS.str());
00796   return true;
00797 }
00798 
00799 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
00800   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
00801       MF->getFunction()->needsUnwindTableEntry())
00802     return CFI_M_EH;
00803 
00804   if (MMI->hasDebugInfo())
00805     return CFI_M_Debug;
00806 
00807   return CFI_M_None;
00808 }
00809 
00810 bool AsmPrinter::needsSEHMoves() {
00811   return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
00812 }
00813 
00814 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
00815   ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
00816   if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
00817       ExceptionHandlingType != ExceptionHandling::ARM)
00818     return;
00819 
00820   if (needsCFIMoves() == CFI_M_None)
00821     return;
00822 
00823   const MachineModuleInfo &MMI = MF->getMMI();
00824   const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
00825   unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
00826   const MCCFIInstruction &CFI = Instrs[CFIIndex];
00827   emitCFIInstruction(CFI);
00828 }
00829 
00830 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
00831   // The operands are the MCSymbol and the frame offset of the allocation.
00832   MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
00833   int FrameOffset = MI.getOperand(1).getImm();
00834 
00835   // Emit a symbol assignment.
00836   OutStreamer->EmitAssignment(FrameAllocSym,
00837                              MCConstantExpr::create(FrameOffset, OutContext));
00838 }
00839 
00840 /// EmitFunctionBody - This method emits the body and trailer for a
00841 /// function.
00842 void AsmPrinter::EmitFunctionBody() {
00843   EmitFunctionHeader();
00844 
00845   // Emit target-specific gunk before the function body.
00846   EmitFunctionBodyStart();
00847 
00848   bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
00849 
00850   // Print out code for the function.
00851   bool HasAnyRealCode = false;
00852   for (auto &MBB : *MF) {
00853     // Print a label for the basic block.
00854     EmitBasicBlockStart(MBB);
00855     for (auto &MI : MBB) {
00856 
00857       // Print the assembly for the instruction.
00858       if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
00859           !MI.isDebugValue()) {
00860         HasAnyRealCode = true;
00861         ++EmittedInsts;
00862       }
00863 
00864       if (ShouldPrintDebugScopes) {
00865         for (const HandlerInfo &HI : Handlers) {
00866           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
00867                              TimePassesIsEnabled);
00868           HI.Handler->beginInstruction(&MI);
00869         }
00870       }
00871 
00872       if (isVerbose())
00873         emitComments(MI, OutStreamer->GetCommentOS());
00874 
00875       switch (MI.getOpcode()) {
00876       case TargetOpcode::CFI_INSTRUCTION:
00877         emitCFIInstruction(MI);
00878         break;
00879 
00880       case TargetOpcode::LOCAL_ESCAPE:
00881         emitFrameAlloc(MI);
00882         break;
00883 
00884       case TargetOpcode::EH_LABEL:
00885       case TargetOpcode::GC_LABEL:
00886         OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
00887         break;
00888       case TargetOpcode::INLINEASM:
00889         EmitInlineAsm(&MI);
00890         break;
00891       case TargetOpcode::DBG_VALUE:
00892         if (isVerbose()) {
00893           if (!emitDebugValueComment(&MI, *this))
00894             EmitInstruction(&MI);
00895         }
00896         break;
00897       case TargetOpcode::IMPLICIT_DEF:
00898         if (isVerbose()) emitImplicitDef(&MI);
00899         break;
00900       case TargetOpcode::KILL:
00901         if (isVerbose()) emitKill(&MI, *this);
00902         break;
00903       default:
00904         EmitInstruction(&MI);
00905         break;
00906       }
00907 
00908       if (ShouldPrintDebugScopes) {
00909         for (const HandlerInfo &HI : Handlers) {
00910           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
00911                              TimePassesIsEnabled);
00912           HI.Handler->endInstruction();
00913         }
00914       }
00915     }
00916 
00917     EmitBasicBlockEnd(MBB);
00918   }
00919 
00920   // If the function is empty and the object file uses .subsections_via_symbols,
00921   // then we need to emit *something* to the function body to prevent the
00922   // labels from collapsing together.  Just emit a noop.
00923   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
00924     MCInst Noop;
00925     MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
00926     OutStreamer->AddComment("avoids zero-length function");
00927 
00928     // Targets can opt-out of emitting the noop here by leaving the opcode
00929     // unspecified.
00930     if (Noop.getOpcode())
00931       OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
00932   }
00933 
00934   const Function *F = MF->getFunction();
00935   for (const auto &BB : *F) {
00936     if (!BB.hasAddressTaken())
00937       continue;
00938     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
00939     if (Sym->isDefined())
00940       continue;
00941     OutStreamer->AddComment("Address of block that was removed by CodeGen");
00942     OutStreamer->EmitLabel(Sym);
00943   }
00944 
00945   // Emit target-specific gunk after the function body.
00946   EmitFunctionBodyEnd();
00947 
00948   if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
00949       MMI->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) {
00950     // Create a symbol for the end of function.
00951     CurrentFnEnd = createTempSymbol("func_end");
00952     OutStreamer->EmitLabel(CurrentFnEnd);
00953   }
00954 
00955   // If the target wants a .size directive for the size of the function, emit
00956   // it.
00957   if (MAI->hasDotTypeDotSizeDirective()) {
00958     // We can get the size as difference between the function label and the
00959     // temp label.
00960     const MCExpr *SizeExp = MCBinaryExpr::createSub(
00961         MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
00962         MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
00963     if (auto Sym = dyn_cast<MCSymbolELF>(CurrentFnSym))
00964       OutStreamer->emitELFSize(Sym, SizeExp);
00965   }
00966 
00967   for (const HandlerInfo &HI : Handlers) {
00968     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00969     HI.Handler->markFunctionEnd();
00970   }
00971 
00972   // Print out jump tables referenced by the function.
00973   EmitJumpTableInfo();
00974 
00975   // Emit post-function debug and/or EH information.
00976   for (const HandlerInfo &HI : Handlers) {
00977     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00978     HI.Handler->endFunction(MF);
00979   }
00980   MMI->EndFunction();
00981 
00982   OutStreamer->AddBlankLine();
00983 }
00984 
00985 /// \brief Compute the number of Global Variables that uses a Constant.
00986 static unsigned getNumGlobalVariableUses(const Constant *C) {
00987   if (!C)
00988     return 0;
00989 
00990   if (isa<GlobalVariable>(C))
00991     return 1;
00992 
00993   unsigned NumUses = 0;
00994   for (auto *CU : C->users())
00995     NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
00996 
00997   return NumUses;
00998 }
00999 
01000 /// \brief Only consider global GOT equivalents if at least one user is a
01001 /// cstexpr inside an initializer of another global variables. Also, don't
01002 /// handle cstexpr inside instructions. During global variable emission,
01003 /// candidates are skipped and are emitted later in case at least one cstexpr
01004 /// isn't replaced by a PC relative GOT entry access.
01005 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
01006                                      unsigned &NumGOTEquivUsers) {
01007   // Global GOT equivalents are unnamed private globals with a constant
01008   // pointer initializer to another global symbol. They must point to a
01009   // GlobalVariable or Function, i.e., as GlobalValue.
01010   if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
01011       !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
01012     return false;
01013 
01014   // To be a got equivalent, at least one of its users need to be a constant
01015   // expression used by another global variable.
01016   for (auto *U : GV->users())
01017     NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
01018 
01019   return NumGOTEquivUsers > 0;
01020 }
01021 
01022 /// \brief Unnamed constant global variables solely contaning a pointer to
01023 /// another globals variable is equivalent to a GOT table entry; it contains the
01024 /// the address of another symbol. Optimize it and replace accesses to these
01025 /// "GOT equivalents" by using the GOT entry for the final global instead.
01026 /// Compute GOT equivalent candidates among all global variables to avoid
01027 /// emitting them if possible later on, after it use is replaced by a GOT entry
01028 /// access.
01029 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
01030   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
01031     return;
01032 
01033   for (const auto &G : M.globals()) {
01034     unsigned NumGOTEquivUsers = 0;
01035     if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
01036       continue;
01037 
01038     const MCSymbol *GOTEquivSym = getSymbol(&G);
01039     GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
01040   }
01041 }
01042 
01043 /// \brief Constant expressions using GOT equivalent globals may not be eligible
01044 /// for PC relative GOT entry conversion, in such cases we need to emit such
01045 /// globals we previously omitted in EmitGlobalVariable.
01046 void AsmPrinter::emitGlobalGOTEquivs() {
01047   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
01048     return;
01049 
01050   SmallVector<const GlobalVariable *, 8> FailedCandidates;
01051   for (auto &I : GlobalGOTEquivs) {
01052     const GlobalVariable *GV = I.second.first;
01053     unsigned Cnt = I.second.second;
01054     if (Cnt)
01055       FailedCandidates.push_back(GV);
01056   }
01057   GlobalGOTEquivs.clear();
01058 
01059   for (auto *GV : FailedCandidates)
01060     EmitGlobalVariable(GV);
01061 }
01062 
01063 bool AsmPrinter::doFinalization(Module &M) {
01064   // Set the MachineFunction to nullptr so that we can catch attempted
01065   // accesses to MF specific features at the module level and so that
01066   // we can conditionalize accesses based on whether or not it is nullptr.
01067   MF = nullptr;
01068 
01069   // Gather all GOT equivalent globals in the module. We really need two
01070   // passes over the globals: one to compute and another to avoid its emission
01071   // in EmitGlobalVariable, otherwise we would not be able to handle cases
01072   // where the got equivalent shows up before its use.
01073   computeGlobalGOTEquivs(M);
01074 
01075   // Emit global variables.
01076   for (const auto &G : M.globals())
01077     EmitGlobalVariable(&G);
01078 
01079   // Emit remaining GOT equivalent globals.
01080   emitGlobalGOTEquivs();
01081 
01082   // Emit visibility info for declarations
01083   for (const Function &F : M) {
01084     if (!F.isDeclarationForLinker())
01085       continue;
01086     GlobalValue::VisibilityTypes V = F.getVisibility();
01087     if (V == GlobalValue::DefaultVisibility)
01088       continue;
01089 
01090     MCSymbol *Name = getSymbol(&F);
01091     EmitVisibility(Name, V, false);
01092   }
01093 
01094   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
01095 
01096   // Emit module flags.
01097   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
01098   M.getModuleFlagsMetadata(ModuleFlags);
01099   if (!ModuleFlags.empty())
01100     TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
01101 
01102   if (TM.getTargetTriple().isOSBinFormatELF()) {
01103     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
01104 
01105     // Output stubs for external and common global variables.
01106     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
01107     if (!Stubs.empty()) {
01108       OutStreamer->SwitchSection(TLOF.getDataSection());
01109       const DataLayout &DL = M.getDataLayout();
01110 
01111       for (const auto &Stub : Stubs) {
01112         OutStreamer->EmitLabel(Stub.first);
01113         OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
01114                                      DL.getPointerSize());
01115       }
01116     }
01117   }
01118 
01119   // Finalize debug and EH information.
01120   for (const HandlerInfo &HI : Handlers) {
01121     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
01122                        TimePassesIsEnabled);
01123     HI.Handler->endModule();
01124     delete HI.Handler;
01125   }
01126   Handlers.clear();
01127   DD = nullptr;
01128 
01129   // If the target wants to know about weak references, print them all.
01130   if (MAI->getWeakRefDirective()) {
01131     // FIXME: This is not lazy, it would be nice to only print weak references
01132     // to stuff that is actually used.  Note that doing so would require targets
01133     // to notice uses in operands (due to constant exprs etc).  This should
01134     // happen with the MC stuff eventually.
01135 
01136     // Print out module-level global variables here.
01137     for (const auto &G : M.globals()) {
01138       if (!G.hasExternalWeakLinkage())
01139         continue;
01140       OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
01141     }
01142 
01143     for (const auto &F : M) {
01144       if (!F.hasExternalWeakLinkage())
01145         continue;
01146       OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
01147     }
01148   }
01149 
01150   OutStreamer->AddBlankLine();
01151   for (const auto &Alias : M.aliases()) {
01152     MCSymbol *Name = getSymbol(&Alias);
01153 
01154     if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
01155       OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
01156     else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
01157       OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
01158     else
01159       assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
01160 
01161     // Set the symbol type to function if the alias has a function type.
01162     // This affects codegen when the aliasee is not a function.
01163     if (Alias.getType()->getPointerElementType()->isFunctionTy())
01164       OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
01165 
01166     EmitVisibility(Name, Alias.getVisibility());
01167 
01168     // Emit the directives as assignments aka .set:
01169     OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
01170 
01171     // If the aliasee does not correspond to a symbol in the output, i.e. the
01172     // alias is not of an object or the aliased object is private, then set the
01173     // size of the alias symbol from the type of the alias. We don't do this in
01174     // other situations as the alias and aliasee having differing types but same
01175     // size may be intentional.
01176     const GlobalObject *BaseObject = Alias.getBaseObject();
01177     if (MAI->hasDotTypeDotSizeDirective() && Alias.getValueType()->isSized() &&
01178         (!BaseObject || BaseObject->hasPrivateLinkage())) {
01179       const DataLayout &DL = M.getDataLayout();
01180       uint64_t Size = DL.getTypeAllocSize(Alias.getValueType());
01181       OutStreamer->emitELFSize(cast<MCSymbolELF>(Name),
01182                                MCConstantExpr::create(Size, OutContext));
01183     }
01184   }
01185 
01186   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
01187   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
01188   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
01189     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
01190       MP->finishAssembly(M, *MI, *this);
01191 
01192   // Emit llvm.ident metadata in an '.ident' directive.
01193   EmitModuleIdents(M);
01194 
01195   // Emit __morestack address if needed for indirect calls.
01196   if (MMI->usesMorestackAddr()) {
01197     MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
01198         getDataLayout(), SectionKind::getReadOnly(),
01199         /*C=*/nullptr);
01200     OutStreamer->SwitchSection(ReadOnlySection);
01201 
01202     MCSymbol *AddrSymbol =
01203         OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
01204     OutStreamer->EmitLabel(AddrSymbol);
01205 
01206     unsigned PtrSize = M.getDataLayout().getPointerSize(0);
01207     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
01208                                  PtrSize);
01209   }
01210 
01211   // If we don't have any trampolines, then we don't require stack memory
01212   // to be executable. Some targets have a directive to declare this.
01213   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
01214   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
01215     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
01216       OutStreamer->SwitchSection(S);
01217 
01218   // Allow the target to emit any magic that it wants at the end of the file,
01219   // after everything else has gone out.
01220   EmitEndOfAsmFile(M);
01221 
01222   delete Mang; Mang = nullptr;
01223   MMI = nullptr;
01224 
01225   OutStreamer->Finish();
01226   OutStreamer->reset();
01227 
01228   return false;
01229 }
01230 
01231 MCSymbol *AsmPrinter::getCurExceptionSym() {
01232   if (!CurExceptionSym)
01233     CurExceptionSym = createTempSymbol("exception");
01234   return CurExceptionSym;
01235 }
01236 
01237 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
01238   this->MF = &MF;
01239   // Get the function symbol.
01240   CurrentFnSym = getSymbol(MF.getFunction());
01241   CurrentFnSymForSize = CurrentFnSym;
01242   CurrentFnBegin = nullptr;
01243   CurExceptionSym = nullptr;
01244   bool NeedsLocalForSize = MAI->needsLocalForSize();
01245   if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
01246       MMI->hasEHFunclets() || NeedsLocalForSize) {
01247     CurrentFnBegin = createTempSymbol("func_begin");
01248     if (NeedsLocalForSize)
01249       CurrentFnSymForSize = CurrentFnBegin;
01250   }
01251 
01252   if (isVerbose())
01253     LI = &getAnalysis<MachineLoopInfo>();
01254 }
01255 
01256 namespace {
01257 // Keep track the alignment, constpool entries per Section.
01258   struct SectionCPs {
01259     MCSection *S;
01260     unsigned Alignment;
01261     SmallVector<unsigned, 4> CPEs;
01262     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
01263   };
01264 }
01265 
01266 /// EmitConstantPool - Print to the current output stream assembly
01267 /// representations of the constants in the constant pool MCP. This is
01268 /// used to print out constants which have been "spilled to memory" by
01269 /// the code generator.
01270 ///
01271 void AsmPrinter::EmitConstantPool() {
01272   const MachineConstantPool *MCP = MF->getConstantPool();
01273   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
01274   if (CP.empty()) return;
01275 
01276   // Calculate sections for constant pool entries. We collect entries to go into
01277   // the same section together to reduce amount of section switch statements.
01278   SmallVector<SectionCPs, 4> CPSections;
01279   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
01280     const MachineConstantPoolEntry &CPE = CP[i];
01281     unsigned Align = CPE.getAlignment();
01282 
01283     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
01284 
01285     const Constant *C = nullptr;
01286     if (!CPE.isMachineConstantPoolEntry())
01287       C = CPE.Val.ConstVal;
01288 
01289     MCSection *S =
01290         getObjFileLowering().getSectionForConstant(getDataLayout(), Kind, C);
01291 
01292     // The number of sections are small, just do a linear search from the
01293     // last section to the first.
01294     bool Found = false;
01295     unsigned SecIdx = CPSections.size();
01296     while (SecIdx != 0) {
01297       if (CPSections[--SecIdx].S == S) {
01298         Found = true;
01299         break;
01300       }
01301     }
01302     if (!Found) {
01303       SecIdx = CPSections.size();
01304       CPSections.push_back(SectionCPs(S, Align));
01305     }
01306 
01307     if (Align > CPSections[SecIdx].Alignment)
01308       CPSections[SecIdx].Alignment = Align;
01309     CPSections[SecIdx].CPEs.push_back(i);
01310   }
01311 
01312   // Now print stuff into the calculated sections.
01313   const MCSection *CurSection = nullptr;
01314   unsigned Offset = 0;
01315   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
01316     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
01317       unsigned CPI = CPSections[i].CPEs[j];
01318       MCSymbol *Sym = GetCPISymbol(CPI);
01319       if (!Sym->isUndefined())
01320         continue;
01321 
01322       if (CurSection != CPSections[i].S) {
01323         OutStreamer->SwitchSection(CPSections[i].S);
01324         EmitAlignment(Log2_32(CPSections[i].Alignment));
01325         CurSection = CPSections[i].S;
01326         Offset = 0;
01327       }
01328 
01329       MachineConstantPoolEntry CPE = CP[CPI];
01330 
01331       // Emit inter-object padding for alignment.
01332       unsigned AlignMask = CPE.getAlignment() - 1;
01333       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
01334       OutStreamer->EmitZeros(NewOffset - Offset);
01335 
01336       Type *Ty = CPE.getType();
01337       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
01338 
01339       OutStreamer->EmitLabel(Sym);
01340       if (CPE.isMachineConstantPoolEntry())
01341         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
01342       else
01343         EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
01344     }
01345   }
01346 }
01347 
01348 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
01349 /// by the current function to the current output stream.
01350 ///
01351 void AsmPrinter::EmitJumpTableInfo() {
01352   const DataLayout &DL = MF->getDataLayout();
01353   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01354   if (!MJTI) return;
01355   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
01356   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01357   if (JT.empty()) return;
01358 
01359   // Pick the directive to use to print the jump table entries, and switch to
01360   // the appropriate section.
01361   const Function *F = MF->getFunction();
01362   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
01363   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
01364       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
01365       *F);
01366   if (JTInDiffSection) {
01367     // Drop it in the readonly section.
01368     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
01369     OutStreamer->SwitchSection(ReadOnlySection);
01370   }
01371 
01372   EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
01373 
01374   // Jump tables in code sections are marked with a data_region directive
01375   // where that's supported.
01376   if (!JTInDiffSection)
01377     OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
01378 
01379   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
01380     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01381 
01382     // If this jump table was deleted, ignore it.
01383     if (JTBBs.empty()) continue;
01384 
01385     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
01386     /// emit a .set directive for each unique entry.
01387     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
01388         MAI->doesSetDirectiveSuppressesReloc()) {
01389       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
01390       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
01391       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
01392       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
01393         const MachineBasicBlock *MBB = JTBBs[ii];
01394         if (!EmittedSets.insert(MBB).second)
01395           continue;
01396 
01397         // .set LJTSet, LBB32-base
01398         const MCExpr *LHS =
01399           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
01400         OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
01401                                     MCBinaryExpr::createSub(LHS, Base,
01402                                                             OutContext));
01403       }
01404     }
01405 
01406     // On some targets (e.g. Darwin) we want to emit two consecutive labels
01407     // before each jump table.  The first label is never referenced, but tells
01408     // the assembler and linker the extents of the jump table object.  The
01409     // second label is actually referenced by the code.
01410     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
01411       // FIXME: This doesn't have to have any specific name, just any randomly
01412       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
01413       OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
01414 
01415     OutStreamer->EmitLabel(GetJTISymbol(JTI));
01416 
01417     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
01418       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
01419   }
01420   if (!JTInDiffSection)
01421     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
01422 }
01423 
01424 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
01425 /// current stream.
01426 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
01427                                     const MachineBasicBlock *MBB,
01428                                     unsigned UID) const {
01429   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
01430   const MCExpr *Value = nullptr;
01431   switch (MJTI->getEntryKind()) {
01432   case MachineJumpTableInfo::EK_Inline:
01433     llvm_unreachable("Cannot emit EK_Inline jump table entry");
01434   case MachineJumpTableInfo::EK_Custom32:
01435     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
01436         MJTI, MBB, UID, OutContext);
01437     break;
01438   case MachineJumpTableInfo::EK_BlockAddress:
01439     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
01440     //     .word LBB123
01441     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
01442     break;
01443   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
01444     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
01445     // with a relocation as gp-relative, e.g.:
01446     //     .gprel32 LBB123
01447     MCSymbol *MBBSym = MBB->getSymbol();
01448     OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
01449     return;
01450   }
01451 
01452   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
01453     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
01454     // with a relocation as gp-relative, e.g.:
01455     //     .gpdword LBB123
01456     MCSymbol *MBBSym = MBB->getSymbol();
01457     OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
01458     return;
01459   }
01460 
01461   case MachineJumpTableInfo::EK_LabelDifference32: {
01462     // Each entry is the address of the block minus the address of the jump
01463     // table. This is used for PIC jump tables where gprel32 is not supported.
01464     // e.g.:
01465     //      .word LBB123 - LJTI1_2
01466     // If the .set directive avoids relocations, this is emitted as:
01467     //      .set L4_5_set_123, LBB123 - LJTI1_2
01468     //      .word L4_5_set_123
01469     if (MAI->doesSetDirectiveSuppressesReloc()) {
01470       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
01471                                       OutContext);
01472       break;
01473     }
01474     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
01475     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
01476     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
01477     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
01478     break;
01479   }
01480   }
01481 
01482   assert(Value && "Unknown entry kind!");
01483 
01484   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
01485   OutStreamer->EmitValue(Value, EntrySize);
01486 }
01487 
01488 
01489 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
01490 /// special global used by LLVM.  If so, emit it and return true, otherwise
01491 /// do nothing and return false.
01492 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
01493   if (GV->getName() == "llvm.used") {
01494     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
01495       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
01496     return true;
01497   }
01498 
01499   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
01500   if (StringRef(GV->getSection()) == "llvm.metadata" ||
01501       GV->hasAvailableExternallyLinkage())
01502     return true;
01503 
01504   if (!GV->hasAppendingLinkage()) return false;
01505 
01506   assert(GV->hasInitializer() && "Not a special LLVM global!");
01507 
01508   if (GV->getName() == "llvm.global_ctors") {
01509     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
01510                        /* isCtor */ true);
01511 
01512     if (TM.getRelocationModel() == Reloc::Static &&
01513         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01514       StringRef Sym(".constructors_used");
01515       OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
01516                                        MCSA_Reference);
01517     }
01518     return true;
01519   }
01520 
01521   if (GV->getName() == "llvm.global_dtors") {
01522     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
01523                        /* isCtor */ false);
01524 
01525     if (TM.getRelocationModel() == Reloc::Static &&
01526         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01527       StringRef Sym(".destructors_used");
01528       OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
01529                                        MCSA_Reference);
01530     }
01531     return true;
01532   }
01533 
01534   return false;
01535 }
01536 
01537 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
01538 /// global in the specified llvm.used list for which emitUsedDirectiveFor
01539 /// is true, as being used with this directive.
01540 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
01541   // Should be an array of 'i8*'.
01542   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
01543     const GlobalValue *GV =
01544       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
01545     if (GV)
01546       OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
01547   }
01548 }
01549 
01550 namespace {
01551 struct Structor {
01552   Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
01553   int Priority;
01554   llvm::Constant *Func;
01555   llvm::GlobalValue *ComdatKey;
01556 };
01557 } // end namespace
01558 
01559 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
01560 /// priority.
01561 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
01562                                     bool isCtor) {
01563   // Should be an array of '{ int, void ()* }' structs.  The first value is the
01564   // init priority.
01565   if (!isa<ConstantArray>(List)) return;
01566 
01567   // Sanity check the structors list.
01568   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
01569   if (!InitList) return; // Not an array!
01570   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
01571   // FIXME: Only allow the 3-field form in LLVM 4.0.
01572   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
01573     return; // Not an array of two or three elements!
01574   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
01575       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
01576   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
01577     return; // Not (int, ptr, ptr).
01578 
01579   // Gather the structors in a form that's convenient for sorting by priority.
01580   SmallVector<Structor, 8> Structors;
01581   for (Value *O : InitList->operands()) {
01582     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
01583     if (!CS) continue; // Malformed.
01584     if (CS->getOperand(1)->isNullValue())
01585       break;  // Found a null terminator, skip the rest.
01586     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
01587     if (!Priority) continue; // Malformed.
01588     Structors.push_back(Structor());
01589     Structor &S = Structors.back();
01590     S.Priority = Priority->getLimitedValue(65535);
01591     S.Func = CS->getOperand(1);
01592     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
01593       S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
01594   }
01595 
01596   // Emit the function pointers in the target-specific order
01597   unsigned Align = Log2_32(DL.getPointerPrefAlignment());
01598   std::stable_sort(Structors.begin(), Structors.end(),
01599                    [](const Structor &L,
01600                       const Structor &R) { return L.Priority < R.Priority; });
01601   for (Structor &S : Structors) {
01602     const TargetLoweringObjectFile &Obj = getObjFileLowering();
01603     const MCSymbol *KeySym = nullptr;
01604     if (GlobalValue *GV = S.ComdatKey) {
01605       if (GV->hasAvailableExternallyLinkage())
01606         // If the associated variable is available_externally, some other TU
01607         // will provide its dynamic initializer.
01608         continue;
01609 
01610       KeySym = getSymbol(GV);
01611     }
01612     MCSection *OutputSection =
01613         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
01614                 : Obj.getStaticDtorSection(S.Priority, KeySym));
01615     OutStreamer->SwitchSection(OutputSection);
01616     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
01617       EmitAlignment(Align);
01618     EmitXXStructor(DL, S.Func);
01619   }
01620 }
01621 
01622 void AsmPrinter::EmitModuleIdents(Module &M) {
01623   if (!MAI->hasIdentDirective())
01624     return;
01625 
01626   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
01627     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
01628       const MDNode *N = NMD->getOperand(i);
01629       assert(N->getNumOperands() == 1 &&
01630              "llvm.ident metadata entry can have only one operand");
01631       const MDString *S = cast<MDString>(N->getOperand(0));
01632       OutStreamer->EmitIdent(S->getString());
01633     }
01634   }
01635 }
01636 
01637 //===--------------------------------------------------------------------===//
01638 // Emission and print routines
01639 //
01640 
01641 /// EmitInt8 - Emit a byte directive and value.
01642 ///
01643 void AsmPrinter::EmitInt8(int Value) const {
01644   OutStreamer->EmitIntValue(Value, 1);
01645 }
01646 
01647 /// EmitInt16 - Emit a short directive and value.
01648 ///
01649 void AsmPrinter::EmitInt16(int Value) const {
01650   OutStreamer->EmitIntValue(Value, 2);
01651 }
01652 
01653 /// EmitInt32 - Emit a long directive and value.
01654 ///
01655 void AsmPrinter::EmitInt32(int Value) const {
01656   OutStreamer->EmitIntValue(Value, 4);
01657 }
01658 
01659 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
01660 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
01661 /// .set if it avoids relocations.
01662 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
01663                                      unsigned Size) const {
01664   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
01665 }
01666 
01667 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
01668 /// where the size in bytes of the directive is specified by Size and Label
01669 /// specifies the label.  This implicitly uses .set if it is available.
01670 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
01671                                      unsigned Size,
01672                                      bool IsSectionRelative) const {
01673   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
01674     OutStreamer->EmitCOFFSecRel32(Label);
01675     return;
01676   }
01677 
01678   // Emit Label+Offset (or just Label if Offset is zero)
01679   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
01680   if (Offset)
01681     Expr = MCBinaryExpr::createAdd(
01682         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
01683 
01684   OutStreamer->EmitValue(Expr, Size);
01685 }
01686 
01687 //===----------------------------------------------------------------------===//
01688 
01689 // EmitAlignment - Emit an alignment directive to the specified power of
01690 // two boundary.  For example, if you pass in 3 here, you will get an 8
01691 // byte alignment.  If a global value is specified, and if that global has
01692 // an explicit alignment requested, it will override the alignment request
01693 // if required for correctness.
01694 //
01695 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
01696   if (GV)
01697     NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
01698 
01699   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
01700 
01701   assert(NumBits <
01702              static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
01703          "undefined behavior");
01704   if (getCurrentSection()->getKind().isText())
01705     OutStreamer->EmitCodeAlignment(1u << NumBits);
01706   else
01707     OutStreamer->EmitValueToAlignment(1u << NumBits);
01708 }
01709 
01710 //===----------------------------------------------------------------------===//
01711 // Constant emission.
01712 //===----------------------------------------------------------------------===//
01713 
01714 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
01715   MCContext &Ctx = OutContext;
01716 
01717   if (CV->isNullValue() || isa<UndefValue>(CV))
01718     return MCConstantExpr::create(0, Ctx);
01719 
01720   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
01721     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
01722 
01723   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
01724     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
01725 
01726   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
01727     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
01728 
01729   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
01730   if (!CE) {
01731     llvm_unreachable("Unknown constant value to lower!");
01732   }
01733 
01734   if (const MCExpr *RelocExpr
01735       = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
01736     return RelocExpr;
01737 
01738   switch (CE->getOpcode()) {
01739   default:
01740     // If the code isn't optimized, there may be outstanding folding
01741     // opportunities. Attempt to fold the expression using DataLayout as a
01742     // last resort before giving up.
01743     if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
01744       if (C != CE)
01745         return lowerConstant(C);
01746 
01747     // Otherwise report the problem to the user.
01748     {
01749       std::string S;
01750       raw_string_ostream OS(S);
01751       OS << "Unsupported expression in static initializer: ";
01752       CE->printAsOperand(OS, /*PrintType=*/false,
01753                      !MF ? nullptr : MF->getFunction()->getParent());
01754       report_fatal_error(OS.str());
01755     }
01756   case Instruction::GetElementPtr: {
01757     // Generate a symbolic expression for the byte address
01758     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
01759     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
01760 
01761     const MCExpr *Base = lowerConstant(CE->getOperand(0));
01762     if (!OffsetAI)
01763       return Base;
01764 
01765     int64_t Offset = OffsetAI.getSExtValue();
01766     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
01767                                    Ctx);
01768   }
01769 
01770   case Instruction::Trunc:
01771     // We emit the value and depend on the assembler to truncate the generated
01772     // expression properly.  This is important for differences between
01773     // blockaddress labels.  Since the two labels are in the same function, it
01774     // is reasonable to treat their delta as a 32-bit value.
01775     // FALL THROUGH.
01776   case Instruction::BitCast:
01777     return lowerConstant(CE->getOperand(0));
01778 
01779   case Instruction::IntToPtr: {
01780     const DataLayout &DL = getDataLayout();
01781 
01782     // Handle casts to pointers by changing them into casts to the appropriate
01783     // integer type.  This promotes constant folding and simplifies this code.
01784     Constant *Op = CE->getOperand(0);
01785     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
01786                                       false/*ZExt*/);
01787     return lowerConstant(Op);
01788   }
01789 
01790   case Instruction::PtrToInt: {
01791     const DataLayout &DL = getDataLayout();
01792 
01793     // Support only foldable casts to/from pointers that can be eliminated by
01794     // changing the pointer to the appropriately sized integer type.
01795     Constant *Op = CE->getOperand(0);
01796     Type *Ty = CE->getType();
01797 
01798     const MCExpr *OpExpr = lowerConstant(Op);
01799 
01800     // We can emit the pointer value into this slot if the slot is an
01801     // integer slot equal to the size of the pointer.
01802     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
01803       return OpExpr;
01804 
01805     // Otherwise the pointer is smaller than the resultant integer, mask off
01806     // the high bits so we are sure to get a proper truncation if the input is
01807     // a constant expr.
01808     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
01809     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
01810     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
01811   }
01812 
01813   // The MC library also has a right-shift operator, but it isn't consistently
01814   // signed or unsigned between different targets.
01815   case Instruction::Add:
01816   case Instruction::Sub:
01817   case Instruction::Mul:
01818   case Instruction::SDiv:
01819   case Instruction::SRem:
01820   case Instruction::Shl:
01821   case Instruction::And:
01822   case Instruction::Or:
01823   case Instruction::Xor: {
01824     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
01825     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
01826     switch (CE->getOpcode()) {
01827     default: llvm_unreachable("Unknown binary operator constant cast expr");
01828     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
01829     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
01830     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
01831     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
01832     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
01833     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
01834     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
01835     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
01836     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
01837     }
01838   }
01839   }
01840 }
01841 
01842 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
01843                                    AsmPrinter &AP,
01844                                    const Constant *BaseCV = nullptr,
01845                                    uint64_t Offset = 0);
01846 
01847 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
01848 
01849 /// isRepeatedByteSequence - Determine whether the given value is
01850 /// composed of a repeated sequence of identical bytes and return the
01851 /// byte value.  If it is not a repeated sequence, return -1.
01852 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
01853   StringRef Data = V->getRawDataValues();
01854   assert(!Data.empty() && "Empty aggregates should be CAZ node");
01855   char C = Data[0];
01856   for (unsigned i = 1, e = Data.size(); i != e; ++i)
01857     if (Data[i] != C) return -1;
01858   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
01859 }
01860 
01861 
01862 /// isRepeatedByteSequence - Determine whether the given value is
01863 /// composed of a repeated sequence of identical bytes and return the
01864 /// byte value.  If it is not a repeated sequence, return -1.
01865 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
01866   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
01867     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
01868     assert(Size % 8 == 0);
01869 
01870     // Extend the element to take zero padding into account.
01871     APInt Value = CI->getValue().zextOrSelf(Size);
01872     if (!Value.isSplat(8))
01873       return -1;
01874 
01875     return Value.zextOrTrunc(8).getZExtValue();
01876   }
01877   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
01878     // Make sure all array elements are sequences of the same repeated
01879     // byte.
01880     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
01881     Constant *Op0 = CA->getOperand(0);
01882     int Byte = isRepeatedByteSequence(Op0, DL);
01883     if (Byte == -1)
01884       return -1;
01885 
01886     // All array elements must be equal.
01887     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
01888       if (CA->getOperand(i) != Op0)
01889         return -1;
01890     return Byte;
01891   }
01892 
01893   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
01894     return isRepeatedByteSequence(CDS);
01895 
01896   return -1;
01897 }
01898 
01899 static void emitGlobalConstantDataSequential(const DataLayout &DL,
01900                                              const ConstantDataSequential *CDS,
01901                                              AsmPrinter &AP) {
01902 
01903   // See if we can aggregate this into a .fill, if so, emit it as such.
01904   int Value = isRepeatedByteSequence(CDS, DL);
01905   if (Value != -1) {
01906     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
01907     // Don't emit a 1-byte object as a .fill.
01908     if (Bytes > 1)
01909       return AP.OutStreamer->EmitFill(Bytes, Value);
01910   }
01911 
01912   // If this can be emitted with .ascii/.asciz, emit it as such.
01913   if (CDS->isString())
01914     return AP.OutStreamer->EmitBytes(CDS->getAsString());
01915 
01916   // Otherwise, emit the values in successive locations.
01917   unsigned ElementByteSize = CDS->getElementByteSize();
01918   if (isa<IntegerType>(CDS->getElementType())) {
01919     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01920       if (AP.isVerbose())
01921         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
01922                                                  CDS->getElementAsInteger(i));
01923       AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
01924                                    ElementByteSize);
01925     }
01926   } else {
01927     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
01928       emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP);
01929   }
01930 
01931   unsigned Size = DL.getTypeAllocSize(CDS->getType());
01932   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
01933                         CDS->getNumElements();
01934   if (unsigned Padding = Size - EmittedSize)
01935     AP.OutStreamer->EmitZeros(Padding);
01936 
01937 }
01938 
01939 static void emitGlobalConstantArray(const DataLayout &DL,
01940                                     const ConstantArray *CA, AsmPrinter &AP,
01941                                     const Constant *BaseCV, uint64_t Offset) {
01942   // See if we can aggregate some values.  Make sure it can be
01943   // represented as a series of bytes of the constant value.
01944   int Value = isRepeatedByteSequence(CA, DL);
01945 
01946   if (Value != -1) {
01947     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
01948     AP.OutStreamer->EmitFill(Bytes, Value);
01949   }
01950   else {
01951     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
01952       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
01953       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
01954     }
01955   }
01956 }
01957 
01958 static void emitGlobalConstantVector(const DataLayout &DL,
01959                                      const ConstantVector *CV, AsmPrinter &AP) {
01960   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
01961     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
01962 
01963   unsigned Size = DL.getTypeAllocSize(CV->getType());
01964   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
01965                          CV->getType()->getNumElements();
01966   if (unsigned Padding = Size - EmittedSize)
01967     AP.OutStreamer->EmitZeros(Padding);
01968 }
01969 
01970 static void emitGlobalConstantStruct(const DataLayout &DL,
01971                                      const ConstantStruct *CS, AsmPrinter &AP,
01972                                      const Constant *BaseCV, uint64_t Offset) {
01973   // Print the fields in successive locations. Pad to align if needed!
01974   unsigned Size = DL.getTypeAllocSize(CS->getType());
01975   const StructLayout *Layout = DL.getStructLayout(CS->getType());
01976   uint64_t SizeSoFar = 0;
01977   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
01978     const Constant *Field = CS->getOperand(i);
01979 
01980     // Print the actual field value.
01981     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
01982 
01983     // Check if padding is needed and insert one or more 0s.
01984     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
01985     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
01986                         - Layout->getElementOffset(i)) - FieldSize;
01987     SizeSoFar += FieldSize + PadSize;
01988 
01989     // Insert padding - this may include padding to increase the size of the
01990     // current field up to the ABI size (if the struct is not packed) as well
01991     // as padding to ensure that the next field starts at the right offset.
01992     AP.OutStreamer->EmitZeros(PadSize);
01993   }
01994   assert(SizeSoFar == Layout->getSizeInBytes() &&
01995          "Layout of constant struct may be incorrect!");
01996 }
01997 
01998 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
01999   APInt API = CFP->getValueAPF().bitcastToAPInt();
02000 
02001   // First print a comment with what we think the original floating-point value
02002   // should have been.
02003   if (AP.isVerbose()) {
02004     SmallString<8> StrVal;
02005     CFP->getValueAPF().toString(StrVal);
02006 
02007     if (CFP->getType())
02008       CFP->getType()->print(AP.OutStreamer->GetCommentOS());
02009     else
02010       AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
02011     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
02012   }
02013 
02014   // Now iterate through the APInt chunks, emitting them in endian-correct
02015   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
02016   // floats).
02017   unsigned NumBytes = API.getBitWidth() / 8;
02018   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
02019   const uint64_t *p = API.getRawData();
02020 
02021   // PPC's long double has odd notions of endianness compared to how LLVM
02022   // handles it: p[0] goes first for *big* endian on PPC.
02023   if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
02024     int Chunk = API.getNumWords() - 1;
02025 
02026     if (TrailingBytes)
02027       AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
02028 
02029     for (; Chunk >= 0; --Chunk)
02030       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
02031   } else {
02032     unsigned Chunk;
02033     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
02034       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
02035 
02036     if (TrailingBytes)
02037       AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
02038   }
02039 
02040   // Emit the tail padding for the long double.
02041   const DataLayout &DL = AP.getDataLayout();
02042   AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
02043                             DL.getTypeStoreSize(CFP->getType()));
02044 }
02045 
02046 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
02047   const DataLayout &DL = AP.getDataLayout();
02048   unsigned BitWidth = CI->getBitWidth();
02049 
02050   // Copy the value as we may massage the layout for constants whose bit width
02051   // is not a multiple of 64-bits.
02052   APInt Realigned(CI->getValue());
02053   uint64_t ExtraBits = 0;
02054   unsigned ExtraBitsSize = BitWidth & 63;
02055 
02056   if (ExtraBitsSize) {
02057     // The bit width of the data is not a multiple of 64-bits.
02058     // The extra bits are expected to be at the end of the chunk of the memory.
02059     // Little endian:
02060     // * Nothing to be done, just record the extra bits to emit.
02061     // Big endian:
02062     // * Record the extra bits to emit.
02063     // * Realign the raw data to emit the chunks of 64-bits.
02064     if (DL.isBigEndian()) {
02065       // Basically the structure of the raw data is a chunk of 64-bits cells:
02066       //    0        1         BitWidth / 64
02067       // [chunk1][chunk2] ... [chunkN].
02068       // The most significant chunk is chunkN and it should be emitted first.
02069       // However, due to the alignment issue chunkN contains useless bits.
02070       // Realign the chunks so that they contain only useless information:
02071       // ExtraBits     0       1       (BitWidth / 64) - 1
02072       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
02073       ExtraBits = Realigned.getRawData()[0] &
02074         (((uint64_t)-1) >> (64 - ExtraBitsSize));
02075       Realigned = Realigned.lshr(ExtraBitsSize);
02076     } else
02077       ExtraBits = Realigned.getRawData()[BitWidth / 64];
02078   }
02079 
02080   // We don't expect assemblers to support integer data directives
02081   // for more than 64 bits, so we emit the data in at most 64-bit
02082   // quantities at a time.
02083   const uint64_t *RawData = Realigned.getRawData();
02084   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
02085     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
02086     AP.OutStreamer->EmitIntValue(Val, 8);
02087   }
02088 
02089   if (ExtraBitsSize) {
02090     // Emit the extra bits after the 64-bits chunks.
02091 
02092     // Emit a directive that fills the expected size.
02093     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
02094     Size -= (BitWidth / 64) * 8;
02095     assert(Size && Size * 8 >= ExtraBitsSize &&
02096            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
02097            == ExtraBits && "Directive too small for extra bits.");
02098     AP.OutStreamer->EmitIntValue(ExtraBits, Size);
02099   }
02100 }
02101 
02102 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
02103 /// equivalent global, by a target specific GOT pc relative access to the
02104 /// final symbol.
02105 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
02106                                          const Constant *BaseCst,
02107                                          uint64_t Offset) {
02108   // The global @foo below illustrates a global that uses a got equivalent.
02109   //
02110   //  @bar = global i32 42
02111   //  @gotequiv = private unnamed_addr constant i32* @bar
02112   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
02113   //                             i64 ptrtoint (i32* @foo to i64))
02114   //                        to i32)
02115   //
02116   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
02117   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
02118   // form:
02119   //
02120   //  foo = cstexpr, where
02121   //    cstexpr := <gotequiv> - "." + <cst>
02122   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
02123   //
02124   // After canonicalization by evaluateAsRelocatable `ME` turns into:
02125   //
02126   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
02127   //    gotpcrelcst := <offset from @foo base> + <cst>
02128   //
02129   MCValue MV;
02130   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
02131     return;
02132   const MCSymbolRefExpr *SymA = MV.getSymA();
02133   if (!SymA)
02134     return;
02135 
02136   // Check that GOT equivalent symbol is cached.
02137   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
02138   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
02139     return;
02140 
02141   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
02142   if (!BaseGV)
02143     return;
02144 
02145   // Check for a valid base symbol
02146   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
02147   const MCSymbolRefExpr *SymB = MV.getSymB();
02148 
02149   if (!SymB || BaseSym != &SymB->getSymbol())
02150     return;
02151 
02152   // Make sure to match:
02153   //
02154   //    gotpcrelcst := <offset from @foo base> + <cst>
02155   //
02156   // If gotpcrelcst is positive it means that we can safely fold the pc rel
02157   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
02158   // if the target knows how to encode it.
02159   //
02160   int64_t GOTPCRelCst = Offset + MV.getConstant();
02161   if (GOTPCRelCst < 0)
02162     return;
02163   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
02164     return;
02165 
02166   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
02167   //
02168   //  bar:
02169   //    .long 42
02170   //  gotequiv:
02171   //    .quad bar
02172   //  foo:
02173   //    .long gotequiv - "." + <cst>
02174   //
02175   // is replaced by the target specific equivalent to:
02176   //
02177   //  bar:
02178   //    .long 42
02179   //  foo:
02180   //    .long bar@GOTPCREL+<gotpcrelcst>
02181   //
02182   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
02183   const GlobalVariable *GV = Result.first;
02184   int NumUses = (int)Result.second;
02185   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
02186   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
02187   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
02188       FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
02189 
02190   // Update GOT equivalent usage information
02191   --NumUses;
02192   if (NumUses >= 0)
02193     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
02194 }
02195 
02196 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
02197                                    AsmPrinter &AP, const Constant *BaseCV,
02198                                    uint64_t Offset) {
02199   uint64_t Size = DL.getTypeAllocSize(CV->getType());
02200 
02201   // Globals with sub-elements such as combinations of arrays and structs
02202   // are handled recursively by emitGlobalConstantImpl. Keep track of the
02203   // constant symbol base and the current position with BaseCV and Offset.
02204   if (!BaseCV && CV->hasOneUse())
02205     BaseCV = dyn_cast<Constant>(CV->user_back());
02206 
02207   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
02208     return AP.OutStreamer->EmitZeros(Size);
02209 
02210   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
02211     switch (Size) {
02212     case 1:
02213     case 2:
02214     case 4:
02215     case 8:
02216       if (AP.isVerbose())
02217         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
02218                                                  CI->getZExtValue());
02219       AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
02220       return;
02221     default:
02222       emitGlobalConstantLargeInt(CI, AP);
02223       return;
02224     }
02225   }
02226 
02227   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
02228     return emitGlobalConstantFP(CFP, AP);
02229 
02230   if (isa<ConstantPointerNull>(CV)) {
02231     AP.OutStreamer->EmitIntValue(0, Size);
02232     return;
02233   }
02234 
02235   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
02236     return emitGlobalConstantDataSequential(DL, CDS, AP);
02237 
02238   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
02239     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
02240 
02241   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
02242     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
02243 
02244   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
02245     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
02246     // vectors).
02247     if (CE->getOpcode() == Instruction::BitCast)
02248       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
02249 
02250     if (Size > 8) {
02251       // If the constant expression's size is greater than 64-bits, then we have
02252       // to emit the value in chunks. Try to constant fold the value and emit it
02253       // that way.
02254       Constant *New = ConstantFoldConstantExpression(CE, DL);
02255       if (New && New != CE)
02256         return emitGlobalConstantImpl(DL, New, AP);
02257     }
02258   }
02259 
02260   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
02261     return emitGlobalConstantVector(DL, V, AP);
02262 
02263   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
02264   // thread the streamer with EmitValue.
02265   const MCExpr *ME = AP.lowerConstant(CV);
02266 
02267   // Since lowerConstant already folded and got rid of all IR pointer and
02268   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
02269   // directly.
02270   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
02271     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
02272 
02273   AP.OutStreamer->EmitValue(ME, Size);
02274 }
02275 
02276 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
02277 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
02278   uint64_t Size = DL.getTypeAllocSize(CV->getType());
02279   if (Size)
02280     emitGlobalConstantImpl(DL, CV, *this);
02281   else if (MAI->hasSubsectionsViaSymbols()) {
02282     // If the global has zero size, emit a single byte so that two labels don't
02283     // look like they are at the same location.
02284     OutStreamer->EmitIntValue(0, 1);
02285   }
02286 }
02287 
02288 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
02289   // Target doesn't support this yet!
02290   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
02291 }
02292 
02293 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
02294   if (Offset > 0)
02295     OS << '+' << Offset;
02296   else if (Offset < 0)
02297     OS << Offset;
02298 }
02299 
02300 //===----------------------------------------------------------------------===//
02301 // Symbol Lowering Routines.
02302 //===----------------------------------------------------------------------===//
02303 
02304 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
02305   return OutContext.createTempSymbol(Name, true);
02306 }
02307 
02308 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
02309   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
02310 }
02311 
02312 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
02313   return MMI->getAddrLabelSymbol(BB);
02314 }
02315 
02316 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
02317 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
02318   const DataLayout &DL = getDataLayout();
02319   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
02320                                       "CPI" + Twine(getFunctionNumber()) + "_" +
02321                                       Twine(CPID));
02322 }
02323 
02324 /// GetJTISymbol - Return the symbol for the specified jump table entry.
02325 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
02326   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
02327 }
02328 
02329 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
02330 /// FIXME: privatize to AsmPrinter.
02331 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
02332   const DataLayout &DL = getDataLayout();
02333   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
02334                                       Twine(getFunctionNumber()) + "_" +
02335                                       Twine(UID) + "_set_" + Twine(MBBID));
02336 }
02337 
02338 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
02339                                                    StringRef Suffix) const {
02340   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
02341                                                            TM);
02342 }
02343 
02344 /// Return the MCSymbol for the specified ExternalSymbol.
02345 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
02346   SmallString<60> NameStr;
02347   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
02348   return OutContext.getOrCreateSymbol(NameStr);
02349 }
02350 
02351 
02352 
02353 /// PrintParentLoopComment - Print comments about parent loops of this one.
02354 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02355                                    unsigned FunctionNumber) {
02356   if (!Loop) return;
02357   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
02358   OS.indent(Loop->getLoopDepth()*2)
02359     << "Parent Loop BB" << FunctionNumber << "_"
02360     << Loop->getHeader()->getNumber()
02361     << " Depth=" << Loop->getLoopDepth() << '\n';
02362 }
02363 
02364 
02365 /// PrintChildLoopComment - Print comments about child loops within
02366 /// the loop for this basic block, with nesting.
02367 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02368                                   unsigned FunctionNumber) {
02369   // Add child loop information
02370   for (const MachineLoop *CL : *Loop) {
02371     OS.indent(CL->getLoopDepth()*2)
02372       << "Child Loop BB" << FunctionNumber << "_"
02373       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
02374       << '\n';
02375     PrintChildLoopComment(OS, CL, FunctionNumber);
02376   }
02377 }
02378 
02379 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
02380 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
02381                                        const MachineLoopInfo *LI,
02382                                        const AsmPrinter &AP) {
02383   // Add loop depth information
02384   const MachineLoop *Loop = LI->getLoopFor(&MBB);
02385   if (!Loop) return;
02386 
02387   MachineBasicBlock *Header = Loop->getHeader();
02388   assert(Header && "No header for loop");
02389 
02390   // If this block is not a loop header, just print out what is the loop header
02391   // and return.
02392   if (Header != &MBB) {
02393     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
02394                                Twine(AP.getFunctionNumber())+"_" +
02395                                Twine(Loop->getHeader()->getNumber())+
02396                                " Depth="+Twine(Loop->getLoopDepth()));
02397     return;
02398   }
02399 
02400   // Otherwise, it is a loop header.  Print out information about child and
02401   // parent loops.
02402   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
02403 
02404   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
02405 
02406   OS << "=>";
02407   OS.indent(Loop->getLoopDepth()*2-2);
02408 
02409   OS << "This ";
02410   if (Loop->empty())
02411     OS << "Inner ";
02412   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
02413 
02414   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
02415 }
02416 
02417 
02418 /// EmitBasicBlockStart - This method prints the label for the specified
02419 /// MachineBasicBlock, an alignment (if present) and a comment describing
02420 /// it if appropriate.
02421 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
02422   // End the previous funclet and start a new one.
02423   if (MBB.isEHFuncletEntry()) {
02424     for (const HandlerInfo &HI : Handlers) {
02425       HI.Handler->endFunclet();
02426       HI.Handler->beginFunclet(MBB);
02427     }
02428   }
02429 
02430   // Emit an alignment directive for this block, if needed.
02431   if (unsigned Align = MBB.getAlignment())
02432     EmitAlignment(Align);
02433 
02434   // If the block has its address taken, emit any labels that were used to
02435   // reference the block.  It is possible that there is more than one label
02436   // here, because multiple LLVM BB's may have been RAUW'd to this block after
02437   // the references were generated.
02438   if (MBB.hasAddressTaken()) {
02439     const BasicBlock *BB = MBB.getBasicBlock();
02440     if (isVerbose())
02441       OutStreamer->AddComment("Block address taken");
02442 
02443     // MBBs can have their address taken as part of CodeGen without having
02444     // their corresponding BB's address taken in IR
02445     if (BB->hasAddressTaken())
02446       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
02447         OutStreamer->EmitLabel(Sym);
02448   }
02449 
02450   // Print some verbose block comments.
02451   if (isVerbose()) {
02452     if (const BasicBlock *BB = MBB.getBasicBlock()) {
02453       if (BB->hasName()) {
02454         BB->printAsOperand(OutStreamer->GetCommentOS(),
02455                            /*PrintType=*/false, BB->getModule());
02456         OutStreamer->GetCommentOS() << '\n';
02457       }
02458     }
02459     emitBasicBlockLoopComments(MBB, LI, *this);
02460   }
02461 
02462   // Print the main label for the block.
02463   if (MBB.pred_empty() ||
02464       (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) {
02465     if (isVerbose()) {
02466       // NOTE: Want this comment at start of line, don't emit with AddComment.
02467       OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
02468     }
02469   } else {
02470     OutStreamer->EmitLabel(MBB.getSymbol());
02471   }
02472 }
02473 
02474 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
02475                                 bool IsDefinition) const {
02476   MCSymbolAttr Attr = MCSA_Invalid;
02477 
02478   switch (Visibility) {
02479   default: break;
02480   case GlobalValue::HiddenVisibility:
02481     if (IsDefinition)
02482       Attr = MAI->getHiddenVisibilityAttr();
02483     else
02484       Attr = MAI->getHiddenDeclarationVisibilityAttr();
02485     break;
02486   case GlobalValue::ProtectedVisibility:
02487     Attr = MAI->getProtectedVisibilityAttr();
02488     break;
02489   }
02490 
02491   if (Attr != MCSA_Invalid)
02492     OutStreamer->EmitSymbolAttribute(Sym, Attr);
02493 }
02494 
02495 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
02496 /// exactly one predecessor and the control transfer mechanism between
02497 /// the predecessor and this block is a fall-through.
02498 bool AsmPrinter::
02499 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
02500   // If this is a landing pad, it isn't a fall through.  If it has no preds,
02501   // then nothing falls through to it.
02502   if (MBB->isEHPad() || MBB->pred_empty())
02503     return false;
02504 
02505   // If there isn't exactly one predecessor, it can't be a fall through.
02506   if (MBB->pred_size() > 1)
02507     return false;
02508 
02509   // The predecessor has to be immediately before this block.
02510   MachineBasicBlock *Pred = *MBB->pred_begin();
02511   if (!Pred->isLayoutSuccessor(MBB))
02512     return false;
02513 
02514   // If the block is completely empty, then it definitely does fall through.
02515   if (Pred->empty())
02516     return true;
02517 
02518   // Check the terminators in the previous blocks
02519   for (const auto &MI : Pred->terminators()) {
02520     // If it is not a simple branch, we are in a table somewhere.
02521     if (!MI.isBranch() || MI.isIndirectBranch())
02522       return false;
02523 
02524     // If we are the operands of one of the branches, this is not a fall
02525     // through. Note that targets with delay slots will usually bundle
02526     // terminators with the delay slot instruction.
02527     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
02528       if (OP->isJTI())
02529         return false;
02530       if (OP->isMBB() && OP->getMBB() == MBB)
02531         return false;
02532     }
02533   }
02534 
02535   return true;
02536 }
02537 
02538 
02539 
02540 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
02541   if (!S.usesMetadata())
02542     return nullptr;
02543 
02544   assert(!S.useStatepoints() && "statepoints do not currently support custom"
02545          " stackmap formats, please see the documentation for a description of"
02546          " the default format.  If you really need a custom serialized format,"
02547          " please file a bug");
02548 
02549   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
02550   gcp_map_type::iterator GCPI = GCMap.find(&S);
02551   if (GCPI != GCMap.end())
02552     return GCPI->second.get();
02553 
02554   const char *Name = S.getName().c_str();
02555 
02556   for (GCMetadataPrinterRegistry::iterator
02557          I = GCMetadataPrinterRegistry::begin(),
02558          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
02559     if (strcmp(Name, I->getName()) == 0) {
02560       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
02561       GMP->S = &S;
02562       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
02563       return IterBool.first->second.get();
02564     }
02565 
02566   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
02567 }
02568 
02569 /// Pin vtable to this file.
02570 AsmPrinterHandler::~AsmPrinterHandler() {}
02571 
02572 void AsmPrinterHandler::markFunctionEnd() {}