LLVM API Documentation

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