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