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 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
334 assert(Scope && Scope->getScopeNode());
335 assert(Scope->isAbstractScope());
336 assert(!Scope->getInlinedAt());
338 const MDNode *SP = Scope->getScopeNode();
340 DIE *&AbsDef = AbstractSPDies[SP];
344 ProcessedSPNodes.insert(SP);
346 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
347 // was inlined from another compile unit.
348 AbsDef = &SPMap[SP]->constructAbstractSubprogramScopeDIE(Scope);
351 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
352 if (!GenerateGnuPubSections)
355 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
358 // Create new DwarfCompileUnit for the given metadata node with tag
359 // DW_TAG_compile_unit.
360 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
361 StringRef FN = DIUnit.getFilename();
362 CompilationDir = DIUnit.getDirectory();
364 auto OwnedUnit = make_unique<DwarfCompileUnit>(
365 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
366 DwarfCompileUnit &NewCU = *OwnedUnit;
367 DIE &Die = NewCU.getUnitDie();
368 InfoHolder.addUnit(std::move(OwnedUnit));
370 // LTO with assembly output shares a single line table amongst multiple CUs.
371 // To avoid the compilation directory being ambiguous, let the line table
372 // explicitly describe the directory of all files, never relying on the
373 // compilation directory.
374 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
375 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
376 NewCU.getUniqueID(), CompilationDir);
378 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
379 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
380 DIUnit.getLanguage());
381 NewCU.addString(Die, dwarf::DW_AT_name, FN);
383 if (!useSplitDwarf()) {
384 NewCU.initStmtList(DwarfLineSectionSym);
386 // If we're using split dwarf the compilation dir is going to be in the
387 // skeleton CU and so we don't need to duplicate it here.
388 if (!CompilationDir.empty())
389 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
391 addGnuPubAttributes(NewCU, Die);
394 if (DIUnit.isOptimized())
395 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
397 StringRef Flags = DIUnit.getFlags();
399 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
401 if (unsigned RVer = DIUnit.getRunTimeVersion())
402 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
403 dwarf::DW_FORM_data1, RVer);
408 if (useSplitDwarf()) {
409 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
410 DwarfInfoDWOSectionSym);
411 NewCU.setSkeleton(constructSkeletonCU(NewCU));
413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
414 DwarfInfoSectionSym);
416 CUMap.insert(std::make_pair(DIUnit, &NewCU));
417 CUDieMap.insert(std::make_pair(&Die, &NewCU));
421 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
423 DIImportedEntity Module(N);
424 assert(Module.Verify());
425 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
426 D->addChild(TheCU.constructImportedEntityDIE(Module));
429 // Emit all Dwarf sections that should come prior to the content. Create
430 // global DIEs and emit initial debug info sections. This is invoked by
431 // the target AsmPrinter.
432 void DwarfDebug::beginModule() {
433 if (DisableDebugInfoPrinting)
436 const Module *M = MMI->getModule();
438 FunctionDIs = makeSubprogramMap(*M);
440 // If module has named metadata anchors then use them, otherwise scan the
441 // module using debug info finder to collect debug info.
442 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
445 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
447 // Emit initial sections so we can reference labels later.
450 SingleCU = CU_Nodes->getNumOperands() == 1;
452 for (MDNode *N : CU_Nodes->operands()) {
453 DICompileUnit CUNode(N);
454 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
455 DIArray ImportedEntities = CUNode.getImportedEntities();
456 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
457 ScopesWithImportedEntities.push_back(std::make_pair(
458 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
459 ImportedEntities.getElement(i)));
460 std::sort(ScopesWithImportedEntities.begin(),
461 ScopesWithImportedEntities.end(), less_first());
462 DIArray GVs = CUNode.getGlobalVariables();
463 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
464 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
465 DIArray SPs = CUNode.getSubprograms();
466 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
467 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
468 DIArray EnumTypes = CUNode.getEnumTypes();
469 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
470 DIType Ty(EnumTypes.getElement(i));
471 // The enum types array by design contains pointers to
472 // MDNodes rather than DIRefs. Unique them here.
473 DIType UniqueTy(resolve(Ty.getRef()));
474 CU.getOrCreateTypeDIE(UniqueTy);
476 DIArray RetainedTypes = CUNode.getRetainedTypes();
477 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
478 DIType Ty(RetainedTypes.getElement(i));
479 // The retained types array by design contains pointers to
480 // MDNodes rather than DIRefs. Unique them here.
481 DIType UniqueTy(resolve(Ty.getRef()));
482 CU.getOrCreateTypeDIE(UniqueTy);
484 // Emit imported_modules last so that the relevant context is already
486 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
487 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
490 // Tell MMI that we have debug info.
491 MMI->setDebugInfoAvailability(true);
493 // Prime section data.
494 SectionMap[Asm->getObjFileLowering().getTextSection()];
497 void DwarfDebug::finishVariableDefinitions() {
498 for (const auto &Var : ConcreteVariables) {
499 DIE *VariableDie = Var->getDIE();
501 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
502 // in the ConcreteVariables list, rather than looking it up again here.
503 // DIE::getUnit isn't simple - it walks parent pointers, etc.
504 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
506 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
507 if (AbsVar && AbsVar->getDIE()) {
508 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
511 Unit->applyVariableAttributes(*Var, *VariableDie);
515 void DwarfDebug::finishSubprogramDefinitions() {
516 for (const auto &P : SPMap)
517 P.second->finishSubprogramDefinition(DISubprogram(P.first));
521 // Collect info for variables that were optimized out.
522 void DwarfDebug::collectDeadVariables() {
523 const Module *M = MMI->getModule();
525 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
526 for (MDNode *N : CU_Nodes->operands()) {
527 DICompileUnit TheCU(N);
528 // Construct subprogram DIE and add variables DIEs.
529 DwarfCompileUnit *SPCU =
530 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
531 assert(SPCU && "Unable to find Compile Unit!");
532 DIArray Subprograms = TheCU.getSubprograms();
533 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
534 DISubprogram SP(Subprograms.getElement(i));
535 if (ProcessedSPNodes.count(SP) != 0)
537 assert(SP.isSubprogram() &&
538 "CU's subprogram list contains a non-subprogram");
539 assert(SP.isDefinition() &&
540 "CU's subprogram list contains a subprogram declaration");
541 DIArray Variables = SP.getVariables();
542 if (Variables.getNumElements() == 0)
545 DIE *SPDIE = AbstractSPDies.lookup(SP);
547 SPDIE = SPCU->getDIE(SP);
549 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
550 DIVariable DV(Variables.getElement(vi));
551 assert(DV.isVariable());
552 DbgVariable NewVar(DV, DIExpression(nullptr), this);
553 auto VariableDie = SPCU->constructVariableDIE(NewVar);
554 SPCU->applyVariableAttributes(NewVar, *VariableDie);
555 SPDIE->addChild(std::move(VariableDie));
562 void DwarfDebug::finalizeModuleInfo() {
563 finishSubprogramDefinitions();
565 finishVariableDefinitions();
567 // Collect info for variables that were optimized out.
568 collectDeadVariables();
570 // Handle anything that needs to be done on a per-unit basis after
571 // all other generation.
572 for (const auto &TheU : getUnits()) {
573 // Emit DW_AT_containing_type attribute to connect types with their
574 // vtable holding type.
575 TheU->constructContainingTypeDIEs();
577 // Add CU specific attributes if we need to add any.
578 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
579 // If we're splitting the dwarf out now that we've got the entire
580 // CU then add the dwo id to it.
581 DwarfCompileUnit *SkCU =
582 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
583 if (useSplitDwarf()) {
584 // Emit a unique identifier for this CU.
585 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
586 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
587 dwarf::DW_FORM_data8, ID);
588 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
589 dwarf::DW_FORM_data8, ID);
591 // We don't keep track of which addresses are used in which CU so this
592 // is a bit pessimistic under LTO.
593 if (!AddrPool.isEmpty())
594 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
595 DwarfAddrSectionSym, DwarfAddrSectionSym);
596 if (!TheU->getRangeLists().empty())
597 SkCU->addSectionLabel(
598 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
599 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
602 // If we have code split among multiple sections or non-contiguous
603 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
604 // remain in the .o file, otherwise add a DW_AT_low_pc.
605 // FIXME: We should use ranges allow reordering of code ala
606 // .subsections_via_symbols in mach-o. This would mean turning on
607 // ranges for all subprogram DIEs for mach-o.
608 DwarfCompileUnit &U =
609 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
610 unsigned NumRanges = TheU->getRanges().size();
613 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
614 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
615 DwarfDebugRangeSectionSym);
617 // A DW_AT_low_pc attribute may also be specified in combination with
618 // DW_AT_ranges to specify the default base address for use in
619 // location lists (see Section 2.6.2) and range lists (see Section
621 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
624 RangeSpan &Range = TheU->getRanges().back();
625 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
631 // Compute DIE offsets and sizes.
632 InfoHolder.computeSizeAndOffsets();
634 SkeletonHolder.computeSizeAndOffsets();
637 void DwarfDebug::endSections() {
638 // Filter labels by section.
639 for (const SymbolCU &SCU : ArangeLabels) {
640 if (SCU.Sym->isInSection()) {
641 // Make a note of this symbol and it's section.
642 const MCSection *Section = &SCU.Sym->getSection();
643 if (!Section->getKind().isMetadata())
644 SectionMap[Section].push_back(SCU);
646 // Some symbols (e.g. common/bss on mach-o) can have no section but still
647 // appear in the output. This sucks as we rely on sections to build
648 // arange spans. We can do it without, but it's icky.
649 SectionMap[nullptr].push_back(SCU);
653 // Build a list of sections used.
654 std::vector<const MCSection *> Sections;
655 for (const auto &it : SectionMap) {
656 const MCSection *Section = it.first;
657 Sections.push_back(Section);
660 // Sort the sections into order.
661 // This is only done to ensure consistent output order across different runs.
662 std::sort(Sections.begin(), Sections.end(), SectionSort);
664 // Add terminating symbols for each section.
665 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
666 const MCSection *Section = Sections[ID];
667 MCSymbol *Sym = nullptr;
670 // We can't call MCSection::getLabelEndName, as it's only safe to do so
671 // if we know the section name up-front. For user-created sections, the
672 // resulting label may not be valid to use as a label. (section names can
673 // use a greater set of characters on some systems)
674 Sym = Asm->GetTempSymbol("debug_end", ID);
675 Asm->OutStreamer.SwitchSection(Section);
676 Asm->OutStreamer.EmitLabel(Sym);
679 // Insert a final terminator.
680 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
684 // Emit all Dwarf sections that should come after the content.
685 void DwarfDebug::endModule() {
686 assert(CurFn == nullptr);
687 assert(CurMI == nullptr);
692 // End any existing sections.
693 // TODO: Does this need to happen?
696 // Finalize the debug info for the module.
697 finalizeModuleInfo();
701 // Emit all the DIEs into a debug info section.
704 // Corresponding abbreviations into a abbrev section.
707 // Emit info into a debug aranges section.
708 if (GenerateARangeSection)
711 // Emit info into a debug ranges section.
714 if (useSplitDwarf()) {
717 emitDebugAbbrevDWO();
720 // Emit DWO addresses.
721 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
723 // Emit info into a debug loc section.
726 // Emit info into the dwarf accelerator table sections.
727 if (useDwarfAccelTables()) {
730 emitAccelNamespaces();
734 // Emit the pubnames and pubtypes sections if requested.
735 if (HasDwarfPubSections) {
736 emitDebugPubNames(GenerateGnuPubSections);
737 emitDebugPubTypes(GenerateGnuPubSections);
742 AbstractVariables.clear();
744 // Reset these for the next Module if we have one.
748 // Find abstract variable, if any, associated with Var.
749 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
750 DIVariable &Cleansed) {
751 LLVMContext &Ctx = DV->getContext();
752 // More then one inlined variable corresponds to one abstract variable.
753 // FIXME: This duplication of variables when inlining should probably be
754 // removed. It's done to allow each DIVariable to describe its location
755 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
756 // make it accurate then remove this duplication/cleansing stuff.
757 Cleansed = cleanseInlinedVariable(DV, Ctx);
758 auto I = AbstractVariables.find(Cleansed);
759 if (I != AbstractVariables.end())
760 return I->second.get();
764 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
766 return getExistingAbstractVariable(DV, Cleansed);
769 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
770 LexicalScope *Scope) {
771 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
772 addNonArgumentScopeVariable(Scope, AbsDbgVariable.get());
773 AbstractVariables[Var] = std::move(AbsDbgVariable);
776 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
777 const MDNode *ScopeNode) {
778 DIVariable Cleansed = DV;
779 if (getExistingAbstractVariable(DV, Cleansed))
782 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
786 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
787 const MDNode *ScopeNode) {
788 DIVariable Cleansed = DV;
789 if (getExistingAbstractVariable(DV, Cleansed))
792 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
793 createAbstractVariable(Cleansed, Scope);
796 // If Var is a current function argument then add it to CurrentFnArguments list.
797 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
798 if (Scope->getParent())
800 DIVariable DV = Var->getVariable();
801 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
803 unsigned ArgNo = DV.getArgNumber();
807 size_t Size = CurrentFnArguments.size();
809 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
810 // llvm::Function argument size is not good indicator of how many
811 // arguments does the function have at source level.
813 CurrentFnArguments.resize(ArgNo * 2);
814 assert(!CurrentFnArguments[ArgNo - 1]);
815 CurrentFnArguments[ArgNo - 1] = Var;
819 // Collect variable information from side table maintained by MMI.
820 void DwarfDebug::collectVariableInfoFromMMITable(
821 SmallPtrSetImpl<const MDNode *> &Processed) {
822 for (const auto &VI : MMI->getVariableDbgInfo()) {
825 Processed.insert(VI.Var);
826 DIVariable DV(VI.Var);
827 DIExpression Expr(VI.Expr);
828 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
830 // If variable scope is not found then skip this variable.
834 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
835 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
836 DbgVariable *RegVar = ConcreteVariables.back().get();
837 RegVar->setFrameIndex(VI.Slot);
838 addScopeVariable(Scope, RegVar);
842 // Get .debug_loc entry for the instruction range starting at MI.
843 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
844 const MDNode *Expr = MI->getDebugExpression();
845 const MDNode *Var = MI->getDebugVariable();
847 assert(MI->getNumOperands() == 4);
848 if (MI->getOperand(0).isReg()) {
849 MachineLocation MLoc;
850 // If the second operand is an immediate, this is a
851 // register-indirect address.
852 if (!MI->getOperand(1).isImm())
853 MLoc.set(MI->getOperand(0).getReg());
855 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
856 return DebugLocEntry::Value(Var, Expr, MLoc);
858 if (MI->getOperand(0).isImm())
859 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
860 if (MI->getOperand(0).isFPImm())
861 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
862 if (MI->getOperand(0).isCImm())
863 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
865 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
868 /// Determine whether two variable pieces overlap.
869 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
870 if (!P1.isVariablePiece() || !P2.isVariablePiece())
872 unsigned l1 = P1.getPieceOffset();
873 unsigned l2 = P2.getPieceOffset();
874 unsigned r1 = l1 + P1.getPieceSize();
875 unsigned r2 = l2 + P2.getPieceSize();
876 // True where [l1,r1[ and [r1,r2[ overlap.
877 return (l1 < r2) && (l2 < r1);
880 /// Build the location list for all DBG_VALUEs in the function that
881 /// describe the same variable. If the ranges of several independent
882 /// pieces of the same variable overlap partially, split them up and
883 /// combine the ranges. The resulting DebugLocEntries are will have
884 /// strict monotonically increasing begin addresses and will never
889 // Ranges History [var, loc, piece ofs size]
890 // 0 | [x, (reg0, piece 0, 32)]
891 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
893 // 3 | [clobber reg0]
894 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
898 // [0-1] [x, (reg0, piece 0, 32)]
899 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
900 // [3-4] [x, (reg1, piece 32, 32)]
901 // [4- ] [x, (mem, piece 0, 64)]
903 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
904 const DbgValueHistoryMap::InstrRanges &Ranges) {
905 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
907 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
908 const MachineInstr *Begin = I->first;
909 const MachineInstr *End = I->second;
910 assert(Begin->isDebugValue() && "Invalid History entry");
912 // Check if a variable is inaccessible in this range.
913 if (Begin->getNumOperands() > 1 &&
914 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
919 // If this piece overlaps with any open ranges, truncate them.
920 DIExpression DIExpr = Begin->getDebugExpression();
921 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
922 [&](DebugLocEntry::Value R) {
923 return piecesOverlap(DIExpr, R.getExpression());
925 OpenRanges.erase(Last, OpenRanges.end());
927 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
928 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
930 const MCSymbol *EndLabel;
932 EndLabel = getLabelAfterInsn(End);
933 else if (std::next(I) == Ranges.end())
934 EndLabel = FunctionEndSym;
936 EndLabel = getLabelBeforeInsn(std::next(I)->first);
937 assert(EndLabel && "Forgot label after instruction ending a range!");
939 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
941 auto Value = getDebugLocValue(Begin);
942 DebugLocEntry Loc(StartLabel, EndLabel, Value);
943 bool couldMerge = false;
945 // If this is a piece, it may belong to the current DebugLocEntry.
946 if (DIExpr.isVariablePiece()) {
947 // Add this value to the list of open ranges.
948 OpenRanges.push_back(Value);
950 // Attempt to add the piece to the last entry.
951 if (!DebugLoc.empty())
952 if (DebugLoc.back().MergeValues(Loc))
957 // Need to add a new DebugLocEntry. Add all values from still
958 // valid non-overlapping pieces.
959 if (OpenRanges.size())
960 Loc.addValues(OpenRanges);
962 DebugLoc.push_back(std::move(Loc));
965 // Attempt to coalesce the ranges of two otherwise identical
967 auto CurEntry = DebugLoc.rbegin();
968 auto PrevEntry = std::next(CurEntry);
969 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
973 dbgs() << CurEntry->getValues().size() << " Values:\n";
974 for (auto Value : CurEntry->getValues()) {
975 Value.getVariable()->dump();
976 Value.getExpression()->dump();
984 // Find variables for each lexical scope.
986 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
987 SmallPtrSetImpl<const MDNode *> &Processed) {
988 // Grab the variable info that was squirreled away in the MMI side-table.
989 collectVariableInfoFromMMITable(Processed);
991 for (const auto &I : DbgValues) {
992 DIVariable DV(I.first);
993 if (Processed.count(DV))
996 // Instruction ranges, specifying where DV is accessible.
997 const auto &Ranges = I.second;
1001 LexicalScope *Scope = nullptr;
1002 if (MDNode *IA = DV.getInlinedAt()) {
1003 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1004 Scope = LScopes.findInlinedScope(DebugLoc::get(
1005 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1007 Scope = LScopes.findLexicalScope(DV.getContext());
1008 // If variable scope is not found then skip this variable.
1012 Processed.insert(DV);
1013 const MachineInstr *MInsn = Ranges.front().first;
1014 assert(MInsn->isDebugValue() && "History must begin with debug value");
1015 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1016 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1017 DbgVariable *RegVar = ConcreteVariables.back().get();
1018 addScopeVariable(Scope, RegVar);
1020 // Check if the first DBG_VALUE is valid for the rest of the function.
1021 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1024 // Handle multiple DBG_VALUE instructions describing one variable.
1025 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1027 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1028 DebugLocList &LocList = DotDebugLocEntries.back();
1029 LocList.CU = &TheCU;
1031 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1033 // Build the location list for this variable.
1034 buildLocationList(LocList.List, Ranges);
1037 // Collect info for variables that were optimized out.
1038 DIArray Variables = SP.getVariables();
1039 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1040 DIVariable DV(Variables.getElement(i));
1041 assert(DV.isVariable());
1042 if (!Processed.insert(DV))
1044 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1045 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1046 DIExpression NoExpr;
1047 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1048 addScopeVariable(Scope, ConcreteVariables.back().get());
1053 // Return Label preceding the instruction.
1054 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1055 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1056 assert(Label && "Didn't insert label before instruction");
1060 // Return Label immediately following the instruction.
1061 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1062 return LabelsAfterInsn.lookup(MI);
1065 // Process beginning of an instruction.
1066 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1067 assert(CurMI == nullptr);
1069 // Check if source location changes, but ignore DBG_VALUE locations.
1070 if (!MI->isDebugValue()) {
1071 DebugLoc DL = MI->getDebugLoc();
1072 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1075 if (DL == PrologEndLoc) {
1076 Flags |= DWARF2_FLAG_PROLOGUE_END;
1077 PrologEndLoc = DebugLoc();
1079 if (PrologEndLoc.isUnknown())
1080 Flags |= DWARF2_FLAG_IS_STMT;
1082 if (!DL.isUnknown()) {
1083 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1084 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1086 recordSourceLine(0, 0, nullptr, 0);
1090 // Insert labels where requested.
1091 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1092 LabelsBeforeInsn.find(MI);
1095 if (I == LabelsBeforeInsn.end())
1098 // Label already assigned.
1103 PrevLabel = MMI->getContext().CreateTempSymbol();
1104 Asm->OutStreamer.EmitLabel(PrevLabel);
1106 I->second = PrevLabel;
1109 // Process end of an instruction.
1110 void DwarfDebug::endInstruction() {
1111 assert(CurMI != nullptr);
1112 // Don't create a new label after DBG_VALUE instructions.
1113 // They don't generate code.
1114 if (!CurMI->isDebugValue())
1115 PrevLabel = nullptr;
1117 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1118 LabelsAfterInsn.find(CurMI);
1122 if (I == LabelsAfterInsn.end())
1125 // Label already assigned.
1129 // We need a label after this instruction.
1131 PrevLabel = MMI->getContext().CreateTempSymbol();
1132 Asm->OutStreamer.EmitLabel(PrevLabel);
1134 I->second = PrevLabel;
1137 // Each LexicalScope has first instruction and last instruction to mark
1138 // beginning and end of a scope respectively. Create an inverse map that list
1139 // scopes starts (and ends) with an instruction. One instruction may start (or
1140 // end) multiple scopes. Ignore scopes that are not reachable.
1141 void DwarfDebug::identifyScopeMarkers() {
1142 SmallVector<LexicalScope *, 4> WorkList;
1143 WorkList.push_back(LScopes.getCurrentFunctionScope());
1144 while (!WorkList.empty()) {
1145 LexicalScope *S = WorkList.pop_back_val();
1147 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1148 if (!Children.empty())
1149 WorkList.append(Children.begin(), Children.end());
1151 if (S->isAbstractScope())
1154 for (const InsnRange &R : S->getRanges()) {
1155 assert(R.first && "InsnRange does not have first instruction!");
1156 assert(R.second && "InsnRange does not have second instruction!");
1157 requestLabelBeforeInsn(R.first);
1158 requestLabelAfterInsn(R.second);
1163 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1164 // First known non-DBG_VALUE and non-frame setup location marks
1165 // the beginning of the function body.
1166 for (const auto &MBB : *MF)
1167 for (const auto &MI : MBB)
1168 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1169 !MI.getDebugLoc().isUnknown())
1170 return MI.getDebugLoc();
1174 // Gather pre-function debug information. Assumes being called immediately
1175 // after the function entry point has been emitted.
1176 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1179 // If there's no debug info for the function we're not going to do anything.
1180 if (!MMI->hasDebugInfo())
1183 auto DI = FunctionDIs.find(MF->getFunction());
1184 if (DI == FunctionDIs.end())
1187 // Grab the lexical scopes for the function, if we don't have any of those
1188 // then we're not going to be able to do anything.
1189 LScopes.initialize(*MF);
1190 if (LScopes.empty())
1193 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1195 // Make sure that each lexical scope will have a begin/end label.
1196 identifyScopeMarkers();
1198 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1199 // belongs to so that we add to the correct per-cu line table in the
1201 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1202 // FnScope->getScopeNode() and DI->second should represent the same function,
1203 // though they may not be the same MDNode due to inline functions merged in
1204 // LTO where the debug info metadata still differs (either due to distinct
1205 // written differences - two versions of a linkonce_odr function
1206 // written/copied into two separate files, or some sub-optimal metadata that
1207 // isn't structurally identical (see: file path/name info from clang, which
1208 // includes the directory of the cpp file being built, even when the file name
1209 // is absolute (such as an <> lookup header)))
1210 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1211 assert(TheCU && "Unable to find compile unit!");
1212 if (Asm->OutStreamer.hasRawTextSupport())
1213 // Use a single line table if we are generating assembly.
1214 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1216 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1218 // Emit a label for the function so that we have a beginning address.
1219 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1220 // Assumes in correct section after the entry point.
1221 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1223 // Calculate history for local variables.
1224 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1227 // Request labels for the full history.
1228 for (const auto &I : DbgValues) {
1229 const auto &Ranges = I.second;
1233 // The first mention of a function argument gets the FunctionBeginSym
1234 // label, so arguments are visible when breaking at function entry.
1235 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1236 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1237 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1238 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1239 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1240 // Mark all non-overlapping initial pieces.
1241 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1242 DIExpression Piece = I->first->getDebugExpression();
1243 if (std::all_of(Ranges.begin(), I,
1244 [&](DbgValueHistoryMap::InstrRange Pred) {
1245 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1247 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1254 for (const auto &Range : Ranges) {
1255 requestLabelBeforeInsn(Range.first);
1257 requestLabelAfterInsn(Range.second);
1261 PrevInstLoc = DebugLoc();
1262 PrevLabel = FunctionBeginSym;
1264 // Record beginning of function.
1265 PrologEndLoc = findPrologueEndLoc(MF);
1266 if (!PrologEndLoc.isUnknown()) {
1267 DebugLoc FnStartDL =
1268 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1270 FnStartDL.getLine(), FnStartDL.getCol(),
1271 FnStartDL.getScope(MF->getFunction()->getContext()),
1272 // We'd like to list the prologue as "not statements" but GDB behaves
1273 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1274 DWARF2_FLAG_IS_STMT);
1278 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1279 if (addCurrentFnArgument(Var, LS))
1281 addNonArgumentScopeVariable(LS, Var);
1284 void DwarfDebug::addNonArgumentScopeVariable(LexicalScope *LS,
1286 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1287 DIVariable DV = Var->getVariable();
1288 // Variables with positive arg numbers are parameters.
1289 if (unsigned ArgNum = DV.getArgNumber()) {
1290 // Keep all parameters in order at the start of the variable list to ensure
1291 // function types are correct (no out-of-order parameters)
1293 // This could be improved by only doing it for optimized builds (unoptimized
1294 // builds have the right order to begin with), searching from the back (this
1295 // would catch the unoptimized case quickly), or doing a binary search
1296 // rather than linear search.
1297 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1298 while (I != Vars.end()) {
1299 unsigned CurNum = (*I)->getVariable().getArgNumber();
1300 // A local (non-parameter) variable has been found, insert immediately
1304 // A later indexed parameter has been found, insert immediately before it.
1305 if (CurNum > ArgNum)
1309 Vars.insert(I, Var);
1313 Vars.push_back(Var);
1316 // Gather and emit post-function debug information.
1317 void DwarfDebug::endFunction(const MachineFunction *MF) {
1318 assert(CurFn == MF &&
1319 "endFunction should be called with the same function as beginFunction");
1321 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1322 !FunctionDIs.count(MF->getFunction())) {
1323 // If we don't have a lexical scope for this function then there will
1324 // be a hole in the range information. Keep note of this by setting the
1325 // previously used section to nullptr.
1331 // Define end label for subprogram.
1332 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1333 // Assumes in correct section after the entry point.
1334 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1336 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1337 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1339 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1340 DISubprogram SP(FnScope->getScopeNode());
1341 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1343 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1344 collectVariableInfo(TheCU, SP, ProcessedVars);
1346 // Add the range of this function to the list of ranges for the CU.
1347 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1349 // Under -gmlt, skip building the subprogram if there are no inlined
1350 // subroutines inside it.
1351 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1352 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1353 assert(ScopeVariables.empty());
1354 assert(CurrentFnArguments.empty());
1355 assert(DbgValues.empty());
1356 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1357 // by a -gmlt CU. Add a test and remove this assertion.
1358 assert(AbstractVariables.empty());
1359 LabelsBeforeInsn.clear();
1360 LabelsAfterInsn.clear();
1361 PrevLabel = nullptr;
1367 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1369 // Construct abstract scopes.
1370 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1371 DISubprogram SP(AScope->getScopeNode());
1372 assert(SP.isSubprogram());
1373 // Collect info for variables that were optimized out.
1374 DIArray Variables = SP.getVariables();
1375 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1376 DIVariable DV(Variables.getElement(i));
1377 assert(DV && DV.isVariable());
1378 if (!ProcessedVars.insert(DV))
1380 ensureAbstractVariableIsCreated(DV, DV.getContext());
1381 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1382 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1384 constructAbstractSubprogramScopeDIE(AScope);
1387 TheCU.constructSubprogramScopeDIE(FnScope);
1390 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1391 // DbgVariables except those that are also in AbstractVariables (since they
1392 // can be used cross-function)
1393 ScopeVariables.clear();
1394 CurrentFnArguments.clear();
1396 LabelsBeforeInsn.clear();
1397 LabelsAfterInsn.clear();
1398 PrevLabel = nullptr;
1402 // Register a source line with debug info. Returns the unique label that was
1403 // emitted and which provides correspondence to the source line list.
1404 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1409 unsigned Discriminator = 0;
1410 if (DIScope Scope = DIScope(S)) {
1411 assert(Scope.isScope());
1412 Fn = Scope.getFilename();
1413 Dir = Scope.getDirectory();
1414 if (Scope.isLexicalBlockFile())
1415 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1417 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1418 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1419 .getOrCreateSourceID(Fn, Dir);
1421 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1425 //===----------------------------------------------------------------------===//
1427 //===----------------------------------------------------------------------===//
1429 // Emit initial Dwarf sections with a label at the start of each one.
1430 void DwarfDebug::emitSectionLabels() {
1431 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1433 // Dwarf sections base addresses.
1434 DwarfInfoSectionSym =
1435 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1436 if (useSplitDwarf()) {
1437 DwarfInfoDWOSectionSym =
1438 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1439 DwarfTypesDWOSectionSym =
1440 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1442 DwarfAbbrevSectionSym =
1443 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1444 if (useSplitDwarf())
1445 DwarfAbbrevDWOSectionSym = emitSectionSym(
1446 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1447 if (GenerateARangeSection)
1448 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1450 DwarfLineSectionSym =
1451 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1452 if (GenerateGnuPubSections) {
1453 DwarfGnuPubNamesSectionSym =
1454 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1455 DwarfGnuPubTypesSectionSym =
1456 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1457 } else if (HasDwarfPubSections) {
1458 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1459 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1462 DwarfStrSectionSym =
1463 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1464 if (useSplitDwarf()) {
1465 DwarfStrDWOSectionSym =
1466 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1467 DwarfAddrSectionSym =
1468 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1469 DwarfDebugLocSectionSym =
1470 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1472 DwarfDebugLocSectionSym =
1473 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1474 DwarfDebugRangeSectionSym =
1475 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1478 // Recursively emits a debug information entry.
1479 void DwarfDebug::emitDIE(DIE &Die) {
1480 // Get the abbreviation for this DIE.
1481 const DIEAbbrev &Abbrev = Die.getAbbrev();
1483 // Emit the code (index) for the abbreviation.
1484 if (Asm->isVerbose())
1485 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1486 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1487 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1488 dwarf::TagString(Abbrev.getTag()));
1489 Asm->EmitULEB128(Abbrev.getNumber());
1491 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1492 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1494 // Emit the DIE attribute values.
1495 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1496 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1497 dwarf::Form Form = AbbrevData[i].getForm();
1498 assert(Form && "Too many attributes for DIE (check abbreviation)");
1500 if (Asm->isVerbose()) {
1501 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1502 if (Attr == dwarf::DW_AT_accessibility)
1503 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1504 cast<DIEInteger>(Values[i])->getValue()));
1507 // Emit an attribute using the defined form.
1508 Values[i]->EmitValue(Asm, Form);
1511 // Emit the DIE children if any.
1512 if (Abbrev.hasChildren()) {
1513 for (auto &Child : Die.getChildren())
1516 Asm->OutStreamer.AddComment("End Of Children Mark");
1521 // Emit the debug info section.
1522 void DwarfDebug::emitDebugInfo() {
1523 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1525 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1528 // Emit the abbreviation section.
1529 void DwarfDebug::emitAbbreviations() {
1530 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1532 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1535 // Emit the last address of the section and the end of the line matrix.
1536 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1537 // Define last address of section.
1538 Asm->OutStreamer.AddComment("Extended Op");
1541 Asm->OutStreamer.AddComment("Op size");
1542 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1543 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1544 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1546 Asm->OutStreamer.AddComment("Section end label");
1548 Asm->OutStreamer.EmitSymbolValue(
1549 Asm->GetTempSymbol("section_end", SectionEnd),
1550 Asm->getDataLayout().getPointerSize());
1552 // Mark end of matrix.
1553 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1559 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1560 StringRef TableName, StringRef SymName) {
1561 Accel.FinalizeTable(Asm, TableName);
1562 Asm->OutStreamer.SwitchSection(Section);
1563 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1564 Asm->OutStreamer.EmitLabel(SectionBegin);
1566 // Emit the full data.
1567 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1570 // Emit visible names into a hashed accelerator table section.
1571 void DwarfDebug::emitAccelNames() {
1572 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1573 "Names", "names_begin");
1576 // Emit objective C classes and categories into a hashed accelerator table
1578 void DwarfDebug::emitAccelObjC() {
1579 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1580 "ObjC", "objc_begin");
1583 // Emit namespace dies into a hashed accelerator table.
1584 void DwarfDebug::emitAccelNamespaces() {
1585 emitAccel(AccelNamespace,
1586 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1587 "namespac", "namespac_begin");
1590 // Emit type dies into a hashed accelerator table.
1591 void DwarfDebug::emitAccelTypes() {
1592 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1593 "types", "types_begin");
1596 // Public name handling.
1597 // The format for the various pubnames:
1599 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1600 // for the DIE that is named.
1602 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1603 // into the CU and the index value is computed according to the type of value
1604 // for the DIE that is named.
1606 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1607 // it's the offset within the debug_info/debug_types dwo section, however, the
1608 // reference in the pubname header doesn't change.
1610 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1611 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1613 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1615 // We could have a specification DIE that has our most of our knowledge,
1616 // look for that now.
1617 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1619 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1620 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1621 Linkage = dwarf::GIEL_EXTERNAL;
1622 } else if (Die->findAttribute(dwarf::DW_AT_external))
1623 Linkage = dwarf::GIEL_EXTERNAL;
1625 switch (Die->getTag()) {
1626 case dwarf::DW_TAG_class_type:
1627 case dwarf::DW_TAG_structure_type:
1628 case dwarf::DW_TAG_union_type:
1629 case dwarf::DW_TAG_enumeration_type:
1630 return dwarf::PubIndexEntryDescriptor(
1631 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1632 ? dwarf::GIEL_STATIC
1633 : dwarf::GIEL_EXTERNAL);
1634 case dwarf::DW_TAG_typedef:
1635 case dwarf::DW_TAG_base_type:
1636 case dwarf::DW_TAG_subrange_type:
1637 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1638 case dwarf::DW_TAG_namespace:
1639 return dwarf::GIEK_TYPE;
1640 case dwarf::DW_TAG_subprogram:
1641 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1642 case dwarf::DW_TAG_constant:
1643 case dwarf::DW_TAG_variable:
1644 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1645 case dwarf::DW_TAG_enumerator:
1646 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1647 dwarf::GIEL_STATIC);
1649 return dwarf::GIEK_NONE;
1653 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1655 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1656 const MCSection *PSec =
1657 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1658 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1660 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1663 void DwarfDebug::emitDebugPubSection(
1664 bool GnuStyle, const MCSection *PSec, StringRef Name,
1665 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1666 for (const auto &NU : CUMap) {
1667 DwarfCompileUnit *TheU = NU.second;
1669 const auto &Globals = (TheU->*Accessor)();
1671 if (Globals.empty())
1674 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1676 unsigned ID = TheU->getUniqueID();
1678 // Start the dwarf pubnames section.
1679 Asm->OutStreamer.SwitchSection(PSec);
1682 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1683 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1684 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1685 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1687 Asm->OutStreamer.EmitLabel(BeginLabel);
1689 Asm->OutStreamer.AddComment("DWARF Version");
1690 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1692 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1693 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1695 Asm->OutStreamer.AddComment("Compilation Unit Length");
1696 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1698 // Emit the pubnames for this compilation unit.
1699 for (const auto &GI : Globals) {
1700 const char *Name = GI.getKeyData();
1701 const DIE *Entity = GI.second;
1703 Asm->OutStreamer.AddComment("DIE offset");
1704 Asm->EmitInt32(Entity->getOffset());
1707 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1708 Asm->OutStreamer.AddComment(
1709 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1710 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1711 Asm->EmitInt8(Desc.toBits());
1714 Asm->OutStreamer.AddComment("External Name");
1715 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1718 Asm->OutStreamer.AddComment("End Mark");
1720 Asm->OutStreamer.EmitLabel(EndLabel);
1724 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1725 const MCSection *PSec =
1726 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1727 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1729 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1732 // Emit visible names into a debug str section.
1733 void DwarfDebug::emitDebugStr() {
1734 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1735 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1738 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1739 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1740 const DITypeIdentifierMap &Map,
1741 ArrayRef<DebugLocEntry::Value> Values) {
1742 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1743 return P.isVariablePiece();
1744 }) && "all values are expected to be pieces");
1745 assert(std::is_sorted(Values.begin(), Values.end()) &&
1746 "pieces are expected to be sorted");
1748 unsigned Offset = 0;
1749 for (auto Piece : Values) {
1750 DIExpression Expr = Piece.getExpression();
1751 unsigned PieceOffset = Expr.getPieceOffset();
1752 unsigned PieceSize = Expr.getPieceSize();
1753 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1754 if (Offset < PieceOffset) {
1755 // The DWARF spec seriously mandates pieces with no locations for gaps.
1756 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1757 Offset += PieceOffset-Offset;
1760 Offset += PieceSize;
1762 const unsigned SizeOfByte = 8;
1764 DIVariable Var = Piece.getVariable();
1765 assert(!Var.isIndirect() && "indirect address for piece");
1766 unsigned VarSize = Var.getSizeInBits(Map);
1767 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1768 && "piece is larger than or outside of variable");
1769 assert(PieceSize*SizeOfByte != VarSize
1770 && "piece covers entire variable");
1772 if (Piece.isLocation() && Piece.getLoc().isReg())
1773 Asm->EmitDwarfRegOpPiece(Streamer,
1775 PieceSize*SizeOfByte);
1777 emitDebugLocValue(Streamer, Piece);
1778 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1784 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1785 const DebugLocEntry &Entry) {
1786 const DebugLocEntry::Value Value = Entry.getValues()[0];
1787 if (Value.isVariablePiece())
1788 // Emit all pieces that belong to the same variable and range.
1789 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1791 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1792 emitDebugLocValue(Streamer, Value);
1795 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1796 const DebugLocEntry::Value &Value) {
1797 DIVariable DV = Value.getVariable();
1799 if (Value.isInt()) {
1800 DIBasicType BTy(resolve(DV.getType()));
1801 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1802 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1803 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1804 Streamer.EmitSLEB128(Value.getInt());
1806 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1807 Streamer.EmitULEB128(Value.getInt());
1809 } else if (Value.isLocation()) {
1810 MachineLocation Loc = Value.getLoc();
1811 DIExpression Expr = Value.getExpression();
1814 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1816 // Complex address entry.
1817 unsigned N = Expr.getNumElements();
1819 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1820 if (Loc.getOffset()) {
1822 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1823 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1824 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1825 Streamer.EmitSLEB128(Expr.getElement(1));
1827 // If first address element is OpPlus then emit
1828 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1829 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1830 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1834 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1837 // Emit remaining complex address elements.
1838 for (; i < N; ++i) {
1839 uint64_t Element = Expr.getElement(i);
1840 if (Element == dwarf::DW_OP_plus) {
1841 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1842 Streamer.EmitULEB128(Expr.getElement(++i));
1843 } else if (Element == dwarf::DW_OP_deref) {
1845 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1846 } else if (Element == dwarf::DW_OP_piece) {
1848 // handled in emitDebugLocEntry.
1850 llvm_unreachable("unknown Opcode found in complex address");
1854 // else ... ignore constant fp. There is not any good way to
1855 // to represent them here in dwarf.
1859 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1860 Asm->OutStreamer.AddComment("Loc expr size");
1861 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1862 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1863 Asm->EmitLabelDifference(end, begin, 2);
1864 Asm->OutStreamer.EmitLabel(begin);
1866 APByteStreamer Streamer(*Asm);
1867 emitDebugLocEntry(Streamer, Entry);
1869 Asm->OutStreamer.EmitLabel(end);
1872 // Emit locations into the debug loc section.
1873 void DwarfDebug::emitDebugLoc() {
1874 // Start the dwarf loc section.
1875 Asm->OutStreamer.SwitchSection(
1876 Asm->getObjFileLowering().getDwarfLocSection());
1877 unsigned char Size = Asm->getDataLayout().getPointerSize();
1878 for (const auto &DebugLoc : DotDebugLocEntries) {
1879 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1880 const DwarfCompileUnit *CU = DebugLoc.CU;
1881 assert(!CU->getRanges().empty());
1882 for (const auto &Entry : DebugLoc.List) {
1883 // Set up the range. This range is relative to the entry point of the
1884 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1885 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1886 if (CU->getRanges().size() == 1) {
1887 // Grab the begin symbol from the first range as our base.
1888 const MCSymbol *Base = CU->getRanges()[0].getStart();
1889 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1890 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1892 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1893 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1896 emitDebugLocEntryLocation(Entry);
1898 Asm->OutStreamer.EmitIntValue(0, Size);
1899 Asm->OutStreamer.EmitIntValue(0, Size);
1903 void DwarfDebug::emitDebugLocDWO() {
1904 Asm->OutStreamer.SwitchSection(
1905 Asm->getObjFileLowering().getDwarfLocDWOSection());
1906 for (const auto &DebugLoc : DotDebugLocEntries) {
1907 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1908 for (const auto &Entry : DebugLoc.List) {
1909 // Just always use start_length for now - at least that's one address
1910 // rather than two. We could get fancier and try to, say, reuse an
1911 // address we know we've emitted elsewhere (the start of the function?
1912 // The start of the CU or CU subrange that encloses this range?)
1913 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1914 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1915 Asm->EmitULEB128(idx);
1916 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1918 emitDebugLocEntryLocation(Entry);
1920 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1925 const MCSymbol *Start, *End;
1928 // Emit a debug aranges section, containing a CU lookup for any
1929 // address we can tie back to a CU.
1930 void DwarfDebug::emitDebugARanges() {
1931 // Start the dwarf aranges section.
1932 Asm->OutStreamer.SwitchSection(
1933 Asm->getObjFileLowering().getDwarfARangesSection());
1935 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1939 // Build a list of sections used.
1940 std::vector<const MCSection *> Sections;
1941 for (const auto &it : SectionMap) {
1942 const MCSection *Section = it.first;
1943 Sections.push_back(Section);
1946 // Sort the sections into order.
1947 // This is only done to ensure consistent output order across different runs.
1948 std::sort(Sections.begin(), Sections.end(), SectionSort);
1950 // Build a set of address spans, sorted by CU.
1951 for (const MCSection *Section : Sections) {
1952 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1953 if (List.size() < 2)
1956 // Sort the symbols by offset within the section.
1957 std::sort(List.begin(), List.end(),
1958 [&](const SymbolCU &A, const SymbolCU &B) {
1959 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1960 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1962 // Symbols with no order assigned should be placed at the end.
1963 // (e.g. section end labels)
1971 // If we have no section (e.g. common), just write out
1972 // individual spans for each symbol.
1974 for (const SymbolCU &Cur : List) {
1976 Span.Start = Cur.Sym;
1979 Spans[Cur.CU].push_back(Span);
1982 // Build spans between each label.
1983 const MCSymbol *StartSym = List[0].Sym;
1984 for (size_t n = 1, e = List.size(); n < e; n++) {
1985 const SymbolCU &Prev = List[n - 1];
1986 const SymbolCU &Cur = List[n];
1988 // Try and build the longest span we can within the same CU.
1989 if (Cur.CU != Prev.CU) {
1991 Span.Start = StartSym;
1993 Spans[Prev.CU].push_back(Span);
2000 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2002 // Build a list of CUs used.
2003 std::vector<DwarfCompileUnit *> CUs;
2004 for (const auto &it : Spans) {
2005 DwarfCompileUnit *CU = it.first;
2009 // Sort the CU list (again, to ensure consistent output order).
2010 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2011 return A->getUniqueID() < B->getUniqueID();
2014 // Emit an arange table for each CU we used.
2015 for (DwarfCompileUnit *CU : CUs) {
2016 std::vector<ArangeSpan> &List = Spans[CU];
2018 // Emit size of content not including length itself.
2019 unsigned ContentSize =
2020 sizeof(int16_t) + // DWARF ARange version number
2021 sizeof(int32_t) + // Offset of CU in the .debug_info section
2022 sizeof(int8_t) + // Pointer Size (in bytes)
2023 sizeof(int8_t); // Segment Size (in bytes)
2025 unsigned TupleSize = PtrSize * 2;
2027 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2029 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2031 ContentSize += Padding;
2032 ContentSize += (List.size() + 1) * TupleSize;
2034 // For each compile unit, write the list of spans it covers.
2035 Asm->OutStreamer.AddComment("Length of ARange Set");
2036 Asm->EmitInt32(ContentSize);
2037 Asm->OutStreamer.AddComment("DWARF Arange version number");
2038 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2039 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2040 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2041 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2042 Asm->EmitInt8(PtrSize);
2043 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2046 Asm->OutStreamer.EmitFill(Padding, 0xff);
2048 for (const ArangeSpan &Span : List) {
2049 Asm->EmitLabelReference(Span.Start, PtrSize);
2051 // Calculate the size as being from the span start to it's end.
2053 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2055 // For symbols without an end marker (e.g. common), we
2056 // write a single arange entry containing just that one symbol.
2057 uint64_t Size = SymSize[Span.Start];
2061 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2065 Asm->OutStreamer.AddComment("ARange terminator");
2066 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2067 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2071 // Emit visible names into a debug ranges section.
2072 void DwarfDebug::emitDebugRanges() {
2073 // Start the dwarf ranges section.
2074 Asm->OutStreamer.SwitchSection(
2075 Asm->getObjFileLowering().getDwarfRangesSection());
2077 // Size for our labels.
2078 unsigned char Size = Asm->getDataLayout().getPointerSize();
2080 // Grab the specific ranges for the compile units in the module.
2081 for (const auto &I : CUMap) {
2082 DwarfCompileUnit *TheCU = I.second;
2084 // Iterate over the misc ranges for the compile units in the module.
2085 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2086 // Emit our symbol so we can find the beginning of the range.
2087 Asm->OutStreamer.EmitLabel(List.getSym());
2089 for (const RangeSpan &Range : List.getRanges()) {
2090 const MCSymbol *Begin = Range.getStart();
2091 const MCSymbol *End = Range.getEnd();
2092 assert(Begin && "Range without a begin symbol?");
2093 assert(End && "Range without an end symbol?");
2094 if (TheCU->getRanges().size() == 1) {
2095 // Grab the begin symbol from the first range as our base.
2096 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2097 Asm->EmitLabelDifference(Begin, Base, Size);
2098 Asm->EmitLabelDifference(End, Base, Size);
2100 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2101 Asm->OutStreamer.EmitSymbolValue(End, Size);
2105 // And terminate the list with two 0 values.
2106 Asm->OutStreamer.EmitIntValue(0, Size);
2107 Asm->OutStreamer.EmitIntValue(0, Size);
2110 // Now emit a range for the CU itself.
2111 if (TheCU->getRanges().size() > 1) {
2112 Asm->OutStreamer.EmitLabel(
2113 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2114 for (const RangeSpan &Range : TheCU->getRanges()) {
2115 const MCSymbol *Begin = Range.getStart();
2116 const MCSymbol *End = Range.getEnd();
2117 assert(Begin && "Range without a begin symbol?");
2118 assert(End && "Range without an end symbol?");
2119 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2120 Asm->OutStreamer.EmitSymbolValue(End, Size);
2122 // And terminate the list with two 0 values.
2123 Asm->OutStreamer.EmitIntValue(0, Size);
2124 Asm->OutStreamer.EmitIntValue(0, Size);
2129 // DWARF5 Experimental Separate Dwarf emitters.
2131 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2132 std::unique_ptr<DwarfUnit> NewU) {
2133 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2134 U.getCUNode().getSplitDebugFilename());
2136 if (!CompilationDir.empty())
2137 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2139 addGnuPubAttributes(*NewU, Die);
2141 SkeletonHolder.addUnit(std::move(NewU));
2144 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2145 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2146 // DW_AT_addr_base, DW_AT_ranges_base.
2147 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2149 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2150 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2151 DwarfCompileUnit &NewCU = *OwnedUnit;
2152 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2153 DwarfInfoSectionSym);
2155 NewCU.initStmtList(DwarfLineSectionSym);
2157 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2162 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2163 // compile units that would normally be in debug_info.
2164 void DwarfDebug::emitDebugInfoDWO() {
2165 assert(useSplitDwarf() && "No split dwarf debug info?");
2166 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2167 // emit relocations into the dwo file.
2168 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2171 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2172 // abbreviations for the .debug_info.dwo section.
2173 void DwarfDebug::emitDebugAbbrevDWO() {
2174 assert(useSplitDwarf() && "No split dwarf?");
2175 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2178 void DwarfDebug::emitDebugLineDWO() {
2179 assert(useSplitDwarf() && "No split dwarf?");
2180 Asm->OutStreamer.SwitchSection(
2181 Asm->getObjFileLowering().getDwarfLineDWOSection());
2182 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2185 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2186 // string section and is identical in format to traditional .debug_str
2188 void DwarfDebug::emitDebugStrDWO() {
2189 assert(useSplitDwarf() && "No split dwarf?");
2190 const MCSection *OffSec =
2191 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2192 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2196 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2197 if (!useSplitDwarf())
2200 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2201 return &SplitTypeUnitFileTable;
2204 static uint64_t makeTypeSignature(StringRef Identifier) {
2206 Hash.update(Identifier);
2207 // ... take the least significant 8 bytes and return those. Our MD5
2208 // implementation always returns its results in little endian, swap bytes
2210 MD5::MD5Result Result;
2212 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2215 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2216 StringRef Identifier, DIE &RefDie,
2217 DICompositeType CTy) {
2218 // Fast path if we're building some type units and one has already used the
2219 // address pool we know we're going to throw away all this work anyway, so
2220 // don't bother building dependent types.
2221 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2224 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2226 CU.addDIETypeSignature(RefDie, *TU);
2230 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2231 AddrPool.resetUsedFlag();
2233 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2234 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2235 this, &InfoHolder, getDwoLineTable(CU));
2236 DwarfTypeUnit &NewTU = *OwnedUnit;
2237 DIE &UnitDie = NewTU.getUnitDie();
2239 TypeUnitsUnderConstruction.push_back(
2240 std::make_pair(std::move(OwnedUnit), CTy));
2242 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2245 uint64_t Signature = makeTypeSignature(Identifier);
2246 NewTU.setTypeSignature(Signature);
2248 if (useSplitDwarf())
2249 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2250 DwarfTypesDWOSectionSym);
2252 CU.applyStmtList(UnitDie);
2254 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2257 NewTU.setType(NewTU.createTypeDIE(CTy));
2260 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2261 TypeUnitsUnderConstruction.clear();
2263 // Types referencing entries in the address table cannot be placed in type
2265 if (AddrPool.hasBeenUsed()) {
2267 // Remove all the types built while building this type.
2268 // This is pessimistic as some of these types might not be dependent on
2269 // the type that used an address.
2270 for (const auto &TU : TypeUnitsToAdd)
2271 DwarfTypeUnits.erase(TU.second);
2273 // Construct this type in the CU directly.
2274 // This is inefficient because all the dependent types will be rebuilt
2275 // from scratch, including building them in type units, discovering that
2276 // they depend on addresses, throwing them out and rebuilding them.
2277 CU.constructTypeDIE(RefDie, CTy);
2281 // If the type wasn't dependent on fission addresses, finish adding the type
2282 // and all its dependent types.
2283 for (auto &TU : TypeUnitsToAdd)
2284 InfoHolder.addUnit(std::move(TU.first));
2286 CU.addDIETypeSignature(RefDie, NewTU);
2289 // Accelerator table mutators - add each name along with its companion
2290 // DIE to the proper table while ensuring that the name that we're going
2291 // to reference is in the string table. We do this since the names we
2292 // add may not only be identical to the names in the DIE.
2293 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2294 if (!useDwarfAccelTables())
2296 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2300 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2301 if (!useDwarfAccelTables())
2303 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2307 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2308 if (!useDwarfAccelTables())
2310 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2314 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2315 if (!useDwarfAccelTables())
2317 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),