LLVM API Documentation

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