LLVM API Documentation

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