LLVM API Documentation

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