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