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"
15 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfExpression.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/DIE.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 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
110 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
111 : dwarf::OperationEncodingString(Op));
114 void DebugLocDwarfExpression::EmitSigned(int Value) {
115 BS.EmitSLEB128(Value, Twine(Value));
118 void DebugLocDwarfExpression::EmitUnsigned(unsigned Value) {
119 BS.EmitULEB128(Value, Twine(Value));
122 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
123 // This information is not available while emitting .debug_loc entries.
127 //===----------------------------------------------------------------------===//
129 /// resolve - Look in the DwarfDebug map for the MDNode that
130 /// corresponds to the reference.
131 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
132 return DD->resolve(Ref);
135 bool DbgVariable::isBlockByrefVariable() const {
136 assert(Var.isVariable() && "Invalid complex DbgVariable!");
137 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
140 DIType DbgVariable::getType() const {
141 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
142 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
143 // addresses instead.
144 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
145 /* Byref variables, in Blocks, are declared by the programmer as
146 "SomeType VarName;", but the compiler creates a
147 __Block_byref_x_VarName struct, and gives the variable VarName
148 either the struct, or a pointer to the struct, as its type. This
149 is necessary for various behind-the-scenes things the compiler
150 needs to do with by-reference variables in blocks.
152 However, as far as the original *programmer* is concerned, the
153 variable should still have type 'SomeType', as originally declared.
155 The following function dives into the __Block_byref_x_VarName
156 struct to find the original type of the variable. This will be
157 passed back to the code generating the type for the Debug
158 Information Entry for the variable 'VarName'. 'VarName' will then
159 have the original type 'SomeType' in its debug information.
161 The original type 'SomeType' will be the type of the field named
162 'VarName' inside the __Block_byref_x_VarName struct.
164 NOTE: In order for this to not completely fail on the debugger
165 side, the Debug Information Entry for the variable VarName needs to
166 have a DW_AT_location that tells the debugger how to unwind through
167 the pointers and __Block_byref_x_VarName struct to find the actual
168 value of the variable. The function addBlockByrefType does this. */
170 uint16_t tag = Ty.getTag();
172 if (tag == dwarf::DW_TAG_pointer_type)
173 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
175 DIArray Elements = DICompositeType(subType).getElements();
176 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
177 DIDerivedType DT(Elements.getElement(i));
178 if (getName() == DT.getName())
179 return (resolve(DT.getTypeDerivedFrom()));
185 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
186 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
187 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
188 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
192 InfoHolder(A, "info_string", DIEValueAllocator),
193 UsedNonDefaultText(false),
194 SkeletonHolder(A, "skel_string", DIEValueAllocator),
195 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196 IsPS4(Triple(A->getTargetTriple()).isPS4()),
197 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
198 dwarf::DW_FORM_data4)),
199 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
200 dwarf::DW_FORM_data4)),
201 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
202 dwarf::DW_FORM_data4)),
203 AccelTypes(TypeAtoms) {
208 // Turn on accelerator tables for Darwin by default, pubnames by
209 // default for non-Darwin/PS4, and handle split dwarf.
210 if (DwarfAccelTables == Default)
211 HasDwarfAccelTables = IsDarwin;
213 HasDwarfAccelTables = DwarfAccelTables == Enable;
215 if (SplitDwarf == Default)
216 HasSplitDwarf = false;
218 HasSplitDwarf = SplitDwarf == Enable;
220 if (DwarfPubSections == Default)
221 HasDwarfPubSections = !IsDarwin && !IsPS4;
223 HasDwarfPubSections = DwarfPubSections == Enable;
225 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
226 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
227 : MMI->getModule()->getDwarfVersion();
229 // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
230 // Everybody else uses GNU's.
231 UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
233 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
236 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
241 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
242 DwarfDebug::~DwarfDebug() { }
244 // Switch to the specified MCSection and emit an assembler
245 // temporary label to it if SymbolStem is specified.
246 static void emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
247 StringRef SymbolStem) {
248 Asm->OutStreamer.SwitchSection(Section);
249 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
250 Asm->OutStreamer.EmitLabel(TmpSym);
251 Section->setBeginSymbol(*TmpSym);
254 static bool isObjCClass(StringRef Name) {
255 return Name.startswith("+") || Name.startswith("-");
258 static bool hasObjCCategory(StringRef Name) {
259 if (!isObjCClass(Name))
262 return Name.find(") ") != StringRef::npos;
265 static void getObjCClassCategory(StringRef In, StringRef &Class,
266 StringRef &Category) {
267 if (!hasObjCCategory(In)) {
268 Class = In.slice(In.find('[') + 1, In.find(' '));
273 Class = In.slice(In.find('[') + 1, In.find('('));
274 Category = In.slice(In.find('[') + 1, In.find(' '));
278 static StringRef getObjCMethodName(StringRef In) {
279 return In.slice(In.find(' ') + 1, In.find(']'));
282 // Add the various names to the Dwarf accelerator table names.
283 // TODO: Determine whether or not we should add names for programs
284 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
285 // is only slightly different than the lookup of non-standard ObjC names.
286 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
287 if (!SP.isDefinition())
289 addAccelName(SP.getName(), Die);
291 // If the linkage name is different than the name, go ahead and output
292 // that as well into the name table.
293 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
294 addAccelName(SP.getLinkageName(), Die);
296 // If this is an Objective-C selector name add it to the ObjC accelerator
298 if (isObjCClass(SP.getName())) {
299 StringRef Class, Category;
300 getObjCClassCategory(SP.getName(), Class, Category);
301 addAccelObjC(Class, Die);
303 addAccelObjC(Category, Die);
304 // Also add the base method name to the name table.
305 addAccelName(getObjCMethodName(SP.getName()), Die);
309 /// isSubprogramContext - Return true if Context is either a subprogram
310 /// or another context nested inside a subprogram.
311 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
314 DIDescriptor D(Context);
315 if (D.isSubprogram())
318 return isSubprogramContext(resolve(DIType(Context).getContext()));
322 /// Check whether we should create a DIE for the given Scope, return true
323 /// if we don't create a DIE (the corresponding DIE is null).
324 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
325 if (Scope->isAbstractScope())
328 // We don't create a DIE if there is no Range.
329 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
333 if (Ranges.size() > 1)
336 // We don't create a DIE if we have a single Range and the end label
338 return !getLabelAfterInsn(Ranges.front().second);
341 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
343 if (auto *SkelCU = CU.getSkeleton())
347 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
348 assert(Scope && Scope->getScopeNode());
349 assert(Scope->isAbstractScope());
350 assert(!Scope->getInlinedAt());
352 const MDNode *SP = Scope->getScopeNode();
354 ProcessedSPNodes.insert(SP);
356 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
357 // was inlined from another compile unit.
358 auto &CU = SPMap[SP];
359 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
360 CU.constructAbstractSubprogramScopeDIE(Scope);
364 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
365 if (!GenerateGnuPubSections)
368 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
371 // Create new DwarfCompileUnit for the given metadata node with tag
372 // DW_TAG_compile_unit.
373 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
374 StringRef FN = DIUnit.getFilename();
375 CompilationDir = DIUnit.getDirectory();
377 auto OwnedUnit = make_unique<DwarfCompileUnit>(
378 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
379 DwarfCompileUnit &NewCU = *OwnedUnit;
380 DIE &Die = NewCU.getUnitDie();
381 InfoHolder.addUnit(std::move(OwnedUnit));
383 NewCU.setSkeleton(constructSkeletonCU(NewCU));
385 // LTO with assembly output shares a single line table amongst multiple CUs.
386 // To avoid the compilation directory being ambiguous, let the line table
387 // explicitly describe the directory of all files, never relying on the
388 // compilation directory.
389 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
390 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
391 NewCU.getUniqueID(), CompilationDir);
393 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
394 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
395 DIUnit.getLanguage());
396 NewCU.addString(Die, dwarf::DW_AT_name, FN);
398 if (!useSplitDwarf()) {
399 NewCU.initStmtList();
401 // If we're using split dwarf the compilation dir is going to be in the
402 // skeleton CU and so we don't need to duplicate it here.
403 if (!CompilationDir.empty())
404 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
406 addGnuPubAttributes(NewCU, Die);
409 if (DIUnit.isOptimized())
410 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
412 StringRef Flags = DIUnit.getFlags();
414 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
416 if (unsigned RVer = DIUnit.getRunTimeVersion())
417 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
418 dwarf::DW_FORM_data1, RVer);
421 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
423 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
425 CUMap.insert(std::make_pair(DIUnit, &NewCU));
426 CUDieMap.insert(std::make_pair(&Die, &NewCU));
430 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
432 DIImportedEntity Module(N);
433 assert(Module.Verify());
434 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
435 D->addChild(TheCU.constructImportedEntityDIE(Module));
438 // Emit all Dwarf sections that should come prior to the content. Create
439 // global DIEs and emit initial debug info sections. This is invoked by
440 // the target AsmPrinter.
441 void DwarfDebug::beginModule() {
442 if (DisableDebugInfoPrinting)
445 const Module *M = MMI->getModule();
447 FunctionDIs = makeSubprogramMap(*M);
449 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
452 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
454 // Emit initial sections so we can reference labels later.
457 SingleCU = CU_Nodes->getNumOperands() == 1;
459 for (MDNode *N : CU_Nodes->operands()) {
460 DICompileUnit CUNode(N);
461 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
462 DIArray ImportedEntities = CUNode.getImportedEntities();
463 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
464 ScopesWithImportedEntities.push_back(std::make_pair(
465 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
466 ImportedEntities.getElement(i)));
467 // Stable sort to preserve the order of appearance of imported entities.
468 // This is to avoid out-of-order processing of interdependent declarations
469 // within the same scope, e.g. { namespace A = base; namespace B = A; }
470 std::stable_sort(ScopesWithImportedEntities.begin(),
471 ScopesWithImportedEntities.end(), less_first());
472 DIArray GVs = CUNode.getGlobalVariables();
473 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
474 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
475 DIArray SPs = CUNode.getSubprograms();
476 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
477 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
478 DIArray EnumTypes = CUNode.getEnumTypes();
479 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
480 DIType Ty(EnumTypes.getElement(i));
481 // The enum types array by design contains pointers to
482 // MDNodes rather than DIRefs. Unique them here.
483 DIType UniqueTy(resolve(Ty.getRef()));
484 CU.getOrCreateTypeDIE(UniqueTy);
486 DIArray RetainedTypes = CUNode.getRetainedTypes();
487 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
488 DIType Ty(RetainedTypes.getElement(i));
489 // The retained types array by design contains pointers to
490 // MDNodes rather than DIRefs. Unique them here.
491 DIType UniqueTy(resolve(Ty.getRef()));
492 CU.getOrCreateTypeDIE(UniqueTy);
494 // Emit imported_modules last so that the relevant context is already
496 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
497 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
500 // Tell MMI that we have debug info.
501 MMI->setDebugInfoAvailability(true);
504 void DwarfDebug::finishVariableDefinitions() {
505 for (const auto &Var : ConcreteVariables) {
506 DIE *VariableDie = Var->getDIE();
508 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
509 // in the ConcreteVariables list, rather than looking it up again here.
510 // DIE::getUnit isn't simple - it walks parent pointers, etc.
511 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
513 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
514 if (AbsVar && AbsVar->getDIE()) {
515 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
518 Unit->applyVariableAttributes(*Var, *VariableDie);
522 void DwarfDebug::finishSubprogramDefinitions() {
523 for (const auto &P : SPMap)
524 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
525 CU.finishSubprogramDefinition(DISubprogram(P.first));
530 // Collect info for variables that were optimized out.
531 void DwarfDebug::collectDeadVariables() {
532 const Module *M = MMI->getModule();
534 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
535 for (MDNode *N : CU_Nodes->operands()) {
536 DICompileUnit TheCU(N);
537 // Construct subprogram DIE and add variables DIEs.
538 DwarfCompileUnit *SPCU =
539 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
540 assert(SPCU && "Unable to find Compile Unit!");
541 DIArray Subprograms = TheCU.getSubprograms();
542 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
543 DISubprogram SP(Subprograms.getElement(i));
544 if (ProcessedSPNodes.count(SP) != 0)
546 SPCU->collectDeadVariables(SP);
552 void DwarfDebug::finalizeModuleInfo() {
553 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
555 finishSubprogramDefinitions();
557 finishVariableDefinitions();
559 // Collect info for variables that were optimized out.
560 collectDeadVariables();
562 // Handle anything that needs to be done on a per-unit basis after
563 // all other generation.
564 for (const auto &P : CUMap) {
565 auto &TheCU = *P.second;
566 // Emit DW_AT_containing_type attribute to connect types with their
567 // vtable holding type.
568 TheCU.constructContainingTypeDIEs();
570 // Add CU specific attributes if we need to add any.
571 // If we're splitting the dwarf out now that we've got the entire
572 // CU then add the dwo id to it.
573 auto *SkCU = TheCU.getSkeleton();
574 if (useSplitDwarf()) {
575 // Emit a unique identifier for this CU.
576 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
577 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
578 dwarf::DW_FORM_data8, ID);
579 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
580 dwarf::DW_FORM_data8, ID);
582 // We don't keep track of which addresses are used in which CU so this
583 // is a bit pessimistic under LTO.
584 if (!AddrPool.isEmpty()) {
585 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
586 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
589 if (!SkCU->getRangeLists().empty()) {
590 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
591 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
596 // If we have code split among multiple sections or non-contiguous
597 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
598 // remain in the .o file, otherwise add a DW_AT_low_pc.
599 // FIXME: We should use ranges allow reordering of code ala
600 // .subsections_via_symbols in mach-o. This would mean turning on
601 // ranges for all subprogram DIEs for mach-o.
602 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
603 if (unsigned NumRanges = TheCU.getRanges().size()) {
605 // A DW_AT_low_pc attribute may also be specified in combination with
606 // DW_AT_ranges to specify the default base address for use in
607 // location lists (see Section 2.6.2) and range lists (see Section
609 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
611 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
612 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
616 // Compute DIE offsets and sizes.
617 InfoHolder.computeSizeAndOffsets();
619 SkeletonHolder.computeSizeAndOffsets();
622 // Emit all Dwarf sections that should come after the content.
623 void DwarfDebug::endModule() {
624 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
625 assert(CurFn == nullptr);
626 assert(CurMI == nullptr);
628 // If we aren't actually generating debug info (check beginModule -
629 // conditionalized on !DisableDebugInfoPrinting and the presence of the
630 // llvm.dbg.cu metadata node)
631 if (!TLOF.getDwarfInfoSection()->getBeginSymbol())
634 // Finalize the debug info for the module.
635 finalizeModuleInfo();
642 // Emit info into a debug loc section.
645 // Emit all the DIEs into a debug info section.
648 // Corresponding abbreviations into a abbrev section.
651 // Emit info into a debug aranges section.
652 if (GenerateARangeSection)
655 // Emit info into a debug ranges section.
658 if (useSplitDwarf()) {
661 emitDebugAbbrevDWO();
663 // Emit DWO addresses.
664 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
667 // Emit info into the dwarf accelerator table sections.
668 if (useDwarfAccelTables()) {
671 emitAccelNamespaces();
675 // Emit the pubnames and pubtypes sections if requested.
676 if (HasDwarfPubSections) {
677 emitDebugPubNames(GenerateGnuPubSections);
678 emitDebugPubTypes(GenerateGnuPubSections);
683 AbstractVariables.clear();
686 // Find abstract variable, if any, associated with Var.
687 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
688 DIVariable &Cleansed) {
689 LLVMContext &Ctx = DV->getContext();
690 // More then one inlined variable corresponds to one abstract variable.
691 // FIXME: This duplication of variables when inlining should probably be
692 // removed. It's done to allow each DIVariable to describe its location
693 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
694 // make it accurate then remove this duplication/cleansing stuff.
695 Cleansed = cleanseInlinedVariable(DV, Ctx);
696 auto I = AbstractVariables.find(Cleansed);
697 if (I != AbstractVariables.end())
698 return I->second.get();
702 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
704 return getExistingAbstractVariable(DV, Cleansed);
707 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
708 LexicalScope *Scope) {
709 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
710 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
711 AbstractVariables[Var] = std::move(AbsDbgVariable);
714 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
715 const MDNode *ScopeNode) {
716 DIVariable Cleansed = DV;
717 if (getExistingAbstractVariable(DV, Cleansed))
720 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
724 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
725 const MDNode *ScopeNode) {
726 DIVariable Cleansed = DV;
727 if (getExistingAbstractVariable(DV, Cleansed))
730 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
731 createAbstractVariable(Cleansed, Scope);
734 // Collect variable information from side table maintained by MMI.
735 void DwarfDebug::collectVariableInfoFromMMITable(
736 SmallPtrSetImpl<const MDNode *> &Processed) {
737 for (const auto &VI : MMI->getVariableDbgInfo()) {
740 Processed.insert(VI.Var);
741 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
743 // If variable scope is not found then skip this variable.
747 DIVariable DV(VI.Var);
748 DIExpression Expr(VI.Expr);
749 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
750 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
751 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
752 ConcreteVariables.push_back(std::move(RegVar));
756 // Get .debug_loc entry for the instruction range starting at MI.
757 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
758 const MDNode *Expr = MI->getDebugExpression();
759 const MDNode *Var = MI->getDebugVariable();
761 assert(MI->getNumOperands() == 4);
762 if (MI->getOperand(0).isReg()) {
763 MachineLocation MLoc;
764 // If the second operand is an immediate, this is a
765 // register-indirect address.
766 if (!MI->getOperand(1).isImm())
767 MLoc.set(MI->getOperand(0).getReg());
769 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
770 return DebugLocEntry::Value(Var, Expr, MLoc);
772 if (MI->getOperand(0).isImm())
773 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
774 if (MI->getOperand(0).isFPImm())
775 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
776 if (MI->getOperand(0).isCImm())
777 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
779 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
782 /// Determine whether two variable pieces overlap.
783 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
784 if (!P1.isBitPiece() || !P2.isBitPiece())
786 unsigned l1 = P1.getBitPieceOffset();
787 unsigned l2 = P2.getBitPieceOffset();
788 unsigned r1 = l1 + P1.getBitPieceSize();
789 unsigned r2 = l2 + P2.getBitPieceSize();
790 // True where [l1,r1[ and [r1,r2[ overlap.
791 return (l1 < r2) && (l2 < r1);
794 /// Build the location list for all DBG_VALUEs in the function that
795 /// describe the same variable. If the ranges of several independent
796 /// pieces of the same variable overlap partially, split them up and
797 /// combine the ranges. The resulting DebugLocEntries are will have
798 /// strict monotonically increasing begin addresses and will never
803 // Ranges History [var, loc, piece ofs size]
804 // 0 | [x, (reg0, piece 0, 32)]
805 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
807 // 3 | [clobber reg0]
808 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
813 // [0-1] [x, (reg0, piece 0, 32)]
814 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
815 // [3-4] [x, (reg1, piece 32, 32)]
816 // [4- ] [x, (mem, piece 0, 64)]
818 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
819 const DbgValueHistoryMap::InstrRanges &Ranges) {
820 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
822 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
823 const MachineInstr *Begin = I->first;
824 const MachineInstr *End = I->second;
825 assert(Begin->isDebugValue() && "Invalid History entry");
827 // Check if a variable is inaccessible in this range.
828 if (Begin->getNumOperands() > 1 &&
829 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
834 // If this piece overlaps with any open ranges, truncate them.
835 DIExpression DIExpr = Begin->getDebugExpression();
836 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
837 [&](DebugLocEntry::Value R) {
838 return piecesOverlap(DIExpr, R.getExpression());
840 OpenRanges.erase(Last, OpenRanges.end());
842 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
843 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
845 const MCSymbol *EndLabel;
847 EndLabel = getLabelAfterInsn(End);
848 else if (std::next(I) == Ranges.end())
849 EndLabel = Asm->getFunctionEnd();
851 EndLabel = getLabelBeforeInsn(std::next(I)->first);
852 assert(EndLabel && "Forgot label after instruction ending a range!");
854 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
856 auto Value = getDebugLocValue(Begin);
857 DebugLocEntry Loc(StartLabel, EndLabel, Value);
858 bool couldMerge = false;
860 // If this is a piece, it may belong to the current DebugLocEntry.
861 if (DIExpr.isBitPiece()) {
862 // Add this value to the list of open ranges.
863 OpenRanges.push_back(Value);
865 // Attempt to add the piece to the last entry.
866 if (!DebugLoc.empty())
867 if (DebugLoc.back().MergeValues(Loc))
872 // Need to add a new DebugLocEntry. Add all values from still
873 // valid non-overlapping pieces.
874 if (OpenRanges.size())
875 Loc.addValues(OpenRanges);
877 DebugLoc.push_back(std::move(Loc));
880 // Attempt to coalesce the ranges of two otherwise identical
882 auto CurEntry = DebugLoc.rbegin();
883 auto PrevEntry = std::next(CurEntry);
884 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
888 dbgs() << CurEntry->getValues().size() << " Values:\n";
889 for (auto Value : CurEntry->getValues()) {
890 Value.getVariable()->dump();
891 Value.getExpression()->dump();
899 // Find variables for each lexical scope.
901 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
902 SmallPtrSetImpl<const MDNode *> &Processed) {
903 // Grab the variable info that was squirreled away in the MMI side-table.
904 collectVariableInfoFromMMITable(Processed);
906 for (const auto &I : DbgValues) {
907 DIVariable DV(I.first);
908 if (Processed.count(DV))
911 // Instruction ranges, specifying where DV is accessible.
912 const auto &Ranges = I.second;
916 LexicalScope *Scope = nullptr;
917 if (MDNode *IA = DV.getInlinedAt())
918 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
920 Scope = LScopes.findLexicalScope(DV.getContext());
921 // If variable scope is not found then skip this variable.
925 Processed.insert(DV);
926 const MachineInstr *MInsn = Ranges.front().first;
927 assert(MInsn->isDebugValue() && "History must begin with debug value");
928 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
929 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
930 DbgVariable *RegVar = ConcreteVariables.back().get();
931 InfoHolder.addScopeVariable(Scope, RegVar);
933 // Check if the first DBG_VALUE is valid for the rest of the function.
934 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
937 // Handle multiple DBG_VALUE instructions describing one variable.
938 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
940 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
941 DebugLocList &LocList = DotDebugLocEntries.back();
944 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
946 // Build the location list for this variable.
947 buildLocationList(LocList.List, Ranges);
948 // Finalize the entry by lowering it into a DWARF bytestream.
949 for (auto &Entry : LocList.List)
950 Entry.finalize(*Asm, TypeIdentifierMap);
953 // Collect info for variables that were optimized out.
954 DIArray Variables = SP.getVariables();
955 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
956 DIVariable DV(Variables.getElement(i));
957 assert(DV.isVariable());
958 if (!Processed.insert(DV).second)
960 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
961 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
963 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
964 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
969 // Return Label preceding the instruction.
970 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
971 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
972 assert(Label && "Didn't insert label before instruction");
976 // Return Label immediately following the instruction.
977 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
978 return LabelsAfterInsn.lookup(MI);
981 // Process beginning of an instruction.
982 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
983 assert(CurMI == nullptr);
985 // Check if source location changes, but ignore DBG_VALUE locations.
986 if (!MI->isDebugValue()) {
987 DebugLoc DL = MI->getDebugLoc();
988 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
991 if (DL == PrologEndLoc) {
992 Flags |= DWARF2_FLAG_PROLOGUE_END;
993 PrologEndLoc = DebugLoc();
994 Flags |= DWARF2_FLAG_IS_STMT;
997 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
998 Flags |= DWARF2_FLAG_IS_STMT;
1000 if (!DL.isUnknown()) {
1001 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1002 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1004 recordSourceLine(0, 0, nullptr, 0);
1008 // Insert labels where requested.
1009 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1010 LabelsBeforeInsn.find(MI);
1013 if (I == LabelsBeforeInsn.end())
1016 // Label already assigned.
1021 PrevLabel = MMI->getContext().CreateTempSymbol();
1022 Asm->OutStreamer.EmitLabel(PrevLabel);
1024 I->second = PrevLabel;
1027 // Process end of an instruction.
1028 void DwarfDebug::endInstruction() {
1029 assert(CurMI != nullptr);
1030 // Don't create a new label after DBG_VALUE instructions.
1031 // They don't generate code.
1032 if (!CurMI->isDebugValue())
1033 PrevLabel = nullptr;
1035 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1036 LabelsAfterInsn.find(CurMI);
1040 if (I == LabelsAfterInsn.end())
1043 // Label already assigned.
1047 // We need a label after this instruction.
1049 PrevLabel = MMI->getContext().CreateTempSymbol();
1050 Asm->OutStreamer.EmitLabel(PrevLabel);
1052 I->second = PrevLabel;
1055 // Each LexicalScope has first instruction and last instruction to mark
1056 // beginning and end of a scope respectively. Create an inverse map that list
1057 // scopes starts (and ends) with an instruction. One instruction may start (or
1058 // end) multiple scopes. Ignore scopes that are not reachable.
1059 void DwarfDebug::identifyScopeMarkers() {
1060 SmallVector<LexicalScope *, 4> WorkList;
1061 WorkList.push_back(LScopes.getCurrentFunctionScope());
1062 while (!WorkList.empty()) {
1063 LexicalScope *S = WorkList.pop_back_val();
1065 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1066 if (!Children.empty())
1067 WorkList.append(Children.begin(), Children.end());
1069 if (S->isAbstractScope())
1072 for (const InsnRange &R : S->getRanges()) {
1073 assert(R.first && "InsnRange does not have first instruction!");
1074 assert(R.second && "InsnRange does not have second instruction!");
1075 requestLabelBeforeInsn(R.first);
1076 requestLabelAfterInsn(R.second);
1081 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1082 // First known non-DBG_VALUE and non-frame setup location marks
1083 // the beginning of the function body.
1084 for (const auto &MBB : *MF)
1085 for (const auto &MI : MBB)
1086 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1087 !MI.getDebugLoc().isUnknown()) {
1088 // Did the target forget to set the FrameSetup flag for CFI insns?
1089 assert(!MI.isCFIInstruction() &&
1090 "First non-frame-setup instruction is a CFI instruction.");
1091 return MI.getDebugLoc();
1096 // Gather pre-function debug information. Assumes being called immediately
1097 // after the function entry point has been emitted.
1098 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1101 // If there's no debug info for the function we're not going to do anything.
1102 if (!MMI->hasDebugInfo())
1105 auto DI = FunctionDIs.find(MF->getFunction());
1106 if (DI == FunctionDIs.end())
1109 // Grab the lexical scopes for the function, if we don't have any of those
1110 // then we're not going to be able to do anything.
1111 LScopes.initialize(*MF);
1112 if (LScopes.empty())
1115 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1117 // Make sure that each lexical scope will have a begin/end label.
1118 identifyScopeMarkers();
1120 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1121 // belongs to so that we add to the correct per-cu line table in the
1123 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1124 // FnScope->getScopeNode() and DI->second should represent the same function,
1125 // though they may not be the same MDNode due to inline functions merged in
1126 // LTO where the debug info metadata still differs (either due to distinct
1127 // written differences - two versions of a linkonce_odr function
1128 // written/copied into two separate files, or some sub-optimal metadata that
1129 // isn't structurally identical (see: file path/name info from clang, which
1130 // includes the directory of the cpp file being built, even when the file name
1131 // is absolute (such as an <> lookup header)))
1132 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1133 assert(TheCU && "Unable to find compile unit!");
1134 if (Asm->OutStreamer.hasRawTextSupport())
1135 // Use a single line table if we are generating assembly.
1136 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1138 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1140 // Calculate history for local variables.
1141 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1144 // Request labels for the full history.
1145 for (const auto &I : DbgValues) {
1146 const auto &Ranges = I.second;
1150 // The first mention of a function argument gets the CurrentFnBegin
1151 // label, so arguments are visible when breaking at function entry.
1152 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1153 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1154 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1155 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1156 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1157 // Mark all non-overlapping initial pieces.
1158 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1159 DIExpression Piece = I->first->getDebugExpression();
1160 if (std::all_of(Ranges.begin(), I,
1161 [&](DbgValueHistoryMap::InstrRange Pred) {
1162 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1164 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1171 for (const auto &Range : Ranges) {
1172 requestLabelBeforeInsn(Range.first);
1174 requestLabelAfterInsn(Range.second);
1178 PrevInstLoc = DebugLoc();
1179 PrevLabel = Asm->getFunctionBegin();
1181 // Record beginning of function.
1182 PrologEndLoc = findPrologueEndLoc(MF);
1183 if (!PrologEndLoc.isUnknown()) {
1184 DebugLoc FnStartDL =
1185 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1187 // We'd like to list the prologue as "not statements" but GDB behaves
1188 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1189 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1190 FnStartDL.getScope(MF->getFunction()->getContext()),
1191 DWARF2_FLAG_IS_STMT);
1195 // Gather and emit post-function debug information.
1196 void DwarfDebug::endFunction(const MachineFunction *MF) {
1197 assert(CurFn == MF &&
1198 "endFunction should be called with the same function as beginFunction");
1200 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1201 !FunctionDIs.count(MF->getFunction())) {
1202 // If we don't have a lexical scope for this function then there will
1203 // be a hole in the range information. Keep note of this by setting the
1204 // previously used section to nullptr.
1210 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1211 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1213 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1214 DISubprogram SP(FnScope->getScopeNode());
1215 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1217 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1218 collectVariableInfo(TheCU, SP, ProcessedVars);
1220 // Add the range of this function to the list of ranges for the CU.
1221 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1223 // Under -gmlt, skip building the subprogram if there are no inlined
1224 // subroutines inside it.
1225 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1226 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1227 assert(InfoHolder.getScopeVariables().empty());
1228 assert(DbgValues.empty());
1229 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1230 // by a -gmlt CU. Add a test and remove this assertion.
1231 assert(AbstractVariables.empty());
1232 LabelsBeforeInsn.clear();
1233 LabelsAfterInsn.clear();
1234 PrevLabel = nullptr;
1240 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1242 // Construct abstract scopes.
1243 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1244 DISubprogram SP(AScope->getScopeNode());
1245 assert(SP.isSubprogram());
1246 // Collect info for variables that were optimized out.
1247 DIArray Variables = SP.getVariables();
1248 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1249 DIVariable DV(Variables.getElement(i));
1250 assert(DV && DV.isVariable());
1251 if (!ProcessedVars.insert(DV).second)
1253 ensureAbstractVariableIsCreated(DV, DV.getContext());
1254 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1255 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1257 constructAbstractSubprogramScopeDIE(AScope);
1260 TheCU.constructSubprogramScopeDIE(FnScope);
1261 if (auto *SkelCU = TheCU.getSkeleton())
1262 if (!LScopes.getAbstractScopesList().empty())
1263 SkelCU->constructSubprogramScopeDIE(FnScope);
1266 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1267 // DbgVariables except those that are also in AbstractVariables (since they
1268 // can be used cross-function)
1269 InfoHolder.getScopeVariables().clear();
1271 LabelsBeforeInsn.clear();
1272 LabelsAfterInsn.clear();
1273 PrevLabel = nullptr;
1277 // Register a source line with debug info. Returns the unique label that was
1278 // emitted and which provides correspondence to the source line list.
1279 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1284 unsigned Discriminator = 0;
1285 if (DIScope Scope = DIScope(S)) {
1286 assert(Scope.isScope());
1287 Fn = Scope.getFilename();
1288 Dir = Scope.getDirectory();
1289 if (Scope.isLexicalBlockFile())
1290 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1292 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1293 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1294 .getOrCreateSourceID(Fn, Dir);
1296 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1300 //===----------------------------------------------------------------------===//
1302 //===----------------------------------------------------------------------===//
1304 // Emit initial Dwarf sections with a label at the start of each one.
1305 void DwarfDebug::emitSectionLabels() {
1306 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1308 // Dwarf sections base addresses.
1309 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1310 if (useSplitDwarf()) {
1311 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1312 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1314 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1315 if (useSplitDwarf())
1316 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1318 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1319 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1320 if (useSplitDwarf()) {
1321 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1322 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1323 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1325 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1326 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1329 // Emit the debug info section.
1330 void DwarfDebug::emitDebugInfo() {
1331 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1332 Holder.emitUnits(/* UseOffsets */ false);
1335 // Emit the abbreviation section.
1336 void DwarfDebug::emitAbbreviations() {
1337 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1339 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1342 // Emit the last address of the section and the end of the line matrix.
1343 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1344 // Define last address of section.
1345 Asm->OutStreamer.AddComment("Extended Op");
1348 Asm->OutStreamer.AddComment("Op size");
1349 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1350 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1351 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1353 Asm->OutStreamer.AddComment("Section end label");
1355 Asm->OutStreamer.EmitSymbolValue(
1356 Asm->GetTempSymbol("section_end", SectionEnd),
1357 Asm->getDataLayout().getPointerSize());
1359 // Mark end of matrix.
1360 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1366 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1367 StringRef TableName, StringRef SymName) {
1368 Accel.FinalizeTable(Asm, TableName);
1369 emitSectionSym(Asm, Section, SymName);
1371 // Emit the full data.
1372 Accel.emit(Asm, Section->getBeginSymbol(), this);
1375 // Emit visible names into a hashed accelerator table section.
1376 void DwarfDebug::emitAccelNames() {
1377 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1378 "Names", "names_begin");
1381 // Emit objective C classes and categories into a hashed accelerator table
1383 void DwarfDebug::emitAccelObjC() {
1384 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1385 "ObjC", "objc_begin");
1388 // Emit namespace dies into a hashed accelerator table.
1389 void DwarfDebug::emitAccelNamespaces() {
1390 emitAccel(AccelNamespace,
1391 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1392 "namespac", "namespac_begin");
1395 // Emit type dies into a hashed accelerator table.
1396 void DwarfDebug::emitAccelTypes() {
1397 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1398 "types", "types_begin");
1401 // Public name handling.
1402 // The format for the various pubnames:
1404 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1405 // for the DIE that is named.
1407 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1408 // into the CU and the index value is computed according to the type of value
1409 // for the DIE that is named.
1411 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1412 // it's the offset within the debug_info/debug_types dwo section, however, the
1413 // reference in the pubname header doesn't change.
1415 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1416 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1418 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1420 // We could have a specification DIE that has our most of our knowledge,
1421 // look for that now.
1422 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1424 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1425 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1426 Linkage = dwarf::GIEL_EXTERNAL;
1427 } else if (Die->findAttribute(dwarf::DW_AT_external))
1428 Linkage = dwarf::GIEL_EXTERNAL;
1430 switch (Die->getTag()) {
1431 case dwarf::DW_TAG_class_type:
1432 case dwarf::DW_TAG_structure_type:
1433 case dwarf::DW_TAG_union_type:
1434 case dwarf::DW_TAG_enumeration_type:
1435 return dwarf::PubIndexEntryDescriptor(
1436 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1437 ? dwarf::GIEL_STATIC
1438 : dwarf::GIEL_EXTERNAL);
1439 case dwarf::DW_TAG_typedef:
1440 case dwarf::DW_TAG_base_type:
1441 case dwarf::DW_TAG_subrange_type:
1442 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1443 case dwarf::DW_TAG_namespace:
1444 return dwarf::GIEK_TYPE;
1445 case dwarf::DW_TAG_subprogram:
1446 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1447 case dwarf::DW_TAG_variable:
1448 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1449 case dwarf::DW_TAG_enumerator:
1450 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1451 dwarf::GIEL_STATIC);
1453 return dwarf::GIEK_NONE;
1457 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1459 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1460 const MCSection *PSec =
1461 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1462 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1464 emitDebugPubSection(GnuStyle, PSec, "Names",
1465 &DwarfCompileUnit::getGlobalNames);
1468 void DwarfDebug::emitDebugPubSection(
1469 bool GnuStyle, const MCSection *PSec, StringRef Name,
1470 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1471 for (const auto &NU : CUMap) {
1472 DwarfCompileUnit *TheU = NU.second;
1474 const auto &Globals = (TheU->*Accessor)();
1476 if (Globals.empty())
1479 if (auto *Skeleton = TheU->getSkeleton())
1481 unsigned ID = TheU->getUniqueID();
1483 // Start the dwarf pubnames section.
1484 Asm->OutStreamer.SwitchSection(PSec);
1487 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1488 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1489 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1490 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1492 Asm->OutStreamer.EmitLabel(BeginLabel);
1494 Asm->OutStreamer.AddComment("DWARF Version");
1495 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1497 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1498 Asm->emitSectionOffset(TheU->getLabelBegin());
1500 Asm->OutStreamer.AddComment("Compilation Unit Length");
1501 Asm->EmitInt32(TheU->getLength());
1503 // Emit the pubnames for this compilation unit.
1504 for (const auto &GI : Globals) {
1505 const char *Name = GI.getKeyData();
1506 const DIE *Entity = GI.second;
1508 Asm->OutStreamer.AddComment("DIE offset");
1509 Asm->EmitInt32(Entity->getOffset());
1512 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1513 Asm->OutStreamer.AddComment(
1514 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1515 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1516 Asm->EmitInt8(Desc.toBits());
1519 Asm->OutStreamer.AddComment("External Name");
1520 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1523 Asm->OutStreamer.AddComment("End Mark");
1525 Asm->OutStreamer.EmitLabel(EndLabel);
1529 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1530 const MCSection *PSec =
1531 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1532 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1534 emitDebugPubSection(GnuStyle, PSec, "Types",
1535 &DwarfCompileUnit::getGlobalTypes);
1538 // Emit visible names into a debug str section.
1539 void DwarfDebug::emitDebugStr() {
1540 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1541 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1545 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1546 const DebugLocEntry &Entry) {
1547 auto Comment = Entry.getComments().begin();
1548 auto End = Entry.getComments().end();
1549 for (uint8_t Byte : Entry.getDWARFBytes())
1550 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1553 static void emitDebugLocValue(const AsmPrinter &AP,
1554 const DITypeIdentifierMap &TypeIdentifierMap,
1555 ByteStreamer &Streamer,
1556 const DebugLocEntry::Value &Value,
1557 unsigned PieceOffsetInBits) {
1558 DIVariable DV = Value.getVariable();
1559 DebugLocDwarfExpression DwarfExpr(
1560 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1561 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1563 if (Value.isInt()) {
1564 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1565 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1566 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1567 DwarfExpr.AddSignedConstant(Value.getInt());
1569 DwarfExpr.AddUnsignedConstant(Value.getInt());
1570 } else if (Value.isLocation()) {
1571 MachineLocation Loc = Value.getLoc();
1572 DIExpression Expr = Value.getExpression();
1573 if (!Expr || (Expr.getNumElements() == 0))
1575 AP.EmitDwarfRegOp(Streamer, Loc);
1577 // Complex address entry.
1578 if (Loc.getOffset()) {
1579 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1580 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1582 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1586 // else ... ignore constant fp. There is not any good way to
1587 // to represent them here in dwarf.
1592 void DebugLocEntry::finalize(const AsmPrinter &AP,
1593 const DITypeIdentifierMap &TypeIdentifierMap) {
1594 BufferByteStreamer Streamer(DWARFBytes, Comments);
1595 const DebugLocEntry::Value Value = Values[0];
1596 if (Value.isBitPiece()) {
1597 // Emit all pieces that belong to the same variable and range.
1598 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1599 return P.isBitPiece();
1600 }) && "all values are expected to be pieces");
1601 assert(std::is_sorted(Values.begin(), Values.end()) &&
1602 "pieces are expected to be sorted");
1604 unsigned Offset = 0;
1605 for (auto Piece : Values) {
1606 DIExpression Expr = Piece.getExpression();
1607 unsigned PieceOffset = Expr.getBitPieceOffset();
1608 unsigned PieceSize = Expr.getBitPieceSize();
1609 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1610 if (Offset < PieceOffset) {
1611 // The DWARF spec seriously mandates pieces with no locations for gaps.
1612 DebugLocDwarfExpression Expr(
1613 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1614 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1615 Expr.AddOpPiece(PieceOffset-Offset, 0);
1616 Offset += PieceOffset-Offset;
1618 Offset += PieceSize;
1621 DIVariable Var = Piece.getVariable();
1622 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1623 assert(PieceSize+PieceOffset <= VarSize
1624 && "piece is larger than or outside of variable");
1625 assert(PieceSize != VarSize
1626 && "piece covers entire variable");
1628 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1631 assert(Values.size() == 1 && "only pieces may have >1 value");
1632 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1637 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1638 Asm->OutStreamer.AddComment("Loc expr size");
1639 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1640 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1641 Asm->EmitLabelDifference(end, begin, 2);
1642 Asm->OutStreamer.EmitLabel(begin);
1644 APByteStreamer Streamer(*Asm);
1645 emitDebugLocEntry(Streamer, Entry);
1647 Asm->OutStreamer.EmitLabel(end);
1650 // Emit locations into the debug loc section.
1651 void DwarfDebug::emitDebugLoc() {
1652 // Start the dwarf loc section.
1653 Asm->OutStreamer.SwitchSection(
1654 Asm->getObjFileLowering().getDwarfLocSection());
1655 unsigned char Size = Asm->getDataLayout().getPointerSize();
1656 for (const auto &DebugLoc : DotDebugLocEntries) {
1657 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1658 const DwarfCompileUnit *CU = DebugLoc.CU;
1659 for (const auto &Entry : DebugLoc.List) {
1660 // Set up the range. This range is relative to the entry point of the
1661 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1662 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1663 if (auto *Base = CU->getBaseAddress()) {
1664 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1665 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1667 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1668 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1671 emitDebugLocEntryLocation(Entry);
1673 Asm->OutStreamer.EmitIntValue(0, Size);
1674 Asm->OutStreamer.EmitIntValue(0, Size);
1678 void DwarfDebug::emitDebugLocDWO() {
1679 Asm->OutStreamer.SwitchSection(
1680 Asm->getObjFileLowering().getDwarfLocDWOSection());
1681 for (const auto &DebugLoc : DotDebugLocEntries) {
1682 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1683 for (const auto &Entry : DebugLoc.List) {
1684 // Just always use start_length for now - at least that's one address
1685 // rather than two. We could get fancier and try to, say, reuse an
1686 // address we know we've emitted elsewhere (the start of the function?
1687 // The start of the CU or CU subrange that encloses this range?)
1688 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1689 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1690 Asm->EmitULEB128(idx);
1691 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1693 emitDebugLocEntryLocation(Entry);
1695 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1700 const MCSymbol *Start, *End;
1703 // Emit a debug aranges section, containing a CU lookup for any
1704 // address we can tie back to a CU.
1705 void DwarfDebug::emitDebugARanges() {
1706 // Provides a unique id per text section.
1707 MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1709 // Filter labels by section.
1710 for (const SymbolCU &SCU : ArangeLabels) {
1711 if (SCU.Sym->isInSection()) {
1712 // Make a note of this symbol and it's section.
1713 const MCSection *Section = &SCU.Sym->getSection();
1714 if (!Section->getKind().isMetadata())
1715 SectionMap[Section].push_back(SCU);
1717 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1718 // appear in the output. This sucks as we rely on sections to build
1719 // arange spans. We can do it without, but it's icky.
1720 SectionMap[nullptr].push_back(SCU);
1724 // Add terminating symbols for each section.
1726 for (const auto &I : SectionMap) {
1727 const MCSection *Section = I.first;
1728 MCSymbol *Sym = nullptr;
1731 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1732 // if we know the section name up-front. For user-created sections, the
1733 // resulting label may not be valid to use as a label. (section names can
1734 // use a greater set of characters on some systems)
1735 Sym = Asm->GetTempSymbol("debug_end", ID);
1736 Asm->OutStreamer.SwitchSection(Section);
1737 Asm->OutStreamer.EmitLabel(Sym);
1740 // Insert a final terminator.
1741 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1745 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1747 for (auto &I : SectionMap) {
1748 const MCSection *Section = I.first;
1749 SmallVector<SymbolCU, 8> &List = I.second;
1750 if (List.size() < 2)
1753 // If we have no section (e.g. common), just write out
1754 // individual spans for each symbol.
1756 for (const SymbolCU &Cur : List) {
1758 Span.Start = Cur.Sym;
1761 Spans[Cur.CU].push_back(Span);
1766 // Sort the symbols by offset within the section.
1767 std::sort(List.begin(), List.end(),
1768 [&](const SymbolCU &A, const SymbolCU &B) {
1769 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1770 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1772 // Symbols with no order assigned should be placed at the end.
1773 // (e.g. section end labels)
1781 // Build spans between each label.
1782 const MCSymbol *StartSym = List[0].Sym;
1783 for (size_t n = 1, e = List.size(); n < e; n++) {
1784 const SymbolCU &Prev = List[n - 1];
1785 const SymbolCU &Cur = List[n];
1787 // Try and build the longest span we can within the same CU.
1788 if (Cur.CU != Prev.CU) {
1790 Span.Start = StartSym;
1792 Spans[Prev.CU].push_back(Span);
1798 // Start the dwarf aranges section.
1799 Asm->OutStreamer.SwitchSection(
1800 Asm->getObjFileLowering().getDwarfARangesSection());
1802 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1804 // Build a list of CUs used.
1805 std::vector<DwarfCompileUnit *> CUs;
1806 for (const auto &it : Spans) {
1807 DwarfCompileUnit *CU = it.first;
1811 // Sort the CU list (again, to ensure consistent output order).
1812 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1813 return A->getUniqueID() < B->getUniqueID();
1816 // Emit an arange table for each CU we used.
1817 for (DwarfCompileUnit *CU : CUs) {
1818 std::vector<ArangeSpan> &List = Spans[CU];
1820 // Describe the skeleton CU's offset and length, not the dwo file's.
1821 if (auto *Skel = CU->getSkeleton())
1824 // Emit size of content not including length itself.
1825 unsigned ContentSize =
1826 sizeof(int16_t) + // DWARF ARange version number
1827 sizeof(int32_t) + // Offset of CU in the .debug_info section
1828 sizeof(int8_t) + // Pointer Size (in bytes)
1829 sizeof(int8_t); // Segment Size (in bytes)
1831 unsigned TupleSize = PtrSize * 2;
1833 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1835 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1837 ContentSize += Padding;
1838 ContentSize += (List.size() + 1) * TupleSize;
1840 // For each compile unit, write the list of spans it covers.
1841 Asm->OutStreamer.AddComment("Length of ARange Set");
1842 Asm->EmitInt32(ContentSize);
1843 Asm->OutStreamer.AddComment("DWARF Arange version number");
1844 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1845 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1846 Asm->emitSectionOffset(CU->getLabelBegin());
1847 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1848 Asm->EmitInt8(PtrSize);
1849 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1852 Asm->OutStreamer.EmitFill(Padding, 0xff);
1854 for (const ArangeSpan &Span : List) {
1855 Asm->EmitLabelReference(Span.Start, PtrSize);
1857 // Calculate the size as being from the span start to it's end.
1859 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1861 // For symbols without an end marker (e.g. common), we
1862 // write a single arange entry containing just that one symbol.
1863 uint64_t Size = SymSize[Span.Start];
1867 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1871 Asm->OutStreamer.AddComment("ARange terminator");
1872 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1873 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1877 // Emit visible names into a debug ranges section.
1878 void DwarfDebug::emitDebugRanges() {
1879 // Start the dwarf ranges section.
1880 Asm->OutStreamer.SwitchSection(
1881 Asm->getObjFileLowering().getDwarfRangesSection());
1883 // Size for our labels.
1884 unsigned char Size = Asm->getDataLayout().getPointerSize();
1886 // Grab the specific ranges for the compile units in the module.
1887 for (const auto &I : CUMap) {
1888 DwarfCompileUnit *TheCU = I.second;
1890 if (auto *Skel = TheCU->getSkeleton())
1893 // Iterate over the misc ranges for the compile units in the module.
1894 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1895 // Emit our symbol so we can find the beginning of the range.
1896 Asm->OutStreamer.EmitLabel(List.getSym());
1898 for (const RangeSpan &Range : List.getRanges()) {
1899 const MCSymbol *Begin = Range.getStart();
1900 const MCSymbol *End = Range.getEnd();
1901 assert(Begin && "Range without a begin symbol?");
1902 assert(End && "Range without an end symbol?");
1903 if (auto *Base = TheCU->getBaseAddress()) {
1904 Asm->EmitLabelDifference(Begin, Base, Size);
1905 Asm->EmitLabelDifference(End, Base, Size);
1907 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1908 Asm->OutStreamer.EmitSymbolValue(End, Size);
1912 // And terminate the list with two 0 values.
1913 Asm->OutStreamer.EmitIntValue(0, Size);
1914 Asm->OutStreamer.EmitIntValue(0, Size);
1919 // DWARF5 Experimental Separate Dwarf emitters.
1921 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1922 std::unique_ptr<DwarfUnit> NewU) {
1923 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1924 U.getCUNode().getSplitDebugFilename());
1926 if (!CompilationDir.empty())
1927 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1929 addGnuPubAttributes(*NewU, Die);
1931 SkeletonHolder.addUnit(std::move(NewU));
1934 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1935 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1936 // DW_AT_addr_base, DW_AT_ranges_base.
1937 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1939 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1940 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1941 DwarfCompileUnit &NewCU = *OwnedUnit;
1942 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1944 NewCU.initStmtList();
1946 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1951 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1952 // compile units that would normally be in debug_info.
1953 void DwarfDebug::emitDebugInfoDWO() {
1954 assert(useSplitDwarf() && "No split dwarf debug info?");
1955 // Don't emit relocations into the dwo file.
1956 InfoHolder.emitUnits(/* UseOffsets */ true);
1959 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1960 // abbreviations for the .debug_info.dwo section.
1961 void DwarfDebug::emitDebugAbbrevDWO() {
1962 assert(useSplitDwarf() && "No split dwarf?");
1963 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1966 void DwarfDebug::emitDebugLineDWO() {
1967 assert(useSplitDwarf() && "No split dwarf?");
1968 Asm->OutStreamer.SwitchSection(
1969 Asm->getObjFileLowering().getDwarfLineDWOSection());
1970 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1973 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1974 // string section and is identical in format to traditional .debug_str
1976 void DwarfDebug::emitDebugStrDWO() {
1977 assert(useSplitDwarf() && "No split dwarf?");
1978 const MCSection *OffSec =
1979 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1980 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1984 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1985 if (!useSplitDwarf())
1988 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1989 return &SplitTypeUnitFileTable;
1992 static uint64_t makeTypeSignature(StringRef Identifier) {
1994 Hash.update(Identifier);
1995 // ... take the least significant 8 bytes and return those. Our MD5
1996 // implementation always returns its results in little endian, swap bytes
1998 MD5::MD5Result Result;
2000 return support::endian::read64le(Result + 8);
2003 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2004 StringRef Identifier, DIE &RefDie,
2005 DICompositeType CTy) {
2006 // Fast path if we're building some type units and one has already used the
2007 // address pool we know we're going to throw away all this work anyway, so
2008 // don't bother building dependent types.
2009 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2012 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2014 CU.addDIETypeSignature(RefDie, *TU);
2018 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2019 AddrPool.resetUsedFlag();
2021 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2022 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2023 this, &InfoHolder, getDwoLineTable(CU));
2024 DwarfTypeUnit &NewTU = *OwnedUnit;
2025 DIE &UnitDie = NewTU.getUnitDie();
2027 TypeUnitsUnderConstruction.push_back(
2028 std::make_pair(std::move(OwnedUnit), CTy));
2030 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2033 uint64_t Signature = makeTypeSignature(Identifier);
2034 NewTU.setTypeSignature(Signature);
2036 if (useSplitDwarf())
2037 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2039 CU.applyStmtList(UnitDie);
2041 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2044 NewTU.setType(NewTU.createTypeDIE(CTy));
2047 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2048 TypeUnitsUnderConstruction.clear();
2050 // Types referencing entries in the address table cannot be placed in type
2052 if (AddrPool.hasBeenUsed()) {
2054 // Remove all the types built while building this type.
2055 // This is pessimistic as some of these types might not be dependent on
2056 // the type that used an address.
2057 for (const auto &TU : TypeUnitsToAdd)
2058 DwarfTypeUnits.erase(TU.second);
2060 // Construct this type in the CU directly.
2061 // This is inefficient because all the dependent types will be rebuilt
2062 // from scratch, including building them in type units, discovering that
2063 // they depend on addresses, throwing them out and rebuilding them.
2064 CU.constructTypeDIE(RefDie, CTy);
2068 // If the type wasn't dependent on fission addresses, finish adding the type
2069 // and all its dependent types.
2070 for (auto &TU : TypeUnitsToAdd)
2071 InfoHolder.addUnit(std::move(TU.first));
2073 CU.addDIETypeSignature(RefDie, NewTU);
2076 // Accelerator table mutators - add each name along with its companion
2077 // DIE to the proper table while ensuring that the name that we're going
2078 // to reference is in the string table. We do this since the names we
2079 // add may not only be identical to the names in the DIE.
2080 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2081 if (!useDwarfAccelTables())
2083 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2087 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2088 if (!useDwarfAccelTables())
2090 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2094 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2095 if (!useDwarfAccelTables())
2097 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2101 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2102 if (!useDwarfAccelTables())
2104 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),