LLVM API Documentation

DwarfDebug.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 contains support for writing dwarf debug info into asm files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ByteStreamer.h"
00015 #include "DwarfDebug.h"
00016 #include "DIE.h"
00017 #include "DIEHash.h"
00018 #include "DwarfUnit.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/ADT/Triple.h"
00023 #include "llvm/CodeGen/MachineFunction.h"
00024 #include "llvm/CodeGen/MachineModuleInfo.h"
00025 #include "llvm/IR/Constants.h"
00026 #include "llvm/IR/DIBuilder.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/DebugInfo.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/Module.h"
00031 #include "llvm/IR/ValueHandle.h"
00032 #include "llvm/MC/MCAsmInfo.h"
00033 #include "llvm/MC/MCSection.h"
00034 #include "llvm/MC/MCStreamer.h"
00035 #include "llvm/MC/MCSymbol.h"
00036 #include "llvm/Support/CommandLine.h"
00037 #include "llvm/Support/Debug.h"
00038 #include "llvm/Support/Dwarf.h"
00039 #include "llvm/Support/Endian.h"
00040 #include "llvm/Support/ErrorHandling.h"
00041 #include "llvm/Support/FormattedStream.h"
00042 #include "llvm/Support/LEB128.h"
00043 #include "llvm/Support/MD5.h"
00044 #include "llvm/Support/Path.h"
00045 #include "llvm/Support/Timer.h"
00046 #include "llvm/Target/TargetFrameLowering.h"
00047 #include "llvm/Target/TargetLoweringObjectFile.h"
00048 #include "llvm/Target/TargetMachine.h"
00049 #include "llvm/Target/TargetOptions.h"
00050 #include "llvm/Target/TargetRegisterInfo.h"
00051 #include "llvm/Target/TargetSubtargetInfo.h"
00052 using namespace llvm;
00053 
00054 #define DEBUG_TYPE "dwarfdebug"
00055 
00056 static cl::opt<bool>
00057 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
00058                          cl::desc("Disable debug info printing"));
00059 
00060 static cl::opt<bool> UnknownLocations(
00061     "use-unknown-locations", cl::Hidden,
00062     cl::desc("Make an absence of debug location information explicit."),
00063     cl::init(false));
00064 
00065 static cl::opt<bool>
00066 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
00067                        cl::desc("Generate GNU-style pubnames and pubtypes"),
00068                        cl::init(false));
00069 
00070 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
00071                                            cl::Hidden,
00072                                            cl::desc("Generate dwarf aranges"),
00073                                            cl::init(false));
00074 
00075 namespace {
00076 enum DefaultOnOff { Default, Enable, Disable };
00077 }
00078 
00079 static cl::opt<DefaultOnOff>
00080 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
00081                  cl::desc("Output prototype dwarf accelerator tables."),
00082                  cl::values(clEnumVal(Default, "Default for platform"),
00083                             clEnumVal(Enable, "Enabled"),
00084                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
00085                  cl::init(Default));
00086 
00087 static cl::opt<DefaultOnOff>
00088 SplitDwarf("split-dwarf", cl::Hidden,
00089            cl::desc("Output DWARF5 split debug info."),
00090            cl::values(clEnumVal(Default, "Default for platform"),
00091                       clEnumVal(Enable, "Enabled"),
00092                       clEnumVal(Disable, "Disabled"), clEnumValEnd),
00093            cl::init(Default));
00094 
00095 static cl::opt<DefaultOnOff>
00096 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
00097                  cl::desc("Generate DWARF pubnames and pubtypes sections"),
00098                  cl::values(clEnumVal(Default, "Default for platform"),
00099                             clEnumVal(Enable, "Enabled"),
00100                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
00101                  cl::init(Default));
00102 
00103 static const char *const DWARFGroupName = "DWARF Emission";
00104 static const char *const DbgTimerName = "DWARF Debug Writer";
00105 
00106 //===----------------------------------------------------------------------===//
00107 
00108 /// resolve - Look in the DwarfDebug map for the MDNode that
00109 /// corresponds to the reference.
00110 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
00111   return DD->resolve(Ref);
00112 }
00113 
00114 bool DbgVariable::isBlockByrefVariable() const {
00115   assert(Var.isVariable() && "Invalid complex DbgVariable!");
00116   return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
00117 }
00118 
00119 DIType DbgVariable::getType() const {
00120   DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
00121   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
00122   // addresses instead.
00123   if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
00124     /* Byref variables, in Blocks, are declared by the programmer as
00125        "SomeType VarName;", but the compiler creates a
00126        __Block_byref_x_VarName struct, and gives the variable VarName
00127        either the struct, or a pointer to the struct, as its type.  This
00128        is necessary for various behind-the-scenes things the compiler
00129        needs to do with by-reference variables in blocks.
00130 
00131        However, as far as the original *programmer* is concerned, the
00132        variable should still have type 'SomeType', as originally declared.
00133 
00134        The following function dives into the __Block_byref_x_VarName
00135        struct to find the original type of the variable.  This will be
00136        passed back to the code generating the type for the Debug
00137        Information Entry for the variable 'VarName'.  'VarName' will then
00138        have the original type 'SomeType' in its debug information.
00139 
00140        The original type 'SomeType' will be the type of the field named
00141        'VarName' inside the __Block_byref_x_VarName struct.
00142 
00143        NOTE: In order for this to not completely fail on the debugger
00144        side, the Debug Information Entry for the variable VarName needs to
00145        have a DW_AT_location that tells the debugger how to unwind through
00146        the pointers and __Block_byref_x_VarName struct to find the actual
00147        value of the variable.  The function addBlockByrefType does this.  */
00148     DIType subType = Ty;
00149     uint16_t tag = Ty.getTag();
00150 
00151     if (tag == dwarf::DW_TAG_pointer_type)
00152       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
00153 
00154     DIArray Elements = DICompositeType(subType).getElements();
00155     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
00156       DIDerivedType DT(Elements.getElement(i));
00157       if (getName() == DT.getName())
00158         return (resolve(DT.getTypeDerivedFrom()));
00159     }
00160   }
00161   return Ty;
00162 }
00163 
00164 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
00165     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
00166     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
00167     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
00168 
00169 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
00170     : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
00171       GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
00172       UsedNonDefaultText(false),
00173       SkeletonHolder(A, "skel_string", DIEValueAllocator),
00174       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
00175                                        dwarf::DW_FORM_data4)),
00176       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
00177                                       dwarf::DW_FORM_data4)),
00178       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
00179                                            dwarf::DW_FORM_data4)),
00180       AccelTypes(TypeAtoms) {
00181 
00182   DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
00183   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
00184   DwarfLineSectionSym = nullptr;
00185   DwarfAddrSectionSym = nullptr;
00186   DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
00187   FunctionBeginSym = FunctionEndSym = nullptr;
00188   CurFn = nullptr;
00189   CurMI = nullptr;
00190 
00191   // Turn on accelerator tables for Darwin by default, pubnames by
00192   // default for non-Darwin, and handle split dwarf.
00193   bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
00194 
00195   if (DwarfAccelTables == Default)
00196     HasDwarfAccelTables = IsDarwin;
00197   else
00198     HasDwarfAccelTables = DwarfAccelTables == Enable;
00199 
00200   if (SplitDwarf == Default)
00201     HasSplitDwarf = false;
00202   else
00203     HasSplitDwarf = SplitDwarf == Enable;
00204 
00205   if (DwarfPubSections == Default)
00206     HasDwarfPubSections = !IsDarwin;
00207   else
00208     HasDwarfPubSections = DwarfPubSections == Enable;
00209 
00210   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
00211   DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
00212                                     : MMI->getModule()->getDwarfVersion();
00213 
00214   Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
00215 
00216   {
00217     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
00218     beginModule();
00219   }
00220 }
00221 
00222 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
00223 DwarfDebug::~DwarfDebug() { }
00224 
00225 // Switch to the specified MCSection and emit an assembler
00226 // temporary label to it if SymbolStem is specified.
00227 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
00228                                 const char *SymbolStem = nullptr) {
00229   Asm->OutStreamer.SwitchSection(Section);
00230   if (!SymbolStem)
00231     return nullptr;
00232 
00233   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
00234   Asm->OutStreamer.EmitLabel(TmpSym);
00235   return TmpSym;
00236 }
00237 
00238 static bool isObjCClass(StringRef Name) {
00239   return Name.startswith("+") || Name.startswith("-");
00240 }
00241 
00242 static bool hasObjCCategory(StringRef Name) {
00243   if (!isObjCClass(Name))
00244     return false;
00245 
00246   return Name.find(") ") != StringRef::npos;
00247 }
00248 
00249 static void getObjCClassCategory(StringRef In, StringRef &Class,
00250                                  StringRef &Category) {
00251   if (!hasObjCCategory(In)) {
00252     Class = In.slice(In.find('[') + 1, In.find(' '));
00253     Category = "";
00254     return;
00255   }
00256 
00257   Class = In.slice(In.find('[') + 1, In.find('('));
00258   Category = In.slice(In.find('[') + 1, In.find(' '));
00259   return;
00260 }
00261 
00262 static StringRef getObjCMethodName(StringRef In) {
00263   return In.slice(In.find(' ') + 1, In.find(']'));
00264 }
00265 
00266 // Helper for sorting sections into a stable output order.
00267 static bool SectionSort(const MCSection *A, const MCSection *B) {
00268   std::string LA = (A ? A->getLabelBeginName() : "");
00269   std::string LB = (B ? B->getLabelBeginName() : "");
00270   return LA < LB;
00271 }
00272 
00273 // Add the various names to the Dwarf accelerator table names.
00274 // TODO: Determine whether or not we should add names for programs
00275 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
00276 // is only slightly different than the lookup of non-standard ObjC names.
00277 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
00278   if (!SP.isDefinition())
00279     return;
00280   addAccelName(SP.getName(), Die);
00281 
00282   // If the linkage name is different than the name, go ahead and output
00283   // that as well into the name table.
00284   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
00285     addAccelName(SP.getLinkageName(), Die);
00286 
00287   // If this is an Objective-C selector name add it to the ObjC accelerator
00288   // too.
00289   if (isObjCClass(SP.getName())) {
00290     StringRef Class, Category;
00291     getObjCClassCategory(SP.getName(), Class, Category);
00292     addAccelObjC(Class, Die);
00293     if (Category != "")
00294       addAccelObjC(Category, Die);
00295     // Also add the base method name to the name table.
00296     addAccelName(getObjCMethodName(SP.getName()), Die);
00297   }
00298 }
00299 
00300 /// isSubprogramContext - Return true if Context is either a subprogram
00301 /// or another context nested inside a subprogram.
00302 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
00303   if (!Context)
00304     return false;
00305   DIDescriptor D(Context);
00306   if (D.isSubprogram())
00307     return true;
00308   if (D.isType())
00309     return isSubprogramContext(resolve(DIType(Context).getContext()));
00310   return false;
00311 }
00312 
00313 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
00314 // and DW_AT_high_pc attributes. If there are global variables in this
00315 // scope then create and insert DIEs for these variables.
00316 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
00317                                           DISubprogram SP) {
00318   DIE *SPDie = SPCU.getOrCreateSubprogramDIE(SP);
00319 
00320   attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
00321 
00322   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
00323   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
00324   SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
00325 
00326   // Add name to the name table, we do this here because we're guaranteed
00327   // to have concrete versions of our DW_TAG_subprogram nodes.
00328   addSubprogramNames(SP, *SPDie);
00329 
00330   return *SPDie;
00331 }
00332 
00333 /// Check whether we should create a DIE for the given Scope, return true
00334 /// if we don't create a DIE (the corresponding DIE is null).
00335 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
00336   if (Scope->isAbstractScope())
00337     return false;
00338 
00339   // We don't create a DIE if there is no Range.
00340   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
00341   if (Ranges.empty())
00342     return true;
00343 
00344   if (Ranges.size() > 1)
00345     return false;
00346 
00347   // We don't create a DIE if we have a single Range and the end label
00348   // is null.
00349   return !getLabelAfterInsn(Ranges.front().second);
00350 }
00351 
00352 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
00353                             dwarf::Attribute A, const MCSymbol *L,
00354                             const MCSymbol *Sec) {
00355   if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
00356     U.addSectionLabel(D, A, L);
00357   else
00358     U.addSectionDelta(D, A, L, Sec);
00359 }
00360 
00361 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
00362                                    const SmallVectorImpl<InsnRange> &Range) {
00363   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
00364   // emitting it appropriately.
00365   MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
00366 
00367   // Under fission, ranges are specified by constant offsets relative to the
00368   // CU's DW_AT_GNU_ranges_base.
00369   if (useSplitDwarf())
00370     TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
00371                           DwarfDebugRangeSectionSym);
00372   else
00373     addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
00374                     DwarfDebugRangeSectionSym);
00375 
00376   RangeSpanList List(RangeSym);
00377   for (const InsnRange &R : Range) {
00378     RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
00379     List.addRange(std::move(Span));
00380   }
00381 
00382   // Add the range list to the set of ranges to be emitted.
00383   TheCU.addRangeList(std::move(List));
00384 }
00385 
00386 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
00387                                     const SmallVectorImpl<InsnRange> &Ranges) {
00388   assert(!Ranges.empty());
00389   if (Ranges.size() == 1)
00390     attachLowHighPC(TheCU, Die, getLabelBeforeInsn(Ranges.front().first),
00391                     getLabelAfterInsn(Ranges.front().second));
00392   else
00393     addScopeRangeList(TheCU, Die, Ranges);
00394 }
00395 
00396 // Construct new DW_TAG_lexical_block for this scope and attach
00397 // DW_AT_low_pc/DW_AT_high_pc labels.
00398 std::unique_ptr<DIE>
00399 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
00400                                      LexicalScope *Scope) {
00401   if (isLexicalScopeDIENull(Scope))
00402     return nullptr;
00403 
00404   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
00405   if (Scope->isAbstractScope())
00406     return ScopeDIE;
00407 
00408   attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
00409 
00410   return ScopeDIE;
00411 }
00412 
00413 // This scope represents inlined body of a function. Construct DIE to
00414 // represent this concrete inlined copy of the function.
00415 std::unique_ptr<DIE>
00416 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
00417                                      LexicalScope *Scope) {
00418   assert(Scope->getScopeNode());
00419   DIScope DS(Scope->getScopeNode());
00420   DISubprogram InlinedSP = getDISubprogram(DS);
00421   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
00422   // was inlined from another compile unit.
00423   DIE *OriginDIE = AbstractSPDies[InlinedSP];
00424   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
00425 
00426   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
00427   TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
00428 
00429   attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
00430 
00431   InlinedSubprogramDIEs.insert(OriginDIE);
00432 
00433   // Add the call site information to the DIE.
00434   DILocation DL(Scope->getInlinedAt());
00435   TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
00436                 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
00437   TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
00438 
00439   // Add name to the name table, we do this here because we're guaranteed
00440   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
00441   addSubprogramNames(InlinedSP, *ScopeDIE);
00442 
00443   return ScopeDIE;
00444 }
00445 
00446 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
00447                                                  DbgVariable &DV,
00448                                                  const LexicalScope &Scope,
00449                                                  DIE *&ObjectPointer) {
00450   auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
00451   if (DV.isObjectPointer())
00452     ObjectPointer = Var.get();
00453   return Var;
00454 }
00455 
00456 DIE *DwarfDebug::createScopeChildrenDIE(
00457     DwarfCompileUnit &TheCU, LexicalScope *Scope,
00458     SmallVectorImpl<std::unique_ptr<DIE>> &Children,
00459     unsigned *ChildScopeCount) {
00460   DIE *ObjectPointer = nullptr;
00461 
00462   for (DbgVariable *DV : ScopeVariables.lookup(Scope))
00463     Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
00464 
00465   unsigned ChildCountWithoutScopes = Children.size();
00466 
00467   for (LexicalScope *LS : Scope->getChildren())
00468     constructScopeDIE(TheCU, LS, Children);
00469 
00470   if (ChildScopeCount)
00471     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
00472 
00473   return ObjectPointer;
00474 }
00475 
00476 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
00477                                            LexicalScope *Scope, DIE &ScopeDIE) {
00478   // We create children when the scope DIE is not null.
00479   SmallVector<std::unique_ptr<DIE>, 8> Children;
00480   DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
00481 
00482   // Add children
00483   for (auto &I : Children)
00484     ScopeDIE.addChild(std::move(I));
00485 
00486   return ObjectPointer;
00487 }
00488 
00489 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
00490                                                      LexicalScope *Scope) {
00491   assert(Scope && Scope->getScopeNode());
00492   assert(Scope->isAbstractScope());
00493   assert(!Scope->getInlinedAt());
00494 
00495   DISubprogram SP(Scope->getScopeNode());
00496 
00497   ProcessedSPNodes.insert(SP);
00498 
00499   DIE *&AbsDef = AbstractSPDies[SP];
00500   if (AbsDef)
00501     return;
00502 
00503   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
00504   // was inlined from another compile unit.
00505   DwarfCompileUnit &SPCU = *SPMap[SP];
00506   DIE *ContextDIE;
00507 
00508   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
00509   // the important distinction that the DIDescriptor is not associated with the
00510   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
00511   // any). It could be refactored to some common utility function.
00512   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
00513     ContextDIE = &SPCU.getUnitDie();
00514     SPCU.getOrCreateSubprogramDIE(SPDecl);
00515   } else
00516     ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
00517 
00518   // Passing null as the associated DIDescriptor because the abstract definition
00519   // shouldn't be found by lookup.
00520   AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
00521                                  DIDescriptor());
00522   SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
00523 
00524   SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
00525   if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
00526     SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
00527 }
00528 
00529 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
00530                                              LexicalScope *Scope) {
00531   assert(Scope && Scope->getScopeNode());
00532   assert(!Scope->getInlinedAt());
00533   assert(!Scope->isAbstractScope());
00534   DISubprogram Sub(Scope->getScopeNode());
00535 
00536   assert(Sub.isSubprogram());
00537 
00538   ProcessedSPNodes.insert(Sub);
00539 
00540   DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
00541 
00542   // Collect arguments for current function.
00543   assert(LScopes.isCurrentFunctionScope(Scope));
00544   DIE *ObjectPointer = nullptr;
00545   for (DbgVariable *ArgDV : CurrentFnArguments)
00546     if (ArgDV)
00547       ScopeDIE.addChild(
00548           constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
00549 
00550   // If this is a variadic function, add an unspecified parameter.
00551   DITypeArray FnArgs = Sub.getType().getTypeArray();
00552   // If we have a single element of null, it is a function that returns void.
00553   // If we have more than one elements and the last one is null, it is a
00554   // variadic function.
00555   if (FnArgs.getNumElements() > 1 &&
00556       !FnArgs.getElement(FnArgs.getNumElements() - 1))
00557     ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
00558 
00559   // Collect lexical scope children first.
00560   // ObjectPointer might be a local (non-argument) local variable if it's a
00561   // block's synthetic this pointer.
00562   if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
00563     assert(!ObjectPointer && "multiple object pointers can't be described");
00564     ObjectPointer = BlockObjPtr;
00565   }
00566 
00567   if (ObjectPointer)
00568     TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
00569 
00570   return ScopeDIE;
00571 }
00572 
00573 // Construct a DIE for this scope.
00574 void DwarfDebug::constructScopeDIE(
00575     DwarfCompileUnit &TheCU, LexicalScope *Scope,
00576     SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
00577   if (!Scope || !Scope->getScopeNode())
00578     return;
00579 
00580   DIScope DS(Scope->getScopeNode());
00581 
00582   assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
00583          "Only handle inlined subprograms here, use "
00584          "constructSubprogramScopeDIE for non-inlined "
00585          "subprograms");
00586 
00587   SmallVector<std::unique_ptr<DIE>, 8> Children;
00588 
00589   // We try to create the scope DIE first, then the children DIEs. This will
00590   // avoid creating un-used children then removing them later when we find out
00591   // the scope DIE is null.
00592   std::unique_ptr<DIE> ScopeDIE;
00593   if (Scope->getParent() && DS.isSubprogram()) {
00594     ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
00595     if (!ScopeDIE)
00596       return;
00597     // We create children when the scope DIE is not null.
00598     createScopeChildrenDIE(TheCU, Scope, Children);
00599   } else {
00600     // Early exit when we know the scope DIE is going to be null.
00601     if (isLexicalScopeDIENull(Scope))
00602       return;
00603 
00604     unsigned ChildScopeCount;
00605 
00606     // We create children here when we know the scope DIE is not going to be
00607     // null and the children will be added to the scope DIE.
00608     createScopeChildrenDIE(TheCU, Scope, Children, &ChildScopeCount);
00609 
00610     // There is no need to emit empty lexical block DIE.
00611     std::pair<ImportedEntityMap::const_iterator,
00612               ImportedEntityMap::const_iterator> Range =
00613         std::equal_range(ScopesWithImportedEntities.begin(),
00614                          ScopesWithImportedEntities.end(),
00615                          std::pair<const MDNode *, const MDNode *>(DS, nullptr),
00616                          less_first());
00617     for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
00618          ++i)
00619       Children.push_back(
00620           constructImportedEntityDIE(TheCU, DIImportedEntity(i->second)));
00621     // If there are only other scopes as children, put them directly in the
00622     // parent instead, as this scope would serve no purpose.
00623     if (Children.size() == ChildScopeCount) {
00624       FinalChildren.insert(FinalChildren.end(),
00625                            std::make_move_iterator(Children.begin()),
00626                            std::make_move_iterator(Children.end()));
00627       return;
00628     }
00629     ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
00630     assert(ScopeDIE && "Scope DIE should not be null.");
00631   }
00632 
00633   // Add children
00634   for (auto &I : Children)
00635     ScopeDIE->addChild(std::move(I));
00636 
00637   FinalChildren.push_back(std::move(ScopeDIE));
00638 }
00639 
00640 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
00641   if (!GenerateGnuPubSections)
00642     return;
00643 
00644   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
00645 }
00646 
00647 // Create new DwarfCompileUnit for the given metadata node with tag
00648 // DW_TAG_compile_unit.
00649 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
00650   StringRef FN = DIUnit.getFilename();
00651   CompilationDir = DIUnit.getDirectory();
00652 
00653   auto OwnedUnit = make_unique<DwarfCompileUnit>(
00654       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
00655   DwarfCompileUnit &NewCU = *OwnedUnit;
00656   DIE &Die = NewCU.getUnitDie();
00657   InfoHolder.addUnit(std::move(OwnedUnit));
00658 
00659   // LTO with assembly output shares a single line table amongst multiple CUs.
00660   // To avoid the compilation directory being ambiguous, let the line table
00661   // explicitly describe the directory of all files, never relying on the
00662   // compilation directory.
00663   if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
00664     Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
00665         NewCU.getUniqueID(), CompilationDir);
00666 
00667   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
00668   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
00669                 DIUnit.getLanguage());
00670   NewCU.addString(Die, dwarf::DW_AT_name, FN);
00671 
00672   if (!useSplitDwarf()) {
00673     NewCU.initStmtList(DwarfLineSectionSym);
00674 
00675     // If we're using split dwarf the compilation dir is going to be in the
00676     // skeleton CU and so we don't need to duplicate it here.
00677     if (!CompilationDir.empty())
00678       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
00679 
00680     addGnuPubAttributes(NewCU, Die);
00681   }
00682 
00683   if (DIUnit.isOptimized())
00684     NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
00685 
00686   StringRef Flags = DIUnit.getFlags();
00687   if (!Flags.empty())
00688     NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
00689 
00690   if (unsigned RVer = DIUnit.getRunTimeVersion())
00691     NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
00692                   dwarf::DW_FORM_data1, RVer);
00693 
00694   if (!FirstCU)
00695     FirstCU = &NewCU;
00696 
00697   if (useSplitDwarf()) {
00698     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
00699                       DwarfInfoDWOSectionSym);
00700     NewCU.setSkeleton(constructSkeletonCU(NewCU));
00701   } else
00702     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
00703                       DwarfInfoSectionSym);
00704 
00705   CUMap.insert(std::make_pair(DIUnit, &NewCU));
00706   CUDieMap.insert(std::make_pair(&Die, &NewCU));
00707   return NewCU;
00708 }
00709 
00710 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
00711                                                   const MDNode *N) {
00712   DIImportedEntity Module(N);
00713   assert(Module.Verify());
00714   if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
00715     D->addChild(constructImportedEntityDIE(TheCU, Module));
00716 }
00717 
00718 std::unique_ptr<DIE>
00719 DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
00720                                        const DIImportedEntity &Module) {
00721   assert(Module.Verify() &&
00722          "Use one of the MDNode * overloads to handle invalid metadata");
00723   std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
00724   TheCU.insertDIE(Module, IMDie.get());
00725   DIE *EntityDie;
00726   DIDescriptor Entity = resolve(Module.getEntity());
00727   if (Entity.isNameSpace())
00728     EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
00729   else if (Entity.isSubprogram())
00730     EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
00731   else if (Entity.isType())
00732     EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
00733   else
00734     EntityDie = TheCU.getDIE(Entity);
00735   assert(EntityDie);
00736   TheCU.addSourceLine(*IMDie, Module.getLineNumber(),
00737                       Module.getContext().getFilename(),
00738                       Module.getContext().getDirectory());
00739   TheCU.addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
00740   StringRef Name = Module.getName();
00741   if (!Name.empty())
00742     TheCU.addString(*IMDie, dwarf::DW_AT_name, Name);
00743 
00744   return IMDie;
00745 }
00746 
00747 // Emit all Dwarf sections that should come prior to the content. Create
00748 // global DIEs and emit initial debug info sections. This is invoked by
00749 // the target AsmPrinter.
00750 void DwarfDebug::beginModule() {
00751   if (DisableDebugInfoPrinting)
00752     return;
00753 
00754   const Module *M = MMI->getModule();
00755 
00756   FunctionDIs = makeSubprogramMap(*M);
00757 
00758   // If module has named metadata anchors then use them, otherwise scan the
00759   // module using debug info finder to collect debug info.
00760   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
00761   if (!CU_Nodes)
00762     return;
00763   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
00764 
00765   // Emit initial sections so we can reference labels later.
00766   emitSectionLabels();
00767 
00768   SingleCU = CU_Nodes->getNumOperands() == 1;
00769 
00770   for (MDNode *N : CU_Nodes->operands()) {
00771     DICompileUnit CUNode(N);
00772     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
00773     DIArray ImportedEntities = CUNode.getImportedEntities();
00774     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
00775       ScopesWithImportedEntities.push_back(std::make_pair(
00776           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
00777           ImportedEntities.getElement(i)));
00778     std::sort(ScopesWithImportedEntities.begin(),
00779               ScopesWithImportedEntities.end(), less_first());
00780     DIArray GVs = CUNode.getGlobalVariables();
00781     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
00782       CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
00783     DIArray SPs = CUNode.getSubprograms();
00784     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
00785       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
00786     DIArray EnumTypes = CUNode.getEnumTypes();
00787     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
00788       DIType Ty(EnumTypes.getElement(i));
00789       // The enum types array by design contains pointers to
00790       // MDNodes rather than DIRefs. Unique them here.
00791       DIType UniqueTy(resolve(Ty.getRef()));
00792       CU.getOrCreateTypeDIE(UniqueTy);
00793     }
00794     DIArray RetainedTypes = CUNode.getRetainedTypes();
00795     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
00796       DIType Ty(RetainedTypes.getElement(i));
00797       // The retained types array by design contains pointers to
00798       // MDNodes rather than DIRefs. Unique them here.
00799       DIType UniqueTy(resolve(Ty.getRef()));
00800       CU.getOrCreateTypeDIE(UniqueTy);
00801     }
00802     // Emit imported_modules last so that the relevant context is already
00803     // available.
00804     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
00805       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
00806   }
00807 
00808   // Tell MMI that we have debug info.
00809   MMI->setDebugInfoAvailability(true);
00810 
00811   // Prime section data.
00812   SectionMap[Asm->getObjFileLowering().getTextSection()];
00813 }
00814 
00815 void DwarfDebug::finishVariableDefinitions() {
00816   for (const auto &Var : ConcreteVariables) {
00817     DIE *VariableDie = Var->getDIE();
00818     assert(VariableDie);
00819     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
00820     // in the ConcreteVariables list, rather than looking it up again here.
00821     // DIE::getUnit isn't simple - it walks parent pointers, etc.
00822     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
00823     assert(Unit);
00824     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
00825     if (AbsVar && AbsVar->getDIE()) {
00826       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
00827                         *AbsVar->getDIE());
00828     } else
00829       Unit->applyVariableAttributes(*Var, *VariableDie);
00830   }
00831 }
00832 
00833 void DwarfDebug::finishSubprogramDefinitions() {
00834   const Module *M = MMI->getModule();
00835 
00836   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
00837   for (MDNode *N : CU_Nodes->operands()) {
00838     DICompileUnit TheCU(N);
00839     // Construct subprogram DIE and add variables DIEs.
00840     DwarfCompileUnit *SPCU =
00841         static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
00842     DIArray Subprograms = TheCU.getSubprograms();
00843     for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
00844       DISubprogram SP(Subprograms.getElement(i));
00845       // Perhaps the subprogram is in another CU (such as due to comdat
00846       // folding, etc), in which case ignore it here.
00847       if (SPMap[SP] != SPCU)
00848         continue;
00849       DIE *D = SPCU->getDIE(SP);
00850       if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
00851         if (D)
00852           // If this subprogram has an abstract definition, reference that
00853           SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
00854       } else {
00855         if (!D)
00856           // Lazily construct the subprogram if we didn't see either concrete or
00857           // inlined versions during codegen.
00858           D = SPCU->getOrCreateSubprogramDIE(SP);
00859         // And attach the attributes
00860         SPCU->applySubprogramAttributesToDefinition(SP, *D);
00861       }
00862     }
00863   }
00864 }
00865 
00866 
00867 // Collect info for variables that were optimized out.
00868 void DwarfDebug::collectDeadVariables() {
00869   const Module *M = MMI->getModule();
00870 
00871   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
00872     for (MDNode *N : CU_Nodes->operands()) {
00873       DICompileUnit TheCU(N);
00874       // Construct subprogram DIE and add variables DIEs.
00875       DwarfCompileUnit *SPCU =
00876           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
00877       assert(SPCU && "Unable to find Compile Unit!");
00878       DIArray Subprograms = TheCU.getSubprograms();
00879       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
00880         DISubprogram SP(Subprograms.getElement(i));
00881         if (ProcessedSPNodes.count(SP) != 0)
00882           continue;
00883         assert(SP.isSubprogram() &&
00884                "CU's subprogram list contains a non-subprogram");
00885         assert(SP.isDefinition() &&
00886                "CU's subprogram list contains a subprogram declaration");
00887         DIArray Variables = SP.getVariables();
00888         if (Variables.getNumElements() == 0)
00889           continue;
00890 
00891         DIE *SPDIE = AbstractSPDies.lookup(SP);
00892         if (!SPDIE)
00893           SPDIE = SPCU->getDIE(SP);
00894         assert(SPDIE);
00895         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
00896           DIVariable DV(Variables.getElement(vi));
00897           assert(DV.isVariable());
00898           DbgVariable NewVar(DV, this);
00899           auto VariableDie = SPCU->constructVariableDIE(NewVar);
00900           SPCU->applyVariableAttributes(NewVar, *VariableDie);
00901           SPDIE->addChild(std::move(VariableDie));
00902         }
00903       }
00904     }
00905   }
00906 }
00907 
00908 void DwarfDebug::finalizeModuleInfo() {
00909   finishSubprogramDefinitions();
00910 
00911   finishVariableDefinitions();
00912 
00913   // Collect info for variables that were optimized out.
00914   collectDeadVariables();
00915 
00916   // Handle anything that needs to be done on a per-unit basis after
00917   // all other generation.
00918   for (const auto &TheU : getUnits()) {
00919     // Emit DW_AT_containing_type attribute to connect types with their
00920     // vtable holding type.
00921     TheU->constructContainingTypeDIEs();
00922 
00923     // Add CU specific attributes if we need to add any.
00924     if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
00925       // If we're splitting the dwarf out now that we've got the entire
00926       // CU then add the dwo id to it.
00927       DwarfCompileUnit *SkCU =
00928           static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
00929       if (useSplitDwarf()) {
00930         // Emit a unique identifier for this CU.
00931         uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
00932         TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
00933                       dwarf::DW_FORM_data8, ID);
00934         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
00935                       dwarf::DW_FORM_data8, ID);
00936 
00937         // We don't keep track of which addresses are used in which CU so this
00938         // is a bit pessimistic under LTO.
00939         if (!AddrPool.isEmpty())
00940           addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
00941                           dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
00942                           DwarfAddrSectionSym);
00943         if (!TheU->getRangeLists().empty())
00944           addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
00945                           dwarf::DW_AT_GNU_ranges_base,
00946                           DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
00947       }
00948 
00949       // If we have code split among multiple sections or non-contiguous
00950       // ranges of code then emit a DW_AT_ranges attribute on the unit that will
00951       // remain in the .o file, otherwise add a DW_AT_low_pc.
00952       // FIXME: We should use ranges allow reordering of code ala
00953       // .subsections_via_symbols in mach-o. This would mean turning on
00954       // ranges for all subprogram DIEs for mach-o.
00955       DwarfCompileUnit &U =
00956           SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
00957       unsigned NumRanges = TheU->getRanges().size();
00958       if (NumRanges) {
00959         if (NumRanges > 1) {
00960           addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
00961                           Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
00962                           DwarfDebugRangeSectionSym);
00963 
00964           // A DW_AT_low_pc attribute may also be specified in combination with
00965           // DW_AT_ranges to specify the default base address for use in
00966           // location lists (see Section 2.6.2) and range lists (see Section
00967           // 2.17.3).
00968           U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
00969                     0);
00970         } else {
00971           RangeSpan &Range = TheU->getRanges().back();
00972           attachLowHighPC(U, U.getUnitDie(), Range.getStart(), Range.getEnd());
00973         }
00974       }
00975     }
00976   }
00977 
00978   // Compute DIE offsets and sizes.
00979   InfoHolder.computeSizeAndOffsets();
00980   if (useSplitDwarf())
00981     SkeletonHolder.computeSizeAndOffsets();
00982 }
00983 
00984 void DwarfDebug::endSections() {
00985   // Filter labels by section.
00986   for (const SymbolCU &SCU : ArangeLabels) {
00987     if (SCU.Sym->isInSection()) {
00988       // Make a note of this symbol and it's section.
00989       const MCSection *Section = &SCU.Sym->getSection();
00990       if (!Section->getKind().isMetadata())
00991         SectionMap[Section].push_back(SCU);
00992     } else {
00993       // Some symbols (e.g. common/bss on mach-o) can have no section but still
00994       // appear in the output. This sucks as we rely on sections to build
00995       // arange spans. We can do it without, but it's icky.
00996       SectionMap[nullptr].push_back(SCU);
00997     }
00998   }
00999 
01000   // Build a list of sections used.
01001   std::vector<const MCSection *> Sections;
01002   for (const auto &it : SectionMap) {
01003     const MCSection *Section = it.first;
01004     Sections.push_back(Section);
01005   }
01006 
01007   // Sort the sections into order.
01008   // This is only done to ensure consistent output order across different runs.
01009   std::sort(Sections.begin(), Sections.end(), SectionSort);
01010 
01011   // Add terminating symbols for each section.
01012   for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
01013     const MCSection *Section = Sections[ID];
01014     MCSymbol *Sym = nullptr;
01015 
01016     if (Section) {
01017       // We can't call MCSection::getLabelEndName, as it's only safe to do so
01018       // if we know the section name up-front. For user-created sections, the
01019       // resulting label may not be valid to use as a label. (section names can
01020       // use a greater set of characters on some systems)
01021       Sym = Asm->GetTempSymbol("debug_end", ID);
01022       Asm->OutStreamer.SwitchSection(Section);
01023       Asm->OutStreamer.EmitLabel(Sym);
01024     }
01025 
01026     // Insert a final terminator.
01027     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
01028   }
01029 }
01030 
01031 // Emit all Dwarf sections that should come after the content.
01032 void DwarfDebug::endModule() {
01033   assert(CurFn == nullptr);
01034   assert(CurMI == nullptr);
01035 
01036   if (!FirstCU)
01037     return;
01038 
01039   // End any existing sections.
01040   // TODO: Does this need to happen?
01041   endSections();
01042 
01043   // Finalize the debug info for the module.
01044   finalizeModuleInfo();
01045 
01046   emitDebugStr();
01047 
01048   // Emit all the DIEs into a debug info section.
01049   emitDebugInfo();
01050 
01051   // Corresponding abbreviations into a abbrev section.
01052   emitAbbreviations();
01053 
01054   // Emit info into a debug aranges section.
01055   if (GenerateARangeSection)
01056     emitDebugARanges();
01057 
01058   // Emit info into a debug ranges section.
01059   emitDebugRanges();
01060 
01061   if (useSplitDwarf()) {
01062     emitDebugStrDWO();
01063     emitDebugInfoDWO();
01064     emitDebugAbbrevDWO();
01065     emitDebugLineDWO();
01066     emitDebugLocDWO();
01067     // Emit DWO addresses.
01068     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
01069   } else
01070     // Emit info into a debug loc section.
01071     emitDebugLoc();
01072 
01073   // Emit info into the dwarf accelerator table sections.
01074   if (useDwarfAccelTables()) {
01075     emitAccelNames();
01076     emitAccelObjC();
01077     emitAccelNamespaces();
01078     emitAccelTypes();
01079   }
01080 
01081   // Emit the pubnames and pubtypes sections if requested.
01082   if (HasDwarfPubSections) {
01083     emitDebugPubNames(GenerateGnuPubSections);
01084     emitDebugPubTypes(GenerateGnuPubSections);
01085   }
01086 
01087   // clean up.
01088   SPMap.clear();
01089   AbstractVariables.clear();
01090 
01091   // Reset these for the next Module if we have one.
01092   FirstCU = nullptr;
01093 }
01094 
01095 // Find abstract variable, if any, associated with Var.
01096 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
01097                                                      DIVariable &Cleansed) {
01098   LLVMContext &Ctx = DV->getContext();
01099   // More then one inlined variable corresponds to one abstract variable.
01100   // FIXME: This duplication of variables when inlining should probably be
01101   // removed. It's done to allow each DIVariable to describe its location
01102   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
01103   // make it accurate then remove this duplication/cleansing stuff.
01104   Cleansed = cleanseInlinedVariable(DV, Ctx);
01105   auto I = AbstractVariables.find(Cleansed);
01106   if (I != AbstractVariables.end())
01107     return I->second.get();
01108   return nullptr;
01109 }
01110 
01111 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
01112   DIVariable Cleansed;
01113   return getExistingAbstractVariable(DV, Cleansed);
01114 }
01115 
01116 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
01117                                         LexicalScope *Scope) {
01118   auto AbsDbgVariable = make_unique<DbgVariable>(Var, this);
01119   addScopeVariable(Scope, AbsDbgVariable.get());
01120   AbstractVariables[Var] = std::move(AbsDbgVariable);
01121 }
01122 
01123 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
01124                                                  const MDNode *ScopeNode) {
01125   DIVariable Cleansed = DV;
01126   if (getExistingAbstractVariable(DV, Cleansed))
01127     return;
01128 
01129   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
01130 }
01131 
01132 void
01133 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
01134                                                     const MDNode *ScopeNode) {
01135   DIVariable Cleansed = DV;
01136   if (getExistingAbstractVariable(DV, Cleansed))
01137     return;
01138 
01139   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
01140     createAbstractVariable(Cleansed, Scope);
01141 }
01142 
01143 // If Var is a current function argument then add it to CurrentFnArguments list.
01144 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
01145   if (!LScopes.isCurrentFunctionScope(Scope))
01146     return false;
01147   DIVariable DV = Var->getVariable();
01148   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
01149     return false;
01150   unsigned ArgNo = DV.getArgNumber();
01151   if (ArgNo == 0)
01152     return false;
01153 
01154   size_t Size = CurrentFnArguments.size();
01155   if (Size == 0)
01156     CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
01157   // llvm::Function argument size is not good indicator of how many
01158   // arguments does the function have at source level.
01159   if (ArgNo > Size)
01160     CurrentFnArguments.resize(ArgNo * 2);
01161   assert(!CurrentFnArguments[ArgNo - 1]);
01162   CurrentFnArguments[ArgNo - 1] = Var;
01163   return true;
01164 }
01165 
01166 // Collect variable information from side table maintained by MMI.
01167 void DwarfDebug::collectVariableInfoFromMMITable(
01168     SmallPtrSetImpl<const MDNode *> &Processed) {
01169   for (const auto &VI : MMI->getVariableDbgInfo()) {
01170     if (!VI.Var)
01171       continue;
01172     Processed.insert(VI.Var);
01173     DIVariable DV(VI.Var);
01174     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
01175 
01176     // If variable scope is not found then skip this variable.
01177     if (!Scope)
01178       continue;
01179 
01180     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
01181     ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
01182     DbgVariable *RegVar = ConcreteVariables.back().get();
01183     RegVar->setFrameIndex(VI.Slot);
01184     addScopeVariable(Scope, RegVar);
01185   }
01186 }
01187 
01188 // Get .debug_loc entry for the instruction range starting at MI.
01189 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
01190   const MDNode *Var = MI->getDebugVariable();
01191 
01192   assert(MI->getNumOperands() == 3);
01193   if (MI->getOperand(0).isReg()) {
01194     MachineLocation MLoc;
01195     // If the second operand is an immediate, this is a
01196     // register-indirect address.
01197     if (!MI->getOperand(1).isImm())
01198       MLoc.set(MI->getOperand(0).getReg());
01199     else
01200       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
01201     return DebugLocEntry::Value(Var, MLoc);
01202   }
01203   if (MI->getOperand(0).isImm())
01204     return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
01205   if (MI->getOperand(0).isFPImm())
01206     return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
01207   if (MI->getOperand(0).isCImm())
01208     return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
01209 
01210   llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
01211 }
01212 
01213 /// Determine whether two variable pieces overlap.
01214 static bool piecesOverlap(DIVariable P1, DIVariable P2) {
01215   if (!P1.isVariablePiece() || !P2.isVariablePiece())
01216     return true;
01217   unsigned l1 = P1.getPieceOffset();
01218   unsigned l2 = P2.getPieceOffset();
01219   unsigned r1 = l1 + P1.getPieceSize();
01220   unsigned r2 = l2 + P2.getPieceSize();
01221   // True where [l1,r1[ and [r1,r2[ overlap.
01222   return (l1 < r2) && (l2 < r1);
01223 }
01224 
01225 /// Build the location list for all DBG_VALUEs in the function that
01226 /// describe the same variable.  If the ranges of several independent
01227 /// pieces of the same variable overlap partially, split them up and
01228 /// combine the ranges. The resulting DebugLocEntries are will have
01229 /// strict monotonically increasing begin addresses and will never
01230 /// overlap.
01231 //
01232 // Input:
01233 //
01234 //   Ranges History [var, loc, piece ofs size]
01235 // 0 |      [x, (reg0, piece 0, 32)]
01236 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
01237 // 2 | |    ...
01238 // 3   |    [clobber reg0]
01239 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
01240 //
01241 // Output:
01242 //
01243 // [0-1]    [x, (reg0, piece  0, 32)]
01244 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
01245 // [3-4]    [x, (reg1, piece 32, 32)]
01246 // [4- ]    [x, (mem,  piece  0, 64)]
01247 void
01248 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
01249                               const DbgValueHistoryMap::InstrRanges &Ranges) {
01250   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
01251 
01252   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
01253     const MachineInstr *Begin = I->first;
01254     const MachineInstr *End = I->second;
01255     assert(Begin->isDebugValue() && "Invalid History entry");
01256 
01257     // Check if a variable is inaccessible in this range.
01258     if (Begin->getNumOperands() > 1 &&
01259         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
01260       OpenRanges.clear();
01261       continue;
01262     }
01263 
01264     // If this piece overlaps with any open ranges, truncate them.
01265     DIVariable DIVar = Begin->getDebugVariable();
01266     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
01267                                [&](DebugLocEntry::Value R) {
01268                                  return piecesOverlap(DIVar, R.getVariable());
01269                                });
01270     OpenRanges.erase(Last, OpenRanges.end());
01271 
01272     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
01273     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
01274 
01275     const MCSymbol *EndLabel;
01276     if (End != nullptr)
01277       EndLabel = getLabelAfterInsn(End);
01278     else if (std::next(I) == Ranges.end())
01279       EndLabel = FunctionEndSym;
01280     else
01281       EndLabel = getLabelBeforeInsn(std::next(I)->first);
01282     assert(EndLabel && "Forgot label after instruction ending a range!");
01283 
01284     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
01285 
01286     auto Value = getDebugLocValue(Begin);
01287     DebugLocEntry Loc(StartLabel, EndLabel, Value);
01288     bool couldMerge = false;
01289 
01290     // If this is a piece, it may belong to the current DebugLocEntry.
01291     if (DIVar.isVariablePiece()) {
01292       // Add this value to the list of open ranges.
01293       OpenRanges.push_back(Value);
01294 
01295       // Attempt to add the piece to the last entry.
01296       if (!DebugLoc.empty())
01297         if (DebugLoc.back().MergeValues(Loc))
01298           couldMerge = true;
01299     }
01300 
01301     if (!couldMerge) {
01302       // Need to add a new DebugLocEntry. Add all values from still
01303       // valid non-overlapping pieces.
01304       if (OpenRanges.size())
01305         Loc.addValues(OpenRanges);
01306 
01307       DebugLoc.push_back(std::move(Loc));
01308     }
01309 
01310     // Attempt to coalesce the ranges of two otherwise identical
01311     // DebugLocEntries.
01312     auto CurEntry = DebugLoc.rbegin();
01313     auto PrevEntry = std::next(CurEntry);
01314     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
01315       DebugLoc.pop_back();
01316 
01317     DEBUG(dbgs() << "Values:\n";
01318           for (auto Value : CurEntry->getValues())
01319             Value.getVariable()->dump();
01320           dbgs() << "-----\n");
01321   }
01322 }
01323 
01324 
01325 // Find variables for each lexical scope.
01326 void
01327 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
01328   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
01329   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
01330 
01331   // Grab the variable info that was squirreled away in the MMI side-table.
01332   collectVariableInfoFromMMITable(Processed);
01333 
01334   for (const auto &I : DbgValues) {
01335     DIVariable DV(I.first);
01336     if (Processed.count(DV))
01337       continue;
01338 
01339     // Instruction ranges, specifying where DV is accessible.
01340     const auto &Ranges = I.second;
01341     if (Ranges.empty())
01342       continue;
01343 
01344     LexicalScope *Scope = nullptr;
01345     if (MDNode *IA = DV.getInlinedAt()) {
01346       DebugLoc DL = DebugLoc::getFromDILocation(IA);
01347       Scope = LScopes.findInlinedScope(DebugLoc::get(
01348           DL.getLine(), DL.getCol(), DV.getContext(), IA));
01349     } else
01350       Scope = LScopes.findLexicalScope(DV.getContext());
01351     // If variable scope is not found then skip this variable.
01352     if (!Scope)
01353       continue;
01354 
01355     Processed.insert(getEntireVariable(DV));
01356     const MachineInstr *MInsn = Ranges.front().first;
01357     assert(MInsn->isDebugValue() && "History must begin with debug value");
01358     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
01359     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
01360     DbgVariable *RegVar = ConcreteVariables.back().get();
01361     addScopeVariable(Scope, RegVar);
01362 
01363     // Check if the first DBG_VALUE is valid for the rest of the function.
01364     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
01365       continue;
01366 
01367     // Handle multiple DBG_VALUE instructions describing one variable.
01368     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
01369 
01370     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
01371     DebugLocList &LocList = DotDebugLocEntries.back();
01372     LocList.CU = TheCU;
01373     LocList.Label =
01374         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
01375 
01376     // Build the location list for this variable.
01377     buildLocationList(LocList.List, Ranges);
01378   }
01379 
01380   // Collect info for variables that were optimized out.
01381   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
01382   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
01383     DIVariable DV(Variables.getElement(i));
01384     assert(DV.isVariable());
01385     if (!Processed.insert(DV))
01386       continue;
01387     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
01388       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
01389       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
01390       addScopeVariable(Scope, ConcreteVariables.back().get());
01391     }
01392   }
01393 }
01394 
01395 // Return Label preceding the instruction.
01396 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
01397   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
01398   assert(Label && "Didn't insert label before instruction");
01399   return Label;
01400 }
01401 
01402 // Return Label immediately following the instruction.
01403 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
01404   return LabelsAfterInsn.lookup(MI);
01405 }
01406 
01407 // Process beginning of an instruction.
01408 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
01409   assert(CurMI == nullptr);
01410   CurMI = MI;
01411   // Check if source location changes, but ignore DBG_VALUE locations.
01412   if (!MI->isDebugValue()) {
01413     DebugLoc DL = MI->getDebugLoc();
01414     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
01415       unsigned Flags = 0;
01416       PrevInstLoc = DL;
01417       if (DL == PrologEndLoc) {
01418         Flags |= DWARF2_FLAG_PROLOGUE_END;
01419         PrologEndLoc = DebugLoc();
01420       }
01421       if (PrologEndLoc.isUnknown())
01422         Flags |= DWARF2_FLAG_IS_STMT;
01423 
01424       if (!DL.isUnknown()) {
01425         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
01426         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
01427       } else
01428         recordSourceLine(0, 0, nullptr, 0);
01429     }
01430   }
01431 
01432   // Insert labels where requested.
01433   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
01434       LabelsBeforeInsn.find(MI);
01435 
01436   // No label needed.
01437   if (I == LabelsBeforeInsn.end())
01438     return;
01439 
01440   // Label already assigned.
01441   if (I->second)
01442     return;
01443 
01444   if (!PrevLabel) {
01445     PrevLabel = MMI->getContext().CreateTempSymbol();
01446     Asm->OutStreamer.EmitLabel(PrevLabel);
01447   }
01448   I->second = PrevLabel;
01449 }
01450 
01451 // Process end of an instruction.
01452 void DwarfDebug::endInstruction() {
01453   assert(CurMI != nullptr);
01454   // Don't create a new label after DBG_VALUE instructions.
01455   // They don't generate code.
01456   if (!CurMI->isDebugValue())
01457     PrevLabel = nullptr;
01458 
01459   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
01460       LabelsAfterInsn.find(CurMI);
01461   CurMI = nullptr;
01462 
01463   // No label needed.
01464   if (I == LabelsAfterInsn.end())
01465     return;
01466 
01467   // Label already assigned.
01468   if (I->second)
01469     return;
01470 
01471   // We need a label after this instruction.
01472   if (!PrevLabel) {
01473     PrevLabel = MMI->getContext().CreateTempSymbol();
01474     Asm->OutStreamer.EmitLabel(PrevLabel);
01475   }
01476   I->second = PrevLabel;
01477 }
01478 
01479 // Each LexicalScope has first instruction and last instruction to mark
01480 // beginning and end of a scope respectively. Create an inverse map that list
01481 // scopes starts (and ends) with an instruction. One instruction may start (or
01482 // end) multiple scopes. Ignore scopes that are not reachable.
01483 void DwarfDebug::identifyScopeMarkers() {
01484   SmallVector<LexicalScope *, 4> WorkList;
01485   WorkList.push_back(LScopes.getCurrentFunctionScope());
01486   while (!WorkList.empty()) {
01487     LexicalScope *S = WorkList.pop_back_val();
01488 
01489     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
01490     if (!Children.empty())
01491       WorkList.append(Children.begin(), Children.end());
01492 
01493     if (S->isAbstractScope())
01494       continue;
01495 
01496     for (const InsnRange &R : S->getRanges()) {
01497       assert(R.first && "InsnRange does not have first instruction!");
01498       assert(R.second && "InsnRange does not have second instruction!");
01499       requestLabelBeforeInsn(R.first);
01500       requestLabelAfterInsn(R.second);
01501     }
01502   }
01503 }
01504 
01505 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
01506   // First known non-DBG_VALUE and non-frame setup location marks
01507   // the beginning of the function body.
01508   for (const auto &MBB : *MF)
01509     for (const auto &MI : MBB)
01510       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
01511           !MI.getDebugLoc().isUnknown())
01512         return MI.getDebugLoc();
01513   return DebugLoc();
01514 }
01515 
01516 // Gather pre-function debug information.  Assumes being called immediately
01517 // after the function entry point has been emitted.
01518 void DwarfDebug::beginFunction(const MachineFunction *MF) {
01519   CurFn = MF;
01520 
01521   // If there's no debug info for the function we're not going to do anything.
01522   if (!MMI->hasDebugInfo())
01523     return;
01524 
01525   auto DI = FunctionDIs.find(MF->getFunction());
01526   if (DI == FunctionDIs.end())
01527     return;
01528 
01529   // Grab the lexical scopes for the function, if we don't have any of those
01530   // then we're not going to be able to do anything.
01531   LScopes.initialize(*MF);
01532   if (LScopes.empty())
01533     return;
01534 
01535   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
01536 
01537   // Make sure that each lexical scope will have a begin/end label.
01538   identifyScopeMarkers();
01539 
01540   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
01541   // belongs to so that we add to the correct per-cu line table in the
01542   // non-asm case.
01543   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
01544   // FnScope->getScopeNode() and DI->second should represent the same function,
01545   // though they may not be the same MDNode due to inline functions merged in
01546   // LTO where the debug info metadata still differs (either due to distinct
01547   // written differences - two versions of a linkonce_odr function
01548   // written/copied into two separate files, or some sub-optimal metadata that
01549   // isn't structurally identical (see: file path/name info from clang, which
01550   // includes the directory of the cpp file being built, even when the file name
01551   // is absolute (such as an <> lookup header)))
01552   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
01553   assert(TheCU && "Unable to find compile unit!");
01554   if (Asm->OutStreamer.hasRawTextSupport())
01555     // Use a single line table if we are generating assembly.
01556     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
01557   else
01558     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
01559 
01560   // Emit a label for the function so that we have a beginning address.
01561   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
01562   // Assumes in correct section after the entry point.
01563   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
01564 
01565   // Calculate history for local variables.
01566   calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
01567                            DbgValues);
01568 
01569   // Request labels for the full history.
01570   for (const auto &I : DbgValues) {
01571     const auto &Ranges = I.second;
01572     if (Ranges.empty())
01573       continue;
01574 
01575     // The first mention of a function argument gets the FunctionBeginSym
01576     // label, so arguments are visible when breaking at function entry.
01577     DIVariable DV(Ranges.front().first->getDebugVariable());
01578     if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
01579         getDISubprogram(DV.getContext()).describes(MF->getFunction())) {
01580       if (!DV.isVariablePiece())
01581         LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
01582       else {
01583         // Mark all non-overlapping initial pieces.
01584         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
01585           DIVariable Piece = I->first->getDebugVariable();
01586           if (std::all_of(Ranges.begin(), I,
01587                           [&](DbgValueHistoryMap::InstrRange Pred){
01588                 return !piecesOverlap(Piece, Pred.first->getDebugVariable());
01589               }))
01590             LabelsBeforeInsn[I->first] = FunctionBeginSym;
01591           else
01592             break;
01593         }
01594       }
01595     }
01596 
01597     for (const auto &Range : Ranges) {
01598       requestLabelBeforeInsn(Range.first);
01599       if (Range.second)
01600         requestLabelAfterInsn(Range.second);
01601     }
01602   }
01603 
01604   PrevInstLoc = DebugLoc();
01605   PrevLabel = FunctionBeginSym;
01606 
01607   // Record beginning of function.
01608   PrologEndLoc = findPrologueEndLoc(MF);
01609   if (!PrologEndLoc.isUnknown()) {
01610     DebugLoc FnStartDL =
01611         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
01612     recordSourceLine(
01613         FnStartDL.getLine(), FnStartDL.getCol(),
01614         FnStartDL.getScope(MF->getFunction()->getContext()),
01615         // We'd like to list the prologue as "not statements" but GDB behaves
01616         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
01617         DWARF2_FLAG_IS_STMT);
01618   }
01619 }
01620 
01621 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
01622   if (addCurrentFnArgument(Var, LS))
01623     return;
01624   SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
01625   DIVariable DV = Var->getVariable();
01626   // Variables with positive arg numbers are parameters.
01627   if (unsigned ArgNum = DV.getArgNumber()) {
01628     // Keep all parameters in order at the start of the variable list to ensure
01629     // function types are correct (no out-of-order parameters)
01630     //
01631     // This could be improved by only doing it for optimized builds (unoptimized
01632     // builds have the right order to begin with), searching from the back (this
01633     // would catch the unoptimized case quickly), or doing a binary search
01634     // rather than linear search.
01635     SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
01636     while (I != Vars.end()) {
01637       unsigned CurNum = (*I)->getVariable().getArgNumber();
01638       // A local (non-parameter) variable has been found, insert immediately
01639       // before it.
01640       if (CurNum == 0)
01641         break;
01642       // A later indexed parameter has been found, insert immediately before it.
01643       if (CurNum > ArgNum)
01644         break;
01645       ++I;
01646     }
01647     Vars.insert(I, Var);
01648     return;
01649   }
01650 
01651   Vars.push_back(Var);
01652 }
01653 
01654 // Gather and emit post-function debug information.
01655 void DwarfDebug::endFunction(const MachineFunction *MF) {
01656   // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
01657   // though the beginFunction may not be called at all.
01658   // We should handle both cases.
01659   if (!CurFn)
01660     CurFn = MF;
01661   else
01662     assert(CurFn == MF);
01663   assert(CurFn != nullptr);
01664 
01665   if (!MMI->hasDebugInfo() || LScopes.empty() ||
01666       !FunctionDIs.count(MF->getFunction())) {
01667     // If we don't have a lexical scope for this function then there will
01668     // be a hole in the range information. Keep note of this by setting the
01669     // previously used section to nullptr.
01670     PrevCU = nullptr;
01671     CurFn = nullptr;
01672     return;
01673   }
01674 
01675   // Define end label for subprogram.
01676   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
01677   // Assumes in correct section after the entry point.
01678   Asm->OutStreamer.EmitLabel(FunctionEndSym);
01679 
01680   // Set DwarfDwarfCompileUnitID in MCContext to default value.
01681   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
01682 
01683   SmallPtrSet<const MDNode *, 16> ProcessedVars;
01684   collectVariableInfo(ProcessedVars);
01685 
01686   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
01687   DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
01688 
01689   // Construct abstract scopes.
01690   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
01691     DISubprogram SP(AScope->getScopeNode());
01692     assert(SP.isSubprogram());
01693     // Collect info for variables that were optimized out.
01694     DIArray Variables = SP.getVariables();
01695     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
01696       DIVariable DV(Variables.getElement(i));
01697       assert(DV && DV.isVariable());
01698       if (!ProcessedVars.insert(DV))
01699         continue;
01700       ensureAbstractVariableIsCreated(DV, DV.getContext());
01701     }
01702     constructAbstractSubprogramScopeDIE(TheCU, AScope);
01703   }
01704 
01705   DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
01706   if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
01707     TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
01708 
01709   // Add the range of this function to the list of ranges for the CU.
01710   RangeSpan Span(FunctionBeginSym, FunctionEndSym);
01711   TheCU.addRange(std::move(Span));
01712 
01713   // Clear debug info
01714   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
01715   // DbgVariables except those that are also in AbstractVariables (since they
01716   // can be used cross-function)
01717   ScopeVariables.clear();
01718   CurrentFnArguments.clear();
01719   DbgValues.clear();
01720   LabelsBeforeInsn.clear();
01721   LabelsAfterInsn.clear();
01722   PrevLabel = nullptr;
01723   CurFn = nullptr;
01724 }
01725 
01726 // Register a source line with debug info. Returns the  unique label that was
01727 // emitted and which provides correspondence to the source line list.
01728 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
01729                                   unsigned Flags) {
01730   StringRef Fn;
01731   StringRef Dir;
01732   unsigned Src = 1;
01733   unsigned Discriminator = 0;
01734   if (DIScope Scope = DIScope(S)) {
01735     assert(Scope.isScope());
01736     Fn = Scope.getFilename();
01737     Dir = Scope.getDirectory();
01738     if (Scope.isLexicalBlockFile())
01739       Discriminator = DILexicalBlockFile(S).getDiscriminator();
01740 
01741     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
01742     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
01743               .getOrCreateSourceID(Fn, Dir);
01744   }
01745   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
01746                                          Discriminator, Fn);
01747 }
01748 
01749 //===----------------------------------------------------------------------===//
01750 // Emit Methods
01751 //===----------------------------------------------------------------------===//
01752 
01753 // Emit initial Dwarf sections with a label at the start of each one.
01754 void DwarfDebug::emitSectionLabels() {
01755   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
01756 
01757   // Dwarf sections base addresses.
01758   DwarfInfoSectionSym =
01759       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
01760   if (useSplitDwarf()) {
01761     DwarfInfoDWOSectionSym =
01762         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
01763     DwarfTypesDWOSectionSym =
01764         emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
01765   }
01766   DwarfAbbrevSectionSym =
01767       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
01768   if (useSplitDwarf())
01769     DwarfAbbrevDWOSectionSym = emitSectionSym(
01770         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
01771   if (GenerateARangeSection)
01772     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
01773 
01774   DwarfLineSectionSym =
01775       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
01776   if (GenerateGnuPubSections) {
01777     DwarfGnuPubNamesSectionSym =
01778         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
01779     DwarfGnuPubTypesSectionSym =
01780         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
01781   } else if (HasDwarfPubSections) {
01782     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
01783     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
01784   }
01785 
01786   DwarfStrSectionSym =
01787       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
01788   if (useSplitDwarf()) {
01789     DwarfStrDWOSectionSym =
01790         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
01791     DwarfAddrSectionSym =
01792         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
01793     DwarfDebugLocSectionSym =
01794         emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
01795   } else
01796     DwarfDebugLocSectionSym =
01797         emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
01798   DwarfDebugRangeSectionSym =
01799       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
01800 }
01801 
01802 // Recursively emits a debug information entry.
01803 void DwarfDebug::emitDIE(DIE &Die) {
01804   // Get the abbreviation for this DIE.
01805   const DIEAbbrev &Abbrev = Die.getAbbrev();
01806 
01807   // Emit the code (index) for the abbreviation.
01808   if (Asm->isVerbose())
01809     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
01810                                 "] 0x" + Twine::utohexstr(Die.getOffset()) +
01811                                 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
01812                                 dwarf::TagString(Abbrev.getTag()));
01813   Asm->EmitULEB128(Abbrev.getNumber());
01814 
01815   const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
01816   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
01817 
01818   // Emit the DIE attribute values.
01819   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
01820     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
01821     dwarf::Form Form = AbbrevData[i].getForm();
01822     assert(Form && "Too many attributes for DIE (check abbreviation)");
01823 
01824     if (Asm->isVerbose()) {
01825       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
01826       if (Attr == dwarf::DW_AT_accessibility)
01827         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
01828             cast<DIEInteger>(Values[i])->getValue()));
01829     }
01830 
01831     // Emit an attribute using the defined form.
01832     Values[i]->EmitValue(Asm, Form);
01833   }
01834 
01835   // Emit the DIE children if any.
01836   if (Abbrev.hasChildren()) {
01837     for (auto &Child : Die.getChildren())
01838       emitDIE(*Child);
01839 
01840     Asm->OutStreamer.AddComment("End Of Children Mark");
01841     Asm->EmitInt8(0);
01842   }
01843 }
01844 
01845 // Emit the debug info section.
01846 void DwarfDebug::emitDebugInfo() {
01847   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
01848 
01849   Holder.emitUnits(this, DwarfAbbrevSectionSym);
01850 }
01851 
01852 // Emit the abbreviation section.
01853 void DwarfDebug::emitAbbreviations() {
01854   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
01855 
01856   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
01857 }
01858 
01859 // Emit the last address of the section and the end of the line matrix.
01860 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
01861   // Define last address of section.
01862   Asm->OutStreamer.AddComment("Extended Op");
01863   Asm->EmitInt8(0);
01864 
01865   Asm->OutStreamer.AddComment("Op size");
01866   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
01867   Asm->OutStreamer.AddComment("DW_LNE_set_address");
01868   Asm->EmitInt8(dwarf::DW_LNE_set_address);
01869 
01870   Asm->OutStreamer.AddComment("Section end label");
01871 
01872   Asm->OutStreamer.EmitSymbolValue(
01873       Asm->GetTempSymbol("section_end", SectionEnd),
01874       Asm->getDataLayout().getPointerSize());
01875 
01876   // Mark end of matrix.
01877   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
01878   Asm->EmitInt8(0);
01879   Asm->EmitInt8(1);
01880   Asm->EmitInt8(1);
01881 }
01882 
01883 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
01884                            StringRef TableName, StringRef SymName) {
01885   Accel.FinalizeTable(Asm, TableName);
01886   Asm->OutStreamer.SwitchSection(Section);
01887   auto *SectionBegin = Asm->GetTempSymbol(SymName);
01888   Asm->OutStreamer.EmitLabel(SectionBegin);
01889 
01890   // Emit the full data.
01891   Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
01892 }
01893 
01894 // Emit visible names into a hashed accelerator table section.
01895 void DwarfDebug::emitAccelNames() {
01896   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
01897             "Names", "names_begin");
01898 }
01899 
01900 // Emit objective C classes and categories into a hashed accelerator table
01901 // section.
01902 void DwarfDebug::emitAccelObjC() {
01903   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
01904             "ObjC", "objc_begin");
01905 }
01906 
01907 // Emit namespace dies into a hashed accelerator table.
01908 void DwarfDebug::emitAccelNamespaces() {
01909   emitAccel(AccelNamespace,
01910             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
01911             "namespac", "namespac_begin");
01912 }
01913 
01914 // Emit type dies into a hashed accelerator table.
01915 void DwarfDebug::emitAccelTypes() {
01916   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
01917             "types", "types_begin");
01918 }
01919 
01920 // Public name handling.
01921 // The format for the various pubnames:
01922 //
01923 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
01924 // for the DIE that is named.
01925 //
01926 // gnu pubnames - offset/index value/name tuples where the offset is the offset
01927 // into the CU and the index value is computed according to the type of value
01928 // for the DIE that is named.
01929 //
01930 // For type units the offset is the offset of the skeleton DIE. For split dwarf
01931 // it's the offset within the debug_info/debug_types dwo section, however, the
01932 // reference in the pubname header doesn't change.
01933 
01934 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
01935 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
01936                                                         const DIE *Die) {
01937   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
01938 
01939   // We could have a specification DIE that has our most of our knowledge,
01940   // look for that now.
01941   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
01942   if (SpecVal) {
01943     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
01944     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
01945       Linkage = dwarf::GIEL_EXTERNAL;
01946   } else if (Die->findAttribute(dwarf::DW_AT_external))
01947     Linkage = dwarf::GIEL_EXTERNAL;
01948 
01949   switch (Die->getTag()) {
01950   case dwarf::DW_TAG_class_type:
01951   case dwarf::DW_TAG_structure_type:
01952   case dwarf::DW_TAG_union_type:
01953   case dwarf::DW_TAG_enumeration_type:
01954     return dwarf::PubIndexEntryDescriptor(
01955         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
01956                               ? dwarf::GIEL_STATIC
01957                               : dwarf::GIEL_EXTERNAL);
01958   case dwarf::DW_TAG_typedef:
01959   case dwarf::DW_TAG_base_type:
01960   case dwarf::DW_TAG_subrange_type:
01961     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
01962   case dwarf::DW_TAG_namespace:
01963     return dwarf::GIEK_TYPE;
01964   case dwarf::DW_TAG_subprogram:
01965     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
01966   case dwarf::DW_TAG_constant:
01967   case dwarf::DW_TAG_variable:
01968     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
01969   case dwarf::DW_TAG_enumerator:
01970     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
01971                                           dwarf::GIEL_STATIC);
01972   default:
01973     return dwarf::GIEK_NONE;
01974   }
01975 }
01976 
01977 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
01978 ///
01979 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
01980   const MCSection *PSec =
01981       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
01982                : Asm->getObjFileLowering().getDwarfPubNamesSection();
01983 
01984   emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
01985 }
01986 
01987 void DwarfDebug::emitDebugPubSection(
01988     bool GnuStyle, const MCSection *PSec, StringRef Name,
01989     const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
01990   for (const auto &NU : CUMap) {
01991     DwarfCompileUnit *TheU = NU.second;
01992 
01993     const auto &Globals = (TheU->*Accessor)();
01994 
01995     if (Globals.empty())
01996       continue;
01997 
01998     if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
01999       TheU = Skeleton;
02000     unsigned ID = TheU->getUniqueID();
02001 
02002     // Start the dwarf pubnames section.
02003     Asm->OutStreamer.SwitchSection(PSec);
02004 
02005     // Emit the header.
02006     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
02007     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
02008     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
02009     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
02010 
02011     Asm->OutStreamer.EmitLabel(BeginLabel);
02012 
02013     Asm->OutStreamer.AddComment("DWARF Version");
02014     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
02015 
02016     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
02017     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
02018 
02019     Asm->OutStreamer.AddComment("Compilation Unit Length");
02020     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
02021 
02022     // Emit the pubnames for this compilation unit.
02023     for (const auto &GI : Globals) {
02024       const char *Name = GI.getKeyData();
02025       const DIE *Entity = GI.second;
02026 
02027       Asm->OutStreamer.AddComment("DIE offset");
02028       Asm->EmitInt32(Entity->getOffset());
02029 
02030       if (GnuStyle) {
02031         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
02032         Asm->OutStreamer.AddComment(
02033             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
02034             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
02035         Asm->EmitInt8(Desc.toBits());
02036       }
02037 
02038       Asm->OutStreamer.AddComment("External Name");
02039       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
02040     }
02041 
02042     Asm->OutStreamer.AddComment("End Mark");
02043     Asm->EmitInt32(0);
02044     Asm->OutStreamer.EmitLabel(EndLabel);
02045   }
02046 }
02047 
02048 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
02049   const MCSection *PSec =
02050       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
02051                : Asm->getObjFileLowering().getDwarfPubTypesSection();
02052 
02053   emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
02054 }
02055 
02056 // Emit visible names into a debug str section.
02057 void DwarfDebug::emitDebugStr() {
02058   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
02059   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
02060 }
02061 
02062 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
02063 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
02064                                const DITypeIdentifierMap &Map,
02065                                ArrayRef<DebugLocEntry::Value> Values) {
02066   assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
02067         return P.isVariablePiece();
02068       }) && "all values are expected to be pieces");
02069   assert(std::is_sorted(Values.begin(), Values.end()) &&
02070          "pieces are expected to be sorted");
02071 
02072   unsigned Offset = 0;
02073   for (auto Piece : Values) {
02074     DIVariable Var = Piece.getVariable();
02075     unsigned PieceOffset = Var.getPieceOffset();
02076     unsigned PieceSize = Var.getPieceSize();
02077     assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
02078     if (Offset < PieceOffset) {
02079       // The DWARF spec seriously mandates pieces with no locations for gaps.
02080       Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
02081       Offset += PieceOffset-Offset;
02082     }
02083 
02084     Offset += PieceSize;
02085 
02086     const unsigned SizeOfByte = 8;
02087     assert(!Var.isIndirect() && "indirect address for piece");
02088 #ifndef NDEBUG
02089     unsigned VarSize = Var.getSizeInBits(Map);
02090     assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
02091            && "piece is larger than or outside of variable");
02092     assert(PieceSize*SizeOfByte != VarSize
02093            && "piece covers entire variable");
02094 #endif
02095     if (Piece.isLocation() && Piece.getLoc().isReg())
02096       Asm->EmitDwarfRegOpPiece(Streamer,
02097                                Piece.getLoc(),
02098                                PieceSize*SizeOfByte);
02099     else {
02100       emitDebugLocValue(Streamer, Piece);
02101       Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
02102     }
02103   }
02104 }
02105 
02106 
02107 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
02108                                    const DebugLocEntry &Entry) {
02109   const DebugLocEntry::Value Value = Entry.getValues()[0];
02110   if (Value.isVariablePiece())
02111     // Emit all pieces that belong to the same variable and range.
02112     return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
02113 
02114   assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
02115   emitDebugLocValue(Streamer, Value);
02116 }
02117 
02118 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
02119                                    const DebugLocEntry::Value &Value) {
02120   DIVariable DV = Value.getVariable();
02121   // Regular entry.
02122   if (Value.isInt()) {
02123     DIBasicType BTy(resolve(DV.getType()));
02124     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
02125                          BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
02126       Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
02127       Streamer.EmitSLEB128(Value.getInt());
02128     } else {
02129       Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
02130       Streamer.EmitULEB128(Value.getInt());
02131     }
02132   } else if (Value.isLocation()) {
02133     MachineLocation Loc = Value.getLoc();
02134     if (!DV.hasComplexAddress())
02135       // Regular entry.
02136       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
02137     else {
02138       // Complex address entry.
02139       unsigned N = DV.getNumAddrElements();
02140       unsigned i = 0;
02141       if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
02142         if (Loc.getOffset()) {
02143           i = 2;
02144           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
02145           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
02146           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
02147           Streamer.EmitSLEB128(DV.getAddrElement(1));
02148         } else {
02149           // If first address element is OpPlus then emit
02150           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
02151           MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
02152           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
02153           i = 2;
02154         }
02155       } else {
02156         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
02157       }
02158 
02159       // Emit remaining complex address elements.
02160       for (; i < N; ++i) {
02161         uint64_t Element = DV.getAddrElement(i);
02162         if (Element == DIBuilder::OpPlus) {
02163           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
02164           Streamer.EmitULEB128(DV.getAddrElement(++i));
02165         } else if (Element == DIBuilder::OpDeref) {
02166           if (!Loc.isReg())
02167             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
02168         } else if (Element == DIBuilder::OpPiece) {
02169           i += 3;
02170           // handled in emitDebugLocEntry.
02171         } else
02172           llvm_unreachable("unknown Opcode found in complex address");
02173       }
02174     }
02175   }
02176   // else ... ignore constant fp. There is not any good way to
02177   // to represent them here in dwarf.
02178   // FIXME: ^
02179 }
02180 
02181 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
02182   Asm->OutStreamer.AddComment("Loc expr size");
02183   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
02184   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
02185   Asm->EmitLabelDifference(end, begin, 2);
02186   Asm->OutStreamer.EmitLabel(begin);
02187   // Emit the entry.
02188   APByteStreamer Streamer(*Asm);
02189   emitDebugLocEntry(Streamer, Entry);
02190   // Close the range.
02191   Asm->OutStreamer.EmitLabel(end);
02192 }
02193 
02194 // Emit locations into the debug loc section.
02195 void DwarfDebug::emitDebugLoc() {
02196   // Start the dwarf loc section.
02197   Asm->OutStreamer.SwitchSection(
02198       Asm->getObjFileLowering().getDwarfLocSection());
02199   unsigned char Size = Asm->getDataLayout().getPointerSize();
02200   for (const auto &DebugLoc : DotDebugLocEntries) {
02201     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
02202     const DwarfCompileUnit *CU = DebugLoc.CU;
02203     assert(!CU->getRanges().empty());
02204     for (const auto &Entry : DebugLoc.List) {
02205       // Set up the range. This range is relative to the entry point of the
02206       // compile unit. This is a hard coded 0 for low_pc when we're emitting
02207       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
02208       if (CU->getRanges().size() == 1) {
02209         // Grab the begin symbol from the first range as our base.
02210         const MCSymbol *Base = CU->getRanges()[0].getStart();
02211         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
02212         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
02213       } else {
02214         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
02215         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
02216       }
02217 
02218       emitDebugLocEntryLocation(Entry);
02219     }
02220     Asm->OutStreamer.EmitIntValue(0, Size);
02221     Asm->OutStreamer.EmitIntValue(0, Size);
02222   }
02223 }
02224 
02225 void DwarfDebug::emitDebugLocDWO() {
02226   Asm->OutStreamer.SwitchSection(
02227       Asm->getObjFileLowering().getDwarfLocDWOSection());
02228   for (const auto &DebugLoc : DotDebugLocEntries) {
02229     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
02230     for (const auto &Entry : DebugLoc.List) {
02231       // Just always use start_length for now - at least that's one address
02232       // rather than two. We could get fancier and try to, say, reuse an
02233       // address we know we've emitted elsewhere (the start of the function?
02234       // The start of the CU or CU subrange that encloses this range?)
02235       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
02236       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
02237       Asm->EmitULEB128(idx);
02238       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
02239 
02240       emitDebugLocEntryLocation(Entry);
02241     }
02242     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
02243   }
02244 }
02245 
02246 struct ArangeSpan {
02247   const MCSymbol *Start, *End;
02248 };
02249 
02250 // Emit a debug aranges section, containing a CU lookup for any
02251 // address we can tie back to a CU.
02252 void DwarfDebug::emitDebugARanges() {
02253   // Start the dwarf aranges section.
02254   Asm->OutStreamer.SwitchSection(
02255       Asm->getObjFileLowering().getDwarfARangesSection());
02256 
02257   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
02258 
02259   SpansType Spans;
02260 
02261   // Build a list of sections used.
02262   std::vector<const MCSection *> Sections;
02263   for (const auto &it : SectionMap) {
02264     const MCSection *Section = it.first;
02265     Sections.push_back(Section);
02266   }
02267 
02268   // Sort the sections into order.
02269   // This is only done to ensure consistent output order across different runs.
02270   std::sort(Sections.begin(), Sections.end(), SectionSort);
02271 
02272   // Build a set of address spans, sorted by CU.
02273   for (const MCSection *Section : Sections) {
02274     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
02275     if (List.size() < 2)
02276       continue;
02277 
02278     // Sort the symbols by offset within the section.
02279     std::sort(List.begin(), List.end(),
02280               [&](const SymbolCU &A, const SymbolCU &B) {
02281       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
02282       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
02283 
02284       // Symbols with no order assigned should be placed at the end.
02285       // (e.g. section end labels)
02286       if (IA == 0)
02287         return false;
02288       if (IB == 0)
02289         return true;
02290       return IA < IB;
02291     });
02292 
02293     // If we have no section (e.g. common), just write out
02294     // individual spans for each symbol.
02295     if (!Section) {
02296       for (const SymbolCU &Cur : List) {
02297         ArangeSpan Span;
02298         Span.Start = Cur.Sym;
02299         Span.End = nullptr;
02300         if (Cur.CU)
02301           Spans[Cur.CU].push_back(Span);
02302       }
02303     } else {
02304       // Build spans between each label.
02305       const MCSymbol *StartSym = List[0].Sym;
02306       for (size_t n = 1, e = List.size(); n < e; n++) {
02307         const SymbolCU &Prev = List[n - 1];
02308         const SymbolCU &Cur = List[n];
02309 
02310         // Try and build the longest span we can within the same CU.
02311         if (Cur.CU != Prev.CU) {
02312           ArangeSpan Span;
02313           Span.Start = StartSym;
02314           Span.End = Cur.Sym;
02315           Spans[Prev.CU].push_back(Span);
02316           StartSym = Cur.Sym;
02317         }
02318       }
02319     }
02320   }
02321 
02322   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
02323 
02324   // Build a list of CUs used.
02325   std::vector<DwarfCompileUnit *> CUs;
02326   for (const auto &it : Spans) {
02327     DwarfCompileUnit *CU = it.first;
02328     CUs.push_back(CU);
02329   }
02330 
02331   // Sort the CU list (again, to ensure consistent output order).
02332   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
02333     return A->getUniqueID() < B->getUniqueID();
02334   });
02335 
02336   // Emit an arange table for each CU we used.
02337   for (DwarfCompileUnit *CU : CUs) {
02338     std::vector<ArangeSpan> &List = Spans[CU];
02339 
02340     // Emit size of content not including length itself.
02341     unsigned ContentSize =
02342         sizeof(int16_t) + // DWARF ARange version number
02343         sizeof(int32_t) + // Offset of CU in the .debug_info section
02344         sizeof(int8_t) +  // Pointer Size (in bytes)
02345         sizeof(int8_t);   // Segment Size (in bytes)
02346 
02347     unsigned TupleSize = PtrSize * 2;
02348 
02349     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
02350     unsigned Padding =
02351         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
02352 
02353     ContentSize += Padding;
02354     ContentSize += (List.size() + 1) * TupleSize;
02355 
02356     // For each compile unit, write the list of spans it covers.
02357     Asm->OutStreamer.AddComment("Length of ARange Set");
02358     Asm->EmitInt32(ContentSize);
02359     Asm->OutStreamer.AddComment("DWARF Arange version number");
02360     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
02361     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
02362     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
02363     Asm->OutStreamer.AddComment("Address Size (in bytes)");
02364     Asm->EmitInt8(PtrSize);
02365     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
02366     Asm->EmitInt8(0);
02367 
02368     Asm->OutStreamer.EmitFill(Padding, 0xff);
02369 
02370     for (const ArangeSpan &Span : List) {
02371       Asm->EmitLabelReference(Span.Start, PtrSize);
02372 
02373       // Calculate the size as being from the span start to it's end.
02374       if (Span.End) {
02375         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
02376       } else {
02377         // For symbols without an end marker (e.g. common), we
02378         // write a single arange entry containing just that one symbol.
02379         uint64_t Size = SymSize[Span.Start];
02380         if (Size == 0)
02381           Size = 1;
02382 
02383         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
02384       }
02385     }
02386 
02387     Asm->OutStreamer.AddComment("ARange terminator");
02388     Asm->OutStreamer.EmitIntValue(0, PtrSize);
02389     Asm->OutStreamer.EmitIntValue(0, PtrSize);
02390   }
02391 }
02392 
02393 // Emit visible names into a debug ranges section.
02394 void DwarfDebug::emitDebugRanges() {
02395   // Start the dwarf ranges section.
02396   Asm->OutStreamer.SwitchSection(
02397       Asm->getObjFileLowering().getDwarfRangesSection());
02398 
02399   // Size for our labels.
02400   unsigned char Size = Asm->getDataLayout().getPointerSize();
02401 
02402   // Grab the specific ranges for the compile units in the module.
02403   for (const auto &I : CUMap) {
02404     DwarfCompileUnit *TheCU = I.second;
02405 
02406     // Iterate over the misc ranges for the compile units in the module.
02407     for (const RangeSpanList &List : TheCU->getRangeLists()) {
02408       // Emit our symbol so we can find the beginning of the range.
02409       Asm->OutStreamer.EmitLabel(List.getSym());
02410 
02411       for (const RangeSpan &Range : List.getRanges()) {
02412         const MCSymbol *Begin = Range.getStart();
02413         const MCSymbol *End = Range.getEnd();
02414         assert(Begin && "Range without a begin symbol?");
02415         assert(End && "Range without an end symbol?");
02416         if (TheCU->getRanges().size() == 1) {
02417           // Grab the begin symbol from the first range as our base.
02418           const MCSymbol *Base = TheCU->getRanges()[0].getStart();
02419           Asm->EmitLabelDifference(Begin, Base, Size);
02420           Asm->EmitLabelDifference(End, Base, Size);
02421         } else {
02422           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
02423           Asm->OutStreamer.EmitSymbolValue(End, Size);
02424         }
02425       }
02426 
02427       // And terminate the list with two 0 values.
02428       Asm->OutStreamer.EmitIntValue(0, Size);
02429       Asm->OutStreamer.EmitIntValue(0, Size);
02430     }
02431 
02432     // Now emit a range for the CU itself.
02433     if (TheCU->getRanges().size() > 1) {
02434       Asm->OutStreamer.EmitLabel(
02435           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
02436       for (const RangeSpan &Range : TheCU->getRanges()) {
02437         const MCSymbol *Begin = Range.getStart();
02438         const MCSymbol *End = Range.getEnd();
02439         assert(Begin && "Range without a begin symbol?");
02440         assert(End && "Range without an end symbol?");
02441         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
02442         Asm->OutStreamer.EmitSymbolValue(End, Size);
02443       }
02444       // And terminate the list with two 0 values.
02445       Asm->OutStreamer.EmitIntValue(0, Size);
02446       Asm->OutStreamer.EmitIntValue(0, Size);
02447     }
02448   }
02449 }
02450 
02451 // DWARF5 Experimental Separate Dwarf emitters.
02452 
02453 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
02454                                   std::unique_ptr<DwarfUnit> NewU) {
02455   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
02456                        U.getCUNode().getSplitDebugFilename());
02457 
02458   if (!CompilationDir.empty())
02459     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
02460 
02461   addGnuPubAttributes(*NewU, Die);
02462 
02463   SkeletonHolder.addUnit(std::move(NewU));
02464 }
02465 
02466 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
02467 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
02468 // DW_AT_addr_base, DW_AT_ranges_base.
02469 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
02470 
02471   auto OwnedUnit = make_unique<DwarfCompileUnit>(
02472       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
02473   DwarfCompileUnit &NewCU = *OwnedUnit;
02474   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
02475                     DwarfInfoSectionSym);
02476 
02477   NewCU.initStmtList(DwarfLineSectionSym);
02478 
02479   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
02480 
02481   return NewCU;
02482 }
02483 
02484 // Emit the .debug_info.dwo section for separated dwarf. This contains the
02485 // compile units that would normally be in debug_info.
02486 void DwarfDebug::emitDebugInfoDWO() {
02487   assert(useSplitDwarf() && "No split dwarf debug info?");
02488   // Don't pass an abbrev symbol, using a constant zero instead so as not to
02489   // emit relocations into the dwo file.
02490   InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
02491 }
02492 
02493 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
02494 // abbreviations for the .debug_info.dwo section.
02495 void DwarfDebug::emitDebugAbbrevDWO() {
02496   assert(useSplitDwarf() && "No split dwarf?");
02497   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
02498 }
02499 
02500 void DwarfDebug::emitDebugLineDWO() {
02501   assert(useSplitDwarf() && "No split dwarf?");
02502   Asm->OutStreamer.SwitchSection(
02503       Asm->getObjFileLowering().getDwarfLineDWOSection());
02504   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
02505 }
02506 
02507 // Emit the .debug_str.dwo section for separated dwarf. This contains the
02508 // string section and is identical in format to traditional .debug_str
02509 // sections.
02510 void DwarfDebug::emitDebugStrDWO() {
02511   assert(useSplitDwarf() && "No split dwarf?");
02512   const MCSection *OffSec =
02513       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
02514   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
02515                          OffSec);
02516 }
02517 
02518 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
02519   if (!useSplitDwarf())
02520     return nullptr;
02521   if (SingleCU)
02522     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
02523   return &SplitTypeUnitFileTable;
02524 }
02525 
02526 static uint64_t makeTypeSignature(StringRef Identifier) {
02527   MD5 Hash;
02528   Hash.update(Identifier);
02529   // ... take the least significant 8 bytes and return those. Our MD5
02530   // implementation always returns its results in little endian, swap bytes
02531   // appropriately.
02532   MD5::MD5Result Result;
02533   Hash.final(Result);
02534   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
02535 }
02536 
02537 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
02538                                       StringRef Identifier, DIE &RefDie,
02539                                       DICompositeType CTy) {
02540   // Fast path if we're building some type units and one has already used the
02541   // address pool we know we're going to throw away all this work anyway, so
02542   // don't bother building dependent types.
02543   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
02544     return;
02545 
02546   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
02547   if (TU) {
02548     CU.addDIETypeSignature(RefDie, *TU);
02549     return;
02550   }
02551 
02552   bool TopLevelType = TypeUnitsUnderConstruction.empty();
02553   AddrPool.resetUsedFlag();
02554 
02555   auto OwnedUnit = make_unique<DwarfTypeUnit>(
02556       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
02557       this, &InfoHolder, getDwoLineTable(CU));
02558   DwarfTypeUnit &NewTU = *OwnedUnit;
02559   DIE &UnitDie = NewTU.getUnitDie();
02560   TU = &NewTU;
02561   TypeUnitsUnderConstruction.push_back(
02562       std::make_pair(std::move(OwnedUnit), CTy));
02563 
02564   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
02565                 CU.getLanguage());
02566 
02567   uint64_t Signature = makeTypeSignature(Identifier);
02568   NewTU.setTypeSignature(Signature);
02569 
02570   if (useSplitDwarf())
02571     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
02572                       DwarfTypesDWOSectionSym);
02573   else {
02574     CU.applyStmtList(UnitDie);
02575     NewTU.initSection(
02576         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
02577   }
02578 
02579   NewTU.setType(NewTU.createTypeDIE(CTy));
02580 
02581   if (TopLevelType) {
02582     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
02583     TypeUnitsUnderConstruction.clear();
02584 
02585     // Types referencing entries in the address table cannot be placed in type
02586     // units.
02587     if (AddrPool.hasBeenUsed()) {
02588 
02589       // Remove all the types built while building this type.
02590       // This is pessimistic as some of these types might not be dependent on
02591       // the type that used an address.
02592       for (const auto &TU : TypeUnitsToAdd)
02593         DwarfTypeUnits.erase(TU.second);
02594 
02595       // Construct this type in the CU directly.
02596       // This is inefficient because all the dependent types will be rebuilt
02597       // from scratch, including building them in type units, discovering that
02598       // they depend on addresses, throwing them out and rebuilding them.
02599       CU.constructTypeDIE(RefDie, CTy);
02600       return;
02601     }
02602 
02603     // If the type wasn't dependent on fission addresses, finish adding the type
02604     // and all its dependent types.
02605     for (auto &TU : TypeUnitsToAdd)
02606       InfoHolder.addUnit(std::move(TU.first));
02607   }
02608   CU.addDIETypeSignature(RefDie, NewTU);
02609 }
02610 
02611 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
02612                                  const MCSymbol *Begin, const MCSymbol *End) {
02613   assert(Begin && "Begin label should not be null!");
02614   assert(End && "End label should not be null!");
02615   assert(Begin->isDefined() && "Invalid starting label");
02616   assert(End->isDefined() && "Invalid end label");
02617 
02618   Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
02619   if (DwarfVersion < 4)
02620     Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
02621   else
02622     Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
02623 }
02624 
02625 // Accelerator table mutators - add each name along with its companion
02626 // DIE to the proper table while ensuring that the name that we're going
02627 // to reference is in the string table. We do this since the names we
02628 // add may not only be identical to the names in the DIE.
02629 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
02630   if (!useDwarfAccelTables())
02631     return;
02632   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
02633                      &Die);
02634 }
02635 
02636 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
02637   if (!useDwarfAccelTables())
02638     return;
02639   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
02640                     &Die);
02641 }
02642 
02643 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
02644   if (!useDwarfAccelTables())
02645     return;
02646   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
02647                          &Die);
02648 }
02649 
02650 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
02651   if (!useDwarfAccelTables())
02652     return;
02653   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
02654                      &Die);
02655 }