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 "DwarfDebug.h"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
18 #include "DIE.h"
19 #include "DIEHash.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
54 using namespace llvm;
56 #define DEBUG_TYPE "dwarfdebug"
58 static cl::opt<bool>
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
65 cl::init(false));
67 static cl::opt<bool>
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
70 cl::init(false));
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73 cl::Hidden,
74 cl::desc("Generate dwarf aranges"),
75 cl::init(false));
77 namespace {
78 enum DefaultOnOff { Default, Enable, Disable };
79 }
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 cl::init(Default));
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 cl::init(Default));
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 cl::init(Default));
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).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
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 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
191 CurFn = nullptr;
192 CurMI = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
198 else
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
203 else
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
208 else
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
217 {
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
219 beginModule();
220 }
221 }
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
231 if (!SymbolStem)
232 return nullptr;
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
236 return TmpSym;
237 }
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
241 }
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
245 return false;
247 return Name.find(") ") != StringRef::npos;
248 }
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
254 Category = "";
255 return;
256 }
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
260 return;
261 }
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
265 }
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
271 return LA < LB;
272 }
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
280 return;
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
289 // too.
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
294 if (Category != "")
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
298 }
299 }
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
304 if (!Context)
305 return false;
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
308 return true;
309 if (D.isType())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
311 return false;
312 }
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
318 return false;
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
322 if (Ranges.empty())
323 return true;
325 if (Ranges.size() > 1)
326 return false;
328 // We don't create a DIE if we have a single Range and the end label
329 // is null.
330 return !getLabelAfterInsn(Ranges.front().second);
331 }
333 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
334 DbgVariable &DV,
335 const LexicalScope &Scope,
336 DIE *&ObjectPointer) {
337 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
338 if (DV.isObjectPointer())
339 ObjectPointer = Var.get();
340 return Var;
341 }
343 DIE *DwarfDebug::createScopeChildrenDIE(
344 DwarfCompileUnit &TheCU, LexicalScope *Scope,
345 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
346 unsigned *ChildScopeCount) {
347 DIE *ObjectPointer = nullptr;
349 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
350 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
352 unsigned ChildCountWithoutScopes = Children.size();
354 for (LexicalScope *LS : Scope->getChildren())
355 TheCU.constructScopeDIE(LS, Children);
357 if (ChildScopeCount)
358 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
360 return ObjectPointer;
361 }
363 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
364 LexicalScope *Scope, DIE &ScopeDIE) {
365 // We create children when the scope DIE is not null.
366 SmallVector<std::unique_ptr<DIE>, 8> Children;
367 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
369 // Add children
370 for (auto &I : Children)
371 ScopeDIE.addChild(std::move(I));
373 return ObjectPointer;
374 }
376 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
377 LexicalScope *Scope) {
378 assert(Scope && Scope->getScopeNode());
379 assert(Scope->isAbstractScope());
380 assert(!Scope->getInlinedAt());
382 DISubprogram SP(Scope->getScopeNode());
384 ProcessedSPNodes.insert(SP);
386 DIE *&AbsDef = AbstractSPDies[SP];
387 if (AbsDef)
388 return;
390 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
391 // was inlined from another compile unit.
392 DwarfCompileUnit &SPCU = *SPMap[SP];
393 DIE *ContextDIE;
395 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
396 // the important distinction that the DIDescriptor is not associated with the
397 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
398 // any). It could be refactored to some common utility function.
399 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
400 ContextDIE = &SPCU.getUnitDie();
401 SPCU.getOrCreateSubprogramDIE(SPDecl);
402 } else
403 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
405 // Passing null as the associated DIDescriptor because the abstract definition
406 // shouldn't be found by lookup.
407 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
408 DIDescriptor());
409 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
411 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
412 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
413 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
414 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
415 }
417 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
418 LexicalScope *Scope) {
419 assert(Scope && Scope->getScopeNode());
420 assert(!Scope->getInlinedAt());
421 assert(!Scope->isAbstractScope());
422 DISubprogram Sub(Scope->getScopeNode());
424 assert(Sub.isSubprogram());
426 ProcessedSPNodes.insert(Sub);
428 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
430 // Collect arguments for current function.
431 assert(LScopes.isCurrentFunctionScope(Scope));
432 DIE *ObjectPointer = nullptr;
433 for (DbgVariable *ArgDV : CurrentFnArguments)
434 if (ArgDV)
435 ScopeDIE.addChild(
436 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
438 // If this is a variadic function, add an unspecified parameter.
439 DITypeArray FnArgs = Sub.getType().getTypeArray();
440 // If we have a single element of null, it is a function that returns void.
441 // If we have more than one elements and the last one is null, it is a
442 // variadic function.
443 if (FnArgs.getNumElements() > 1 &&
444 !FnArgs.getElement(FnArgs.getNumElements() - 1))
445 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
447 // Collect lexical scope children first.
448 // ObjectPointer might be a local (non-argument) local variable if it's a
449 // block's synthetic this pointer.
450 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
451 assert(!ObjectPointer && "multiple object pointers can't be described");
452 ObjectPointer = BlockObjPtr;
453 }
455 if (ObjectPointer)
456 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
457 }
459 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
460 if (!GenerateGnuPubSections)
461 return;
463 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
464 }
466 // Create new DwarfCompileUnit for the given metadata node with tag
467 // DW_TAG_compile_unit.
468 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
469 StringRef FN = DIUnit.getFilename();
470 CompilationDir = DIUnit.getDirectory();
472 auto OwnedUnit = make_unique<DwarfCompileUnit>(
473 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
474 DwarfCompileUnit &NewCU = *OwnedUnit;
475 DIE &Die = NewCU.getUnitDie();
476 InfoHolder.addUnit(std::move(OwnedUnit));
478 // LTO with assembly output shares a single line table amongst multiple CUs.
479 // To avoid the compilation directory being ambiguous, let the line table
480 // explicitly describe the directory of all files, never relying on the
481 // compilation directory.
482 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
483 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
484 NewCU.getUniqueID(), CompilationDir);
486 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
487 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
488 DIUnit.getLanguage());
489 NewCU.addString(Die, dwarf::DW_AT_name, FN);
491 if (!useSplitDwarf()) {
492 NewCU.initStmtList(DwarfLineSectionSym);
494 // If we're using split dwarf the compilation dir is going to be in the
495 // skeleton CU and so we don't need to duplicate it here.
496 if (!CompilationDir.empty())
497 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
499 addGnuPubAttributes(NewCU, Die);
500 }
502 if (DIUnit.isOptimized())
503 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
505 StringRef Flags = DIUnit.getFlags();
506 if (!Flags.empty())
507 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
509 if (unsigned RVer = DIUnit.getRunTimeVersion())
510 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
511 dwarf::DW_FORM_data1, RVer);
513 if (!FirstCU)
514 FirstCU = &NewCU;
516 if (useSplitDwarf()) {
517 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
518 DwarfInfoDWOSectionSym);
519 NewCU.setSkeleton(constructSkeletonCU(NewCU));
520 } else
521 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
522 DwarfInfoSectionSym);
524 CUMap.insert(std::make_pair(DIUnit, &NewCU));
525 CUDieMap.insert(std::make_pair(&Die, &NewCU));
526 return NewCU;
527 }
529 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
530 const MDNode *N) {
531 DIImportedEntity Module(N);
532 assert(Module.Verify());
533 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
534 D->addChild(TheCU.constructImportedEntityDIE(Module));
535 }
537 // Emit all Dwarf sections that should come prior to the content. Create
538 // global DIEs and emit initial debug info sections. This is invoked by
539 // the target AsmPrinter.
540 void DwarfDebug::beginModule() {
541 if (DisableDebugInfoPrinting)
542 return;
544 const Module *M = MMI->getModule();
546 FunctionDIs = makeSubprogramMap(*M);
548 // If module has named metadata anchors then use them, otherwise scan the
549 // module using debug info finder to collect debug info.
550 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
551 if (!CU_Nodes)
552 return;
553 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
555 // Emit initial sections so we can reference labels later.
556 emitSectionLabels();
558 SingleCU = CU_Nodes->getNumOperands() == 1;
560 for (MDNode *N : CU_Nodes->operands()) {
561 DICompileUnit CUNode(N);
562 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
563 DIArray ImportedEntities = CUNode.getImportedEntities();
564 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
565 ScopesWithImportedEntities.push_back(std::make_pair(
566 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
567 ImportedEntities.getElement(i)));
568 std::sort(ScopesWithImportedEntities.begin(),
569 ScopesWithImportedEntities.end(), less_first());
570 DIArray GVs = CUNode.getGlobalVariables();
571 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
572 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
573 DIArray SPs = CUNode.getSubprograms();
574 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
575 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
576 DIArray EnumTypes = CUNode.getEnumTypes();
577 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
578 DIType Ty(EnumTypes.getElement(i));
579 // The enum types array by design contains pointers to
580 // MDNodes rather than DIRefs. Unique them here.
581 DIType UniqueTy(resolve(Ty.getRef()));
582 CU.getOrCreateTypeDIE(UniqueTy);
583 }
584 DIArray RetainedTypes = CUNode.getRetainedTypes();
585 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
586 DIType Ty(RetainedTypes.getElement(i));
587 // The retained types array by design contains pointers to
588 // MDNodes rather than DIRefs. Unique them here.
589 DIType UniqueTy(resolve(Ty.getRef()));
590 CU.getOrCreateTypeDIE(UniqueTy);
591 }
592 // Emit imported_modules last so that the relevant context is already
593 // available.
594 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
595 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
596 }
598 // Tell MMI that we have debug info.
599 MMI->setDebugInfoAvailability(true);
601 // Prime section data.
602 SectionMap[Asm->getObjFileLowering().getTextSection()];
603 }
605 void DwarfDebug::finishVariableDefinitions() {
606 for (const auto &Var : ConcreteVariables) {
607 DIE *VariableDie = Var->getDIE();
608 assert(VariableDie);
609 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
610 // in the ConcreteVariables list, rather than looking it up again here.
611 // DIE::getUnit isn't simple - it walks parent pointers, etc.
612 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
613 assert(Unit);
614 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
615 if (AbsVar && AbsVar->getDIE()) {
616 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
617 *AbsVar->getDIE());
618 } else
619 Unit->applyVariableAttributes(*Var, *VariableDie);
620 }
621 }
623 void DwarfDebug::finishSubprogramDefinitions() {
624 const Module *M = MMI->getModule();
626 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
627 for (MDNode *N : CU_Nodes->operands()) {
628 DICompileUnit TheCU(N);
629 // Construct subprogram DIE and add variables DIEs.
630 DwarfCompileUnit *SPCU =
631 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
632 DIArray Subprograms = TheCU.getSubprograms();
633 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
634 DISubprogram SP(Subprograms.getElement(i));
635 // Perhaps the subprogram is in another CU (such as due to comdat
636 // folding, etc), in which case ignore it here.
637 if (SPMap[SP] != SPCU)
638 continue;
639 DIE *D = SPCU->getDIE(SP);
640 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
641 if (D)
642 // If this subprogram has an abstract definition, reference that
643 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
644 } else {
645 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
646 // Lazily construct the subprogram if we didn't see either concrete or
647 // inlined versions during codegen. (except in -gmlt ^ where we want
648 // to omit these entirely)
649 D = SPCU->getOrCreateSubprogramDIE(SP);
650 if (D)
651 // And attach the attributes
652 SPCU->applySubprogramAttributesToDefinition(SP, *D);
653 }
654 }
655 }
656 }
659 // Collect info for variables that were optimized out.
660 void DwarfDebug::collectDeadVariables() {
661 const Module *M = MMI->getModule();
663 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
664 for (MDNode *N : CU_Nodes->operands()) {
665 DICompileUnit TheCU(N);
666 // Construct subprogram DIE and add variables DIEs.
667 DwarfCompileUnit *SPCU =
668 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
669 assert(SPCU && "Unable to find Compile Unit!");
670 DIArray Subprograms = TheCU.getSubprograms();
671 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
672 DISubprogram SP(Subprograms.getElement(i));
673 if (ProcessedSPNodes.count(SP) != 0)
674 continue;
675 assert(SP.isSubprogram() &&
676 "CU's subprogram list contains a non-subprogram");
677 assert(SP.isDefinition() &&
678 "CU's subprogram list contains a subprogram declaration");
679 DIArray Variables = SP.getVariables();
680 if (Variables.getNumElements() == 0)
681 continue;
683 DIE *SPDIE = AbstractSPDies.lookup(SP);
684 if (!SPDIE)
685 SPDIE = SPCU->getDIE(SP);
686 assert(SPDIE);
687 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
688 DIVariable DV(Variables.getElement(vi));
689 assert(DV.isVariable());
690 DbgVariable NewVar(DV, DIExpression(nullptr), this);
691 auto VariableDie = SPCU->constructVariableDIE(NewVar);
692 SPCU->applyVariableAttributes(NewVar, *VariableDie);
693 SPDIE->addChild(std::move(VariableDie));
694 }
695 }
696 }
697 }
698 }
700 void DwarfDebug::finalizeModuleInfo() {
701 finishSubprogramDefinitions();
703 finishVariableDefinitions();
705 // Collect info for variables that were optimized out.
706 collectDeadVariables();
708 // Handle anything that needs to be done on a per-unit basis after
709 // all other generation.
710 for (const auto &TheU : getUnits()) {
711 // Emit DW_AT_containing_type attribute to connect types with their
712 // vtable holding type.
713 TheU->constructContainingTypeDIEs();
715 // Add CU specific attributes if we need to add any.
716 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
717 // If we're splitting the dwarf out now that we've got the entire
718 // CU then add the dwo id to it.
719 DwarfCompileUnit *SkCU =
720 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
721 if (useSplitDwarf()) {
722 // Emit a unique identifier for this CU.
723 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
724 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
725 dwarf::DW_FORM_data8, ID);
726 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
727 dwarf::DW_FORM_data8, ID);
729 // We don't keep track of which addresses are used in which CU so this
730 // is a bit pessimistic under LTO.
731 if (!AddrPool.isEmpty())
732 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
733 DwarfAddrSectionSym, DwarfAddrSectionSym);
734 if (!TheU->getRangeLists().empty())
735 SkCU->addSectionLabel(
736 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
737 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
738 }
740 // If we have code split among multiple sections or non-contiguous
741 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
742 // remain in the .o file, otherwise add a DW_AT_low_pc.
743 // FIXME: We should use ranges allow reordering of code ala
744 // .subsections_via_symbols in mach-o. This would mean turning on
745 // ranges for all subprogram DIEs for mach-o.
746 DwarfCompileUnit &U =
747 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
748 unsigned NumRanges = TheU->getRanges().size();
749 if (NumRanges) {
750 if (NumRanges > 1) {
751 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
752 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
753 DwarfDebugRangeSectionSym);
755 // A DW_AT_low_pc attribute may also be specified in combination with
756 // DW_AT_ranges to specify the default base address for use in
757 // location lists (see Section 2.6.2) and range lists (see Section
758 // 2.17.3).
759 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
760 0);
761 } else {
762 RangeSpan &Range = TheU->getRanges().back();
763 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
764 }
765 }
766 }
767 }
769 // Compute DIE offsets and sizes.
770 InfoHolder.computeSizeAndOffsets();
771 if (useSplitDwarf())
772 SkeletonHolder.computeSizeAndOffsets();
773 }
775 void DwarfDebug::endSections() {
776 // Filter labels by section.
777 for (const SymbolCU &SCU : ArangeLabels) {
778 if (SCU.Sym->isInSection()) {
779 // Make a note of this symbol and it's section.
780 const MCSection *Section = &SCU.Sym->getSection();
781 if (!Section->getKind().isMetadata())
782 SectionMap[Section].push_back(SCU);
783 } else {
784 // Some symbols (e.g. common/bss on mach-o) can have no section but still
785 // appear in the output. This sucks as we rely on sections to build
786 // arange spans. We can do it without, but it's icky.
787 SectionMap[nullptr].push_back(SCU);
788 }
789 }
791 // Build a list of sections used.
792 std::vector<const MCSection *> Sections;
793 for (const auto &it : SectionMap) {
794 const MCSection *Section = it.first;
795 Sections.push_back(Section);
796 }
798 // Sort the sections into order.
799 // This is only done to ensure consistent output order across different runs.
800 std::sort(Sections.begin(), Sections.end(), SectionSort);
802 // Add terminating symbols for each section.
803 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
804 const MCSection *Section = Sections[ID];
805 MCSymbol *Sym = nullptr;
807 if (Section) {
808 // We can't call MCSection::getLabelEndName, as it's only safe to do so
809 // if we know the section name up-front. For user-created sections, the
810 // resulting label may not be valid to use as a label. (section names can
811 // use a greater set of characters on some systems)
812 Sym = Asm->GetTempSymbol("debug_end", ID);
813 Asm->OutStreamer.SwitchSection(Section);
814 Asm->OutStreamer.EmitLabel(Sym);
815 }
817 // Insert a final terminator.
818 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
819 }
820 }
822 // Emit all Dwarf sections that should come after the content.
823 void DwarfDebug::endModule() {
824 assert(CurFn == nullptr);
825 assert(CurMI == nullptr);
827 if (!FirstCU)
828 return;
830 // End any existing sections.
831 // TODO: Does this need to happen?
832 endSections();
834 // Finalize the debug info for the module.
835 finalizeModuleInfo();
837 emitDebugStr();
839 // Emit all the DIEs into a debug info section.
840 emitDebugInfo();
842 // Corresponding abbreviations into a abbrev section.
843 emitAbbreviations();
845 // Emit info into a debug aranges section.
846 if (GenerateARangeSection)
847 emitDebugARanges();
849 // Emit info into a debug ranges section.
850 emitDebugRanges();
852 if (useSplitDwarf()) {
853 emitDebugStrDWO();
854 emitDebugInfoDWO();
855 emitDebugAbbrevDWO();
856 emitDebugLineDWO();
857 emitDebugLocDWO();
858 // Emit DWO addresses.
859 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
860 } else
861 // Emit info into a debug loc section.
862 emitDebugLoc();
864 // Emit info into the dwarf accelerator table sections.
865 if (useDwarfAccelTables()) {
866 emitAccelNames();
867 emitAccelObjC();
868 emitAccelNamespaces();
869 emitAccelTypes();
870 }
872 // Emit the pubnames and pubtypes sections if requested.
873 if (HasDwarfPubSections) {
874 emitDebugPubNames(GenerateGnuPubSections);
875 emitDebugPubTypes(GenerateGnuPubSections);
876 }
878 // clean up.
879 SPMap.clear();
880 AbstractVariables.clear();
882 // Reset these for the next Module if we have one.
883 FirstCU = nullptr;
884 }
886 // Find abstract variable, if any, associated with Var.
887 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
888 DIVariable &Cleansed) {
889 LLVMContext &Ctx = DV->getContext();
890 // More then one inlined variable corresponds to one abstract variable.
891 // FIXME: This duplication of variables when inlining should probably be
892 // removed. It's done to allow each DIVariable to describe its location
893 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
894 // make it accurate then remove this duplication/cleansing stuff.
895 Cleansed = cleanseInlinedVariable(DV, Ctx);
896 auto I = AbstractVariables.find(Cleansed);
897 if (I != AbstractVariables.end())
898 return I->second.get();
899 return nullptr;
900 }
902 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
903 DIVariable Cleansed;
904 return getExistingAbstractVariable(DV, Cleansed);
905 }
907 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
908 LexicalScope *Scope) {
909 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
910 addScopeVariable(Scope, AbsDbgVariable.get());
911 AbstractVariables[Var] = std::move(AbsDbgVariable);
912 }
914 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
915 const MDNode *ScopeNode) {
916 DIVariable Cleansed = DV;
917 if (getExistingAbstractVariable(DV, Cleansed))
918 return;
920 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
921 }
923 void
924 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
925 const MDNode *ScopeNode) {
926 DIVariable Cleansed = DV;
927 if (getExistingAbstractVariable(DV, Cleansed))
928 return;
930 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
931 createAbstractVariable(Cleansed, Scope);
932 }
934 // If Var is a current function argument then add it to CurrentFnArguments list.
935 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
936 if (!LScopes.isCurrentFunctionScope(Scope))
937 return false;
938 DIVariable DV = Var->getVariable();
939 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
940 return false;
941 unsigned ArgNo = DV.getArgNumber();
942 if (ArgNo == 0)
943 return false;
945 size_t Size = CurrentFnArguments.size();
946 if (Size == 0)
947 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
948 // llvm::Function argument size is not good indicator of how many
949 // arguments does the function have at source level.
950 if (ArgNo > Size)
951 CurrentFnArguments.resize(ArgNo * 2);
952 assert(!CurrentFnArguments[ArgNo - 1]);
953 CurrentFnArguments[ArgNo - 1] = Var;
954 return true;
955 }
957 // Collect variable information from side table maintained by MMI.
958 void DwarfDebug::collectVariableInfoFromMMITable(
959 SmallPtrSetImpl<const MDNode *> &Processed) {
960 for (const auto &VI : MMI->getVariableDbgInfo()) {
961 if (!VI.Var)
962 continue;
963 Processed.insert(VI.Var);
964 DIVariable DV(VI.Var);
965 DIExpression Expr(VI.Expr);
966 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
968 // If variable scope is not found then skip this variable.
969 if (!Scope)
970 continue;
972 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
973 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
974 DbgVariable *RegVar = ConcreteVariables.back().get();
975 RegVar->setFrameIndex(VI.Slot);
976 addScopeVariable(Scope, RegVar);
977 }
978 }
980 // Get .debug_loc entry for the instruction range starting at MI.
981 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
982 const MDNode *Expr = MI->getDebugExpression();
983 const MDNode *Var = MI->getDebugVariable();
985 assert(MI->getNumOperands() == 4);
986 if (MI->getOperand(0).isReg()) {
987 MachineLocation MLoc;
988 // If the second operand is an immediate, this is a
989 // register-indirect address.
990 if (!MI->getOperand(1).isImm())
991 MLoc.set(MI->getOperand(0).getReg());
992 else
993 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
994 return DebugLocEntry::Value(Var, Expr, MLoc);
995 }
996 if (MI->getOperand(0).isImm())
997 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
998 if (MI->getOperand(0).isFPImm())
999 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1000 if (MI->getOperand(0).isCImm())
1001 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1003 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1004 }
1006 /// Determine whether two variable pieces overlap.
1007 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1008 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1009 return true;
1010 unsigned l1 = P1.getPieceOffset();
1011 unsigned l2 = P2.getPieceOffset();
1012 unsigned r1 = l1 + P1.getPieceSize();
1013 unsigned r2 = l2 + P2.getPieceSize();
1014 // True where [l1,r1[ and [r1,r2[ overlap.
1015 return (l1 < r2) && (l2 < r1);
1016 }
1018 /// Build the location list for all DBG_VALUEs in the function that
1019 /// describe the same variable. If the ranges of several independent
1020 /// pieces of the same variable overlap partially, split them up and
1021 /// combine the ranges. The resulting DebugLocEntries are will have
1022 /// strict monotonically increasing begin addresses and will never
1023 /// overlap.
1024 //
1025 // Input:
1026 //
1027 // Ranges History [var, loc, piece ofs size]
1028 // 0 | [x, (reg0, piece 0, 32)]
1029 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1030 // 2 | | ...
1031 // 3 | [clobber reg0]
1032 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1033 //
1034 // Output:
1035 //
1036 // [0-1] [x, (reg0, piece 0, 32)]
1037 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1038 // [3-4] [x, (reg1, piece 32, 32)]
1039 // [4- ] [x, (mem, piece 0, 64)]
1040 void
1041 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1042 const DbgValueHistoryMap::InstrRanges &Ranges) {
1043 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1045 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1046 const MachineInstr *Begin = I->first;
1047 const MachineInstr *End = I->second;
1048 assert(Begin->isDebugValue() && "Invalid History entry");
1050 // Check if a variable is inaccessible in this range.
1051 if (Begin->getNumOperands() > 1 &&
1052 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1053 OpenRanges.clear();
1054 continue;
1055 }
1057 // If this piece overlaps with any open ranges, truncate them.
1058 DIExpression DIExpr = Begin->getDebugExpression();
1059 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1060 [&](DebugLocEntry::Value R) {
1061 return piecesOverlap(DIExpr, R.getExpression());
1062 });
1063 OpenRanges.erase(Last, OpenRanges.end());
1065 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1066 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1068 const MCSymbol *EndLabel;
1069 if (End != nullptr)
1070 EndLabel = getLabelAfterInsn(End);
1071 else if (std::next(I) == Ranges.end())
1072 EndLabel = FunctionEndSym;
1073 else
1074 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1075 assert(EndLabel && "Forgot label after instruction ending a range!");
1077 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1079 auto Value = getDebugLocValue(Begin);
1080 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1081 bool couldMerge = false;
1083 // If this is a piece, it may belong to the current DebugLocEntry.
1084 if (DIExpr.isVariablePiece()) {
1085 // Add this value to the list of open ranges.
1086 OpenRanges.push_back(Value);
1088 // Attempt to add the piece to the last entry.
1089 if (!DebugLoc.empty())
1090 if (DebugLoc.back().MergeValues(Loc))
1091 couldMerge = true;
1092 }
1094 if (!couldMerge) {
1095 // Need to add a new DebugLocEntry. Add all values from still
1096 // valid non-overlapping pieces.
1097 if (OpenRanges.size())
1098 Loc.addValues(OpenRanges);
1100 DebugLoc.push_back(std::move(Loc));
1101 }
1103 // Attempt to coalesce the ranges of two otherwise identical
1104 // DebugLocEntries.
1105 auto CurEntry = DebugLoc.rbegin();
1106 auto PrevEntry = std::next(CurEntry);
1107 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1108 DebugLoc.pop_back();
1110 DEBUG({
1111 dbgs() << CurEntry->getValues().size() << " Values:\n";
1112 for (auto Value : CurEntry->getValues()) {
1113 Value.getVariable()->dump();
1114 Value.getExpression()->dump();
1115 }
1116 dbgs() << "-----\n";
1117 });
1118 }
1119 }
1122 // Find variables for each lexical scope.
1123 void
1124 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1125 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1126 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1128 // Grab the variable info that was squirreled away in the MMI side-table.
1129 collectVariableInfoFromMMITable(Processed);
1131 for (const auto &I : DbgValues) {
1132 DIVariable DV(I.first);
1133 if (Processed.count(DV))
1134 continue;
1136 // Instruction ranges, specifying where DV is accessible.
1137 const auto &Ranges = I.second;
1138 if (Ranges.empty())
1139 continue;
1141 LexicalScope *Scope = nullptr;
1142 if (MDNode *IA = DV.getInlinedAt()) {
1143 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1144 Scope = LScopes.findInlinedScope(DebugLoc::get(
1145 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1146 } else
1147 Scope = LScopes.findLexicalScope(DV.getContext());
1148 // If variable scope is not found then skip this variable.
1149 if (!Scope)
1150 continue;
1152 Processed.insert(DV);
1153 const MachineInstr *MInsn = Ranges.front().first;
1154 assert(MInsn->isDebugValue() && "History must begin with debug value");
1155 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1156 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1157 DbgVariable *RegVar = ConcreteVariables.back().get();
1158 addScopeVariable(Scope, RegVar);
1160 // Check if the first DBG_VALUE is valid for the rest of the function.
1161 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1162 continue;
1164 // Handle multiple DBG_VALUE instructions describing one variable.
1165 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1167 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1168 DebugLocList &LocList = DotDebugLocEntries.back();
1169 LocList.CU = TheCU;
1170 LocList.Label =
1171 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1173 // Build the location list for this variable.
1174 buildLocationList(LocList.List, Ranges);
1175 }
1177 // Collect info for variables that were optimized out.
1178 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1179 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1180 DIVariable DV(Variables.getElement(i));
1181 assert(DV.isVariable());
1182 if (!Processed.insert(DV))
1183 continue;
1184 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1185 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1186 DIExpression NoExpr;
1187 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1188 addScopeVariable(Scope, ConcreteVariables.back().get());
1189 }
1190 }
1191 }
1193 // Return Label preceding the instruction.
1194 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1195 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1196 assert(Label && "Didn't insert label before instruction");
1197 return Label;
1198 }
1200 // Return Label immediately following the instruction.
1201 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1202 return LabelsAfterInsn.lookup(MI);
1203 }
1205 // Process beginning of an instruction.
1206 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1207 assert(CurMI == nullptr);
1208 CurMI = MI;
1209 // Check if source location changes, but ignore DBG_VALUE locations.
1210 if (!MI->isDebugValue()) {
1211 DebugLoc DL = MI->getDebugLoc();
1212 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1213 unsigned Flags = 0;
1214 PrevInstLoc = DL;
1215 if (DL == PrologEndLoc) {
1216 Flags |= DWARF2_FLAG_PROLOGUE_END;
1217 PrologEndLoc = DebugLoc();
1218 }
1219 if (PrologEndLoc.isUnknown())
1220 Flags |= DWARF2_FLAG_IS_STMT;
1222 if (!DL.isUnknown()) {
1223 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1224 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1225 } else
1226 recordSourceLine(0, 0, nullptr, 0);
1227 }
1228 }
1230 // Insert labels where requested.
1231 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1232 LabelsBeforeInsn.find(MI);
1234 // No label needed.
1235 if (I == LabelsBeforeInsn.end())
1236 return;
1238 // Label already assigned.
1239 if (I->second)
1240 return;
1242 if (!PrevLabel) {
1243 PrevLabel = MMI->getContext().CreateTempSymbol();
1244 Asm->OutStreamer.EmitLabel(PrevLabel);
1245 }
1246 I->second = PrevLabel;
1247 }
1249 // Process end of an instruction.
1250 void DwarfDebug::endInstruction() {
1251 assert(CurMI != nullptr);
1252 // Don't create a new label after DBG_VALUE instructions.
1253 // They don't generate code.
1254 if (!CurMI->isDebugValue())
1255 PrevLabel = nullptr;
1257 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1258 LabelsAfterInsn.find(CurMI);
1259 CurMI = nullptr;
1261 // No label needed.
1262 if (I == LabelsAfterInsn.end())
1263 return;
1265 // Label already assigned.
1266 if (I->second)
1267 return;
1269 // We need a label after this instruction.
1270 if (!PrevLabel) {
1271 PrevLabel = MMI->getContext().CreateTempSymbol();
1272 Asm->OutStreamer.EmitLabel(PrevLabel);
1273 }
1274 I->second = PrevLabel;
1275 }
1277 // Each LexicalScope has first instruction and last instruction to mark
1278 // beginning and end of a scope respectively. Create an inverse map that list
1279 // scopes starts (and ends) with an instruction. One instruction may start (or
1280 // end) multiple scopes. Ignore scopes that are not reachable.
1281 void DwarfDebug::identifyScopeMarkers() {
1282 SmallVector<LexicalScope *, 4> WorkList;
1283 WorkList.push_back(LScopes.getCurrentFunctionScope());
1284 while (!WorkList.empty()) {
1285 LexicalScope *S = WorkList.pop_back_val();
1287 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1288 if (!Children.empty())
1289 WorkList.append(Children.begin(), Children.end());
1291 if (S->isAbstractScope())
1292 continue;
1294 for (const InsnRange &R : S->getRanges()) {
1295 assert(R.first && "InsnRange does not have first instruction!");
1296 assert(R.second && "InsnRange does not have second instruction!");
1297 requestLabelBeforeInsn(R.first);
1298 requestLabelAfterInsn(R.second);
1299 }
1300 }
1301 }
1303 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1304 // First known non-DBG_VALUE and non-frame setup location marks
1305 // the beginning of the function body.
1306 for (const auto &MBB : *MF)
1307 for (const auto &MI : MBB)
1308 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1309 !MI.getDebugLoc().isUnknown())
1310 return MI.getDebugLoc();
1311 return DebugLoc();
1312 }
1314 // Gather pre-function debug information. Assumes being called immediately
1315 // after the function entry point has been emitted.
1316 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1317 CurFn = MF;
1319 // If there's no debug info for the function we're not going to do anything.
1320 if (!MMI->hasDebugInfo())
1321 return;
1323 auto DI = FunctionDIs.find(MF->getFunction());
1324 if (DI == FunctionDIs.end())
1325 return;
1327 // Grab the lexical scopes for the function, if we don't have any of those
1328 // then we're not going to be able to do anything.
1329 LScopes.initialize(*MF);
1330 if (LScopes.empty())
1331 return;
1333 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1335 // Make sure that each lexical scope will have a begin/end label.
1336 identifyScopeMarkers();
1338 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1339 // belongs to so that we add to the correct per-cu line table in the
1340 // non-asm case.
1341 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1342 // FnScope->getScopeNode() and DI->second should represent the same function,
1343 // though they may not be the same MDNode due to inline functions merged in
1344 // LTO where the debug info metadata still differs (either due to distinct
1345 // written differences - two versions of a linkonce_odr function
1346 // written/copied into two separate files, or some sub-optimal metadata that
1347 // isn't structurally identical (see: file path/name info from clang, which
1348 // includes the directory of the cpp file being built, even when the file name
1349 // is absolute (such as an <> lookup header)))
1350 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1351 assert(TheCU && "Unable to find compile unit!");
1352 if (Asm->OutStreamer.hasRawTextSupport())
1353 // Use a single line table if we are generating assembly.
1354 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1355 else
1356 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1358 // Emit a label for the function so that we have a beginning address.
1359 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1360 // Assumes in correct section after the entry point.
1361 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1363 // Calculate history for local variables.
1364 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1365 DbgValues);
1367 // Request labels for the full history.
1368 for (const auto &I : DbgValues) {
1369 const auto &Ranges = I.second;
1370 if (Ranges.empty())
1371 continue;
1373 // The first mention of a function argument gets the FunctionBeginSym
1374 // label, so arguments are visible when breaking at function entry.
1375 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1376 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1377 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1378 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1379 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1380 // Mark all non-overlapping initial pieces.
1381 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1382 DIExpression Piece = I->first->getDebugExpression();
1383 if (std::all_of(Ranges.begin(), I,
1384 [&](DbgValueHistoryMap::InstrRange Pred) {
1385 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1386 }))
1387 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1388 else
1389 break;
1390 }
1391 }
1392 }
1394 for (const auto &Range : Ranges) {
1395 requestLabelBeforeInsn(Range.first);
1396 if (Range.second)
1397 requestLabelAfterInsn(Range.second);
1398 }
1399 }
1401 PrevInstLoc = DebugLoc();
1402 PrevLabel = FunctionBeginSym;
1404 // Record beginning of function.
1405 PrologEndLoc = findPrologueEndLoc(MF);
1406 if (!PrologEndLoc.isUnknown()) {
1407 DebugLoc FnStartDL =
1408 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1409 recordSourceLine(
1410 FnStartDL.getLine(), FnStartDL.getCol(),
1411 FnStartDL.getScope(MF->getFunction()->getContext()),
1412 // We'd like to list the prologue as "not statements" but GDB behaves
1413 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1414 DWARF2_FLAG_IS_STMT);
1415 }
1416 }
1418 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1419 if (addCurrentFnArgument(Var, LS))
1420 return;
1421 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1422 DIVariable DV = Var->getVariable();
1423 // Variables with positive arg numbers are parameters.
1424 if (unsigned ArgNum = DV.getArgNumber()) {
1425 // Keep all parameters in order at the start of the variable list to ensure
1426 // function types are correct (no out-of-order parameters)
1427 //
1428 // This could be improved by only doing it for optimized builds (unoptimized
1429 // builds have the right order to begin with), searching from the back (this
1430 // would catch the unoptimized case quickly), or doing a binary search
1431 // rather than linear search.
1432 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1433 while (I != Vars.end()) {
1434 unsigned CurNum = (*I)->getVariable().getArgNumber();
1435 // A local (non-parameter) variable has been found, insert immediately
1436 // before it.
1437 if (CurNum == 0)
1438 break;
1439 // A later indexed parameter has been found, insert immediately before it.
1440 if (CurNum > ArgNum)
1441 break;
1442 ++I;
1443 }
1444 Vars.insert(I, Var);
1445 return;
1446 }
1448 Vars.push_back(Var);
1449 }
1451 // Gather and emit post-function debug information.
1452 void DwarfDebug::endFunction(const MachineFunction *MF) {
1453 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1454 // though the beginFunction may not be called at all.
1455 // We should handle both cases.
1456 if (!CurFn)
1457 CurFn = MF;
1458 else
1459 assert(CurFn == MF);
1460 assert(CurFn != nullptr);
1462 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1463 !FunctionDIs.count(MF->getFunction())) {
1464 // If we don't have a lexical scope for this function then there will
1465 // be a hole in the range information. Keep note of this by setting the
1466 // previously used section to nullptr.
1467 PrevCU = nullptr;
1468 CurFn = nullptr;
1469 return;
1470 }
1472 // Define end label for subprogram.
1473 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1474 // Assumes in correct section after the entry point.
1475 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1477 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1478 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1480 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1481 collectVariableInfo(ProcessedVars);
1483 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1484 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1486 // Add the range of this function to the list of ranges for the CU.
1487 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1489 // Under -gmlt, skip building the subprogram if there are no inlined
1490 // subroutines inside it.
1491 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1492 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1493 assert(ScopeVariables.empty());
1494 assert(CurrentFnArguments.empty());
1495 assert(DbgValues.empty());
1496 assert(AbstractVariables.empty());
1497 LabelsBeforeInsn.clear();
1498 LabelsAfterInsn.clear();
1499 PrevLabel = nullptr;
1500 CurFn = nullptr;
1501 return;
1502 }
1504 // Construct abstract scopes.
1505 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1506 DISubprogram SP(AScope->getScopeNode());
1507 assert(SP.isSubprogram());
1508 // Collect info for variables that were optimized out.
1509 DIArray Variables = SP.getVariables();
1510 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1511 DIVariable DV(Variables.getElement(i));
1512 assert(DV && DV.isVariable());
1513 if (!ProcessedVars.insert(DV))
1514 continue;
1515 ensureAbstractVariableIsCreated(DV, DV.getContext());
1516 }
1517 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1518 }
1520 constructSubprogramScopeDIE(TheCU, FnScope);
1522 // Clear debug info
1523 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1524 // DbgVariables except those that are also in AbstractVariables (since they
1525 // can be used cross-function)
1526 ScopeVariables.clear();
1527 CurrentFnArguments.clear();
1528 DbgValues.clear();
1529 LabelsBeforeInsn.clear();
1530 LabelsAfterInsn.clear();
1531 PrevLabel = nullptr;
1532 CurFn = nullptr;
1533 }
1535 // Register a source line with debug info. Returns the unique label that was
1536 // emitted and which provides correspondence to the source line list.
1537 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1538 unsigned Flags) {
1539 StringRef Fn;
1540 StringRef Dir;
1541 unsigned Src = 1;
1542 unsigned Discriminator = 0;
1543 if (DIScope Scope = DIScope(S)) {
1544 assert(Scope.isScope());
1545 Fn = Scope.getFilename();
1546 Dir = Scope.getDirectory();
1547 if (Scope.isLexicalBlockFile())
1548 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1550 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1551 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1552 .getOrCreateSourceID(Fn, Dir);
1553 }
1554 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1555 Discriminator, Fn);
1556 }
1558 //===----------------------------------------------------------------------===//
1559 // Emit Methods
1560 //===----------------------------------------------------------------------===//
1562 // Emit initial Dwarf sections with a label at the start of each one.
1563 void DwarfDebug::emitSectionLabels() {
1564 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1566 // Dwarf sections base addresses.
1567 DwarfInfoSectionSym =
1568 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1569 if (useSplitDwarf()) {
1570 DwarfInfoDWOSectionSym =
1571 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1572 DwarfTypesDWOSectionSym =
1573 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1574 }
1575 DwarfAbbrevSectionSym =
1576 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1577 if (useSplitDwarf())
1578 DwarfAbbrevDWOSectionSym = emitSectionSym(
1579 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1580 if (GenerateARangeSection)
1581 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1583 DwarfLineSectionSym =
1584 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1585 if (GenerateGnuPubSections) {
1586 DwarfGnuPubNamesSectionSym =
1587 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1588 DwarfGnuPubTypesSectionSym =
1589 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1590 } else if (HasDwarfPubSections) {
1591 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1592 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1593 }
1595 DwarfStrSectionSym =
1596 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1597 if (useSplitDwarf()) {
1598 DwarfStrDWOSectionSym =
1599 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1600 DwarfAddrSectionSym =
1601 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1602 DwarfDebugLocSectionSym =
1603 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1604 } else
1605 DwarfDebugLocSectionSym =
1606 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1607 DwarfDebugRangeSectionSym =
1608 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1609 }
1611 // Recursively emits a debug information entry.
1612 void DwarfDebug::emitDIE(DIE &Die) {
1613 // Get the abbreviation for this DIE.
1614 const DIEAbbrev &Abbrev = Die.getAbbrev();
1616 // Emit the code (index) for the abbreviation.
1617 if (Asm->isVerbose())
1618 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1619 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1620 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1621 dwarf::TagString(Abbrev.getTag()));
1622 Asm->EmitULEB128(Abbrev.getNumber());
1624 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1625 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1627 // Emit the DIE attribute values.
1628 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1629 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1630 dwarf::Form Form = AbbrevData[i].getForm();
1631 assert(Form && "Too many attributes for DIE (check abbreviation)");
1633 if (Asm->isVerbose()) {
1634 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1635 if (Attr == dwarf::DW_AT_accessibility)
1636 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1637 cast<DIEInteger>(Values[i])->getValue()));
1638 }
1640 // Emit an attribute using the defined form.
1641 Values[i]->EmitValue(Asm, Form);
1642 }
1644 // Emit the DIE children if any.
1645 if (Abbrev.hasChildren()) {
1646 for (auto &Child : Die.getChildren())
1647 emitDIE(*Child);
1649 Asm->OutStreamer.AddComment("End Of Children Mark");
1650 Asm->EmitInt8(0);
1651 }
1652 }
1654 // Emit the debug info section.
1655 void DwarfDebug::emitDebugInfo() {
1656 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1658 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1659 }
1661 // Emit the abbreviation section.
1662 void DwarfDebug::emitAbbreviations() {
1663 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1665 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1666 }
1668 // Emit the last address of the section and the end of the line matrix.
1669 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1670 // Define last address of section.
1671 Asm->OutStreamer.AddComment("Extended Op");
1672 Asm->EmitInt8(0);
1674 Asm->OutStreamer.AddComment("Op size");
1675 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1676 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1677 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1679 Asm->OutStreamer.AddComment("Section end label");
1681 Asm->OutStreamer.EmitSymbolValue(
1682 Asm->GetTempSymbol("section_end", SectionEnd),
1683 Asm->getDataLayout().getPointerSize());
1685 // Mark end of matrix.
1686 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1687 Asm->EmitInt8(0);
1688 Asm->EmitInt8(1);
1689 Asm->EmitInt8(1);
1690 }
1692 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1693 StringRef TableName, StringRef SymName) {
1694 Accel.FinalizeTable(Asm, TableName);
1695 Asm->OutStreamer.SwitchSection(Section);
1696 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1697 Asm->OutStreamer.EmitLabel(SectionBegin);
1699 // Emit the full data.
1700 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1701 }
1703 // Emit visible names into a hashed accelerator table section.
1704 void DwarfDebug::emitAccelNames() {
1705 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1706 "Names", "names_begin");
1707 }
1709 // Emit objective C classes and categories into a hashed accelerator table
1710 // section.
1711 void DwarfDebug::emitAccelObjC() {
1712 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1713 "ObjC", "objc_begin");
1714 }
1716 // Emit namespace dies into a hashed accelerator table.
1717 void DwarfDebug::emitAccelNamespaces() {
1718 emitAccel(AccelNamespace,
1719 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1720 "namespac", "namespac_begin");
1721 }
1723 // Emit type dies into a hashed accelerator table.
1724 void DwarfDebug::emitAccelTypes() {
1725 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1726 "types", "types_begin");
1727 }
1729 // Public name handling.
1730 // The format for the various pubnames:
1731 //
1732 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1733 // for the DIE that is named.
1734 //
1735 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1736 // into the CU and the index value is computed according to the type of value
1737 // for the DIE that is named.
1738 //
1739 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1740 // it's the offset within the debug_info/debug_types dwo section, however, the
1741 // reference in the pubname header doesn't change.
1743 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1744 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1745 const DIE *Die) {
1746 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1748 // We could have a specification DIE that has our most of our knowledge,
1749 // look for that now.
1750 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1751 if (SpecVal) {
1752 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1753 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1754 Linkage = dwarf::GIEL_EXTERNAL;
1755 } else if (Die->findAttribute(dwarf::DW_AT_external))
1756 Linkage = dwarf::GIEL_EXTERNAL;
1758 switch (Die->getTag()) {
1759 case dwarf::DW_TAG_class_type:
1760 case dwarf::DW_TAG_structure_type:
1761 case dwarf::DW_TAG_union_type:
1762 case dwarf::DW_TAG_enumeration_type:
1763 return dwarf::PubIndexEntryDescriptor(
1764 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1765 ? dwarf::GIEL_STATIC
1766 : dwarf::GIEL_EXTERNAL);
1767 case dwarf::DW_TAG_typedef:
1768 case dwarf::DW_TAG_base_type:
1769 case dwarf::DW_TAG_subrange_type:
1770 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1771 case dwarf::DW_TAG_namespace:
1772 return dwarf::GIEK_TYPE;
1773 case dwarf::DW_TAG_subprogram:
1774 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1775 case dwarf::DW_TAG_constant:
1776 case dwarf::DW_TAG_variable:
1777 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1778 case dwarf::DW_TAG_enumerator:
1779 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1780 dwarf::GIEL_STATIC);
1781 default:
1782 return dwarf::GIEK_NONE;
1783 }
1784 }
1786 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1787 ///
1788 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1789 const MCSection *PSec =
1790 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1791 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1793 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1794 }
1796 void DwarfDebug::emitDebugPubSection(
1797 bool GnuStyle, const MCSection *PSec, StringRef Name,
1798 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1799 for (const auto &NU : CUMap) {
1800 DwarfCompileUnit *TheU = NU.second;
1802 const auto &Globals = (TheU->*Accessor)();
1804 if (Globals.empty())
1805 continue;
1807 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1808 TheU = Skeleton;
1809 unsigned ID = TheU->getUniqueID();
1811 // Start the dwarf pubnames section.
1812 Asm->OutStreamer.SwitchSection(PSec);
1814 // Emit the header.
1815 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1816 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1817 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1818 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1820 Asm->OutStreamer.EmitLabel(BeginLabel);
1822 Asm->OutStreamer.AddComment("DWARF Version");
1823 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1825 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1826 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1828 Asm->OutStreamer.AddComment("Compilation Unit Length");
1829 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1831 // Emit the pubnames for this compilation unit.
1832 for (const auto &GI : Globals) {
1833 const char *Name = GI.getKeyData();
1834 const DIE *Entity = GI.second;
1836 Asm->OutStreamer.AddComment("DIE offset");
1837 Asm->EmitInt32(Entity->getOffset());
1839 if (GnuStyle) {
1840 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1841 Asm->OutStreamer.AddComment(
1842 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1843 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1844 Asm->EmitInt8(Desc.toBits());
1845 }
1847 Asm->OutStreamer.AddComment("External Name");
1848 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1849 }
1851 Asm->OutStreamer.AddComment("End Mark");
1852 Asm->EmitInt32(0);
1853 Asm->OutStreamer.EmitLabel(EndLabel);
1854 }
1855 }
1857 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1858 const MCSection *PSec =
1859 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1860 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1862 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1863 }
1865 // Emit visible names into a debug str section.
1866 void DwarfDebug::emitDebugStr() {
1867 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1868 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1869 }
1871 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1872 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1873 const DITypeIdentifierMap &Map,
1874 ArrayRef<DebugLocEntry::Value> Values) {
1875 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1876 return P.isVariablePiece();
1877 }) && "all values are expected to be pieces");
1878 assert(std::is_sorted(Values.begin(), Values.end()) &&
1879 "pieces are expected to be sorted");
1881 unsigned Offset = 0;
1882 for (auto Piece : Values) {
1883 DIExpression Expr = Piece.getExpression();
1884 unsigned PieceOffset = Expr.getPieceOffset();
1885 unsigned PieceSize = Expr.getPieceSize();
1886 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1887 if (Offset < PieceOffset) {
1888 // The DWARF spec seriously mandates pieces with no locations for gaps.
1889 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1890 Offset += PieceOffset-Offset;
1891 }
1893 Offset += PieceSize;
1895 const unsigned SizeOfByte = 8;
1896 #ifndef NDEBUG
1897 DIVariable Var = Piece.getVariable();
1898 assert(!Var.isIndirect() && "indirect address for piece");
1899 unsigned VarSize = Var.getSizeInBits(Map);
1900 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1901 && "piece is larger than or outside of variable");
1902 assert(PieceSize*SizeOfByte != VarSize
1903 && "piece covers entire variable");
1904 #endif
1905 if (Piece.isLocation() && Piece.getLoc().isReg())
1906 Asm->EmitDwarfRegOpPiece(Streamer,
1907 Piece.getLoc(),
1908 PieceSize*SizeOfByte);
1909 else {
1910 emitDebugLocValue(Streamer, Piece);
1911 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1912 }
1913 }
1914 }
1917 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1918 const DebugLocEntry &Entry) {
1919 const DebugLocEntry::Value Value = Entry.getValues()[0];
1920 if (Value.isVariablePiece())
1921 // Emit all pieces that belong to the same variable and range.
1922 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1924 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1925 emitDebugLocValue(Streamer, Value);
1926 }
1928 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1929 const DebugLocEntry::Value &Value) {
1930 DIVariable DV = Value.getVariable();
1931 // Regular entry.
1932 if (Value.isInt()) {
1933 DIBasicType BTy(resolve(DV.getType()));
1934 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1935 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1936 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1937 Streamer.EmitSLEB128(Value.getInt());
1938 } else {
1939 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1940 Streamer.EmitULEB128(Value.getInt());
1941 }
1942 } else if (Value.isLocation()) {
1943 MachineLocation Loc = Value.getLoc();
1944 DIExpression Expr = Value.getExpression();
1945 if (!Expr)
1946 // Regular entry.
1947 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1948 else {
1949 // Complex address entry.
1950 unsigned N = Expr.getNumElements();
1951 unsigned i = 0;
1952 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1953 if (Loc.getOffset()) {
1954 i = 2;
1955 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1956 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1957 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1958 Streamer.EmitSLEB128(Expr.getElement(1));
1959 } else {
1960 // If first address element is OpPlus then emit
1961 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1962 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1963 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1964 i = 2;
1965 }
1966 } else {
1967 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1968 }
1970 // Emit remaining complex address elements.
1971 for (; i < N; ++i) {
1972 uint64_t Element = Expr.getElement(i);
1973 if (Element == dwarf::DW_OP_plus) {
1974 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1975 Streamer.EmitULEB128(Expr.getElement(++i));
1976 } else if (Element == dwarf::DW_OP_deref) {
1977 if (!Loc.isReg())
1978 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1979 } else if (Element == dwarf::DW_OP_piece) {
1980 i += 3;
1981 // handled in emitDebugLocEntry.
1982 } else
1983 llvm_unreachable("unknown Opcode found in complex address");
1984 }
1985 }
1986 }
1987 // else ... ignore constant fp. There is not any good way to
1988 // to represent them here in dwarf.
1989 // FIXME: ^
1990 }
1992 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1993 Asm->OutStreamer.AddComment("Loc expr size");
1994 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1995 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1996 Asm->EmitLabelDifference(end, begin, 2);
1997 Asm->OutStreamer.EmitLabel(begin);
1998 // Emit the entry.
1999 APByteStreamer Streamer(*Asm);
2000 emitDebugLocEntry(Streamer, Entry);
2001 // Close the range.
2002 Asm->OutStreamer.EmitLabel(end);
2003 }
2005 // Emit locations into the debug loc section.
2006 void DwarfDebug::emitDebugLoc() {
2007 // Start the dwarf loc section.
2008 Asm->OutStreamer.SwitchSection(
2009 Asm->getObjFileLowering().getDwarfLocSection());
2010 unsigned char Size = Asm->getDataLayout().getPointerSize();
2011 for (const auto &DebugLoc : DotDebugLocEntries) {
2012 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2013 const DwarfCompileUnit *CU = DebugLoc.CU;
2014 assert(!CU->getRanges().empty());
2015 for (const auto &Entry : DebugLoc.List) {
2016 // Set up the range. This range is relative to the entry point of the
2017 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2018 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2019 if (CU->getRanges().size() == 1) {
2020 // Grab the begin symbol from the first range as our base.
2021 const MCSymbol *Base = CU->getRanges()[0].getStart();
2022 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2023 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2024 } else {
2025 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2026 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2027 }
2029 emitDebugLocEntryLocation(Entry);
2030 }
2031 Asm->OutStreamer.EmitIntValue(0, Size);
2032 Asm->OutStreamer.EmitIntValue(0, Size);
2033 }
2034 }
2036 void DwarfDebug::emitDebugLocDWO() {
2037 Asm->OutStreamer.SwitchSection(
2038 Asm->getObjFileLowering().getDwarfLocDWOSection());
2039 for (const auto &DebugLoc : DotDebugLocEntries) {
2040 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2041 for (const auto &Entry : DebugLoc.List) {
2042 // Just always use start_length for now - at least that's one address
2043 // rather than two. We could get fancier and try to, say, reuse an
2044 // address we know we've emitted elsewhere (the start of the function?
2045 // The start of the CU or CU subrange that encloses this range?)
2046 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2047 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2048 Asm->EmitULEB128(idx);
2049 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2051 emitDebugLocEntryLocation(Entry);
2052 }
2053 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2054 }
2055 }
2057 struct ArangeSpan {
2058 const MCSymbol *Start, *End;
2059 };
2061 // Emit a debug aranges section, containing a CU lookup for any
2062 // address we can tie back to a CU.
2063 void DwarfDebug::emitDebugARanges() {
2064 // Start the dwarf aranges section.
2065 Asm->OutStreamer.SwitchSection(
2066 Asm->getObjFileLowering().getDwarfARangesSection());
2068 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2070 SpansType Spans;
2072 // Build a list of sections used.
2073 std::vector<const MCSection *> Sections;
2074 for (const auto &it : SectionMap) {
2075 const MCSection *Section = it.first;
2076 Sections.push_back(Section);
2077 }
2079 // Sort the sections into order.
2080 // This is only done to ensure consistent output order across different runs.
2081 std::sort(Sections.begin(), Sections.end(), SectionSort);
2083 // Build a set of address spans, sorted by CU.
2084 for (const MCSection *Section : Sections) {
2085 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2086 if (List.size() < 2)
2087 continue;
2089 // Sort the symbols by offset within the section.
2090 std::sort(List.begin(), List.end(),
2091 [&](const SymbolCU &A, const SymbolCU &B) {
2092 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2093 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2095 // Symbols with no order assigned should be placed at the end.
2096 // (e.g. section end labels)
2097 if (IA == 0)
2098 return false;
2099 if (IB == 0)
2100 return true;
2101 return IA < IB;
2102 });
2104 // If we have no section (e.g. common), just write out
2105 // individual spans for each symbol.
2106 if (!Section) {
2107 for (const SymbolCU &Cur : List) {
2108 ArangeSpan Span;
2109 Span.Start = Cur.Sym;
2110 Span.End = nullptr;
2111 if (Cur.CU)
2112 Spans[Cur.CU].push_back(Span);
2113 }
2114 } else {
2115 // Build spans between each label.
2116 const MCSymbol *StartSym = List[0].Sym;
2117 for (size_t n = 1, e = List.size(); n < e; n++) {
2118 const SymbolCU &Prev = List[n - 1];
2119 const SymbolCU &Cur = List[n];
2121 // Try and build the longest span we can within the same CU.
2122 if (Cur.CU != Prev.CU) {
2123 ArangeSpan Span;
2124 Span.Start = StartSym;
2125 Span.End = Cur.Sym;
2126 Spans[Prev.CU].push_back(Span);
2127 StartSym = Cur.Sym;
2128 }
2129 }
2130 }
2131 }
2133 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2135 // Build a list of CUs used.
2136 std::vector<DwarfCompileUnit *> CUs;
2137 for (const auto &it : Spans) {
2138 DwarfCompileUnit *CU = it.first;
2139 CUs.push_back(CU);
2140 }
2142 // Sort the CU list (again, to ensure consistent output order).
2143 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2144 return A->getUniqueID() < B->getUniqueID();
2145 });
2147 // Emit an arange table for each CU we used.
2148 for (DwarfCompileUnit *CU : CUs) {
2149 std::vector<ArangeSpan> &List = Spans[CU];
2151 // Emit size of content not including length itself.
2152 unsigned ContentSize =
2153 sizeof(int16_t) + // DWARF ARange version number
2154 sizeof(int32_t) + // Offset of CU in the .debug_info section
2155 sizeof(int8_t) + // Pointer Size (in bytes)
2156 sizeof(int8_t); // Segment Size (in bytes)
2158 unsigned TupleSize = PtrSize * 2;
2160 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2161 unsigned Padding =
2162 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2164 ContentSize += Padding;
2165 ContentSize += (List.size() + 1) * TupleSize;
2167 // For each compile unit, write the list of spans it covers.
2168 Asm->OutStreamer.AddComment("Length of ARange Set");
2169 Asm->EmitInt32(ContentSize);
2170 Asm->OutStreamer.AddComment("DWARF Arange version number");
2171 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2172 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2173 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2174 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2175 Asm->EmitInt8(PtrSize);
2176 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2177 Asm->EmitInt8(0);
2179 Asm->OutStreamer.EmitFill(Padding, 0xff);
2181 for (const ArangeSpan &Span : List) {
2182 Asm->EmitLabelReference(Span.Start, PtrSize);
2184 // Calculate the size as being from the span start to it's end.
2185 if (Span.End) {
2186 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2187 } else {
2188 // For symbols without an end marker (e.g. common), we
2189 // write a single arange entry containing just that one symbol.
2190 uint64_t Size = SymSize[Span.Start];
2191 if (Size == 0)
2192 Size = 1;
2194 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2195 }
2196 }
2198 Asm->OutStreamer.AddComment("ARange terminator");
2199 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2200 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2201 }
2202 }
2204 // Emit visible names into a debug ranges section.
2205 void DwarfDebug::emitDebugRanges() {
2206 // Start the dwarf ranges section.
2207 Asm->OutStreamer.SwitchSection(
2208 Asm->getObjFileLowering().getDwarfRangesSection());
2210 // Size for our labels.
2211 unsigned char Size = Asm->getDataLayout().getPointerSize();
2213 // Grab the specific ranges for the compile units in the module.
2214 for (const auto &I : CUMap) {
2215 DwarfCompileUnit *TheCU = I.second;
2217 // Iterate over the misc ranges for the compile units in the module.
2218 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2219 // Emit our symbol so we can find the beginning of the range.
2220 Asm->OutStreamer.EmitLabel(List.getSym());
2222 for (const RangeSpan &Range : List.getRanges()) {
2223 const MCSymbol *Begin = Range.getStart();
2224 const MCSymbol *End = Range.getEnd();
2225 assert(Begin && "Range without a begin symbol?");
2226 assert(End && "Range without an end symbol?");
2227 if (TheCU->getRanges().size() == 1) {
2228 // Grab the begin symbol from the first range as our base.
2229 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2230 Asm->EmitLabelDifference(Begin, Base, Size);
2231 Asm->EmitLabelDifference(End, Base, Size);
2232 } else {
2233 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2234 Asm->OutStreamer.EmitSymbolValue(End, Size);
2235 }
2236 }
2238 // And terminate the list with two 0 values.
2239 Asm->OutStreamer.EmitIntValue(0, Size);
2240 Asm->OutStreamer.EmitIntValue(0, Size);
2241 }
2243 // Now emit a range for the CU itself.
2244 if (TheCU->getRanges().size() > 1) {
2245 Asm->OutStreamer.EmitLabel(
2246 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2247 for (const RangeSpan &Range : TheCU->getRanges()) {
2248 const MCSymbol *Begin = Range.getStart();
2249 const MCSymbol *End = Range.getEnd();
2250 assert(Begin && "Range without a begin symbol?");
2251 assert(End && "Range without an end symbol?");
2252 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2253 Asm->OutStreamer.EmitSymbolValue(End, Size);
2254 }
2255 // And terminate the list with two 0 values.
2256 Asm->OutStreamer.EmitIntValue(0, Size);
2257 Asm->OutStreamer.EmitIntValue(0, Size);
2258 }
2259 }
2260 }
2262 // DWARF5 Experimental Separate Dwarf emitters.
2264 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2265 std::unique_ptr<DwarfUnit> NewU) {
2266 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2267 U.getCUNode().getSplitDebugFilename());
2269 if (!CompilationDir.empty())
2270 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2272 addGnuPubAttributes(*NewU, Die);
2274 SkeletonHolder.addUnit(std::move(NewU));
2275 }
2277 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2278 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2279 // DW_AT_addr_base, DW_AT_ranges_base.
2280 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2282 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2283 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2284 DwarfCompileUnit &NewCU = *OwnedUnit;
2285 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2286 DwarfInfoSectionSym);
2288 NewCU.initStmtList(DwarfLineSectionSym);
2290 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2292 return NewCU;
2293 }
2295 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2296 // compile units that would normally be in debug_info.
2297 void DwarfDebug::emitDebugInfoDWO() {
2298 assert(useSplitDwarf() && "No split dwarf debug info?");
2299 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2300 // emit relocations into the dwo file.
2301 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2302 }
2304 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2305 // abbreviations for the .debug_info.dwo section.
2306 void DwarfDebug::emitDebugAbbrevDWO() {
2307 assert(useSplitDwarf() && "No split dwarf?");
2308 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2309 }
2311 void DwarfDebug::emitDebugLineDWO() {
2312 assert(useSplitDwarf() && "No split dwarf?");
2313 Asm->OutStreamer.SwitchSection(
2314 Asm->getObjFileLowering().getDwarfLineDWOSection());
2315 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2316 }
2318 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2319 // string section and is identical in format to traditional .debug_str
2320 // sections.
2321 void DwarfDebug::emitDebugStrDWO() {
2322 assert(useSplitDwarf() && "No split dwarf?");
2323 const MCSection *OffSec =
2324 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2325 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2326 OffSec);
2327 }
2329 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2330 if (!useSplitDwarf())
2331 return nullptr;
2332 if (SingleCU)
2333 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2334 return &SplitTypeUnitFileTable;
2335 }
2337 static uint64_t makeTypeSignature(StringRef Identifier) {
2338 MD5 Hash;
2339 Hash.update(Identifier);
2340 // ... take the least significant 8 bytes and return those. Our MD5
2341 // implementation always returns its results in little endian, swap bytes
2342 // appropriately.
2343 MD5::MD5Result Result;
2344 Hash.final(Result);
2345 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2346 }
2348 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2349 StringRef Identifier, DIE &RefDie,
2350 DICompositeType CTy) {
2351 // Fast path if we're building some type units and one has already used the
2352 // address pool we know we're going to throw away all this work anyway, so
2353 // don't bother building dependent types.
2354 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2355 return;
2357 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2358 if (TU) {
2359 CU.addDIETypeSignature(RefDie, *TU);
2360 return;
2361 }
2363 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2364 AddrPool.resetUsedFlag();
2366 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2367 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2368 this, &InfoHolder, getDwoLineTable(CU));
2369 DwarfTypeUnit &NewTU = *OwnedUnit;
2370 DIE &UnitDie = NewTU.getUnitDie();
2371 TU = &NewTU;
2372 TypeUnitsUnderConstruction.push_back(
2373 std::make_pair(std::move(OwnedUnit), CTy));
2375 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2376 CU.getLanguage());
2378 uint64_t Signature = makeTypeSignature(Identifier);
2379 NewTU.setTypeSignature(Signature);
2381 if (useSplitDwarf())
2382 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2383 DwarfTypesDWOSectionSym);
2384 else {
2385 CU.applyStmtList(UnitDie);
2386 NewTU.initSection(
2387 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2388 }
2390 NewTU.setType(NewTU.createTypeDIE(CTy));
2392 if (TopLevelType) {
2393 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2394 TypeUnitsUnderConstruction.clear();
2396 // Types referencing entries in the address table cannot be placed in type
2397 // units.
2398 if (AddrPool.hasBeenUsed()) {
2400 // Remove all the types built while building this type.
2401 // This is pessimistic as some of these types might not be dependent on
2402 // the type that used an address.
2403 for (const auto &TU : TypeUnitsToAdd)
2404 DwarfTypeUnits.erase(TU.second);
2406 // Construct this type in the CU directly.
2407 // This is inefficient because all the dependent types will be rebuilt
2408 // from scratch, including building them in type units, discovering that
2409 // they depend on addresses, throwing them out and rebuilding them.
2410 CU.constructTypeDIE(RefDie, CTy);
2411 return;
2412 }
2414 // If the type wasn't dependent on fission addresses, finish adding the type
2415 // and all its dependent types.
2416 for (auto &TU : TypeUnitsToAdd)
2417 InfoHolder.addUnit(std::move(TU.first));
2418 }
2419 CU.addDIETypeSignature(RefDie, NewTU);
2420 }
2422 // Accelerator table mutators - add each name along with its companion
2423 // DIE to the proper table while ensuring that the name that we're going
2424 // to reference is in the string table. We do this since the names we
2425 // add may not only be identical to the names in the DIE.
2426 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2427 if (!useDwarfAccelTables())
2428 return;
2429 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2430 &Die);
2431 }
2433 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2434 if (!useDwarfAccelTables())
2435 return;
2436 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2437 &Die);
2438 }
2440 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2441 if (!useDwarfAccelTables())
2442 return;
2443 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2444 &Die);
2445 }
2447 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2448 if (!useDwarfAccelTables())
2449 return;
2450 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2451 &Die);
2452 }