1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "ByteStreamer.h"
15 #include "DwarfDebug.h"
16 #include "DIE.h"
17 #include "DIEHash.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MD5.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 using namespace llvm;
52 #define DEBUG_TYPE "dwarfdebug"
54 static cl::opt<bool>
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
61 cl::init(false));
63 static cl::opt<bool>
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
66 cl::init(false));
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
69 cl::Hidden,
70 cl::desc("Generate dwarf aranges"),
71 cl::init(false));
73 namespace {
74 enum DefaultOnOff { Default, Enable, Disable };
75 }
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
83 cl::init(Default));
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 cl::init(Default));
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 cl::init(Default));
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
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);
114 }
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
119 }
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. */
150 DIType subType = Ty;
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).getTypeArray();
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()));
161 }
162 }
163 return Ty;
164 }
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 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
177 dwarf::DW_FORM_data4)),
178 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
179 dwarf::DW_FORM_data4)),
180 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
181 dwarf::DW_FORM_data4)),
182 AccelTypes(TypeAtoms) {
184 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
185 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
186 DwarfLineSectionSym = nullptr;
187 DwarfAddrSectionSym = nullptr;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
189 FunctionBeginSym = FunctionEndSym = nullptr;
190 CurFn = nullptr;
191 CurMI = nullptr;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
199 else
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
204 else
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
209 else
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 {
216 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
217 beginModule();
218 }
219 }
221 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
222 DwarfDebug::~DwarfDebug() { }
224 // Switch to the specified MCSection and emit an assembler
225 // temporary label to it if SymbolStem is specified.
226 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
227 const char *SymbolStem = nullptr) {
228 Asm->OutStreamer.SwitchSection(Section);
229 if (!SymbolStem)
230 return nullptr;
232 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
233 Asm->OutStreamer.EmitLabel(TmpSym);
234 return TmpSym;
235 }
237 static bool isObjCClass(StringRef Name) {
238 return Name.startswith("+") || Name.startswith("-");
239 }
241 static bool hasObjCCategory(StringRef Name) {
242 if (!isObjCClass(Name))
243 return false;
245 return Name.find(") ") != StringRef::npos;
246 }
248 static void getObjCClassCategory(StringRef In, StringRef &Class,
249 StringRef &Category) {
250 if (!hasObjCCategory(In)) {
251 Class = In.slice(In.find('[') + 1, In.find(' '));
252 Category = "";
253 return;
254 }
256 Class = In.slice(In.find('[') + 1, In.find('('));
257 Category = In.slice(In.find('[') + 1, In.find(' '));
258 return;
259 }
261 static StringRef getObjCMethodName(StringRef In) {
262 return In.slice(In.find(' ') + 1, In.find(']'));
263 }
265 // Helper for sorting sections into a stable output order.
266 static bool SectionSort(const MCSection *A, const MCSection *B) {
267 std::string LA = (A ? A->getLabelBeginName() : "");
268 std::string LB = (B ? B->getLabelBeginName() : "");
269 return LA < LB;
270 }
272 // Add the various names to the Dwarf accelerator table names.
273 // TODO: Determine whether or not we should add names for programs
274 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
275 // is only slightly different than the lookup of non-standard ObjC names.
276 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
277 if (!SP.isDefinition())
278 return;
279 addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
287 // too.
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 addAccelObjC(Class, Die);
292 if (Category != "")
293 addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 addAccelName(getObjCMethodName(SP.getName()), Die);
296 }
297 }
299 /// isSubprogramContext - Return true if Context is either a subprogram
300 /// or another context nested inside a subprogram.
301 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
302 if (!Context)
303 return false;
304 DIDescriptor D(Context);
305 if (D.isSubprogram())
306 return true;
307 if (D.isType())
308 return isSubprogramContext(resolve(DIType(Context).getContext()));
309 return false;
310 }
312 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
313 // and DW_AT_high_pc attributes. If there are global variables in this
314 // scope then create and insert DIEs for these variables.
315 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
316 DISubprogram SP) {
317 DIE *SPDie = SPCU.getDIE(SP);
319 assert(SPDie && "Unable to find subprogram DIE!");
321 // If we're updating an abstract DIE, then we will be adding the children and
322 // object pointer later on. But what we don't want to do is process the
323 // concrete DIE twice.
324 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
325 // Pick up abstract subprogram DIE.
326 SPDie = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
327 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
328 } else if (!SP.getFunctionDeclaration()) {
329 // There is not any need to generate specification DIE for a function
330 // defined at compile unit level. If a function is defined inside another
331 // function then gdb prefers the definition at top level and but does not
332 // expect specification DIE in parent function. So avoid creating
333 // specification DIE for a function defined inside a function.
334 DIScope SPContext = resolve(SP.getContext());
335 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
336 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
337 SPCU.addFlag(*SPDie, dwarf::DW_AT_declaration);
339 // Add arguments.
340 DICompositeType SPTy = SP.getType();
341 DIArray Args = SPTy.getTypeArray();
342 uint16_t SPTag = SPTy.getTag();
343 if (SPTag == dwarf::DW_TAG_subroutine_type)
344 SPCU.constructSubprogramArguments(*SPDie, Args);
345 DIE *SPDeclDie = SPDie;
346 SPDie =
347 &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
348 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_specification, *SPDeclDie);
349 }
350 }
352 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
354 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
355 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
356 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
358 // Add name to the name table, we do this here because we're guaranteed
359 // to have concrete versions of our DW_TAG_subprogram nodes.
360 addSubprogramNames(SP, *SPDie);
362 return *SPDie;
363 }
365 /// Check whether we should create a DIE for the given Scope, return true
366 /// if we don't create a DIE (the corresponding DIE is null).
367 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
368 if (Scope->isAbstractScope())
369 return false;
371 // We don't create a DIE if there is no Range.
372 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
373 if (Ranges.empty())
374 return true;
376 if (Ranges.size() > 1)
377 return false;
379 // We don't create a DIE if we have a single Range and the end label
380 // is null.
381 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
382 MCSymbol *End = getLabelAfterInsn(RI->second);
383 return !End;
384 }
386 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
387 dwarf::Attribute A, const MCSymbol *L,
388 const MCSymbol *Sec) {
389 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
390 U.addSectionLabel(D, A, L);
391 else
392 U.addSectionDelta(D, A, L, Sec);
393 }
395 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
396 const SmallVectorImpl<InsnRange> &Range) {
397 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
398 // emitting it appropriately.
399 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
401 // Under fission, ranges are specified by constant offsets relative to the
402 // CU's DW_AT_GNU_ranges_base.
403 if (useSplitDwarf())
404 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
405 DwarfDebugRangeSectionSym);
406 else
407 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
408 DwarfDebugRangeSectionSym);
410 RangeSpanList List(RangeSym);
411 for (const InsnRange &R : Range) {
412 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
413 List.addRange(std::move(Span));
414 }
416 // Add the range list to the set of ranges to be emitted.
417 TheCU.addRangeList(std::move(List));
418 }
420 // Construct new DW_TAG_lexical_block for this scope and attach
421 // DW_AT_low_pc/DW_AT_high_pc labels.
422 std::unique_ptr<DIE>
423 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
424 LexicalScope *Scope) {
425 if (isLexicalScopeDIENull(Scope))
426 return nullptr;
428 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
429 if (Scope->isAbstractScope())
430 return ScopeDIE;
432 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
434 // If we have multiple ranges, emit them into the range section.
435 if (ScopeRanges.size() > 1) {
436 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
437 return ScopeDIE;
438 }
440 // Construct the address range for this DIE.
441 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
442 MCSymbol *Start = getLabelBeforeInsn(RI->first);
443 MCSymbol *End = getLabelAfterInsn(RI->second);
444 assert(End && "End label should not be null!");
446 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
447 assert(End->isDefined() && "Invalid end label for an inlined scope!");
449 attachLowHighPC(TheCU, *ScopeDIE, Start, End);
451 return ScopeDIE;
452 }
454 // This scope represents inlined body of a function. Construct DIE to
455 // represent this concrete inlined copy of the function.
456 std::unique_ptr<DIE>
457 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
458 LexicalScope *Scope) {
459 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
460 assert(!ScopeRanges.empty() &&
461 "LexicalScope does not have instruction markers!");
463 assert(Scope->getScopeNode());
464 DIScope DS(Scope->getScopeNode());
465 DISubprogram InlinedSP = getDISubprogram(DS);
466 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
467 // FIXME: This should be an assert (or possibly a
468 // getOrCreateSubprogram(InlinedSP)) otherwise we're just failing to emit
469 // inlining information.
470 if (!OriginDIE) {
471 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
472 return nullptr;
473 }
475 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
476 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
478 // If we have multiple ranges, emit them into the range section.
479 if (ScopeRanges.size() > 1)
480 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
481 else {
482 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
483 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
484 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
486 if (!StartLabel || !EndLabel)
487 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
489 assert(StartLabel->isDefined() &&
490 "Invalid starting label for an inlined scope!");
491 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
493 attachLowHighPC(TheCU, *ScopeDIE, StartLabel, EndLabel);
494 }
496 InlinedSubprogramDIEs.insert(OriginDIE);
497 TheCU.addUInt(*OriginDIE, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
499 // Add the call site information to the DIE.
500 DILocation DL(Scope->getInlinedAt());
501 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
502 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
503 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
505 // Add name to the name table, we do this here because we're guaranteed
506 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
507 addSubprogramNames(InlinedSP, *ScopeDIE);
509 return ScopeDIE;
510 }
512 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
513 DbgVariable &DV,
514 const LexicalScope &Scope,
515 DIE *&ObjectPointer) {
516 AbstractOrInlined AOI = AOI_None;
517 if (Scope.isAbstractScope())
518 AOI = AOI_Abstract;
519 else if (Scope.getInlinedAt())
520 AOI = AOI_Inlined;
521 auto Var = TheCU.constructVariableDIE(DV, AOI);
522 if (DV.isObjectPointer())
523 ObjectPointer = Var.get();
524 return Var;
525 }
527 DIE *DwarfDebug::createScopeChildrenDIE(
528 DwarfCompileUnit &TheCU, LexicalScope *Scope,
529 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
530 DIE *ObjectPointer = nullptr;
532 // Collect arguments for current function.
533 if (LScopes.isCurrentFunctionScope(Scope)) {
534 for (DbgVariable *ArgDV : CurrentFnArguments)
535 if (ArgDV)
536 Children.push_back(
537 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
539 // If this is a variadic function, add an unspecified parameter.
540 DISubprogram SP(Scope->getScopeNode());
541 DIArray FnArgs = SP.getType().getTypeArray();
542 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
543 .isUnspecifiedParameter()) {
544 Children.push_back(
545 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
546 }
547 }
549 // Collect lexical scope children first.
550 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
551 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
553 for (LexicalScope *LS : Scope->getChildren())
554 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
555 Children.push_back(std::move(Nested));
556 return ObjectPointer;
557 }
559 void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
560 LexicalScope *Scope, DIE &ScopeDIE) {
561 // We create children when the scope DIE is not null.
562 SmallVector<std::unique_ptr<DIE>, 8> Children;
563 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
564 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
566 // Add children
567 for (auto &I : Children)
568 ScopeDIE.addChild(std::move(I));
569 }
571 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
572 LexicalScope *Scope) {
573 assert(Scope && Scope->getScopeNode());
574 assert(Scope->isAbstractScope());
575 assert(!Scope->getInlinedAt());
577 DISubprogram Sub(Scope->getScopeNode());
579 if (!ProcessedSPNodes.insert(Sub))
580 return;
582 if (DIE *ScopeDIE = TheCU.getDIE(Sub)) {
583 AbstractSPDies.insert(std::make_pair(Sub, ScopeDIE));
584 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
585 createAndAddScopeChildren(TheCU, Scope, *ScopeDIE);
586 }
587 }
589 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
590 LexicalScope *Scope) {
591 assert(Scope && Scope->getScopeNode());
592 assert(!Scope->getInlinedAt());
593 assert(!Scope->isAbstractScope());
594 DISubprogram Sub(Scope->getScopeNode());
596 assert(Sub.isSubprogram());
598 ProcessedSPNodes.insert(Sub);
600 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
602 createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
604 return ScopeDIE;
605 }
607 // Construct a DIE for this scope.
608 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
609 LexicalScope *Scope) {
610 if (!Scope || !Scope->getScopeNode())
611 return nullptr;
613 DIScope DS(Scope->getScopeNode());
615 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
616 "Only handle inlined subprograms here, use "
617 "constructSubprogramScopeDIE for non-inlined "
618 "subprograms");
620 SmallVector<std::unique_ptr<DIE>, 8> Children;
622 // We try to create the scope DIE first, then the children DIEs. This will
623 // avoid creating un-used children then removing them later when we find out
624 // the scope DIE is null.
625 std::unique_ptr<DIE> ScopeDIE;
626 if (DS.getContext() && DS.isSubprogram()) {
627 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
628 if (!ScopeDIE)
629 return nullptr;
630 // We create children when the scope DIE is not null.
631 createScopeChildrenDIE(TheCU, Scope, Children);
632 } else {
633 // Early exit when we know the scope DIE is going to be null.
634 if (isLexicalScopeDIENull(Scope))
635 return nullptr;
637 // We create children here when we know the scope DIE is not going to be
638 // null and the children will be added to the scope DIE.
639 createScopeChildrenDIE(TheCU, Scope, Children);
641 // There is no need to emit empty lexical block DIE.
642 std::pair<ImportedEntityMap::const_iterator,
643 ImportedEntityMap::const_iterator> Range =
644 std::equal_range(ScopesWithImportedEntities.begin(),
645 ScopesWithImportedEntities.end(),
646 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
647 less_first());
648 if (Children.empty() && Range.first == Range.second)
649 return nullptr;
650 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
651 assert(ScopeDIE && "Scope DIE should not be null.");
652 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
653 ++i)
654 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
655 }
657 // Add children
658 for (auto &I : Children)
659 ScopeDIE->addChild(std::move(I));
661 return ScopeDIE;
662 }
664 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
665 if (!GenerateGnuPubSections)
666 return;
668 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
669 }
671 // Create new DwarfCompileUnit for the given metadata node with tag
672 // DW_TAG_compile_unit.
673 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
674 StringRef FN = DIUnit.getFilename();
675 CompilationDir = DIUnit.getDirectory();
677 auto OwnedUnit = make_unique<DwarfCompileUnit>(
678 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
679 DwarfCompileUnit &NewCU = *OwnedUnit;
680 DIE &Die = NewCU.getUnitDie();
681 InfoHolder.addUnit(std::move(OwnedUnit));
683 // LTO with assembly output shares a single line table amongst multiple CUs.
684 // To avoid the compilation directory being ambiguous, let the line table
685 // explicitly describe the directory of all files, never relying on the
686 // compilation directory.
687 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
688 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
689 NewCU.getUniqueID(), CompilationDir);
691 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
692 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
693 DIUnit.getLanguage());
694 NewCU.addString(Die, dwarf::DW_AT_name, FN);
696 if (!useSplitDwarf()) {
697 NewCU.initStmtList(DwarfLineSectionSym);
699 // If we're using split dwarf the compilation dir is going to be in the
700 // skeleton CU and so we don't need to duplicate it here.
701 if (!CompilationDir.empty())
702 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
704 addGnuPubAttributes(NewCU, Die);
705 }
707 if (DIUnit.isOptimized())
708 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
710 StringRef Flags = DIUnit.getFlags();
711 if (!Flags.empty())
712 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
714 if (unsigned RVer = DIUnit.getRunTimeVersion())
715 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
716 dwarf::DW_FORM_data1, RVer);
718 if (!FirstCU)
719 FirstCU = &NewCU;
721 if (useSplitDwarf()) {
722 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
723 DwarfInfoDWOSectionSym);
724 NewCU.setSkeleton(constructSkeletonCU(NewCU));
725 } else
726 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
727 DwarfInfoSectionSym);
729 CUMap.insert(std::make_pair(DIUnit, &NewCU));
730 CUDieMap.insert(std::make_pair(&Die, &NewCU));
731 return NewCU;
732 }
734 // Construct subprogram DIE.
735 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
736 const MDNode *N) {
737 // FIXME: We should only call this routine once, however, during LTO if a
738 // program is defined in multiple CUs we could end up calling it out of
739 // beginModule as we walk the CUs.
741 DwarfCompileUnit *&CURef = SPMap[N];
742 if (CURef)
743 return;
744 CURef = &TheCU;
746 DISubprogram SP(N);
747 assert(SP.isSubprogram());
748 if (!SP.isDefinition())
749 // This is a method declaration which will be handled while constructing
750 // class type.
751 return;
753 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
755 // Expose as a global name.
756 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
757 }
759 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
760 const MDNode *N) {
761 DIImportedEntity Module(N);
762 assert(Module.Verify());
763 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
764 constructImportedEntityDIE(TheCU, Module, *D);
765 }
767 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
768 const MDNode *N, DIE &Context) {
769 DIImportedEntity Module(N);
770 assert(Module.Verify());
771 return constructImportedEntityDIE(TheCU, Module, Context);
772 }
774 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
775 const DIImportedEntity &Module,
776 DIE &Context) {
777 assert(Module.Verify() &&
778 "Use one of the MDNode * overloads to handle invalid metadata");
779 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
780 DIE *EntityDie;
781 DIDescriptor Entity = resolve(Module.getEntity());
782 if (Entity.isNameSpace())
783 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
784 else if (Entity.isSubprogram())
785 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
786 else if (Entity.isType())
787 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
788 else
789 EntityDie = TheCU.getDIE(Entity);
790 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
791 Module.getContext().getFilename(),
792 Module.getContext().getDirectory());
793 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
794 StringRef Name = Module.getName();
795 if (!Name.empty())
796 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
797 }
799 // Emit all Dwarf sections that should come prior to the content. Create
800 // global DIEs and emit initial debug info sections. This is invoked by
801 // the target AsmPrinter.
802 void DwarfDebug::beginModule() {
803 if (DisableDebugInfoPrinting)
804 return;
806 const Module *M = MMI->getModule();
808 // If module has named metadata anchors then use them, otherwise scan the
809 // module using debug info finder to collect debug info.
810 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
811 if (!CU_Nodes)
812 return;
813 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
815 // Emit initial sections so we can reference labels later.
816 emitSectionLabels();
818 SingleCU = CU_Nodes->getNumOperands() == 1;
820 for (MDNode *N : CU_Nodes->operands()) {
821 DICompileUnit CUNode(N);
822 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
823 DIArray ImportedEntities = CUNode.getImportedEntities();
824 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
825 ScopesWithImportedEntities.push_back(std::make_pair(
826 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
827 ImportedEntities.getElement(i)));
828 std::sort(ScopesWithImportedEntities.begin(),
829 ScopesWithImportedEntities.end(), less_first());
830 DIArray GVs = CUNode.getGlobalVariables();
831 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
832 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
833 DIArray SPs = CUNode.getSubprograms();
834 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
835 constructSubprogramDIE(CU, SPs.getElement(i));
836 DIArray EnumTypes = CUNode.getEnumTypes();
837 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
838 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
839 DIArray RetainedTypes = CUNode.getRetainedTypes();
840 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
841 DIType Ty(RetainedTypes.getElement(i));
842 // The retained types array by design contains pointers to
843 // MDNodes rather than DIRefs. Unique them here.
844 DIType UniqueTy(resolve(Ty.getRef()));
845 CU.getOrCreateTypeDIE(UniqueTy);
846 }
847 // Emit imported_modules last so that the relevant context is already
848 // available.
849 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
850 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
851 }
853 // Tell MMI that we have debug info.
854 MMI->setDebugInfoAvailability(true);
856 // Prime section data.
857 SectionMap[Asm->getObjFileLowering().getTextSection()];
858 }
860 // Collect info for variables that were optimized out.
861 void DwarfDebug::collectDeadVariables() {
862 const Module *M = MMI->getModule();
864 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
865 for (MDNode *N : CU_Nodes->operands()) {
866 DICompileUnit TheCU(N);
867 // Construct subprogram DIE and add variables DIEs.
868 DwarfCompileUnit *SPCU =
869 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
870 assert(SPCU && "Unable to find Compile Unit!");
871 DIArray Subprograms = TheCU.getSubprograms();
872 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
873 DISubprogram SP(Subprograms.getElement(i));
874 if (ProcessedSPNodes.count(SP) != 0)
875 continue;
876 assert(SP.isSubprogram() &&
877 "CU's subprogram list contains a non-subprogram");
878 if (!SP.isDefinition())
879 continue;
880 DIArray Variables = SP.getVariables();
881 if (Variables.getNumElements() == 0)
882 continue;
884 // FIXME: See the comment in constructSubprogramDIE about duplicate
885 // subprogram DIEs.
886 constructSubprogramDIE(*SPCU, SP);
887 DIE *SPDIE = SPCU->getDIE(SP);
888 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
889 DIVariable DV(Variables.getElement(vi));
890 assert(DV.isVariable());
891 DbgVariable NewVar(DV, nullptr, this);
892 SPDIE->addChild(SPCU->constructVariableDIE(NewVar));
893 }
894 }
895 }
896 }
897 }
899 void DwarfDebug::finalizeModuleInfo() {
900 // Collect info for variables that were optimized out.
901 collectDeadVariables();
903 // Handle anything that needs to be done on a per-unit basis after
904 // all other generation.
905 for (const auto &TheU : getUnits()) {
906 // Emit DW_AT_containing_type attribute to connect types with their
907 // vtable holding type.
908 TheU->constructContainingTypeDIEs();
910 // Add CU specific attributes if we need to add any.
911 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
912 // If we're splitting the dwarf out now that we've got the entire
913 // CU then add the dwo id to it.
914 DwarfCompileUnit *SkCU =
915 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
916 if (useSplitDwarf()) {
917 // Emit a unique identifier for this CU.
918 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
919 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
920 dwarf::DW_FORM_data8, ID);
921 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
922 dwarf::DW_FORM_data8, ID);
924 // We don't keep track of which addresses are used in which CU so this
925 // is a bit pessimistic under LTO.
926 if (!AddrPool.isEmpty())
927 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
928 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
929 DwarfAddrSectionSym);
930 if (!TheU->getRangeLists().empty())
931 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
932 dwarf::DW_AT_GNU_ranges_base,
933 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
934 }
936 // If we have code split among multiple sections or non-contiguous
937 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
938 // remain in the .o file, otherwise add a DW_AT_low_pc.
939 // FIXME: We should use ranges allow reordering of code ala
940 // .subsections_via_symbols in mach-o. This would mean turning on
941 // ranges for all subprogram DIEs for mach-o.
942 DwarfCompileUnit &U =
943 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
944 unsigned NumRanges = TheU->getRanges().size();
945 if (NumRanges) {
946 if (NumRanges > 1) {
947 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
948 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
949 DwarfDebugRangeSectionSym);
951 // A DW_AT_low_pc attribute may also be specified in combination with
952 // DW_AT_ranges to specify the default base address for use in
953 // location lists (see Section 2.6.2) and range lists (see Section
954 // 2.17.3).
955 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
956 0);
957 } else {
958 RangeSpan &Range = TheU->getRanges().back();
959 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
960 Range.getStart());
961 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
962 Range.getStart());
963 }
964 }
965 }
966 }
968 // Compute DIE offsets and sizes.
969 InfoHolder.computeSizeAndOffsets();
970 if (useSplitDwarf())
971 SkeletonHolder.computeSizeAndOffsets();
972 }
974 void DwarfDebug::endSections() {
975 // Filter labels by section.
976 for (const SymbolCU &SCU : ArangeLabels) {
977 if (SCU.Sym->isInSection()) {
978 // Make a note of this symbol and it's section.
979 const MCSection *Section = &SCU.Sym->getSection();
980 if (!Section->getKind().isMetadata())
981 SectionMap[Section].push_back(SCU);
982 } else {
983 // Some symbols (e.g. common/bss on mach-o) can have no section but still
984 // appear in the output. This sucks as we rely on sections to build
985 // arange spans. We can do it without, but it's icky.
986 SectionMap[nullptr].push_back(SCU);
987 }
988 }
990 // Build a list of sections used.
991 std::vector<const MCSection *> Sections;
992 for (const auto &it : SectionMap) {
993 const MCSection *Section = it.first;
994 Sections.push_back(Section);
995 }
997 // Sort the sections into order.
998 // This is only done to ensure consistent output order across different runs.
999 std::sort(Sections.begin(), Sections.end(), SectionSort);
1001 // Add terminating symbols for each section.
1002 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1003 const MCSection *Section = Sections[ID];
1004 MCSymbol *Sym = nullptr;
1006 if (Section) {
1007 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1008 // if we know the section name up-front. For user-created sections, the
1009 // resulting label may not be valid to use as a label. (section names can
1010 // use a greater set of characters on some systems)
1011 Sym = Asm->GetTempSymbol("debug_end", ID);
1012 Asm->OutStreamer.SwitchSection(Section);
1013 Asm->OutStreamer.EmitLabel(Sym);
1014 }
1016 // Insert a final terminator.
1017 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1018 }
1019 }
1021 // Emit all Dwarf sections that should come after the content.
1022 void DwarfDebug::endModule() {
1023 assert(CurFn == nullptr);
1024 assert(CurMI == nullptr);
1026 if (!FirstCU)
1027 return;
1029 // End any existing sections.
1030 // TODO: Does this need to happen?
1031 endSections();
1033 // Finalize the debug info for the module.
1034 finalizeModuleInfo();
1036 emitDebugStr();
1038 // Emit all the DIEs into a debug info section.
1039 emitDebugInfo();
1041 // Corresponding abbreviations into a abbrev section.
1042 emitAbbreviations();
1044 // Emit info into a debug aranges section.
1045 if (GenerateARangeSection)
1046 emitDebugARanges();
1048 // Emit info into a debug ranges section.
1049 emitDebugRanges();
1051 if (useSplitDwarf()) {
1052 emitDebugStrDWO();
1053 emitDebugInfoDWO();
1054 emitDebugAbbrevDWO();
1055 emitDebugLineDWO();
1056 // Emit DWO addresses.
1057 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1058 emitDebugLocDWO();
1059 } else
1060 // Emit info into a debug loc section.
1061 emitDebugLoc();
1063 // Emit info into the dwarf accelerator table sections.
1064 if (useDwarfAccelTables()) {
1065 emitAccelNames();
1066 emitAccelObjC();
1067 emitAccelNamespaces();
1068 emitAccelTypes();
1069 }
1071 // Emit the pubnames and pubtypes sections if requested.
1072 if (HasDwarfPubSections) {
1073 emitDebugPubNames(GenerateGnuPubSections);
1074 emitDebugPubTypes(GenerateGnuPubSections);
1075 }
1077 // clean up.
1078 SPMap.clear();
1080 // Reset these for the next Module if we have one.
1081 FirstCU = nullptr;
1082 }
1084 // Find abstract variable, if any, associated with Var.
1085 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1086 DebugLoc ScopeLoc) {
1087 LLVMContext &Ctx = DV->getContext();
1088 // More then one inlined variable corresponds to one abstract variable.
1089 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1090 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1091 if (AbsDbgVariable)
1092 return AbsDbgVariable;
1094 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1095 if (!Scope)
1096 return nullptr;
1098 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1099 addScopeVariable(Scope, AbsDbgVariable);
1100 AbstractVariables[Var] = AbsDbgVariable;
1101 return AbsDbgVariable;
1102 }
1104 // If Var is a current function argument then add it to CurrentFnArguments list.
1105 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1106 if (!LScopes.isCurrentFunctionScope(Scope))
1107 return false;
1108 DIVariable DV = Var->getVariable();
1109 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1110 return false;
1111 unsigned ArgNo = DV.getArgNumber();
1112 if (ArgNo == 0)
1113 return false;
1115 size_t Size = CurrentFnArguments.size();
1116 if (Size == 0)
1117 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1118 // llvm::Function argument size is not good indicator of how many
1119 // arguments does the function have at source level.
1120 if (ArgNo > Size)
1121 CurrentFnArguments.resize(ArgNo * 2);
1122 CurrentFnArguments[ArgNo - 1] = Var;
1123 return true;
1124 }
1126 // Collect variable information from side table maintained by MMI.
1127 void DwarfDebug::collectVariableInfoFromMMITable(
1128 SmallPtrSet<const MDNode *, 16> &Processed) {
1129 for (const auto &VI : MMI->getVariableDbgInfo()) {
1130 if (!VI.Var)
1131 continue;
1132 Processed.insert(VI.Var);
1133 DIVariable DV(VI.Var);
1134 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1136 // If variable scope is not found then skip this variable.
1137 if (!Scope)
1138 continue;
1140 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1141 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1142 RegVar->setFrameIndex(VI.Slot);
1143 if (!addCurrentFnArgument(RegVar, Scope))
1144 addScopeVariable(Scope, RegVar);
1145 if (AbsDbgVariable)
1146 AbsDbgVariable->setFrameIndex(VI.Slot);
1147 }
1148 }
1150 // Get .debug_loc entry for the instruction range starting at MI.
1151 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1152 const MDNode *Var = MI->getDebugVariable();
1154 assert(MI->getNumOperands() == 3);
1155 if (MI->getOperand(0).isReg()) {
1156 MachineLocation MLoc;
1157 // If the second operand is an immediate, this is a
1158 // register-indirect address.
1159 if (!MI->getOperand(1).isImm())
1160 MLoc.set(MI->getOperand(0).getReg());
1161 else
1162 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1163 return DebugLocEntry::Value(Var, MLoc);
1164 }
1165 if (MI->getOperand(0).isImm())
1166 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1167 if (MI->getOperand(0).isFPImm())
1168 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1169 if (MI->getOperand(0).isCImm())
1170 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1172 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1173 }
1175 // Find variables for each lexical scope.
1176 void
1177 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1178 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1179 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1181 // Grab the variable info that was squirreled away in the MMI side-table.
1182 collectVariableInfoFromMMITable(Processed);
1184 for (const auto &I : DbgValues) {
1185 DIVariable DV(I.first);
1186 if (Processed.count(DV))
1187 continue;
1189 // History contains relevant DBG_VALUE instructions for DV and instructions
1190 // clobbering it.
1191 const SmallVectorImpl<const MachineInstr *> &History = I.second;
1192 if (History.empty())
1193 continue;
1194 const MachineInstr *MInsn = History.front();
1196 LexicalScope *Scope = nullptr;
1197 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1198 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1199 Scope = LScopes.getCurrentFunctionScope();
1200 else if (MDNode *IA = DV.getInlinedAt()) {
1201 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1202 Scope = LScopes.findInlinedScope(DebugLoc::get(
1203 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1204 } else
1205 Scope = LScopes.findLexicalScope(DV.getContext());
1206 // If variable scope is not found then skip this variable.
1207 if (!Scope)
1208 continue;
1210 Processed.insert(DV);
1211 assert(MInsn->isDebugValue() && "History must begin with debug value");
1212 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1213 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1214 if (!addCurrentFnArgument(RegVar, Scope))
1215 addScopeVariable(Scope, RegVar);
1216 if (AbsVar)
1217 AbsVar->setMInsn(MInsn);
1219 // Simplify ranges that are fully coalesced.
1220 if (History.size() <= 1 ||
1221 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1222 RegVar->setMInsn(MInsn);
1223 continue;
1224 }
1226 // Handle multiple DBG_VALUE instructions describing one variable.
1227 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1229 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1230 DebugLocList &LocList = DotDebugLocEntries.back();
1231 LocList.Label =
1232 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1233 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1234 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1235 HI = History.begin(),
1236 HE = History.end();
1237 HI != HE; ++HI) {
1238 const MachineInstr *Begin = *HI;
1239 assert(Begin->isDebugValue() && "Invalid History entry");
1241 // Check if DBG_VALUE is truncating a range.
1242 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1243 !Begin->getOperand(0).getReg())
1244 continue;
1246 // Compute the range for a register location.
1247 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1248 const MCSymbol *SLabel = nullptr;
1250 if (HI + 1 == HE)
1251 // If Begin is the last instruction in History then its value is valid
1252 // until the end of the function.
1253 SLabel = FunctionEndSym;
1254 else {
1255 const MachineInstr *End = HI[1];
1256 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1257 << "\t" << *Begin << "\t" << *End << "\n");
1258 if (End->isDebugValue())
1259 SLabel = getLabelBeforeInsn(End);
1260 else {
1261 // End is a normal instruction clobbering the range.
1262 SLabel = getLabelAfterInsn(End);
1263 assert(SLabel && "Forgot label after clobber instruction");
1264 ++HI;
1265 }
1266 }
1268 // The value is valid until the next DBG_VALUE or clobber.
1269 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1270 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1271 DebugLoc.push_back(std::move(Loc));
1272 }
1273 }
1275 // Collect info for variables that were optimized out.
1276 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1277 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1278 DIVariable DV(Variables.getElement(i));
1279 assert(DV.isVariable());
1280 if (!Processed.insert(DV))
1281 continue;
1282 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1283 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1284 }
1285 }
1287 // Return Label preceding the instruction.
1288 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1289 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1290 assert(Label && "Didn't insert label before instruction");
1291 return Label;
1292 }
1294 // Return Label immediately following the instruction.
1295 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1296 return LabelsAfterInsn.lookup(MI);
1297 }
1299 // Process beginning of an instruction.
1300 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1301 assert(CurMI == nullptr);
1302 CurMI = MI;
1303 // Check if source location changes, but ignore DBG_VALUE locations.
1304 if (!MI->isDebugValue()) {
1305 DebugLoc DL = MI->getDebugLoc();
1306 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1307 unsigned Flags = 0;
1308 PrevInstLoc = DL;
1309 if (DL == PrologEndLoc) {
1310 Flags |= DWARF2_FLAG_PROLOGUE_END;
1311 PrologEndLoc = DebugLoc();
1312 }
1313 if (PrologEndLoc.isUnknown())
1314 Flags |= DWARF2_FLAG_IS_STMT;
1316 if (!DL.isUnknown()) {
1317 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1318 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1319 } else
1320 recordSourceLine(0, 0, nullptr, 0);
1321 }
1322 }
1324 // Insert labels where requested.
1325 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1326 LabelsBeforeInsn.find(MI);
1328 // No label needed.
1329 if (I == LabelsBeforeInsn.end())
1330 return;
1332 // Label already assigned.
1333 if (I->second)
1334 return;
1336 if (!PrevLabel) {
1337 PrevLabel = MMI->getContext().CreateTempSymbol();
1338 Asm->OutStreamer.EmitLabel(PrevLabel);
1339 }
1340 I->second = PrevLabel;
1341 }
1343 // Process end of an instruction.
1344 void DwarfDebug::endInstruction() {
1345 assert(CurMI != nullptr);
1346 // Don't create a new label after DBG_VALUE instructions.
1347 // They don't generate code.
1348 if (!CurMI->isDebugValue())
1349 PrevLabel = nullptr;
1351 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1352 LabelsAfterInsn.find(CurMI);
1353 CurMI = nullptr;
1355 // No label needed.
1356 if (I == LabelsAfterInsn.end())
1357 return;
1359 // Label already assigned.
1360 if (I->second)
1361 return;
1363 // We need a label after this instruction.
1364 if (!PrevLabel) {
1365 PrevLabel = MMI->getContext().CreateTempSymbol();
1366 Asm->OutStreamer.EmitLabel(PrevLabel);
1367 }
1368 I->second = PrevLabel;
1369 }
1371 // Each LexicalScope has first instruction and last instruction to mark
1372 // beginning and end of a scope respectively. Create an inverse map that list
1373 // scopes starts (and ends) with an instruction. One instruction may start (or
1374 // end) multiple scopes. Ignore scopes that are not reachable.
1375 void DwarfDebug::identifyScopeMarkers() {
1376 SmallVector<LexicalScope *, 4> WorkList;
1377 WorkList.push_back(LScopes.getCurrentFunctionScope());
1378 while (!WorkList.empty()) {
1379 LexicalScope *S = WorkList.pop_back_val();
1381 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1382 if (!Children.empty())
1383 WorkList.append(Children.begin(), Children.end());
1385 if (S->isAbstractScope())
1386 continue;
1388 for (const InsnRange &R : S->getRanges()) {
1389 assert(R.first && "InsnRange does not have first instruction!");
1390 assert(R.second && "InsnRange does not have second instruction!");
1391 requestLabelBeforeInsn(R.first);
1392 requestLabelAfterInsn(R.second);
1393 }
1394 }
1395 }
1397 // Gather pre-function debug information. Assumes being called immediately
1398 // after the function entry point has been emitted.
1399 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1400 CurFn = MF;
1402 // If there's no debug info for the function we're not going to do anything.
1403 if (!MMI->hasDebugInfo())
1404 return;
1406 // Grab the lexical scopes for the function, if we don't have any of those
1407 // then we're not going to be able to do anything.
1408 LScopes.initialize(*MF);
1409 if (LScopes.empty())
1410 return;
1412 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1414 // Make sure that each lexical scope will have a begin/end label.
1415 identifyScopeMarkers();
1417 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1418 // belongs to so that we add to the correct per-cu line table in the
1419 // non-asm case.
1420 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1421 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1422 assert(TheCU && "Unable to find compile unit!");
1423 if (Asm->OutStreamer.hasRawTextSupport())
1424 // Use a single line table if we are generating assembly.
1425 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1426 else
1427 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1429 // Emit a label for the function so that we have a beginning address.
1430 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1431 // Assumes in correct section after the entry point.
1432 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1434 // Collect user variables, find the end of the prologue.
1435 for (const auto &MBB : *MF) {
1436 for (const auto &MI : MBB) {
1437 if (MI.isDebugValue()) {
1438 assert(MI.getNumOperands() > 1 && "Invalid machine instruction!");
1439 // Keep track of user variables in order of appearance. Create the
1440 // empty history for each variable so that the order of keys in
1441 // DbgValues is correct. Actual history will be populated in
1442 // calculateDbgValueHistory() function.
1443 const MDNode *Var = MI.getDebugVariable();
1444 DbgValues.insert(
1445 std::make_pair(Var, SmallVector<const MachineInstr *, 4>()));
1446 } else if (!MI.getFlag(MachineInstr::FrameSetup) &&
1447 PrologEndLoc.isUnknown() && !MI.getDebugLoc().isUnknown()) {
1448 // First known non-DBG_VALUE and non-frame setup location marks
1449 // the beginning of the function body.
1450 PrologEndLoc = MI.getDebugLoc();
1451 }
1452 }
1453 }
1455 // Calculate history for local variables.
1456 calculateDbgValueHistory(MF, Asm->TM.getRegisterInfo(), DbgValues);
1458 // Request labels for the full history.
1459 for (auto &I : DbgValues) {
1460 const SmallVectorImpl<const MachineInstr *> &History = I.second;
1461 if (History.empty())
1462 continue;
1464 // The first mention of a function argument gets the FunctionBeginSym
1465 // label, so arguments are visible when breaking at function entry.
1466 DIVariable DV(I.first);
1467 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1468 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1469 LabelsBeforeInsn[History.front()] = FunctionBeginSym;
1471 for (const MachineInstr *MI : History) {
1472 if (MI->isDebugValue())
1473 requestLabelBeforeInsn(MI);
1474 else
1475 requestLabelAfterInsn(MI);
1476 }
1477 }
1479 PrevInstLoc = DebugLoc();
1480 PrevLabel = FunctionBeginSym;
1482 // Record beginning of function.
1483 if (!PrologEndLoc.isUnknown()) {
1484 DebugLoc FnStartDL =
1485 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1486 recordSourceLine(
1487 FnStartDL.getLine(), FnStartDL.getCol(),
1488 FnStartDL.getScope(MF->getFunction()->getContext()),
1489 // We'd like to list the prologue as "not statements" but GDB behaves
1490 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1491 DWARF2_FLAG_IS_STMT);
1492 }
1493 }
1495 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1496 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1497 DIVariable DV = Var->getVariable();
1498 // Variables with positive arg numbers are parameters.
1499 if (unsigned ArgNum = DV.getArgNumber()) {
1500 // Keep all parameters in order at the start of the variable list to ensure
1501 // function types are correct (no out-of-order parameters)
1502 //
1503 // This could be improved by only doing it for optimized builds (unoptimized
1504 // builds have the right order to begin with), searching from the back (this
1505 // would catch the unoptimized case quickly), or doing a binary search
1506 // rather than linear search.
1507 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1508 while (I != Vars.end()) {
1509 unsigned CurNum = (*I)->getVariable().getArgNumber();
1510 // A local (non-parameter) variable has been found, insert immediately
1511 // before it.
1512 if (CurNum == 0)
1513 break;
1514 // A later indexed parameter has been found, insert immediately before it.
1515 if (CurNum > ArgNum)
1516 break;
1517 ++I;
1518 }
1519 Vars.insert(I, Var);
1520 return;
1521 }
1523 Vars.push_back(Var);
1524 }
1526 // Gather and emit post-function debug information.
1527 void DwarfDebug::endFunction(const MachineFunction *MF) {
1528 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1529 // though the beginFunction may not be called at all.
1530 // We should handle both cases.
1531 if (!CurFn)
1532 CurFn = MF;
1533 else
1534 assert(CurFn == MF);
1535 assert(CurFn != nullptr);
1537 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1538 // If we don't have a lexical scope for this function then there will
1539 // be a hole in the range information. Keep note of this by setting the
1540 // previously used section to nullptr.
1541 PrevSection = nullptr;
1542 PrevCU = nullptr;
1543 CurFn = nullptr;
1544 return;
1545 }
1547 // Define end label for subprogram.
1548 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1549 // Assumes in correct section after the entry point.
1550 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1552 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1553 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1555 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1556 collectVariableInfo(ProcessedVars);
1558 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1559 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1561 // Construct abstract scopes.
1562 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1563 DISubprogram SP(AScope->getScopeNode());
1564 if (!SP.isSubprogram())
1565 continue;
1566 // Collect info for variables that were optimized out.
1567 DIArray Variables = SP.getVariables();
1568 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1569 DIVariable DV(Variables.getElement(i));
1570 assert(DV && DV.isVariable());
1571 if (!ProcessedVars.insert(DV))
1572 continue;
1573 // Check that DbgVariable for DV wasn't created earlier, when
1574 // findAbstractVariable() was called for inlined instance of DV.
1575 LLVMContext &Ctx = DV->getContext();
1576 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1577 if (AbstractVariables.lookup(CleanDV))
1578 continue;
1579 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1580 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1581 }
1582 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1583 }
1585 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1586 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1587 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1589 // Add the range of this function to the list of ranges for the CU.
1590 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1591 TheCU.addRange(std::move(Span));
1592 PrevSection = Asm->getCurrentSection();
1593 PrevCU = &TheCU;
1595 // Clear debug info
1596 for (auto &I : ScopeVariables)
1597 DeleteContainerPointers(I.second);
1598 ScopeVariables.clear();
1599 DeleteContainerPointers(CurrentFnArguments);
1600 DbgValues.clear();
1601 AbstractVariables.clear();
1602 LabelsBeforeInsn.clear();
1603 LabelsAfterInsn.clear();
1604 PrevLabel = nullptr;
1605 CurFn = nullptr;
1606 }
1608 // Register a source line with debug info. Returns the unique label that was
1609 // emitted and which provides correspondence to the source line list.
1610 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1611 unsigned Flags) {
1612 StringRef Fn;
1613 StringRef Dir;
1614 unsigned Src = 1;
1615 unsigned Discriminator = 0;
1616 if (S) {
1617 DIDescriptor Scope(S);
1619 if (Scope.isCompileUnit()) {
1620 DICompileUnit CU(S);
1621 Fn = CU.getFilename();
1622 Dir = CU.getDirectory();
1623 } else if (Scope.isFile()) {
1624 DIFile F(S);
1625 Fn = F.getFilename();
1626 Dir = F.getDirectory();
1627 } else if (Scope.isSubprogram()) {
1628 DISubprogram SP(S);
1629 Fn = SP.getFilename();
1630 Dir = SP.getDirectory();
1631 } else if (Scope.isLexicalBlockFile()) {
1632 DILexicalBlockFile DBF(S);
1633 Fn = DBF.getFilename();
1634 Dir = DBF.getDirectory();
1635 } else if (Scope.isLexicalBlock()) {
1636 DILexicalBlock DB(S);
1637 Fn = DB.getFilename();
1638 Dir = DB.getDirectory();
1639 Discriminator = DB.getDiscriminator();
1640 } else
1641 llvm_unreachable("Unexpected scope info");
1643 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1644 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1645 .getOrCreateSourceID(Fn, Dir);
1646 }
1647 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1648 Discriminator, Fn);
1649 }
1651 //===----------------------------------------------------------------------===//
1652 // Emit Methods
1653 //===----------------------------------------------------------------------===//
1655 // Emit initial Dwarf sections with a label at the start of each one.
1656 void DwarfDebug::emitSectionLabels() {
1657 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1659 // Dwarf sections base addresses.
1660 DwarfInfoSectionSym =
1661 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1662 if (useSplitDwarf())
1663 DwarfInfoDWOSectionSym =
1664 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1665 DwarfAbbrevSectionSym =
1666 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1667 if (useSplitDwarf())
1668 DwarfAbbrevDWOSectionSym = emitSectionSym(
1669 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1670 if (GenerateARangeSection)
1671 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1673 DwarfLineSectionSym =
1674 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1675 if (GenerateGnuPubSections) {
1676 DwarfGnuPubNamesSectionSym =
1677 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1678 DwarfGnuPubTypesSectionSym =
1679 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1680 } else if (HasDwarfPubSections) {
1681 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1682 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1683 }
1685 DwarfStrSectionSym =
1686 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1687 if (useSplitDwarf()) {
1688 DwarfStrDWOSectionSym =
1689 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1690 DwarfAddrSectionSym =
1691 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1692 DwarfDebugLocSectionSym =
1693 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1694 } else
1695 DwarfDebugLocSectionSym =
1696 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1697 DwarfDebugRangeSectionSym =
1698 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1699 }
1701 // Recursively emits a debug information entry.
1702 void DwarfDebug::emitDIE(DIE &Die) {
1703 // Get the abbreviation for this DIE.
1704 const DIEAbbrev &Abbrev = Die.getAbbrev();
1706 // Emit the code (index) for the abbreviation.
1707 if (Asm->isVerbose())
1708 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1709 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1710 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1711 dwarf::TagString(Abbrev.getTag()));
1712 Asm->EmitULEB128(Abbrev.getNumber());
1714 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1715 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1717 // Emit the DIE attribute values.
1718 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1719 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1720 dwarf::Form Form = AbbrevData[i].getForm();
1721 assert(Form && "Too many attributes for DIE (check abbreviation)");
1723 if (Asm->isVerbose()) {
1724 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1725 if (Attr == dwarf::DW_AT_accessibility)
1726 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1727 cast<DIEInteger>(Values[i])->getValue()));
1728 }
1730 // Emit an attribute using the defined form.
1731 Values[i]->EmitValue(Asm, Form);
1732 }
1734 // Emit the DIE children if any.
1735 if (Abbrev.hasChildren()) {
1736 for (auto &Child : Die.getChildren())
1737 emitDIE(*Child);
1739 Asm->OutStreamer.AddComment("End Of Children Mark");
1740 Asm->EmitInt8(0);
1741 }
1742 }
1744 // Emit the debug info section.
1745 void DwarfDebug::emitDebugInfo() {
1746 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1748 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1749 }
1751 // Emit the abbreviation section.
1752 void DwarfDebug::emitAbbreviations() {
1753 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1755 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1756 }
1758 // Emit the last address of the section and the end of the line matrix.
1759 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1760 // Define last address of section.
1761 Asm->OutStreamer.AddComment("Extended Op");
1762 Asm->EmitInt8(0);
1764 Asm->OutStreamer.AddComment("Op size");
1765 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1766 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1767 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1769 Asm->OutStreamer.AddComment("Section end label");
1771 Asm->OutStreamer.EmitSymbolValue(
1772 Asm->GetTempSymbol("section_end", SectionEnd),
1773 Asm->getDataLayout().getPointerSize());
1775 // Mark end of matrix.
1776 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1777 Asm->EmitInt8(0);
1778 Asm->EmitInt8(1);
1779 Asm->EmitInt8(1);
1780 }
1782 // Emit visible names into a hashed accelerator table section.
1783 void DwarfDebug::emitAccelNames() {
1784 AccelNames.FinalizeTable(Asm, "Names");
1785 Asm->OutStreamer.SwitchSection(
1786 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1787 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1788 Asm->OutStreamer.EmitLabel(SectionBegin);
1790 // Emit the full data.
1791 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1792 }
1794 // Emit objective C classes and categories into a hashed accelerator table
1795 // section.
1796 void DwarfDebug::emitAccelObjC() {
1797 AccelObjC.FinalizeTable(Asm, "ObjC");
1798 Asm->OutStreamer.SwitchSection(
1799 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1800 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1801 Asm->OutStreamer.EmitLabel(SectionBegin);
1803 // Emit the full data.
1804 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1805 }
1807 // Emit namespace dies into a hashed accelerator table.
1808 void DwarfDebug::emitAccelNamespaces() {
1809 AccelNamespace.FinalizeTable(Asm, "namespac");
1810 Asm->OutStreamer.SwitchSection(
1811 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1812 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1813 Asm->OutStreamer.EmitLabel(SectionBegin);
1815 // Emit the full data.
1816 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1817 }
1819 // Emit type dies into a hashed accelerator table.
1820 void DwarfDebug::emitAccelTypes() {
1822 AccelTypes.FinalizeTable(Asm, "types");
1823 Asm->OutStreamer.SwitchSection(
1824 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1825 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1826 Asm->OutStreamer.EmitLabel(SectionBegin);
1828 // Emit the full data.
1829 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1830 }
1832 // Public name handling.
1833 // The format for the various pubnames:
1834 //
1835 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1836 // for the DIE that is named.
1837 //
1838 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1839 // into the CU and the index value is computed according to the type of value
1840 // for the DIE that is named.
1841 //
1842 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1843 // it's the offset within the debug_info/debug_types dwo section, however, the
1844 // reference in the pubname header doesn't change.
1846 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1847 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1848 const DIE *Die) {
1849 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1851 // We could have a specification DIE that has our most of our knowledge,
1852 // look for that now.
1853 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1854 if (SpecVal) {
1855 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1856 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1857 Linkage = dwarf::GIEL_EXTERNAL;
1858 } else if (Die->findAttribute(dwarf::DW_AT_external))
1859 Linkage = dwarf::GIEL_EXTERNAL;
1861 switch (Die->getTag()) {
1862 case dwarf::DW_TAG_class_type:
1863 case dwarf::DW_TAG_structure_type:
1864 case dwarf::DW_TAG_union_type:
1865 case dwarf::DW_TAG_enumeration_type:
1866 return dwarf::PubIndexEntryDescriptor(
1867 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1868 ? dwarf::GIEL_STATIC
1869 : dwarf::GIEL_EXTERNAL);
1870 case dwarf::DW_TAG_typedef:
1871 case dwarf::DW_TAG_base_type:
1872 case dwarf::DW_TAG_subrange_type:
1873 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1874 case dwarf::DW_TAG_namespace:
1875 return dwarf::GIEK_TYPE;
1876 case dwarf::DW_TAG_subprogram:
1877 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1878 case dwarf::DW_TAG_constant:
1879 case dwarf::DW_TAG_variable:
1880 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1881 case dwarf::DW_TAG_enumerator:
1882 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1883 dwarf::GIEL_STATIC);
1884 default:
1885 return dwarf::GIEK_NONE;
1886 }
1887 }
1889 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1890 ///
1891 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1892 const MCSection *PSec =
1893 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1894 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1896 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1897 }
1899 void DwarfDebug::emitDebugPubSection(
1900 bool GnuStyle, const MCSection *PSec, StringRef Name,
1901 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1902 for (const auto &NU : CUMap) {
1903 DwarfCompileUnit *TheU = NU.second;
1905 const auto &Globals = (TheU->*Accessor)();
1907 if (Globals.empty())
1908 continue;
1910 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1911 TheU = Skeleton;
1912 unsigned ID = TheU->getUniqueID();
1914 // Start the dwarf pubnames section.
1915 Asm->OutStreamer.SwitchSection(PSec);
1917 // Emit the header.
1918 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1919 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1920 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1921 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1923 Asm->OutStreamer.EmitLabel(BeginLabel);
1925 Asm->OutStreamer.AddComment("DWARF Version");
1926 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1928 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1929 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1931 Asm->OutStreamer.AddComment("Compilation Unit Length");
1932 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1934 // Emit the pubnames for this compilation unit.
1935 for (const auto &GI : Globals) {
1936 const char *Name = GI.getKeyData();
1937 const DIE *Entity = GI.second;
1939 Asm->OutStreamer.AddComment("DIE offset");
1940 Asm->EmitInt32(Entity->getOffset());
1942 if (GnuStyle) {
1943 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1944 Asm->OutStreamer.AddComment(
1945 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1946 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1947 Asm->EmitInt8(Desc.toBits());
1948 }
1950 Asm->OutStreamer.AddComment("External Name");
1951 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1952 }
1954 Asm->OutStreamer.AddComment("End Mark");
1955 Asm->EmitInt32(0);
1956 Asm->OutStreamer.EmitLabel(EndLabel);
1957 }
1958 }
1960 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1961 const MCSection *PSec =
1962 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1963 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1965 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1966 }
1968 // Emit visible names into a debug str section.
1969 void DwarfDebug::emitDebugStr() {
1970 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1971 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1972 }
1974 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1975 const DebugLocEntry &Entry) {
1976 assert(Entry.getValues().size() == 1 &&
1977 "multi-value entries are not supported yet.");
1978 const DebugLocEntry::Value Value = Entry.getValues()[0];
1979 DIVariable DV(Value.getVariable());
1980 if (Value.isInt()) {
1981 DIBasicType BTy(resolve(DV.getType()));
1982 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1983 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1984 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1985 Streamer.EmitSLEB128(Value.getInt());
1986 } else {
1987 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1988 Streamer.EmitULEB128(Value.getInt());
1989 }
1990 } else if (Value.isLocation()) {
1991 MachineLocation Loc = Value.getLoc();
1992 if (!DV.hasComplexAddress())
1993 // Regular entry.
1994 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1995 else {
1996 // Complex address entry.
1997 unsigned N = DV.getNumAddrElements();
1998 unsigned i = 0;
1999 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2000 if (Loc.getOffset()) {
2001 i = 2;
2002 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2003 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2004 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2005 Streamer.EmitSLEB128(DV.getAddrElement(1));
2006 } else {
2007 // If first address element is OpPlus then emit
2008 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2009 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2010 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2011 i = 2;
2012 }
2013 } else {
2014 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2015 }
2017 // Emit remaining complex address elements.
2018 for (; i < N; ++i) {
2019 uint64_t Element = DV.getAddrElement(i);
2020 if (Element == DIBuilder::OpPlus) {
2021 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2022 Streamer.EmitULEB128(DV.getAddrElement(++i));
2023 } else if (Element == DIBuilder::OpDeref) {
2024 if (!Loc.isReg())
2025 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2026 } else
2027 llvm_unreachable("unknown Opcode found in complex address");
2028 }
2029 }
2030 }
2031 // else ... ignore constant fp. There is not any good way to
2032 // to represent them here in dwarf.
2033 // FIXME: ^
2034 }
2036 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2037 Asm->OutStreamer.AddComment("Loc expr size");
2038 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2039 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2040 Asm->EmitLabelDifference(end, begin, 2);
2041 Asm->OutStreamer.EmitLabel(begin);
2042 // Emit the entry.
2043 APByteStreamer Streamer(*Asm);
2044 emitDebugLocEntry(Streamer, Entry);
2045 // Close the range.
2046 Asm->OutStreamer.EmitLabel(end);
2047 }
2049 // Emit locations into the debug loc section.
2050 void DwarfDebug::emitDebugLoc() {
2051 // Start the dwarf loc section.
2052 Asm->OutStreamer.SwitchSection(
2053 Asm->getObjFileLowering().getDwarfLocSection());
2054 unsigned char Size = Asm->getDataLayout().getPointerSize();
2055 for (const auto &DebugLoc : DotDebugLocEntries) {
2056 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2057 for (const auto &Entry : DebugLoc.List) {
2058 // Set up the range. This range is relative to the entry point of the
2059 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2060 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2061 const DwarfCompileUnit *CU = Entry.getCU();
2062 if (CU->getRanges().size() == 1) {
2063 // Grab the begin symbol from the first range as our base.
2064 const MCSymbol *Base = CU->getRanges()[0].getStart();
2065 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2066 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2067 } else {
2068 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2069 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2070 }
2072 emitDebugLocEntryLocation(Entry);
2073 }
2074 Asm->OutStreamer.EmitIntValue(0, Size);
2075 Asm->OutStreamer.EmitIntValue(0, Size);
2076 }
2077 }
2079 void DwarfDebug::emitDebugLocDWO() {
2080 Asm->OutStreamer.SwitchSection(
2081 Asm->getObjFileLowering().getDwarfLocDWOSection());
2082 for (const auto &DebugLoc : DotDebugLocEntries) {
2083 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2084 for (const auto &Entry : DebugLoc.List) {
2085 // Just always use start_length for now - at least that's one address
2086 // rather than two. We could get fancier and try to, say, reuse an
2087 // address we know we've emitted elsewhere (the start of the function?
2088 // The start of the CU or CU subrange that encloses this range?)
2089 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2090 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2091 Asm->EmitULEB128(idx);
2092 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2094 emitDebugLocEntryLocation(Entry);
2095 }
2096 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2097 }
2098 }
2100 struct ArangeSpan {
2101 const MCSymbol *Start, *End;
2102 };
2104 // Emit a debug aranges section, containing a CU lookup for any
2105 // address we can tie back to a CU.
2106 void DwarfDebug::emitDebugARanges() {
2107 // Start the dwarf aranges section.
2108 Asm->OutStreamer.SwitchSection(
2109 Asm->getObjFileLowering().getDwarfARangesSection());
2111 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2113 SpansType Spans;
2115 // Build a list of sections used.
2116 std::vector<const MCSection *> Sections;
2117 for (const auto &it : SectionMap) {
2118 const MCSection *Section = it.first;
2119 Sections.push_back(Section);
2120 }
2122 // Sort the sections into order.
2123 // This is only done to ensure consistent output order across different runs.
2124 std::sort(Sections.begin(), Sections.end(), SectionSort);
2126 // Build a set of address spans, sorted by CU.
2127 for (const MCSection *Section : Sections) {
2128 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2129 if (List.size() < 2)
2130 continue;
2132 // Sort the symbols by offset within the section.
2133 std::sort(List.begin(), List.end(),
2134 [&](const SymbolCU &A, const SymbolCU &B) {
2135 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2136 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2138 // Symbols with no order assigned should be placed at the end.
2139 // (e.g. section end labels)
2140 if (IA == 0)
2141 return false;
2142 if (IB == 0)
2143 return true;
2144 return IA < IB;
2145 });
2147 // If we have no section (e.g. common), just write out
2148 // individual spans for each symbol.
2149 if (!Section) {
2150 for (const SymbolCU &Cur : List) {
2151 ArangeSpan Span;
2152 Span.Start = Cur.Sym;
2153 Span.End = nullptr;
2154 if (Cur.CU)
2155 Spans[Cur.CU].push_back(Span);
2156 }
2157 } else {
2158 // Build spans between each label.
2159 const MCSymbol *StartSym = List[0].Sym;
2160 for (size_t n = 1, e = List.size(); n < e; n++) {
2161 const SymbolCU &Prev = List[n - 1];
2162 const SymbolCU &Cur = List[n];
2164 // Try and build the longest span we can within the same CU.
2165 if (Cur.CU != Prev.CU) {
2166 ArangeSpan Span;
2167 Span.Start = StartSym;
2168 Span.End = Cur.Sym;
2169 Spans[Prev.CU].push_back(Span);
2170 StartSym = Cur.Sym;
2171 }
2172 }
2173 }
2174 }
2176 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2178 // Build a list of CUs used.
2179 std::vector<DwarfCompileUnit *> CUs;
2180 for (const auto &it : Spans) {
2181 DwarfCompileUnit *CU = it.first;
2182 CUs.push_back(CU);
2183 }
2185 // Sort the CU list (again, to ensure consistent output order).
2186 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2187 return A->getUniqueID() < B->getUniqueID();
2188 });
2190 // Emit an arange table for each CU we used.
2191 for (DwarfCompileUnit *CU : CUs) {
2192 std::vector<ArangeSpan> &List = Spans[CU];
2194 // Emit size of content not including length itself.
2195 unsigned ContentSize =
2196 sizeof(int16_t) + // DWARF ARange version number
2197 sizeof(int32_t) + // Offset of CU in the .debug_info section
2198 sizeof(int8_t) + // Pointer Size (in bytes)
2199 sizeof(int8_t); // Segment Size (in bytes)
2201 unsigned TupleSize = PtrSize * 2;
2203 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2204 unsigned Padding =
2205 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2207 ContentSize += Padding;
2208 ContentSize += (List.size() + 1) * TupleSize;
2210 // For each compile unit, write the list of spans it covers.
2211 Asm->OutStreamer.AddComment("Length of ARange Set");
2212 Asm->EmitInt32(ContentSize);
2213 Asm->OutStreamer.AddComment("DWARF Arange version number");
2214 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2215 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2216 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2217 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2218 Asm->EmitInt8(PtrSize);
2219 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2220 Asm->EmitInt8(0);
2222 Asm->OutStreamer.EmitFill(Padding, 0xff);
2224 for (const ArangeSpan &Span : List) {
2225 Asm->EmitLabelReference(Span.Start, PtrSize);
2227 // Calculate the size as being from the span start to it's end.
2228 if (Span.End) {
2229 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2230 } else {
2231 // For symbols without an end marker (e.g. common), we
2232 // write a single arange entry containing just that one symbol.
2233 uint64_t Size = SymSize[Span.Start];
2234 if (Size == 0)
2235 Size = 1;
2237 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2238 }
2239 }
2241 Asm->OutStreamer.AddComment("ARange terminator");
2242 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2243 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2244 }
2245 }
2247 // Emit visible names into a debug ranges section.
2248 void DwarfDebug::emitDebugRanges() {
2249 // Start the dwarf ranges section.
2250 Asm->OutStreamer.SwitchSection(
2251 Asm->getObjFileLowering().getDwarfRangesSection());
2253 // Size for our labels.
2254 unsigned char Size = Asm->getDataLayout().getPointerSize();
2256 // Grab the specific ranges for the compile units in the module.
2257 for (const auto &I : CUMap) {
2258 DwarfCompileUnit *TheCU = I.second;
2260 // Iterate over the misc ranges for the compile units in the module.
2261 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2262 // Emit our symbol so we can find the beginning of the range.
2263 Asm->OutStreamer.EmitLabel(List.getSym());
2265 for (const RangeSpan &Range : List.getRanges()) {
2266 const MCSymbol *Begin = Range.getStart();
2267 const MCSymbol *End = Range.getEnd();
2268 assert(Begin && "Range without a begin symbol?");
2269 assert(End && "Range without an end symbol?");
2270 if (TheCU->getRanges().size() == 1) {
2271 // Grab the begin symbol from the first range as our base.
2272 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2273 Asm->EmitLabelDifference(Begin, Base, Size);
2274 Asm->EmitLabelDifference(End, Base, Size);
2275 } else {
2276 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2277 Asm->OutStreamer.EmitSymbolValue(End, Size);
2278 }
2279 }
2281 // And terminate the list with two 0 values.
2282 Asm->OutStreamer.EmitIntValue(0, Size);
2283 Asm->OutStreamer.EmitIntValue(0, Size);
2284 }
2286 // Now emit a range for the CU itself.
2287 if (TheCU->getRanges().size() > 1) {
2288 Asm->OutStreamer.EmitLabel(
2289 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2290 for (const RangeSpan &Range : TheCU->getRanges()) {
2291 const MCSymbol *Begin = Range.getStart();
2292 const MCSymbol *End = Range.getEnd();
2293 assert(Begin && "Range without a begin symbol?");
2294 assert(End && "Range without an end symbol?");
2295 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2296 Asm->OutStreamer.EmitSymbolValue(End, Size);
2297 }
2298 // And terminate the list with two 0 values.
2299 Asm->OutStreamer.EmitIntValue(0, Size);
2300 Asm->OutStreamer.EmitIntValue(0, Size);
2301 }
2302 }
2303 }
2305 // DWARF5 Experimental Separate Dwarf emitters.
2307 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2308 std::unique_ptr<DwarfUnit> NewU) {
2309 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2310 U.getCUNode().getSplitDebugFilename());
2312 if (!CompilationDir.empty())
2313 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2315 addGnuPubAttributes(*NewU, Die);
2317 SkeletonHolder.addUnit(std::move(NewU));
2318 }
2320 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2321 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2322 // DW_AT_addr_base, DW_AT_ranges_base.
2323 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2325 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2326 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2327 DwarfCompileUnit &NewCU = *OwnedUnit;
2328 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2329 DwarfInfoSectionSym);
2331 NewCU.initStmtList(DwarfLineSectionSym);
2333 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2335 return NewCU;
2336 }
2338 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2339 // DW_AT_addr_base.
2340 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2341 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2342 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2344 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), CU, Asm, this,
2345 &SkeletonHolder);
2346 DwarfTypeUnit &NewTU = *OwnedUnit;
2347 NewTU.setTypeSignature(TU.getTypeSignature());
2348 NewTU.setType(nullptr);
2349 NewTU.initSection(
2350 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2352 initSkeletonUnit(TU, NewTU.getUnitDie(), std::move(OwnedUnit));
2353 return NewTU;
2354 }
2356 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2357 // compile units that would normally be in debug_info.
2358 void DwarfDebug::emitDebugInfoDWO() {
2359 assert(useSplitDwarf() && "No split dwarf debug info?");
2360 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2361 // emit relocations into the dwo file.
2362 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2363 }
2365 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2366 // abbreviations for the .debug_info.dwo section.
2367 void DwarfDebug::emitDebugAbbrevDWO() {
2368 assert(useSplitDwarf() && "No split dwarf?");
2369 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2370 }
2372 void DwarfDebug::emitDebugLineDWO() {
2373 assert(useSplitDwarf() && "No split dwarf?");
2374 Asm->OutStreamer.SwitchSection(
2375 Asm->getObjFileLowering().getDwarfLineDWOSection());
2376 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2377 }
2379 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2380 // string section and is identical in format to traditional .debug_str
2381 // sections.
2382 void DwarfDebug::emitDebugStrDWO() {
2383 assert(useSplitDwarf() && "No split dwarf?");
2384 const MCSection *OffSec =
2385 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2386 const MCSymbol *StrSym = DwarfStrSectionSym;
2387 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2388 OffSec, StrSym);
2389 }
2391 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2392 if (!useSplitDwarf())
2393 return nullptr;
2394 if (SingleCU)
2395 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2396 return &SplitTypeUnitFileTable;
2397 }
2399 static uint64_t makeTypeSignature(StringRef Identifier) {
2400 MD5 Hash;
2401 Hash.update(Identifier);
2402 // ... take the least significant 8 bytes and return those. Our MD5
2403 // implementation always returns its results in little endian, swap bytes
2404 // appropriately.
2405 MD5::MD5Result Result;
2406 Hash.final(Result);
2407 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2408 }
2410 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2411 StringRef Identifier, DIE &RefDie,
2412 DICompositeType CTy) {
2413 // Fast path if we're building some type units and one has already used the
2414 // address pool we know we're going to throw away all this work anyway, so
2415 // don't bother building dependent types.
2416 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2417 return;
2419 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2420 if (TU) {
2421 CU.addDIETypeSignature(RefDie, *TU);
2422 return;
2423 }
2425 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2426 AddrPool.resetUsedFlag();
2428 auto OwnedUnit =
2429 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), CU, Asm, this,
2430 &InfoHolder, getDwoLineTable(CU));
2431 DwarfTypeUnit &NewTU = *OwnedUnit;
2432 DIE &UnitDie = NewTU.getUnitDie();
2433 TU = &NewTU;
2434 TypeUnitsUnderConstruction.push_back(
2435 std::make_pair(std::move(OwnedUnit), CTy));
2437 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2438 CU.getLanguage());
2440 uint64_t Signature = makeTypeSignature(Identifier);
2441 NewTU.setTypeSignature(Signature);
2443 if (!useSplitDwarf())
2444 CU.applyStmtList(UnitDie);
2446 NewTU.initSection(
2447 useSplitDwarf()
2448 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2449 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2451 NewTU.setType(NewTU.createTypeDIE(CTy));
2453 if (TopLevelType) {
2454 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2455 TypeUnitsUnderConstruction.clear();
2457 // Types referencing entries in the address table cannot be placed in type
2458 // units.
2459 if (AddrPool.hasBeenUsed()) {
2461 // Remove all the types built while building this type.
2462 // This is pessimistic as some of these types might not be dependent on
2463 // the type that used an address.
2464 for (const auto &TU : TypeUnitsToAdd)
2465 DwarfTypeUnits.erase(TU.second);
2467 // Construct this type in the CU directly.
2468 // This is inefficient because all the dependent types will be rebuilt
2469 // from scratch, including building them in type units, discovering that
2470 // they depend on addresses, throwing them out and rebuilding them.
2471 CU.constructTypeDIE(RefDie, CTy);
2472 return;
2473 }
2475 // If the type wasn't dependent on fission addresses, finish adding the type
2476 // and all its dependent types.
2477 for (auto &TU : TypeUnitsToAdd) {
2478 if (useSplitDwarf())
2479 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2480 InfoHolder.addUnit(std::move(TU.first));
2481 }
2482 }
2483 CU.addDIETypeSignature(RefDie, NewTU);
2484 }
2486 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2487 MCSymbol *Begin, MCSymbol *End) {
2488 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2489 if (DwarfVersion < 4)
2490 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2491 else
2492 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2493 }
2495 // Accelerator table mutators - add each name along with its companion
2496 // DIE to the proper table while ensuring that the name that we're going
2497 // to reference is in the string table. We do this since the names we
2498 // add may not only be identical to the names in the DIE.
2499 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2500 if (!useDwarfAccelTables())
2501 return;
2502 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2503 &Die);
2504 }
2506 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2507 if (!useDwarfAccelTables())
2508 return;
2509 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2510 &Die);
2511 }
2513 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2514 if (!useDwarfAccelTables())
2515 return;
2516 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2517 &Die);
2518 }
2520 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2521 if (!useDwarfAccelTables())
2522 return;
2523 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2524 &Die);
2525 }