1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
334 LexicalScope *Scope, DIE &ScopeDIE) {
335 // We create children when the scope DIE is not null.
336 SmallVector<std::unique_ptr<DIE>, 8> Children;
337 DIE *ObjectPointer = TheCU.createScopeChildrenDIE(Scope, Children);
340 for (auto &I : Children)
341 ScopeDIE.addChild(std::move(I));
343 return ObjectPointer;
346 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
347 LexicalScope *Scope) {
348 assert(Scope && Scope->getScopeNode());
349 assert(Scope->isAbstractScope());
350 assert(!Scope->getInlinedAt());
352 DISubprogram SP(Scope->getScopeNode());
354 ProcessedSPNodes.insert(SP);
356 DIE *&AbsDef = AbstractSPDies[SP];
360 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
361 // was inlined from another compile unit.
362 DwarfCompileUnit &SPCU = *SPMap[SP];
365 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
366 // the important distinction that the DIDescriptor is not associated with the
367 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
368 // any). It could be refactored to some common utility function.
369 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
370 ContextDIE = &SPCU.getUnitDie();
371 SPCU.getOrCreateSubprogramDIE(SPDecl);
373 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
375 // Passing null as the associated DIDescriptor because the abstract definition
376 // shouldn't be found by lookup.
377 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
379 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
381 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
382 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
383 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
384 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
387 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
388 if (!GenerateGnuPubSections)
391 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
394 // Create new DwarfCompileUnit for the given metadata node with tag
395 // DW_TAG_compile_unit.
396 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
397 StringRef FN = DIUnit.getFilename();
398 CompilationDir = DIUnit.getDirectory();
400 auto OwnedUnit = make_unique<DwarfCompileUnit>(
401 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
402 DwarfCompileUnit &NewCU = *OwnedUnit;
403 DIE &Die = NewCU.getUnitDie();
404 InfoHolder.addUnit(std::move(OwnedUnit));
406 // LTO with assembly output shares a single line table amongst multiple CUs.
407 // To avoid the compilation directory being ambiguous, let the line table
408 // explicitly describe the directory of all files, never relying on the
409 // compilation directory.
410 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
411 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
412 NewCU.getUniqueID(), CompilationDir);
414 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
415 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
416 DIUnit.getLanguage());
417 NewCU.addString(Die, dwarf::DW_AT_name, FN);
419 if (!useSplitDwarf()) {
420 NewCU.initStmtList(DwarfLineSectionSym);
422 // If we're using split dwarf the compilation dir is going to be in the
423 // skeleton CU and so we don't need to duplicate it here.
424 if (!CompilationDir.empty())
425 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
427 addGnuPubAttributes(NewCU, Die);
430 if (DIUnit.isOptimized())
431 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
433 StringRef Flags = DIUnit.getFlags();
435 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
437 if (unsigned RVer = DIUnit.getRunTimeVersion())
438 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
439 dwarf::DW_FORM_data1, RVer);
444 if (useSplitDwarf()) {
445 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
446 DwarfInfoDWOSectionSym);
447 NewCU.setSkeleton(constructSkeletonCU(NewCU));
449 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
450 DwarfInfoSectionSym);
452 CUMap.insert(std::make_pair(DIUnit, &NewCU));
453 CUDieMap.insert(std::make_pair(&Die, &NewCU));
457 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
459 DIImportedEntity Module(N);
460 assert(Module.Verify());
461 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
462 D->addChild(TheCU.constructImportedEntityDIE(Module));
465 // Emit all Dwarf sections that should come prior to the content. Create
466 // global DIEs and emit initial debug info sections. This is invoked by
467 // the target AsmPrinter.
468 void DwarfDebug::beginModule() {
469 if (DisableDebugInfoPrinting)
472 const Module *M = MMI->getModule();
474 FunctionDIs = makeSubprogramMap(*M);
476 // If module has named metadata anchors then use them, otherwise scan the
477 // module using debug info finder to collect debug info.
478 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
481 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
483 // Emit initial sections so we can reference labels later.
486 SingleCU = CU_Nodes->getNumOperands() == 1;
488 for (MDNode *N : CU_Nodes->operands()) {
489 DICompileUnit CUNode(N);
490 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
491 DIArray ImportedEntities = CUNode.getImportedEntities();
492 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
493 ScopesWithImportedEntities.push_back(std::make_pair(
494 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
495 ImportedEntities.getElement(i)));
496 std::sort(ScopesWithImportedEntities.begin(),
497 ScopesWithImportedEntities.end(), less_first());
498 DIArray GVs = CUNode.getGlobalVariables();
499 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
500 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
501 DIArray SPs = CUNode.getSubprograms();
502 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
503 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
504 DIArray EnumTypes = CUNode.getEnumTypes();
505 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
506 DIType Ty(EnumTypes.getElement(i));
507 // The enum types array by design contains pointers to
508 // MDNodes rather than DIRefs. Unique them here.
509 DIType UniqueTy(resolve(Ty.getRef()));
510 CU.getOrCreateTypeDIE(UniqueTy);
512 DIArray RetainedTypes = CUNode.getRetainedTypes();
513 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
514 DIType Ty(RetainedTypes.getElement(i));
515 // The retained types array by design contains pointers to
516 // MDNodes rather than DIRefs. Unique them here.
517 DIType UniqueTy(resolve(Ty.getRef()));
518 CU.getOrCreateTypeDIE(UniqueTy);
520 // Emit imported_modules last so that the relevant context is already
522 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
523 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
526 // Tell MMI that we have debug info.
527 MMI->setDebugInfoAvailability(true);
529 // Prime section data.
530 SectionMap[Asm->getObjFileLowering().getTextSection()];
533 void DwarfDebug::finishVariableDefinitions() {
534 for (const auto &Var : ConcreteVariables) {
535 DIE *VariableDie = Var->getDIE();
537 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
538 // in the ConcreteVariables list, rather than looking it up again here.
539 // DIE::getUnit isn't simple - it walks parent pointers, etc.
540 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
542 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
543 if (AbsVar && AbsVar->getDIE()) {
544 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
547 Unit->applyVariableAttributes(*Var, *VariableDie);
551 void DwarfDebug::finishSubprogramDefinitions() {
552 const Module *M = MMI->getModule();
554 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
555 for (MDNode *N : CU_Nodes->operands()) {
556 DICompileUnit TheCU(N);
557 // Construct subprogram DIE and add variables DIEs.
558 DwarfCompileUnit *SPCU =
559 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
560 DIArray Subprograms = TheCU.getSubprograms();
561 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
562 DISubprogram SP(Subprograms.getElement(i));
563 // Perhaps the subprogram is in another CU (such as due to comdat
564 // folding, etc), in which case ignore it here.
565 if (SPMap[SP] != SPCU)
567 DIE *D = SPCU->getDIE(SP);
568 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
570 // If this subprogram has an abstract definition, reference that
571 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
573 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
574 // Lazily construct the subprogram if we didn't see either concrete or
575 // inlined versions during codegen. (except in -gmlt ^ where we want
576 // to omit these entirely)
577 D = SPCU->getOrCreateSubprogramDIE(SP);
579 // And attach the attributes
580 SPCU->applySubprogramAttributesToDefinition(SP, *D);
587 // Collect info for variables that were optimized out.
588 void DwarfDebug::collectDeadVariables() {
589 const Module *M = MMI->getModule();
591 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
592 for (MDNode *N : CU_Nodes->operands()) {
593 DICompileUnit TheCU(N);
594 // Construct subprogram DIE and add variables DIEs.
595 DwarfCompileUnit *SPCU =
596 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
597 assert(SPCU && "Unable to find Compile Unit!");
598 DIArray Subprograms = TheCU.getSubprograms();
599 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
600 DISubprogram SP(Subprograms.getElement(i));
601 if (ProcessedSPNodes.count(SP) != 0)
603 assert(SP.isSubprogram() &&
604 "CU's subprogram list contains a non-subprogram");
605 assert(SP.isDefinition() &&
606 "CU's subprogram list contains a subprogram declaration");
607 DIArray Variables = SP.getVariables();
608 if (Variables.getNumElements() == 0)
611 DIE *SPDIE = AbstractSPDies.lookup(SP);
613 SPDIE = SPCU->getDIE(SP);
615 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
616 DIVariable DV(Variables.getElement(vi));
617 assert(DV.isVariable());
618 DbgVariable NewVar(DV, DIExpression(nullptr), this);
619 auto VariableDie = SPCU->constructVariableDIE(NewVar);
620 SPCU->applyVariableAttributes(NewVar, *VariableDie);
621 SPDIE->addChild(std::move(VariableDie));
628 void DwarfDebug::finalizeModuleInfo() {
629 finishSubprogramDefinitions();
631 finishVariableDefinitions();
633 // Collect info for variables that were optimized out.
634 collectDeadVariables();
636 // Handle anything that needs to be done on a per-unit basis after
637 // all other generation.
638 for (const auto &TheU : getUnits()) {
639 // Emit DW_AT_containing_type attribute to connect types with their
640 // vtable holding type.
641 TheU->constructContainingTypeDIEs();
643 // Add CU specific attributes if we need to add any.
644 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
645 // If we're splitting the dwarf out now that we've got the entire
646 // CU then add the dwo id to it.
647 DwarfCompileUnit *SkCU =
648 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
649 if (useSplitDwarf()) {
650 // Emit a unique identifier for this CU.
651 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
652 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
653 dwarf::DW_FORM_data8, ID);
654 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
655 dwarf::DW_FORM_data8, ID);
657 // We don't keep track of which addresses are used in which CU so this
658 // is a bit pessimistic under LTO.
659 if (!AddrPool.isEmpty())
660 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
661 DwarfAddrSectionSym, DwarfAddrSectionSym);
662 if (!TheU->getRangeLists().empty())
663 SkCU->addSectionLabel(
664 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
665 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
668 // If we have code split among multiple sections or non-contiguous
669 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
670 // remain in the .o file, otherwise add a DW_AT_low_pc.
671 // FIXME: We should use ranges allow reordering of code ala
672 // .subsections_via_symbols in mach-o. This would mean turning on
673 // ranges for all subprogram DIEs for mach-o.
674 DwarfCompileUnit &U =
675 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
676 unsigned NumRanges = TheU->getRanges().size();
679 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
680 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
681 DwarfDebugRangeSectionSym);
683 // A DW_AT_low_pc attribute may also be specified in combination with
684 // DW_AT_ranges to specify the default base address for use in
685 // location lists (see Section 2.6.2) and range lists (see Section
687 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
690 RangeSpan &Range = TheU->getRanges().back();
691 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
697 // Compute DIE offsets and sizes.
698 InfoHolder.computeSizeAndOffsets();
700 SkeletonHolder.computeSizeAndOffsets();
703 void DwarfDebug::endSections() {
704 // Filter labels by section.
705 for (const SymbolCU &SCU : ArangeLabels) {
706 if (SCU.Sym->isInSection()) {
707 // Make a note of this symbol and it's section.
708 const MCSection *Section = &SCU.Sym->getSection();
709 if (!Section->getKind().isMetadata())
710 SectionMap[Section].push_back(SCU);
712 // Some symbols (e.g. common/bss on mach-o) can have no section but still
713 // appear in the output. This sucks as we rely on sections to build
714 // arange spans. We can do it without, but it's icky.
715 SectionMap[nullptr].push_back(SCU);
719 // Build a list of sections used.
720 std::vector<const MCSection *> Sections;
721 for (const auto &it : SectionMap) {
722 const MCSection *Section = it.first;
723 Sections.push_back(Section);
726 // Sort the sections into order.
727 // This is only done to ensure consistent output order across different runs.
728 std::sort(Sections.begin(), Sections.end(), SectionSort);
730 // Add terminating symbols for each section.
731 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
732 const MCSection *Section = Sections[ID];
733 MCSymbol *Sym = nullptr;
736 // We can't call MCSection::getLabelEndName, as it's only safe to do so
737 // if we know the section name up-front. For user-created sections, the
738 // resulting label may not be valid to use as a label. (section names can
739 // use a greater set of characters on some systems)
740 Sym = Asm->GetTempSymbol("debug_end", ID);
741 Asm->OutStreamer.SwitchSection(Section);
742 Asm->OutStreamer.EmitLabel(Sym);
745 // Insert a final terminator.
746 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
750 // Emit all Dwarf sections that should come after the content.
751 void DwarfDebug::endModule() {
752 assert(CurFn == nullptr);
753 assert(CurMI == nullptr);
758 // End any existing sections.
759 // TODO: Does this need to happen?
762 // Finalize the debug info for the module.
763 finalizeModuleInfo();
767 // Emit all the DIEs into a debug info section.
770 // Corresponding abbreviations into a abbrev section.
773 // Emit info into a debug aranges section.
774 if (GenerateARangeSection)
777 // Emit info into a debug ranges section.
780 if (useSplitDwarf()) {
783 emitDebugAbbrevDWO();
786 // Emit DWO addresses.
787 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
789 // Emit info into a debug loc section.
792 // Emit info into the dwarf accelerator table sections.
793 if (useDwarfAccelTables()) {
796 emitAccelNamespaces();
800 // Emit the pubnames and pubtypes sections if requested.
801 if (HasDwarfPubSections) {
802 emitDebugPubNames(GenerateGnuPubSections);
803 emitDebugPubTypes(GenerateGnuPubSections);
808 AbstractVariables.clear();
810 // Reset these for the next Module if we have one.
814 // Find abstract variable, if any, associated with Var.
815 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
816 DIVariable &Cleansed) {
817 LLVMContext &Ctx = DV->getContext();
818 // More then one inlined variable corresponds to one abstract variable.
819 // FIXME: This duplication of variables when inlining should probably be
820 // removed. It's done to allow each DIVariable to describe its location
821 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
822 // make it accurate then remove this duplication/cleansing stuff.
823 Cleansed = cleanseInlinedVariable(DV, Ctx);
824 auto I = AbstractVariables.find(Cleansed);
825 if (I != AbstractVariables.end())
826 return I->second.get();
830 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
832 return getExistingAbstractVariable(DV, Cleansed);
835 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
836 LexicalScope *Scope) {
837 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
838 addScopeVariable(Scope, AbsDbgVariable.get());
839 AbstractVariables[Var] = std::move(AbsDbgVariable);
842 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
843 const MDNode *ScopeNode) {
844 DIVariable Cleansed = DV;
845 if (getExistingAbstractVariable(DV, Cleansed))
848 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
852 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
853 const MDNode *ScopeNode) {
854 DIVariable Cleansed = DV;
855 if (getExistingAbstractVariable(DV, Cleansed))
858 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
859 createAbstractVariable(Cleansed, Scope);
862 // If Var is a current function argument then add it to CurrentFnArguments list.
863 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
864 if (!LScopes.isCurrentFunctionScope(Scope))
866 DIVariable DV = Var->getVariable();
867 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
869 unsigned ArgNo = DV.getArgNumber();
873 size_t Size = CurrentFnArguments.size();
875 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
876 // llvm::Function argument size is not good indicator of how many
877 // arguments does the function have at source level.
879 CurrentFnArguments.resize(ArgNo * 2);
880 assert(!CurrentFnArguments[ArgNo - 1]);
881 CurrentFnArguments[ArgNo - 1] = Var;
885 // Collect variable information from side table maintained by MMI.
886 void DwarfDebug::collectVariableInfoFromMMITable(
887 SmallPtrSetImpl<const MDNode *> &Processed) {
888 for (const auto &VI : MMI->getVariableDbgInfo()) {
891 Processed.insert(VI.Var);
892 DIVariable DV(VI.Var);
893 DIExpression Expr(VI.Expr);
894 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
896 // If variable scope is not found then skip this variable.
900 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
901 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
902 DbgVariable *RegVar = ConcreteVariables.back().get();
903 RegVar->setFrameIndex(VI.Slot);
904 addScopeVariable(Scope, RegVar);
908 // Get .debug_loc entry for the instruction range starting at MI.
909 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
910 const MDNode *Expr = MI->getDebugExpression();
911 const MDNode *Var = MI->getDebugVariable();
913 assert(MI->getNumOperands() == 4);
914 if (MI->getOperand(0).isReg()) {
915 MachineLocation MLoc;
916 // If the second operand is an immediate, this is a
917 // register-indirect address.
918 if (!MI->getOperand(1).isImm())
919 MLoc.set(MI->getOperand(0).getReg());
921 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
922 return DebugLocEntry::Value(Var, Expr, MLoc);
924 if (MI->getOperand(0).isImm())
925 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
926 if (MI->getOperand(0).isFPImm())
927 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
928 if (MI->getOperand(0).isCImm())
929 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
931 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
934 /// Determine whether two variable pieces overlap.
935 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
936 if (!P1.isVariablePiece() || !P2.isVariablePiece())
938 unsigned l1 = P1.getPieceOffset();
939 unsigned l2 = P2.getPieceOffset();
940 unsigned r1 = l1 + P1.getPieceSize();
941 unsigned r2 = l2 + P2.getPieceSize();
942 // True where [l1,r1[ and [r1,r2[ overlap.
943 return (l1 < r2) && (l2 < r1);
946 /// Build the location list for all DBG_VALUEs in the function that
947 /// describe the same variable. If the ranges of several independent
948 /// pieces of the same variable overlap partially, split them up and
949 /// combine the ranges. The resulting DebugLocEntries are will have
950 /// strict monotonically increasing begin addresses and will never
955 // Ranges History [var, loc, piece ofs size]
956 // 0 | [x, (reg0, piece 0, 32)]
957 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
959 // 3 | [clobber reg0]
960 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
964 // [0-1] [x, (reg0, piece 0, 32)]
965 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
966 // [3-4] [x, (reg1, piece 32, 32)]
967 // [4- ] [x, (mem, piece 0, 64)]
969 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
970 const DbgValueHistoryMap::InstrRanges &Ranges) {
971 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
973 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
974 const MachineInstr *Begin = I->first;
975 const MachineInstr *End = I->second;
976 assert(Begin->isDebugValue() && "Invalid History entry");
978 // Check if a variable is inaccessible in this range.
979 if (Begin->getNumOperands() > 1 &&
980 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
985 // If this piece overlaps with any open ranges, truncate them.
986 DIExpression DIExpr = Begin->getDebugExpression();
987 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
988 [&](DebugLocEntry::Value R) {
989 return piecesOverlap(DIExpr, R.getExpression());
991 OpenRanges.erase(Last, OpenRanges.end());
993 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
994 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
996 const MCSymbol *EndLabel;
998 EndLabel = getLabelAfterInsn(End);
999 else if (std::next(I) == Ranges.end())
1000 EndLabel = FunctionEndSym;
1002 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1003 assert(EndLabel && "Forgot label after instruction ending a range!");
1005 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1007 auto Value = getDebugLocValue(Begin);
1008 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1009 bool couldMerge = false;
1011 // If this is a piece, it may belong to the current DebugLocEntry.
1012 if (DIExpr.isVariablePiece()) {
1013 // Add this value to the list of open ranges.
1014 OpenRanges.push_back(Value);
1016 // Attempt to add the piece to the last entry.
1017 if (!DebugLoc.empty())
1018 if (DebugLoc.back().MergeValues(Loc))
1023 // Need to add a new DebugLocEntry. Add all values from still
1024 // valid non-overlapping pieces.
1025 if (OpenRanges.size())
1026 Loc.addValues(OpenRanges);
1028 DebugLoc.push_back(std::move(Loc));
1031 // Attempt to coalesce the ranges of two otherwise identical
1033 auto CurEntry = DebugLoc.rbegin();
1034 auto PrevEntry = std::next(CurEntry);
1035 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1036 DebugLoc.pop_back();
1039 dbgs() << CurEntry->getValues().size() << " Values:\n";
1040 for (auto Value : CurEntry->getValues()) {
1041 Value.getVariable()->dump();
1042 Value.getExpression()->dump();
1044 dbgs() << "-----\n";
1050 // Find variables for each lexical scope.
1052 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1053 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1054 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1056 // Grab the variable info that was squirreled away in the MMI side-table.
1057 collectVariableInfoFromMMITable(Processed);
1059 for (const auto &I : DbgValues) {
1060 DIVariable DV(I.first);
1061 if (Processed.count(DV))
1064 // Instruction ranges, specifying where DV is accessible.
1065 const auto &Ranges = I.second;
1069 LexicalScope *Scope = nullptr;
1070 if (MDNode *IA = DV.getInlinedAt()) {
1071 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1072 Scope = LScopes.findInlinedScope(DebugLoc::get(
1073 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1075 Scope = LScopes.findLexicalScope(DV.getContext());
1076 // If variable scope is not found then skip this variable.
1080 Processed.insert(DV);
1081 const MachineInstr *MInsn = Ranges.front().first;
1082 assert(MInsn->isDebugValue() && "History must begin with debug value");
1083 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1084 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1085 DbgVariable *RegVar = ConcreteVariables.back().get();
1086 addScopeVariable(Scope, RegVar);
1088 // Check if the first DBG_VALUE is valid for the rest of the function.
1089 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1092 // Handle multiple DBG_VALUE instructions describing one variable.
1093 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1095 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1096 DebugLocList &LocList = DotDebugLocEntries.back();
1099 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1101 // Build the location list for this variable.
1102 buildLocationList(LocList.List, Ranges);
1105 // Collect info for variables that were optimized out.
1106 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1107 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1108 DIVariable DV(Variables.getElement(i));
1109 assert(DV.isVariable());
1110 if (!Processed.insert(DV))
1112 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1113 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1114 DIExpression NoExpr;
1115 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1116 addScopeVariable(Scope, ConcreteVariables.back().get());
1121 // Return Label preceding the instruction.
1122 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1123 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1124 assert(Label && "Didn't insert label before instruction");
1128 // Return Label immediately following the instruction.
1129 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1130 return LabelsAfterInsn.lookup(MI);
1133 // Process beginning of an instruction.
1134 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1135 assert(CurMI == nullptr);
1137 // Check if source location changes, but ignore DBG_VALUE locations.
1138 if (!MI->isDebugValue()) {
1139 DebugLoc DL = MI->getDebugLoc();
1140 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1143 if (DL == PrologEndLoc) {
1144 Flags |= DWARF2_FLAG_PROLOGUE_END;
1145 PrologEndLoc = DebugLoc();
1147 if (PrologEndLoc.isUnknown())
1148 Flags |= DWARF2_FLAG_IS_STMT;
1150 if (!DL.isUnknown()) {
1151 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1152 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1154 recordSourceLine(0, 0, nullptr, 0);
1158 // Insert labels where requested.
1159 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1160 LabelsBeforeInsn.find(MI);
1163 if (I == LabelsBeforeInsn.end())
1166 // Label already assigned.
1171 PrevLabel = MMI->getContext().CreateTempSymbol();
1172 Asm->OutStreamer.EmitLabel(PrevLabel);
1174 I->second = PrevLabel;
1177 // Process end of an instruction.
1178 void DwarfDebug::endInstruction() {
1179 assert(CurMI != nullptr);
1180 // Don't create a new label after DBG_VALUE instructions.
1181 // They don't generate code.
1182 if (!CurMI->isDebugValue())
1183 PrevLabel = nullptr;
1185 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1186 LabelsAfterInsn.find(CurMI);
1190 if (I == LabelsAfterInsn.end())
1193 // Label already assigned.
1197 // We need a label after this instruction.
1199 PrevLabel = MMI->getContext().CreateTempSymbol();
1200 Asm->OutStreamer.EmitLabel(PrevLabel);
1202 I->second = PrevLabel;
1205 // Each LexicalScope has first instruction and last instruction to mark
1206 // beginning and end of a scope respectively. Create an inverse map that list
1207 // scopes starts (and ends) with an instruction. One instruction may start (or
1208 // end) multiple scopes. Ignore scopes that are not reachable.
1209 void DwarfDebug::identifyScopeMarkers() {
1210 SmallVector<LexicalScope *, 4> WorkList;
1211 WorkList.push_back(LScopes.getCurrentFunctionScope());
1212 while (!WorkList.empty()) {
1213 LexicalScope *S = WorkList.pop_back_val();
1215 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1216 if (!Children.empty())
1217 WorkList.append(Children.begin(), Children.end());
1219 if (S->isAbstractScope())
1222 for (const InsnRange &R : S->getRanges()) {
1223 assert(R.first && "InsnRange does not have first instruction!");
1224 assert(R.second && "InsnRange does not have second instruction!");
1225 requestLabelBeforeInsn(R.first);
1226 requestLabelAfterInsn(R.second);
1231 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1232 // First known non-DBG_VALUE and non-frame setup location marks
1233 // the beginning of the function body.
1234 for (const auto &MBB : *MF)
1235 for (const auto &MI : MBB)
1236 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1237 !MI.getDebugLoc().isUnknown())
1238 return MI.getDebugLoc();
1242 // Gather pre-function debug information. Assumes being called immediately
1243 // after the function entry point has been emitted.
1244 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1247 // If there's no debug info for the function we're not going to do anything.
1248 if (!MMI->hasDebugInfo())
1251 auto DI = FunctionDIs.find(MF->getFunction());
1252 if (DI == FunctionDIs.end())
1255 // Grab the lexical scopes for the function, if we don't have any of those
1256 // then we're not going to be able to do anything.
1257 LScopes.initialize(*MF);
1258 if (LScopes.empty())
1261 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1263 // Make sure that each lexical scope will have a begin/end label.
1264 identifyScopeMarkers();
1266 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1267 // belongs to so that we add to the correct per-cu line table in the
1269 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1270 // FnScope->getScopeNode() and DI->second should represent the same function,
1271 // though they may not be the same MDNode due to inline functions merged in
1272 // LTO where the debug info metadata still differs (either due to distinct
1273 // written differences - two versions of a linkonce_odr function
1274 // written/copied into two separate files, or some sub-optimal metadata that
1275 // isn't structurally identical (see: file path/name info from clang, which
1276 // includes the directory of the cpp file being built, even when the file name
1277 // is absolute (such as an <> lookup header)))
1278 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1279 assert(TheCU && "Unable to find compile unit!");
1280 if (Asm->OutStreamer.hasRawTextSupport())
1281 // Use a single line table if we are generating assembly.
1282 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1284 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1286 // Emit a label for the function so that we have a beginning address.
1287 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1288 // Assumes in correct section after the entry point.
1289 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1291 // Calculate history for local variables.
1292 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1295 // Request labels for the full history.
1296 for (const auto &I : DbgValues) {
1297 const auto &Ranges = I.second;
1301 // The first mention of a function argument gets the FunctionBeginSym
1302 // label, so arguments are visible when breaking at function entry.
1303 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1304 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1305 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1306 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1307 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1308 // Mark all non-overlapping initial pieces.
1309 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1310 DIExpression Piece = I->first->getDebugExpression();
1311 if (std::all_of(Ranges.begin(), I,
1312 [&](DbgValueHistoryMap::InstrRange Pred) {
1313 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1315 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1322 for (const auto &Range : Ranges) {
1323 requestLabelBeforeInsn(Range.first);
1325 requestLabelAfterInsn(Range.second);
1329 PrevInstLoc = DebugLoc();
1330 PrevLabel = FunctionBeginSym;
1332 // Record beginning of function.
1333 PrologEndLoc = findPrologueEndLoc(MF);
1334 if (!PrologEndLoc.isUnknown()) {
1335 DebugLoc FnStartDL =
1336 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1338 FnStartDL.getLine(), FnStartDL.getCol(),
1339 FnStartDL.getScope(MF->getFunction()->getContext()),
1340 // We'd like to list the prologue as "not statements" but GDB behaves
1341 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1342 DWARF2_FLAG_IS_STMT);
1346 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1347 if (addCurrentFnArgument(Var, LS))
1349 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1350 DIVariable DV = Var->getVariable();
1351 // Variables with positive arg numbers are parameters.
1352 if (unsigned ArgNum = DV.getArgNumber()) {
1353 // Keep all parameters in order at the start of the variable list to ensure
1354 // function types are correct (no out-of-order parameters)
1356 // This could be improved by only doing it for optimized builds (unoptimized
1357 // builds have the right order to begin with), searching from the back (this
1358 // would catch the unoptimized case quickly), or doing a binary search
1359 // rather than linear search.
1360 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1361 while (I != Vars.end()) {
1362 unsigned CurNum = (*I)->getVariable().getArgNumber();
1363 // A local (non-parameter) variable has been found, insert immediately
1367 // A later indexed parameter has been found, insert immediately before it.
1368 if (CurNum > ArgNum)
1372 Vars.insert(I, Var);
1376 Vars.push_back(Var);
1379 // Gather and emit post-function debug information.
1380 void DwarfDebug::endFunction(const MachineFunction *MF) {
1381 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1382 // though the beginFunction may not be called at all.
1383 // We should handle both cases.
1387 assert(CurFn == MF);
1388 assert(CurFn != nullptr);
1390 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1391 !FunctionDIs.count(MF->getFunction())) {
1392 // If we don't have a lexical scope for this function then there will
1393 // be a hole in the range information. Keep note of this by setting the
1394 // previously used section to nullptr.
1400 // Define end label for subprogram.
1401 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1402 // Assumes in correct section after the entry point.
1403 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1405 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1406 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1408 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1409 collectVariableInfo(ProcessedVars);
1411 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1412 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1414 // Add the range of this function to the list of ranges for the CU.
1415 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1417 // Under -gmlt, skip building the subprogram if there are no inlined
1418 // subroutines inside it.
1419 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1420 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1421 assert(ScopeVariables.empty());
1422 assert(CurrentFnArguments.empty());
1423 assert(DbgValues.empty());
1424 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1425 // by a -gmlt CU. Add a test and remove this assertion.
1426 assert(AbstractVariables.empty());
1427 LabelsBeforeInsn.clear();
1428 LabelsAfterInsn.clear();
1429 PrevLabel = nullptr;
1434 // Construct abstract scopes.
1435 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1436 DISubprogram SP(AScope->getScopeNode());
1437 assert(SP.isSubprogram());
1438 // Collect info for variables that were optimized out.
1439 DIArray Variables = SP.getVariables();
1440 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1441 DIVariable DV(Variables.getElement(i));
1442 assert(DV && DV.isVariable());
1443 if (!ProcessedVars.insert(DV))
1445 ensureAbstractVariableIsCreated(DV, DV.getContext());
1447 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1450 TheCU.constructSubprogramScopeDIE(FnScope);
1453 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1454 // DbgVariables except those that are also in AbstractVariables (since they
1455 // can be used cross-function)
1456 ScopeVariables.clear();
1457 CurrentFnArguments.clear();
1459 LabelsBeforeInsn.clear();
1460 LabelsAfterInsn.clear();
1461 PrevLabel = nullptr;
1465 // Register a source line with debug info. Returns the unique label that was
1466 // emitted and which provides correspondence to the source line list.
1467 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1472 unsigned Discriminator = 0;
1473 if (DIScope Scope = DIScope(S)) {
1474 assert(Scope.isScope());
1475 Fn = Scope.getFilename();
1476 Dir = Scope.getDirectory();
1477 if (Scope.isLexicalBlockFile())
1478 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1480 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1481 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1482 .getOrCreateSourceID(Fn, Dir);
1484 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1488 //===----------------------------------------------------------------------===//
1490 //===----------------------------------------------------------------------===//
1492 // Emit initial Dwarf sections with a label at the start of each one.
1493 void DwarfDebug::emitSectionLabels() {
1494 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1496 // Dwarf sections base addresses.
1497 DwarfInfoSectionSym =
1498 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1499 if (useSplitDwarf()) {
1500 DwarfInfoDWOSectionSym =
1501 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1502 DwarfTypesDWOSectionSym =
1503 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1505 DwarfAbbrevSectionSym =
1506 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1507 if (useSplitDwarf())
1508 DwarfAbbrevDWOSectionSym = emitSectionSym(
1509 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1510 if (GenerateARangeSection)
1511 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1513 DwarfLineSectionSym =
1514 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1515 if (GenerateGnuPubSections) {
1516 DwarfGnuPubNamesSectionSym =
1517 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1518 DwarfGnuPubTypesSectionSym =
1519 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1520 } else if (HasDwarfPubSections) {
1521 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1522 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1525 DwarfStrSectionSym =
1526 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1527 if (useSplitDwarf()) {
1528 DwarfStrDWOSectionSym =
1529 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1530 DwarfAddrSectionSym =
1531 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1532 DwarfDebugLocSectionSym =
1533 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1535 DwarfDebugLocSectionSym =
1536 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1537 DwarfDebugRangeSectionSym =
1538 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1541 // Recursively emits a debug information entry.
1542 void DwarfDebug::emitDIE(DIE &Die) {
1543 // Get the abbreviation for this DIE.
1544 const DIEAbbrev &Abbrev = Die.getAbbrev();
1546 // Emit the code (index) for the abbreviation.
1547 if (Asm->isVerbose())
1548 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1549 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1550 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1551 dwarf::TagString(Abbrev.getTag()));
1552 Asm->EmitULEB128(Abbrev.getNumber());
1554 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1555 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1557 // Emit the DIE attribute values.
1558 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1559 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1560 dwarf::Form Form = AbbrevData[i].getForm();
1561 assert(Form && "Too many attributes for DIE (check abbreviation)");
1563 if (Asm->isVerbose()) {
1564 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1565 if (Attr == dwarf::DW_AT_accessibility)
1566 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1567 cast<DIEInteger>(Values[i])->getValue()));
1570 // Emit an attribute using the defined form.
1571 Values[i]->EmitValue(Asm, Form);
1574 // Emit the DIE children if any.
1575 if (Abbrev.hasChildren()) {
1576 for (auto &Child : Die.getChildren())
1579 Asm->OutStreamer.AddComment("End Of Children Mark");
1584 // Emit the debug info section.
1585 void DwarfDebug::emitDebugInfo() {
1586 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1588 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1591 // Emit the abbreviation section.
1592 void DwarfDebug::emitAbbreviations() {
1593 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1595 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1598 // Emit the last address of the section and the end of the line matrix.
1599 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1600 // Define last address of section.
1601 Asm->OutStreamer.AddComment("Extended Op");
1604 Asm->OutStreamer.AddComment("Op size");
1605 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1606 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1607 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1609 Asm->OutStreamer.AddComment("Section end label");
1611 Asm->OutStreamer.EmitSymbolValue(
1612 Asm->GetTempSymbol("section_end", SectionEnd),
1613 Asm->getDataLayout().getPointerSize());
1615 // Mark end of matrix.
1616 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1622 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1623 StringRef TableName, StringRef SymName) {
1624 Accel.FinalizeTable(Asm, TableName);
1625 Asm->OutStreamer.SwitchSection(Section);
1626 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1627 Asm->OutStreamer.EmitLabel(SectionBegin);
1629 // Emit the full data.
1630 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1633 // Emit visible names into a hashed accelerator table section.
1634 void DwarfDebug::emitAccelNames() {
1635 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1636 "Names", "names_begin");
1639 // Emit objective C classes and categories into a hashed accelerator table
1641 void DwarfDebug::emitAccelObjC() {
1642 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1643 "ObjC", "objc_begin");
1646 // Emit namespace dies into a hashed accelerator table.
1647 void DwarfDebug::emitAccelNamespaces() {
1648 emitAccel(AccelNamespace,
1649 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1650 "namespac", "namespac_begin");
1653 // Emit type dies into a hashed accelerator table.
1654 void DwarfDebug::emitAccelTypes() {
1655 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1656 "types", "types_begin");
1659 // Public name handling.
1660 // The format for the various pubnames:
1662 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1663 // for the DIE that is named.
1665 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1666 // into the CU and the index value is computed according to the type of value
1667 // for the DIE that is named.
1669 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1670 // it's the offset within the debug_info/debug_types dwo section, however, the
1671 // reference in the pubname header doesn't change.
1673 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1674 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1676 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1678 // We could have a specification DIE that has our most of our knowledge,
1679 // look for that now.
1680 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1682 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1683 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1684 Linkage = dwarf::GIEL_EXTERNAL;
1685 } else if (Die->findAttribute(dwarf::DW_AT_external))
1686 Linkage = dwarf::GIEL_EXTERNAL;
1688 switch (Die->getTag()) {
1689 case dwarf::DW_TAG_class_type:
1690 case dwarf::DW_TAG_structure_type:
1691 case dwarf::DW_TAG_union_type:
1692 case dwarf::DW_TAG_enumeration_type:
1693 return dwarf::PubIndexEntryDescriptor(
1694 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1695 ? dwarf::GIEL_STATIC
1696 : dwarf::GIEL_EXTERNAL);
1697 case dwarf::DW_TAG_typedef:
1698 case dwarf::DW_TAG_base_type:
1699 case dwarf::DW_TAG_subrange_type:
1700 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1701 case dwarf::DW_TAG_namespace:
1702 return dwarf::GIEK_TYPE;
1703 case dwarf::DW_TAG_subprogram:
1704 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1705 case dwarf::DW_TAG_constant:
1706 case dwarf::DW_TAG_variable:
1707 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1708 case dwarf::DW_TAG_enumerator:
1709 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1710 dwarf::GIEL_STATIC);
1712 return dwarf::GIEK_NONE;
1716 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1718 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1719 const MCSection *PSec =
1720 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1721 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1723 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1726 void DwarfDebug::emitDebugPubSection(
1727 bool GnuStyle, const MCSection *PSec, StringRef Name,
1728 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1729 for (const auto &NU : CUMap) {
1730 DwarfCompileUnit *TheU = NU.second;
1732 const auto &Globals = (TheU->*Accessor)();
1734 if (Globals.empty())
1737 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1739 unsigned ID = TheU->getUniqueID();
1741 // Start the dwarf pubnames section.
1742 Asm->OutStreamer.SwitchSection(PSec);
1745 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1746 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1747 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1748 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1750 Asm->OutStreamer.EmitLabel(BeginLabel);
1752 Asm->OutStreamer.AddComment("DWARF Version");
1753 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1755 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1756 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1758 Asm->OutStreamer.AddComment("Compilation Unit Length");
1759 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1761 // Emit the pubnames for this compilation unit.
1762 for (const auto &GI : Globals) {
1763 const char *Name = GI.getKeyData();
1764 const DIE *Entity = GI.second;
1766 Asm->OutStreamer.AddComment("DIE offset");
1767 Asm->EmitInt32(Entity->getOffset());
1770 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1771 Asm->OutStreamer.AddComment(
1772 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1773 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1774 Asm->EmitInt8(Desc.toBits());
1777 Asm->OutStreamer.AddComment("External Name");
1778 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1781 Asm->OutStreamer.AddComment("End Mark");
1783 Asm->OutStreamer.EmitLabel(EndLabel);
1787 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1788 const MCSection *PSec =
1789 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1790 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1792 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1795 // Emit visible names into a debug str section.
1796 void DwarfDebug::emitDebugStr() {
1797 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1798 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1801 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1802 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1803 const DITypeIdentifierMap &Map,
1804 ArrayRef<DebugLocEntry::Value> Values) {
1805 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1806 return P.isVariablePiece();
1807 }) && "all values are expected to be pieces");
1808 assert(std::is_sorted(Values.begin(), Values.end()) &&
1809 "pieces are expected to be sorted");
1811 unsigned Offset = 0;
1812 for (auto Piece : Values) {
1813 DIExpression Expr = Piece.getExpression();
1814 unsigned PieceOffset = Expr.getPieceOffset();
1815 unsigned PieceSize = Expr.getPieceSize();
1816 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1817 if (Offset < PieceOffset) {
1818 // The DWARF spec seriously mandates pieces with no locations for gaps.
1819 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1820 Offset += PieceOffset-Offset;
1823 Offset += PieceSize;
1825 const unsigned SizeOfByte = 8;
1827 DIVariable Var = Piece.getVariable();
1828 assert(!Var.isIndirect() && "indirect address for piece");
1829 unsigned VarSize = Var.getSizeInBits(Map);
1830 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1831 && "piece is larger than or outside of variable");
1832 assert(PieceSize*SizeOfByte != VarSize
1833 && "piece covers entire variable");
1835 if (Piece.isLocation() && Piece.getLoc().isReg())
1836 Asm->EmitDwarfRegOpPiece(Streamer,
1838 PieceSize*SizeOfByte);
1840 emitDebugLocValue(Streamer, Piece);
1841 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1847 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1848 const DebugLocEntry &Entry) {
1849 const DebugLocEntry::Value Value = Entry.getValues()[0];
1850 if (Value.isVariablePiece())
1851 // Emit all pieces that belong to the same variable and range.
1852 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1854 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1855 emitDebugLocValue(Streamer, Value);
1858 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1859 const DebugLocEntry::Value &Value) {
1860 DIVariable DV = Value.getVariable();
1862 if (Value.isInt()) {
1863 DIBasicType BTy(resolve(DV.getType()));
1864 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1865 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1866 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1867 Streamer.EmitSLEB128(Value.getInt());
1869 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1870 Streamer.EmitULEB128(Value.getInt());
1872 } else if (Value.isLocation()) {
1873 MachineLocation Loc = Value.getLoc();
1874 DIExpression Expr = Value.getExpression();
1877 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1879 // Complex address entry.
1880 unsigned N = Expr.getNumElements();
1882 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1883 if (Loc.getOffset()) {
1885 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1886 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1887 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1888 Streamer.EmitSLEB128(Expr.getElement(1));
1890 // If first address element is OpPlus then emit
1891 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1892 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1893 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1897 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1900 // Emit remaining complex address elements.
1901 for (; i < N; ++i) {
1902 uint64_t Element = Expr.getElement(i);
1903 if (Element == dwarf::DW_OP_plus) {
1904 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1905 Streamer.EmitULEB128(Expr.getElement(++i));
1906 } else if (Element == dwarf::DW_OP_deref) {
1908 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1909 } else if (Element == dwarf::DW_OP_piece) {
1911 // handled in emitDebugLocEntry.
1913 llvm_unreachable("unknown Opcode found in complex address");
1917 // else ... ignore constant fp. There is not any good way to
1918 // to represent them here in dwarf.
1922 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1923 Asm->OutStreamer.AddComment("Loc expr size");
1924 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1925 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1926 Asm->EmitLabelDifference(end, begin, 2);
1927 Asm->OutStreamer.EmitLabel(begin);
1929 APByteStreamer Streamer(*Asm);
1930 emitDebugLocEntry(Streamer, Entry);
1932 Asm->OutStreamer.EmitLabel(end);
1935 // Emit locations into the debug loc section.
1936 void DwarfDebug::emitDebugLoc() {
1937 // Start the dwarf loc section.
1938 Asm->OutStreamer.SwitchSection(
1939 Asm->getObjFileLowering().getDwarfLocSection());
1940 unsigned char Size = Asm->getDataLayout().getPointerSize();
1941 for (const auto &DebugLoc : DotDebugLocEntries) {
1942 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1943 const DwarfCompileUnit *CU = DebugLoc.CU;
1944 assert(!CU->getRanges().empty());
1945 for (const auto &Entry : DebugLoc.List) {
1946 // Set up the range. This range is relative to the entry point of the
1947 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1948 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1949 if (CU->getRanges().size() == 1) {
1950 // Grab the begin symbol from the first range as our base.
1951 const MCSymbol *Base = CU->getRanges()[0].getStart();
1952 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1953 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1955 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1956 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1959 emitDebugLocEntryLocation(Entry);
1961 Asm->OutStreamer.EmitIntValue(0, Size);
1962 Asm->OutStreamer.EmitIntValue(0, Size);
1966 void DwarfDebug::emitDebugLocDWO() {
1967 Asm->OutStreamer.SwitchSection(
1968 Asm->getObjFileLowering().getDwarfLocDWOSection());
1969 for (const auto &DebugLoc : DotDebugLocEntries) {
1970 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1971 for (const auto &Entry : DebugLoc.List) {
1972 // Just always use start_length for now - at least that's one address
1973 // rather than two. We could get fancier and try to, say, reuse an
1974 // address we know we've emitted elsewhere (the start of the function?
1975 // The start of the CU or CU subrange that encloses this range?)
1976 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1977 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1978 Asm->EmitULEB128(idx);
1979 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1981 emitDebugLocEntryLocation(Entry);
1983 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1988 const MCSymbol *Start, *End;
1991 // Emit a debug aranges section, containing a CU lookup for any
1992 // address we can tie back to a CU.
1993 void DwarfDebug::emitDebugARanges() {
1994 // Start the dwarf aranges section.
1995 Asm->OutStreamer.SwitchSection(
1996 Asm->getObjFileLowering().getDwarfARangesSection());
1998 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2002 // Build a list of sections used.
2003 std::vector<const MCSection *> Sections;
2004 for (const auto &it : SectionMap) {
2005 const MCSection *Section = it.first;
2006 Sections.push_back(Section);
2009 // Sort the sections into order.
2010 // This is only done to ensure consistent output order across different runs.
2011 std::sort(Sections.begin(), Sections.end(), SectionSort);
2013 // Build a set of address spans, sorted by CU.
2014 for (const MCSection *Section : Sections) {
2015 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2016 if (List.size() < 2)
2019 // Sort the symbols by offset within the section.
2020 std::sort(List.begin(), List.end(),
2021 [&](const SymbolCU &A, const SymbolCU &B) {
2022 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2023 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2025 // Symbols with no order assigned should be placed at the end.
2026 // (e.g. section end labels)
2034 // If we have no section (e.g. common), just write out
2035 // individual spans for each symbol.
2037 for (const SymbolCU &Cur : List) {
2039 Span.Start = Cur.Sym;
2042 Spans[Cur.CU].push_back(Span);
2045 // Build spans between each label.
2046 const MCSymbol *StartSym = List[0].Sym;
2047 for (size_t n = 1, e = List.size(); n < e; n++) {
2048 const SymbolCU &Prev = List[n - 1];
2049 const SymbolCU &Cur = List[n];
2051 // Try and build the longest span we can within the same CU.
2052 if (Cur.CU != Prev.CU) {
2054 Span.Start = StartSym;
2056 Spans[Prev.CU].push_back(Span);
2063 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2065 // Build a list of CUs used.
2066 std::vector<DwarfCompileUnit *> CUs;
2067 for (const auto &it : Spans) {
2068 DwarfCompileUnit *CU = it.first;
2072 // Sort the CU list (again, to ensure consistent output order).
2073 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2074 return A->getUniqueID() < B->getUniqueID();
2077 // Emit an arange table for each CU we used.
2078 for (DwarfCompileUnit *CU : CUs) {
2079 std::vector<ArangeSpan> &List = Spans[CU];
2081 // Emit size of content not including length itself.
2082 unsigned ContentSize =
2083 sizeof(int16_t) + // DWARF ARange version number
2084 sizeof(int32_t) + // Offset of CU in the .debug_info section
2085 sizeof(int8_t) + // Pointer Size (in bytes)
2086 sizeof(int8_t); // Segment Size (in bytes)
2088 unsigned TupleSize = PtrSize * 2;
2090 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2092 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2094 ContentSize += Padding;
2095 ContentSize += (List.size() + 1) * TupleSize;
2097 // For each compile unit, write the list of spans it covers.
2098 Asm->OutStreamer.AddComment("Length of ARange Set");
2099 Asm->EmitInt32(ContentSize);
2100 Asm->OutStreamer.AddComment("DWARF Arange version number");
2101 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2102 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2103 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2104 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2105 Asm->EmitInt8(PtrSize);
2106 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2109 Asm->OutStreamer.EmitFill(Padding, 0xff);
2111 for (const ArangeSpan &Span : List) {
2112 Asm->EmitLabelReference(Span.Start, PtrSize);
2114 // Calculate the size as being from the span start to it's end.
2116 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2118 // For symbols without an end marker (e.g. common), we
2119 // write a single arange entry containing just that one symbol.
2120 uint64_t Size = SymSize[Span.Start];
2124 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2128 Asm->OutStreamer.AddComment("ARange terminator");
2129 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2130 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2134 // Emit visible names into a debug ranges section.
2135 void DwarfDebug::emitDebugRanges() {
2136 // Start the dwarf ranges section.
2137 Asm->OutStreamer.SwitchSection(
2138 Asm->getObjFileLowering().getDwarfRangesSection());
2140 // Size for our labels.
2141 unsigned char Size = Asm->getDataLayout().getPointerSize();
2143 // Grab the specific ranges for the compile units in the module.
2144 for (const auto &I : CUMap) {
2145 DwarfCompileUnit *TheCU = I.second;
2147 // Iterate over the misc ranges for the compile units in the module.
2148 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2149 // Emit our symbol so we can find the beginning of the range.
2150 Asm->OutStreamer.EmitLabel(List.getSym());
2152 for (const RangeSpan &Range : List.getRanges()) {
2153 const MCSymbol *Begin = Range.getStart();
2154 const MCSymbol *End = Range.getEnd();
2155 assert(Begin && "Range without a begin symbol?");
2156 assert(End && "Range without an end symbol?");
2157 if (TheCU->getRanges().size() == 1) {
2158 // Grab the begin symbol from the first range as our base.
2159 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2160 Asm->EmitLabelDifference(Begin, Base, Size);
2161 Asm->EmitLabelDifference(End, Base, Size);
2163 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2164 Asm->OutStreamer.EmitSymbolValue(End, Size);
2168 // And terminate the list with two 0 values.
2169 Asm->OutStreamer.EmitIntValue(0, Size);
2170 Asm->OutStreamer.EmitIntValue(0, Size);
2173 // Now emit a range for the CU itself.
2174 if (TheCU->getRanges().size() > 1) {
2175 Asm->OutStreamer.EmitLabel(
2176 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2177 for (const RangeSpan &Range : TheCU->getRanges()) {
2178 const MCSymbol *Begin = Range.getStart();
2179 const MCSymbol *End = Range.getEnd();
2180 assert(Begin && "Range without a begin symbol?");
2181 assert(End && "Range without an end symbol?");
2182 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2183 Asm->OutStreamer.EmitSymbolValue(End, Size);
2185 // And terminate the list with two 0 values.
2186 Asm->OutStreamer.EmitIntValue(0, Size);
2187 Asm->OutStreamer.EmitIntValue(0, Size);
2192 // DWARF5 Experimental Separate Dwarf emitters.
2194 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2195 std::unique_ptr<DwarfUnit> NewU) {
2196 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2197 U.getCUNode().getSplitDebugFilename());
2199 if (!CompilationDir.empty())
2200 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2202 addGnuPubAttributes(*NewU, Die);
2204 SkeletonHolder.addUnit(std::move(NewU));
2207 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2208 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2209 // DW_AT_addr_base, DW_AT_ranges_base.
2210 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2212 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2213 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2214 DwarfCompileUnit &NewCU = *OwnedUnit;
2215 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2216 DwarfInfoSectionSym);
2218 NewCU.initStmtList(DwarfLineSectionSym);
2220 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2225 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2226 // compile units that would normally be in debug_info.
2227 void DwarfDebug::emitDebugInfoDWO() {
2228 assert(useSplitDwarf() && "No split dwarf debug info?");
2229 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2230 // emit relocations into the dwo file.
2231 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2234 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2235 // abbreviations for the .debug_info.dwo section.
2236 void DwarfDebug::emitDebugAbbrevDWO() {
2237 assert(useSplitDwarf() && "No split dwarf?");
2238 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2241 void DwarfDebug::emitDebugLineDWO() {
2242 assert(useSplitDwarf() && "No split dwarf?");
2243 Asm->OutStreamer.SwitchSection(
2244 Asm->getObjFileLowering().getDwarfLineDWOSection());
2245 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2248 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2249 // string section and is identical in format to traditional .debug_str
2251 void DwarfDebug::emitDebugStrDWO() {
2252 assert(useSplitDwarf() && "No split dwarf?");
2253 const MCSection *OffSec =
2254 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2255 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2259 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2260 if (!useSplitDwarf())
2263 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2264 return &SplitTypeUnitFileTable;
2267 static uint64_t makeTypeSignature(StringRef Identifier) {
2269 Hash.update(Identifier);
2270 // ... take the least significant 8 bytes and return those. Our MD5
2271 // implementation always returns its results in little endian, swap bytes
2273 MD5::MD5Result Result;
2275 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2278 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2279 StringRef Identifier, DIE &RefDie,
2280 DICompositeType CTy) {
2281 // Fast path if we're building some type units and one has already used the
2282 // address pool we know we're going to throw away all this work anyway, so
2283 // don't bother building dependent types.
2284 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2287 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2289 CU.addDIETypeSignature(RefDie, *TU);
2293 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2294 AddrPool.resetUsedFlag();
2296 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2297 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2298 this, &InfoHolder, getDwoLineTable(CU));
2299 DwarfTypeUnit &NewTU = *OwnedUnit;
2300 DIE &UnitDie = NewTU.getUnitDie();
2302 TypeUnitsUnderConstruction.push_back(
2303 std::make_pair(std::move(OwnedUnit), CTy));
2305 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2308 uint64_t Signature = makeTypeSignature(Identifier);
2309 NewTU.setTypeSignature(Signature);
2311 if (useSplitDwarf())
2312 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2313 DwarfTypesDWOSectionSym);
2315 CU.applyStmtList(UnitDie);
2317 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2320 NewTU.setType(NewTU.createTypeDIE(CTy));
2323 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2324 TypeUnitsUnderConstruction.clear();
2326 // Types referencing entries in the address table cannot be placed in type
2328 if (AddrPool.hasBeenUsed()) {
2330 // Remove all the types built while building this type.
2331 // This is pessimistic as some of these types might not be dependent on
2332 // the type that used an address.
2333 for (const auto &TU : TypeUnitsToAdd)
2334 DwarfTypeUnits.erase(TU.second);
2336 // Construct this type in the CU directly.
2337 // This is inefficient because all the dependent types will be rebuilt
2338 // from scratch, including building them in type units, discovering that
2339 // they depend on addresses, throwing them out and rebuilding them.
2340 CU.constructTypeDIE(RefDie, CTy);
2344 // If the type wasn't dependent on fission addresses, finish adding the type
2345 // and all its dependent types.
2346 for (auto &TU : TypeUnitsToAdd)
2347 InfoHolder.addUnit(std::move(TU.first));
2349 CU.addDIETypeSignature(RefDie, NewTU);
2352 // Accelerator table mutators - add each name along with its companion
2353 // DIE to the proper table while ensuring that the name that we're going
2354 // to reference is in the string table. We do this since the names we
2355 // add may not only be identical to the names in the DIE.
2356 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2357 if (!useDwarfAccelTables())
2359 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2363 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2364 if (!useDwarfAccelTables())
2366 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2370 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2371 if (!useDwarfAccelTables())
2373 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2377 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2378 if (!useDwarfAccelTables())
2380 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),