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