1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
17 #include "DebugLocEntry.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.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/DIE.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/IR/Constants.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/MCDwarf.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Dwarf.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/MD5.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
59 #define DEBUG_TYPE "dwarfdebug"
62 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
63 cl::desc("Disable debug info printing"));
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67 cl::desc("Generate GNU-style pubnames and pubtypes"),
70 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
72 cl::desc("Generate dwarf aranges"),
76 enum DefaultOnOff { Default, Enable, Disable };
79 static cl::opt<DefaultOnOff> UnknownLocations(
80 "use-unknown-locations", cl::Hidden,
81 cl::desc("Make an absence of debug location information explicit."),
82 cl::values(clEnumVal(Default, "At top of block or after label"),
83 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
86 static cl::opt<DefaultOnOff>
87 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
88 cl::desc("Output prototype dwarf accelerator tables."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled")),
94 static cl::opt<DefaultOnOff>
95 SplitDwarf("split-dwarf", cl::Hidden,
96 cl::desc("Output DWARF5 split debug info."),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled")),
102 static cl::opt<DefaultOnOff>
103 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
104 cl::desc("Generate DWARF pubnames and pubtypes sections"),
105 cl::values(clEnumVal(Default, "Default for platform"),
106 clEnumVal(Enable, "Enabled"),
107 clEnumVal(Disable, "Disabled")),
110 enum LinkageNameOption {
115 static cl::opt<LinkageNameOption>
116 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
117 cl::desc("Which DWARF linkage-name attributes to emit."),
118 cl::values(clEnumValN(DefaultLinkageNames, "Default",
119 "Default for platform"),
120 clEnumValN(AllLinkageNames, "All", "All"),
121 clEnumValN(AbstractLinkageNames, "Abstract",
122 "Abstract subprograms")),
123 cl::init(DefaultLinkageNames));
125 static const char *const DWARFGroupName = "dwarf";
126 static const char *const DWARFGroupDescription = "DWARF Emission";
127 static const char *const DbgTimerName = "writer";
128 static const char *const DbgTimerDescription = "DWARF Debug Writer";
130 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
132 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
133 : dwarf::OperationEncodingString(Op));
136 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
137 BS.EmitSLEB128(Value, Twine(Value));
140 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
141 BS.EmitULEB128(Value, Twine(Value));
144 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
145 unsigned MachineReg) {
146 // This information is not available while emitting .debug_loc entries.
150 //===----------------------------------------------------------------------===//
152 bool DbgVariable::isBlockByrefVariable() const {
153 assert(Var && "Invalid complex DbgVariable!");
154 return Var->getType().resolve()->isBlockByrefStruct();
157 const DIType *DbgVariable::getType() const {
158 DIType *Ty = Var->getType().resolve();
159 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
160 // addresses instead.
161 if (Ty->isBlockByrefStruct()) {
162 /* Byref variables, in Blocks, are declared by the programmer as
163 "SomeType VarName;", but the compiler creates a
164 __Block_byref_x_VarName struct, and gives the variable VarName
165 either the struct, or a pointer to the struct, as its type. This
166 is necessary for various behind-the-scenes things the compiler
167 needs to do with by-reference variables in blocks.
169 However, as far as the original *programmer* is concerned, the
170 variable should still have type 'SomeType', as originally declared.
172 The following function dives into the __Block_byref_x_VarName
173 struct to find the original type of the variable. This will be
174 passed back to the code generating the type for the Debug
175 Information Entry for the variable 'VarName'. 'VarName' will then
176 have the original type 'SomeType' in its debug information.
178 The original type 'SomeType' will be the type of the field named
179 'VarName' inside the __Block_byref_x_VarName struct.
181 NOTE: In order for this to not completely fail on the debugger
182 side, the Debug Information Entry for the variable VarName needs to
183 have a DW_AT_location that tells the debugger how to unwind through
184 the pointers and __Block_byref_x_VarName struct to find the actual
185 value of the variable. The function addBlockByrefType does this. */
186 DIType *subType = Ty;
187 uint16_t tag = Ty->getTag();
189 if (tag == dwarf::DW_TAG_pointer_type)
190 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
192 auto Elements = cast<DICompositeType>(subType)->getElements();
193 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
194 auto *DT = cast<DIDerivedType>(Elements[i]);
195 if (getName() == DT->getName())
196 return resolve(DT->getBaseType());
202 static const DwarfAccelTable::Atom TypeAtoms[] = {
203 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
204 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
205 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
207 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
208 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
209 InfoHolder(A, "info_string", DIEValueAllocator),
210 SkeletonHolder(A, "skel_string", DIEValueAllocator),
211 IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
212 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
213 dwarf::DW_FORM_data4)),
214 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
215 dwarf::DW_FORM_data4)),
216 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
217 dwarf::DW_FORM_data4)),
218 AccelTypes(TypeAtoms), DebuggerTuning(DebuggerKind::Default) {
221 const Triple &TT = Asm->TM.getTargetTriple();
223 // Make sure we know our "debugger tuning." The target option takes
224 // precedence; fall back to triple-based defaults.
225 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
226 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
228 DebuggerTuning = DebuggerKind::LLDB;
229 else if (TT.isPS4CPU())
230 DebuggerTuning = DebuggerKind::SCE;
232 DebuggerTuning = DebuggerKind::GDB;
234 // Turn on accelerator tables for LLDB by default.
235 if (DwarfAccelTables == Default)
236 HasDwarfAccelTables = tuneForLLDB();
238 HasDwarfAccelTables = DwarfAccelTables == Enable;
240 HasAppleExtensionAttributes = tuneForLLDB();
242 // Handle split DWARF. Off by default for now.
243 if (SplitDwarf == Default)
244 HasSplitDwarf = false;
246 HasSplitDwarf = SplitDwarf == Enable;
248 // Pubnames/pubtypes on by default for GDB.
249 if (DwarfPubSections == Default)
250 HasDwarfPubSections = tuneForGDB();
252 HasDwarfPubSections = DwarfPubSections == Enable;
254 // SCE defaults to linkage names only for abstract subprograms.
255 if (DwarfLinkageNames == DefaultLinkageNames)
256 UseAllLinkageNames = !tuneForSCE();
258 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
260 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
261 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
262 : MMI->getModule()->getDwarfVersion();
263 // Use dwarf 4 by default if nothing is requested.
264 DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
266 // Work around a GDB bug. GDB doesn't support the standard opcode;
267 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
268 // is defined as of DWARF 3.
269 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
270 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
271 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
273 // GDB does not fully support the DWARF 4 representation for bitfields.
274 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
276 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
279 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
280 DwarfDebug::~DwarfDebug() { }
282 static bool isObjCClass(StringRef Name) {
283 return Name.startswith("+") || Name.startswith("-");
286 static bool hasObjCCategory(StringRef Name) {
287 if (!isObjCClass(Name))
290 return Name.find(") ") != StringRef::npos;
293 static void getObjCClassCategory(StringRef In, StringRef &Class,
294 StringRef &Category) {
295 if (!hasObjCCategory(In)) {
296 Class = In.slice(In.find('[') + 1, In.find(' '));
301 Class = In.slice(In.find('[') + 1, In.find('('));
302 Category = In.slice(In.find('[') + 1, In.find(' '));
305 static StringRef getObjCMethodName(StringRef In) {
306 return In.slice(In.find(' ') + 1, In.find(']'));
309 // Add the various names to the Dwarf accelerator table names.
310 // TODO: Determine whether or not we should add names for programs
311 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
312 // is only slightly different than the lookup of non-standard ObjC names.
313 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
314 if (!SP->isDefinition())
316 addAccelName(SP->getName(), Die);
318 // If the linkage name is different than the name, go ahead and output
319 // that as well into the name table.
320 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
321 addAccelName(SP->getLinkageName(), Die);
323 // If this is an Objective-C selector name add it to the ObjC accelerator
325 if (isObjCClass(SP->getName())) {
326 StringRef Class, Category;
327 getObjCClassCategory(SP->getName(), Class, Category);
328 addAccelObjC(Class, Die);
330 addAccelObjC(Category, Die);
331 // Also add the base method name to the name table.
332 addAccelName(getObjCMethodName(SP->getName()), Die);
336 /// Check whether we should create a DIE for the given Scope, return true
337 /// if we don't create a DIE (the corresponding DIE is null).
338 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
339 if (Scope->isAbstractScope())
342 // We don't create a DIE if there is no Range.
343 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
347 if (Ranges.size() > 1)
350 // We don't create a DIE if we have a single Range and the end label
352 return !getLabelAfterInsn(Ranges.front().second);
355 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
357 if (auto *SkelCU = CU.getSkeleton())
358 if (CU.getCUNode()->getSplitDebugInlining())
362 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
363 assert(Scope && Scope->getScopeNode());
364 assert(Scope->isAbstractScope());
365 assert(!Scope->getInlinedAt());
367 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
369 ProcessedSPNodes.insert(SP);
371 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
372 // was inlined from another compile unit.
373 auto &CU = *CUMap.lookup(SP->getUnit());
374 forBothCUs(CU, [&](DwarfCompileUnit &CU) {
375 CU.constructAbstractSubprogramScopeDIE(Scope);
379 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
380 if (!GenerateGnuPubSections)
383 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
386 // Create new DwarfCompileUnit for the given metadata node with tag
387 // DW_TAG_compile_unit.
389 DwarfDebug::constructDwarfCompileUnit(const DICompileUnit *DIUnit) {
390 StringRef FN = DIUnit->getFilename();
391 CompilationDir = DIUnit->getDirectory();
393 auto OwnedUnit = make_unique<DwarfCompileUnit>(
394 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
395 DwarfCompileUnit &NewCU = *OwnedUnit;
396 DIE &Die = NewCU.getUnitDie();
397 InfoHolder.addUnit(std::move(OwnedUnit));
398 if (useSplitDwarf()) {
399 NewCU.setSkeleton(constructSkeletonCU(NewCU));
400 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
401 DIUnit->getSplitDebugFilename());
404 // LTO with assembly output shares a single line table amongst multiple CUs.
405 // To avoid the compilation directory being ambiguous, let the line table
406 // explicitly describe the directory of all files, never relying on the
407 // compilation directory.
408 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
409 Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
410 NewCU.getUniqueID(), CompilationDir);
412 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit->getProducer());
413 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
414 DIUnit->getSourceLanguage());
415 NewCU.addString(Die, dwarf::DW_AT_name, FN);
417 if (!useSplitDwarf()) {
418 NewCU.initStmtList();
420 // If we're using split dwarf the compilation dir is going to be in the
421 // skeleton CU and so we don't need to duplicate it here.
422 if (!CompilationDir.empty())
423 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
425 addGnuPubAttributes(NewCU, Die);
428 if (useAppleExtensionAttributes()) {
429 if (DIUnit->isOptimized())
430 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
432 StringRef Flags = DIUnit->getFlags();
434 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
436 if (unsigned RVer = DIUnit->getRuntimeVersion())
437 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
438 dwarf::DW_FORM_data1, RVer);
442 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
444 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
446 if (DIUnit->getDWOId()) {
447 // This CU is either a clang module DWO or a skeleton CU.
448 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
450 if (!DIUnit->getSplitDebugFilename().empty())
451 // This is a prefabricated skeleton CU.
452 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
453 DIUnit->getSplitDebugFilename());
456 CUMap.insert({DIUnit, &NewCU});
457 CUDieMap.insert({&Die, &NewCU});
461 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
462 const DIImportedEntity *N) {
463 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
464 D->addChild(TheCU.constructImportedEntityDIE(N));
467 /// Sort and unique GVEs by comparing their fragment offset.
468 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
469 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
470 std::sort(GVEs.begin(), GVEs.end(),
471 [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
472 if (A.Expr != B.Expr && A.Expr && B.Expr) {
473 auto FragmentA = A.Expr->getFragmentInfo();
474 auto FragmentB = B.Expr->getFragmentInfo();
475 if (FragmentA && FragmentB)
476 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
480 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
481 [](DwarfCompileUnit::GlobalExpr A,
482 DwarfCompileUnit::GlobalExpr B) {
483 return A.Expr == B.Expr;
489 // Emit all Dwarf sections that should come prior to the content. Create
490 // global DIEs and emit initial debug info sections. This is invoked by
491 // the target AsmPrinter.
492 void DwarfDebug::beginModule() {
493 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
494 DWARFGroupDescription, TimePassesIsEnabled);
495 if (DisableDebugInfoPrinting)
498 const Module *M = MMI->getModule();
500 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
501 M->debug_compile_units_end());
502 // Tell MMI whether we have debug info.
503 MMI->setDebugInfoAvailability(NumDebugCUs > 0);
504 SingleCU = NumDebugCUs == 1;
505 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
507 for (const GlobalVariable &Global : M->globals()) {
508 SmallVector<DIGlobalVariableExpression *, 1> GVs;
509 Global.getDebugInfo(GVs);
510 for (auto *GVE : GVs)
511 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
514 for (DICompileUnit *CUNode : M->debug_compile_units()) {
515 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
516 for (auto *IE : CUNode->getImportedEntities())
517 CU.addImportedEntity(IE);
520 for (auto *GVE : CUNode->getGlobalVariables())
521 GVMap[GVE->getVariable()].push_back({nullptr, GVE->getExpression()});
522 DenseSet<DIGlobalVariable *> Processed;
523 for (auto *GVE : CUNode->getGlobalVariables()) {
524 DIGlobalVariable *GV = GVE->getVariable();
525 if (Processed.insert(GV).second)
526 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
529 for (auto *Ty : CUNode->getEnumTypes()) {
530 // The enum types array by design contains pointers to
531 // MDNodes rather than DIRefs. Unique them here.
532 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
534 for (auto *Ty : CUNode->getRetainedTypes()) {
535 // The retained types array by design contains pointers to
536 // MDNodes rather than DIRefs. Unique them here.
537 if (DIType *RT = dyn_cast<DIType>(Ty))
538 if (!RT->isExternalTypeRef())
539 // There is no point in force-emitting a forward declaration.
540 CU.getOrCreateTypeDIE(RT);
542 // Emit imported_modules last so that the relevant context is already
544 for (auto *IE : CUNode->getImportedEntities())
545 constructAndAddImportedEntityDIE(CU, IE);
549 void DwarfDebug::finishVariableDefinitions() {
550 for (const auto &Var : ConcreteVariables) {
551 DIE *VariableDie = Var->getDIE();
553 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
554 // in the ConcreteVariables list, rather than looking it up again here.
555 // DIE::getUnit isn't simple - it walks parent pointers, etc.
556 DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
558 DbgVariable *AbsVar = getExistingAbstractVariable(
559 InlinedVariable(Var->getVariable(), Var->getInlinedAt()));
560 if (AbsVar && AbsVar->getDIE()) {
561 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
564 Unit->applyVariableAttributes(*Var, *VariableDie);
568 void DwarfDebug::finishSubprogramDefinitions() {
569 for (const DISubprogram *SP : ProcessedSPNodes)
570 if (SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug)
571 forBothCUs(*CUMap.lookup(SP->getUnit()), [&](DwarfCompileUnit &CU) {
572 CU.finishSubprogramDefinition(SP);
576 void DwarfDebug::finalizeModuleInfo() {
577 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
579 finishSubprogramDefinitions();
581 finishVariableDefinitions();
583 // Handle anything that needs to be done on a per-unit basis after
584 // all other generation.
585 for (const auto &P : CUMap) {
586 auto &TheCU = *P.second;
587 // Emit DW_AT_containing_type attribute to connect types with their
588 // vtable holding type.
589 TheCU.constructContainingTypeDIEs();
591 // Add CU specific attributes if we need to add any.
592 // If we're splitting the dwarf out now that we've got the entire
593 // CU then add the dwo id to it.
594 auto *SkCU = TheCU.getSkeleton();
595 if (useSplitDwarf()) {
596 // Emit a unique identifier for this CU.
597 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
598 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
599 dwarf::DW_FORM_data8, ID);
600 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
601 dwarf::DW_FORM_data8, ID);
603 // We don't keep track of which addresses are used in which CU so this
604 // is a bit pessimistic under LTO.
605 if (!AddrPool.isEmpty()) {
606 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
607 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
610 if (!SkCU->getRangeLists().empty()) {
611 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
612 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
617 // If we have code split among multiple sections or non-contiguous
618 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
619 // remain in the .o file, otherwise add a DW_AT_low_pc.
620 // FIXME: We should use ranges allow reordering of code ala
621 // .subsections_via_symbols in mach-o. This would mean turning on
622 // ranges for all subprogram DIEs for mach-o.
623 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
624 if (unsigned NumRanges = TheCU.getRanges().size()) {
626 // A DW_AT_low_pc attribute may also be specified in combination with
627 // DW_AT_ranges to specify the default base address for use in
628 // location lists (see Section 2.6.2) and range lists (see Section
630 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
632 U.setBaseAddress(TheCU.getRanges().front().getStart());
633 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
636 auto *CUNode = cast<DICompileUnit>(P.first);
637 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
638 if (CUNode->getMacros())
639 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
640 U.getMacroLabelBegin(),
641 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
644 // Compute DIE offsets and sizes.
645 InfoHolder.computeSizeAndOffsets();
647 SkeletonHolder.computeSizeAndOffsets();
650 // Emit all Dwarf sections that should come after the content.
651 void DwarfDebug::endModule() {
652 assert(CurFn == nullptr);
653 assert(CurMI == nullptr);
655 // If we aren't actually generating debug info (check beginModule -
656 // conditionalized on !DisableDebugInfoPrinting and the presence of the
657 // llvm.dbg.cu metadata node)
658 if (!MMI->hasDebugInfo())
661 // Finalize the debug info for the module.
662 finalizeModuleInfo();
669 // Emit info into a debug loc section.
672 // Corresponding abbreviations into a abbrev section.
675 // Emit all the DIEs into a debug info section.
678 // Emit info into a debug aranges section.
679 if (GenerateARangeSection)
682 // Emit info into a debug ranges section.
685 // Emit info into a debug macinfo section.
688 if (useSplitDwarf()) {
691 emitDebugAbbrevDWO();
693 // Emit DWO addresses.
694 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
697 // Emit info into the dwarf accelerator table sections.
698 if (useDwarfAccelTables()) {
701 emitAccelNamespaces();
705 // Emit the pubnames and pubtypes sections if requested.
706 if (HasDwarfPubSections) {
707 emitDebugPubNames(GenerateGnuPubSections);
708 emitDebugPubTypes(GenerateGnuPubSections);
712 AbstractVariables.clear();
715 // Find abstract variable, if any, associated with Var.
717 DwarfDebug::getExistingAbstractVariable(InlinedVariable IV,
718 const DILocalVariable *&Cleansed) {
719 // More then one inlined variable corresponds to one abstract variable.
721 auto I = AbstractVariables.find(Cleansed);
722 if (I != AbstractVariables.end())
723 return I->second.get();
727 DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) {
728 const DILocalVariable *Cleansed;
729 return getExistingAbstractVariable(IV, Cleansed);
732 void DwarfDebug::createAbstractVariable(const DILocalVariable *Var,
733 LexicalScope *Scope) {
734 auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr);
735 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
736 AbstractVariables[Var] = std::move(AbsDbgVariable);
739 void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV,
740 const MDNode *ScopeNode) {
741 const DILocalVariable *Cleansed = nullptr;
742 if (getExistingAbstractVariable(IV, Cleansed))
745 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
746 cast<DILocalScope>(ScopeNode)));
749 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(
750 InlinedVariable IV, const MDNode *ScopeNode) {
751 const DILocalVariable *Cleansed = nullptr;
752 if (getExistingAbstractVariable(IV, Cleansed))
755 if (LexicalScope *Scope =
756 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
757 createAbstractVariable(Cleansed, Scope);
760 // Collect variable information from side table maintained by MF.
761 void DwarfDebug::collectVariableInfoFromMFTable(
762 DenseSet<InlinedVariable> &Processed) {
763 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
766 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
767 "Expected inlined-at fields to agree");
769 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
770 Processed.insert(Var);
771 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
773 // If variable scope is not found then skip this variable.
777 ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode());
778 auto RegVar = make_unique<DbgVariable>(Var.first, Var.second);
779 RegVar->initializeMMI(VI.Expr, VI.Slot);
780 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
781 ConcreteVariables.push_back(std::move(RegVar));
785 // Get .debug_loc entry for the instruction range starting at MI.
786 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
787 const DIExpression *Expr = MI->getDebugExpression();
789 assert(MI->getNumOperands() == 4);
790 if (MI->getOperand(0).isReg()) {
791 MachineLocation MLoc;
792 // If the second operand is an immediate, this is a
793 // register-indirect address.
794 if (!MI->getOperand(1).isImm())
795 MLoc.set(MI->getOperand(0).getReg());
797 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
798 return DebugLocEntry::Value(Expr, MLoc);
800 if (MI->getOperand(0).isImm())
801 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
802 if (MI->getOperand(0).isFPImm())
803 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
804 if (MI->getOperand(0).isCImm())
805 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
807 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
810 /// \brief If this and Next are describing different fragments of the same
811 /// variable, merge them by appending Next's values to the current
813 /// Return true if the merge was successful.
814 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
815 if (Begin == Next.Begin) {
816 auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
817 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
818 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
821 // We can only merge entries if none of the fragments overlap any others.
822 // In doing so, we can take advantage of the fact that both lists are
824 for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
825 for (; j < Next.Values.size(); ++j) {
826 int res = DebugHandlerBase::fragmentCmp(
827 cast<DIExpression>(Values[i].Expression),
828 cast<DIExpression>(Next.Values[j].Expression));
829 if (res == 0) // The two expressions overlap, we can't merge.
831 // Values[i] is entirely before Next.Values[j],
832 // so go back to the next entry of Values.
835 // Next.Values[j] is entirely before Values[i], so go on to the
836 // next entry of Next.Values.
840 addValues(Next.Values);
847 /// Build the location list for all DBG_VALUEs in the function that
848 /// describe the same variable. If the ranges of several independent
849 /// fragments of the same variable overlap partially, split them up and
850 /// combine the ranges. The resulting DebugLocEntries are will have
851 /// strict monotonically increasing begin addresses and will never
856 // Ranges History [var, loc, fragment ofs size]
857 // 0 | [x, (reg0, fragment 0, 32)]
858 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
860 // 3 | [clobber reg0]
861 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
866 // [0-1] [x, (reg0, fragment 0, 32)]
867 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
868 // [3-4] [x, (reg1, fragment 32, 32)]
869 // [4- ] [x, (mem, fragment 0, 64)]
871 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
872 const DbgValueHistoryMap::InstrRanges &Ranges) {
873 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
875 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
876 const MachineInstr *Begin = I->first;
877 const MachineInstr *End = I->second;
878 assert(Begin->isDebugValue() && "Invalid History entry");
880 // Check if a variable is inaccessible in this range.
881 if (Begin->getNumOperands() > 1 &&
882 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
887 // If this fragment overlaps with any open ranges, truncate them.
888 const DIExpression *DIExpr = Begin->getDebugExpression();
889 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
890 return fragmentsOverlap(DIExpr, R.getExpression());
892 OpenRanges.erase(Last, OpenRanges.end());
894 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
895 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
897 const MCSymbol *EndLabel;
899 EndLabel = getLabelAfterInsn(End);
900 else if (std::next(I) == Ranges.end())
901 EndLabel = Asm->getFunctionEnd();
903 EndLabel = getLabelBeforeInsn(std::next(I)->first);
904 assert(EndLabel && "Forgot label after instruction ending a range!");
906 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
908 auto Value = getDebugLocValue(Begin);
909 DebugLocEntry Loc(StartLabel, EndLabel, Value);
910 bool couldMerge = false;
912 // If this is a fragment, it may belong to the current DebugLocEntry.
913 if (DIExpr->isFragment()) {
914 // Add this value to the list of open ranges.
915 OpenRanges.push_back(Value);
917 // Attempt to add the fragment to the last entry.
918 if (!DebugLoc.empty())
919 if (DebugLoc.back().MergeValues(Loc))
924 // Need to add a new DebugLocEntry. Add all values from still
925 // valid non-overlapping fragments.
926 if (OpenRanges.size())
927 Loc.addValues(OpenRanges);
929 DebugLoc.push_back(std::move(Loc));
932 // Attempt to coalesce the ranges of two otherwise identical
934 auto CurEntry = DebugLoc.rbegin();
936 dbgs() << CurEntry->getValues().size() << " Values:\n";
937 for (auto &Value : CurEntry->getValues())
942 auto PrevEntry = std::next(CurEntry);
943 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
948 DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope,
949 InlinedVariable IV) {
950 ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode());
951 ConcreteVariables.push_back(make_unique<DbgVariable>(IV.first, IV.second));
952 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
953 return ConcreteVariables.back().get();
956 // Determine whether this DBG_VALUE is valid at the beginning of the function.
957 static bool validAtEntry(const MachineInstr *MInsn) {
958 auto MBB = MInsn->getParent();
959 // Is it in the entry basic block?
960 if (!MBB->pred_empty())
962 for (MachineBasicBlock::const_reverse_iterator I(MInsn); I != MBB->rend(); ++I)
963 if (!(I->isDebugValue() || I->getFlag(MachineInstr::FrameSetup)))
968 // Find variables for each lexical scope.
969 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
970 const DISubprogram *SP,
971 DenseSet<InlinedVariable> &Processed) {
972 // Grab the variable info that was squirreled away in the MMI side-table.
973 collectVariableInfoFromMFTable(Processed);
975 for (const auto &I : DbgValues) {
976 InlinedVariable IV = I.first;
977 if (Processed.count(IV))
980 // Instruction ranges, specifying where IV is accessible.
981 const auto &Ranges = I.second;
985 LexicalScope *Scope = nullptr;
986 if (const DILocation *IA = IV.second)
987 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
989 Scope = LScopes.findLexicalScope(IV.first->getScope());
990 // If variable scope is not found then skip this variable.
994 Processed.insert(IV);
995 DbgVariable *RegVar = createConcreteVariable(*Scope, IV);
997 const MachineInstr *MInsn = Ranges.front().first;
998 assert(MInsn->isDebugValue() && "History must begin with debug value");
1000 // Check if there is a single DBG_VALUE, valid throughout the function.
1001 // A single constant is also considered valid for the entire function.
1002 if (Ranges.size() == 1 &&
1003 (MInsn->getOperand(0).isImm() ||
1004 (validAtEntry(MInsn) && Ranges.front().second == nullptr))) {
1005 RegVar->initializeDbgValue(MInsn);
1009 // Handle multiple DBG_VALUE instructions describing one variable.
1010 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1012 // Build the location list for this variable.
1013 SmallVector<DebugLocEntry, 8> Entries;
1014 buildLocationList(Entries, Ranges);
1016 // If the variable has a DIBasicType, extract it. Basic types cannot have
1017 // unique identifiers, so don't bother resolving the type with the
1019 const DIBasicType *BT = dyn_cast<DIBasicType>(
1020 static_cast<const Metadata *>(IV.first->getType()));
1022 // Finalize the entry by lowering it into a DWARF bytestream.
1023 for (auto &Entry : Entries)
1024 Entry.finalize(*Asm, List, BT);
1027 // Collect info for variables that were optimized out.
1028 for (const DILocalVariable *DV : SP->getVariables()) {
1029 if (Processed.insert(InlinedVariable(DV, nullptr)).second)
1030 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1031 createConcreteVariable(*Scope, InlinedVariable(DV, nullptr));
1035 // Process beginning of an instruction.
1036 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1037 DebugHandlerBase::beginInstruction(MI);
1040 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1041 if (MI->isDebugValue() || MI->isCFIInstruction())
1043 const DebugLoc &DL = MI->getDebugLoc();
1044 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1045 // the last line number actually emitted, to see if it was line 0.
1046 unsigned LastAsmLine =
1047 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1049 if (DL == PrevInstLoc) {
1050 // If we have an ongoing unspecified location, nothing to do here.
1053 // We have an explicit location, same as the previous location.
1054 // But we might be coming back to it after a line 0 record.
1055 if (LastAsmLine == 0 && DL.getLine() != 0) {
1056 // Reinstate the source location but not marked as a statement.
1057 const MDNode *Scope = DL.getScope();
1058 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1064 // We have an unspecified location, which might want to be line 0.
1065 // If we have already emitted a line-0 record, don't repeat it.
1066 if (LastAsmLine == 0)
1068 // If user said Don't Do That, don't do that.
1069 if (UnknownLocations == Disable)
1071 // See if we have a reason to emit a line-0 record now.
1072 // Reasons to emit a line-0 record include:
1073 // - User asked for it (UnknownLocations).
1074 // - Instruction has a label, so it's referenced from somewhere else,
1075 // possibly debug information; we want it to have a source location.
1076 // - Instruction is at the top of a block; we don't want to inherit the
1077 // location from the physically previous (maybe unrelated) block.
1078 if (UnknownLocations == Enable || PrevLabel ||
1079 (PrevInstBB && PrevInstBB != MI->getParent())) {
1080 // Preserve the file and column numbers, if we can, to save space in
1081 // the encoded line table.
1082 // Do not update PrevInstLoc, it remembers the last non-0 line.
1083 const MDNode *Scope = nullptr;
1084 unsigned Column = 0;
1086 Scope = PrevInstLoc.getScope();
1087 Column = PrevInstLoc.getCol();
1089 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1094 // We have an explicit location, different from the previous location.
1095 // Don't repeat a line-0 record, but otherwise emit the new location.
1096 // (The new location might be an explicit line 0, which we do emit.)
1097 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1100 if (DL == PrologEndLoc) {
1101 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1102 PrologEndLoc = DebugLoc();
1104 // If the line changed, we call that a new statement; unless we went to
1105 // line 0 and came back, in which case it is not a new statement.
1106 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1107 if (DL.getLine() && DL.getLine() != OldLine)
1108 Flags |= DWARF2_FLAG_IS_STMT;
1110 const MDNode *Scope = DL.getScope();
1111 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1113 // If we're not at line 0, remember this location.
1118 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1119 // First known non-DBG_VALUE and non-frame setup location marks
1120 // the beginning of the function body.
1121 for (const auto &MBB : *MF)
1122 for (const auto &MI : MBB)
1123 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1125 return MI.getDebugLoc();
1129 // Gather pre-function debug information. Assumes being called immediately
1130 // after the function entry point has been emitted.
1131 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1134 // If there's no debug info for the function we're not going to do anything.
1135 if (!MMI->hasDebugInfo())
1138 auto DI = MF->getFunction()->getSubprogram();
1142 // Grab the lexical scopes for the function, if we don't have any of those
1143 // then we're not going to be able to do anything.
1144 DebugHandlerBase::beginFunction(MF);
1145 if (LScopes.empty())
1148 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1149 // belongs to so that we add to the correct per-cu line table in the
1151 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1152 // FnScope->getScopeNode() and DI->second should represent the same function,
1153 // though they may not be the same MDNode due to inline functions merged in
1154 // LTO where the debug info metadata still differs (either due to distinct
1155 // written differences - two versions of a linkonce_odr function
1156 // written/copied into two separate files, or some sub-optimal metadata that
1157 // isn't structurally identical (see: file path/name info from clang, which
1158 // includes the directory of the cpp file being built, even when the file name
1159 // is absolute (such as an <> lookup header)))
1160 auto *SP = cast<DISubprogram>(FnScope->getScopeNode());
1161 DwarfCompileUnit *TheCU = CUMap.lookup(SP->getUnit());
1163 assert(SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug &&
1164 "DICompileUnit missing from llvm.dbg.cu?");
1167 if (Asm->OutStreamer->hasRawTextSupport())
1168 // Use a single line table if we are generating assembly.
1169 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1171 Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1173 // Record beginning of function.
1174 PrologEndLoc = findPrologueEndLoc(MF);
1175 if (DILocation *L = PrologEndLoc) {
1176 // We'd like to list the prologue as "not statements" but GDB behaves
1177 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1178 auto *SP = L->getInlinedAtScope()->getSubprogram();
1179 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1183 // Gather and emit post-function debug information.
1184 void DwarfDebug::endFunction(const MachineFunction *MF) {
1185 assert(CurFn == MF &&
1186 "endFunction should be called with the same function as beginFunction");
1188 const DISubprogram *SP = MF->getFunction()->getSubprogram();
1189 if (!MMI->hasDebugInfo() || !SP ||
1190 SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) {
1191 // If we don't have a subprogram for this function then there will be a hole
1192 // in the range information. Keep note of this by setting the previously
1193 // used section to nullptr.
1196 DebugHandlerBase::endFunction(MF);
1200 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1201 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1203 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1204 assert(!FnScope || SP == FnScope->getScopeNode());
1205 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1207 DenseSet<InlinedVariable> ProcessedVars;
1208 collectVariableInfo(TheCU, SP, ProcessedVars);
1210 // Add the range of this function to the list of ranges for the CU.
1211 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1213 // Under -gmlt, skip building the subprogram if there are no inlined
1214 // subroutines inside it.
1215 if (TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1216 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1217 assert(InfoHolder.getScopeVariables().empty());
1218 assert(DbgValues.empty());
1219 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1220 // by a -gmlt CU. Add a test and remove this assertion.
1221 assert(AbstractVariables.empty());
1222 PrevLabel = nullptr;
1224 DebugHandlerBase::endFunction(MF);
1229 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1231 // Construct abstract scopes.
1232 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1233 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1234 // Collect info for variables that were optimized out.
1235 for (const DILocalVariable *DV : SP->getVariables()) {
1236 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1238 ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr),
1240 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1241 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1243 constructAbstractSubprogramScopeDIE(AScope);
1246 ProcessedSPNodes.insert(SP);
1247 TheCU.constructSubprogramScopeDIE(SP, FnScope);
1248 if (auto *SkelCU = TheCU.getSkeleton())
1249 if (!LScopes.getAbstractScopesList().empty() &&
1250 TheCU.getCUNode()->getSplitDebugInlining())
1251 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1254 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1255 // DbgVariables except those that are also in AbstractVariables (since they
1256 // can be used cross-function)
1257 InfoHolder.getScopeVariables().clear();
1258 PrevLabel = nullptr;
1260 DebugHandlerBase::endFunction(MF);
1263 // Register a source line with debug info. Returns the unique label that was
1264 // emitted and which provides correspondence to the source line list.
1265 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1270 unsigned Discriminator = 0;
1271 if (auto *Scope = cast_or_null<DIScope>(S)) {
1272 Fn = Scope->getFilename();
1273 Dir = Scope->getDirectory();
1274 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1275 if (getDwarfVersion() >= 4)
1276 Discriminator = LBF->getDiscriminator();
1278 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1279 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1280 .getOrCreateSourceID(Fn, Dir);
1282 Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1286 //===----------------------------------------------------------------------===//
1288 //===----------------------------------------------------------------------===//
1290 // Emit the debug info section.
1291 void DwarfDebug::emitDebugInfo() {
1292 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1293 Holder.emitUnits(/* UseOffsets */ false);
1296 // Emit the abbreviation section.
1297 void DwarfDebug::emitAbbreviations() {
1298 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1300 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1303 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
1304 StringRef TableName) {
1305 Accel.FinalizeTable(Asm, TableName);
1306 Asm->OutStreamer->SwitchSection(Section);
1308 // Emit the full data.
1309 Accel.emit(Asm, Section->getBeginSymbol(), this);
1312 // Emit visible names into a hashed accelerator table section.
1313 void DwarfDebug::emitAccelNames() {
1314 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1318 // Emit objective C classes and categories into a hashed accelerator table
1320 void DwarfDebug::emitAccelObjC() {
1321 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1325 // Emit namespace dies into a hashed accelerator table.
1326 void DwarfDebug::emitAccelNamespaces() {
1327 emitAccel(AccelNamespace,
1328 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1332 // Emit type dies into a hashed accelerator table.
1333 void DwarfDebug::emitAccelTypes() {
1334 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1338 // Public name handling.
1339 // The format for the various pubnames:
1341 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1342 // for the DIE that is named.
1344 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1345 // into the CU and the index value is computed according to the type of value
1346 // for the DIE that is named.
1348 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1349 // it's the offset within the debug_info/debug_types dwo section, however, the
1350 // reference in the pubname header doesn't change.
1352 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1353 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1355 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1357 // We could have a specification DIE that has our most of our knowledge,
1358 // look for that now.
1359 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1360 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1361 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1362 Linkage = dwarf::GIEL_EXTERNAL;
1363 } else if (Die->findAttribute(dwarf::DW_AT_external))
1364 Linkage = dwarf::GIEL_EXTERNAL;
1366 switch (Die->getTag()) {
1367 case dwarf::DW_TAG_class_type:
1368 case dwarf::DW_TAG_structure_type:
1369 case dwarf::DW_TAG_union_type:
1370 case dwarf::DW_TAG_enumeration_type:
1371 return dwarf::PubIndexEntryDescriptor(
1372 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1373 ? dwarf::GIEL_STATIC
1374 : dwarf::GIEL_EXTERNAL);
1375 case dwarf::DW_TAG_typedef:
1376 case dwarf::DW_TAG_base_type:
1377 case dwarf::DW_TAG_subrange_type:
1378 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1379 case dwarf::DW_TAG_namespace:
1380 return dwarf::GIEK_TYPE;
1381 case dwarf::DW_TAG_subprogram:
1382 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1383 case dwarf::DW_TAG_variable:
1384 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1385 case dwarf::DW_TAG_enumerator:
1386 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1387 dwarf::GIEL_STATIC);
1389 return dwarf::GIEK_NONE;
1393 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1395 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1396 MCSection *PSec = GnuStyle
1397 ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1398 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1400 emitDebugPubSection(GnuStyle, PSec, "Names",
1401 &DwarfCompileUnit::getGlobalNames);
1404 void DwarfDebug::emitDebugPubSection(
1405 bool GnuStyle, MCSection *PSec, StringRef Name,
1406 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1407 for (const auto &NU : CUMap) {
1408 DwarfCompileUnit *TheU = NU.second;
1410 const auto &Globals = (TheU->*Accessor)();
1412 if (Globals.empty())
1415 if (auto *Skeleton = TheU->getSkeleton())
1418 // Start the dwarf pubnames section.
1419 Asm->OutStreamer->SwitchSection(PSec);
1422 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1423 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1424 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1425 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1427 Asm->OutStreamer->EmitLabel(BeginLabel);
1429 Asm->OutStreamer->AddComment("DWARF Version");
1430 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1432 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1433 Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1435 Asm->OutStreamer->AddComment("Compilation Unit Length");
1436 Asm->EmitInt32(TheU->getLength());
1438 // Emit the pubnames for this compilation unit.
1439 for (const auto &GI : Globals) {
1440 const char *Name = GI.getKeyData();
1441 const DIE *Entity = GI.second;
1443 Asm->OutStreamer->AddComment("DIE offset");
1444 Asm->EmitInt32(Entity->getOffset());
1447 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1448 Asm->OutStreamer->AddComment(
1449 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1450 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1451 Asm->EmitInt8(Desc.toBits());
1454 Asm->OutStreamer->AddComment("External Name");
1455 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1458 Asm->OutStreamer->AddComment("End Mark");
1460 Asm->OutStreamer->EmitLabel(EndLabel);
1464 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1465 MCSection *PSec = GnuStyle
1466 ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1467 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1469 emitDebugPubSection(GnuStyle, PSec, "Types",
1470 &DwarfCompileUnit::getGlobalTypes);
1473 /// Emit null-terminated strings into a debug str section.
1474 void DwarfDebug::emitDebugStr() {
1475 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1476 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1479 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1480 const DebugLocStream::Entry &Entry) {
1481 auto &&Comments = DebugLocs.getComments(Entry);
1482 auto Comment = Comments.begin();
1483 auto End = Comments.end();
1484 for (uint8_t Byte : DebugLocs.getBytes(Entry))
1485 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1488 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1489 ByteStreamer &Streamer,
1490 const DebugLocEntry::Value &Value,
1491 DwarfExpression &DwarfExpr) {
1492 DIExpressionCursor ExprCursor(Value.getExpression());
1493 DwarfExpr.addFragmentOffset(Value.getExpression());
1495 if (Value.isInt()) {
1496 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1497 BT->getEncoding() == dwarf::DW_ATE_signed_char))
1498 DwarfExpr.AddSignedConstant(Value.getInt());
1500 DwarfExpr.AddUnsignedConstant(Value.getInt());
1501 } else if (Value.isLocation()) {
1502 MachineLocation Loc = Value.getLoc();
1503 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1504 if (Loc.getOffset())
1505 DwarfExpr.AddMachineRegIndirect(TRI, Loc.getReg(), Loc.getOffset());
1507 DwarfExpr.AddMachineRegExpression(TRI, ExprCursor, Loc.getReg());
1508 } else if (Value.isConstantFP()) {
1509 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1510 DwarfExpr.AddUnsignedConstant(RawBytes);
1512 DwarfExpr.AddExpression(std::move(ExprCursor));
1515 void DebugLocEntry::finalize(const AsmPrinter &AP,
1516 DebugLocStream::ListBuilder &List,
1517 const DIBasicType *BT) {
1518 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1519 BufferByteStreamer Streamer = Entry.getStreamer();
1520 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1521 const DebugLocEntry::Value &Value = Values[0];
1522 if (Value.isFragment()) {
1523 // Emit all fragments that belong to the same variable and range.
1524 assert(all_of(Values, [](DebugLocEntry::Value P) {
1525 return P.isFragment();
1526 }) && "all values are expected to be fragments");
1527 assert(std::is_sorted(Values.begin(), Values.end()) &&
1528 "fragments are expected to be sorted");
1530 for (auto Fragment : Values)
1531 emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
1534 assert(Values.size() == 1 && "only fragments may have >1 value");
1535 emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
1537 DwarfExpr.finalize();
1540 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1542 Asm->OutStreamer->AddComment("Loc expr size");
1543 Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1546 APByteStreamer Streamer(*Asm);
1547 emitDebugLocEntry(Streamer, Entry);
1550 // Emit locations into the debug loc section.
1551 void DwarfDebug::emitDebugLoc() {
1552 // Start the dwarf loc section.
1553 Asm->OutStreamer->SwitchSection(
1554 Asm->getObjFileLowering().getDwarfLocSection());
1555 unsigned char Size = Asm->getDataLayout().getPointerSize();
1556 for (const auto &List : DebugLocs.getLists()) {
1557 Asm->OutStreamer->EmitLabel(List.Label);
1558 const DwarfCompileUnit *CU = List.CU;
1559 for (const auto &Entry : DebugLocs.getEntries(List)) {
1560 // Set up the range. This range is relative to the entry point of the
1561 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1562 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1563 if (auto *Base = CU->getBaseAddress()) {
1564 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1565 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1567 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1568 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1571 emitDebugLocEntryLocation(Entry);
1573 Asm->OutStreamer->EmitIntValue(0, Size);
1574 Asm->OutStreamer->EmitIntValue(0, Size);
1578 void DwarfDebug::emitDebugLocDWO() {
1579 Asm->OutStreamer->SwitchSection(
1580 Asm->getObjFileLowering().getDwarfLocDWOSection());
1581 for (const auto &List : DebugLocs.getLists()) {
1582 Asm->OutStreamer->EmitLabel(List.Label);
1583 for (const auto &Entry : DebugLocs.getEntries(List)) {
1584 // Just always use start_length for now - at least that's one address
1585 // rather than two. We could get fancier and try to, say, reuse an
1586 // address we know we've emitted elsewhere (the start of the function?
1587 // The start of the CU or CU subrange that encloses this range?)
1588 Asm->EmitInt8(dwarf::DW_LLE_startx_length);
1589 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1590 Asm->EmitULEB128(idx);
1591 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1593 emitDebugLocEntryLocation(Entry);
1595 Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
1600 const MCSymbol *Start, *End;
1603 // Emit a debug aranges section, containing a CU lookup for any
1604 // address we can tie back to a CU.
1605 void DwarfDebug::emitDebugARanges() {
1606 // Provides a unique id per text section.
1607 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1609 // Filter labels by section.
1610 for (const SymbolCU &SCU : ArangeLabels) {
1611 if (SCU.Sym->isInSection()) {
1612 // Make a note of this symbol and it's section.
1613 MCSection *Section = &SCU.Sym->getSection();
1614 if (!Section->getKind().isMetadata())
1615 SectionMap[Section].push_back(SCU);
1617 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1618 // appear in the output. This sucks as we rely on sections to build
1619 // arange spans. We can do it without, but it's icky.
1620 SectionMap[nullptr].push_back(SCU);
1624 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1626 for (auto &I : SectionMap) {
1627 MCSection *Section = I.first;
1628 SmallVector<SymbolCU, 8> &List = I.second;
1629 if (List.size() < 1)
1632 // If we have no section (e.g. common), just write out
1633 // individual spans for each symbol.
1635 for (const SymbolCU &Cur : List) {
1637 Span.Start = Cur.Sym;
1640 Spans[Cur.CU].push_back(Span);
1645 // Sort the symbols by offset within the section.
1647 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1648 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1649 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1651 // Symbols with no order assigned should be placed at the end.
1652 // (e.g. section end labels)
1660 // Insert a final terminator.
1661 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1663 // Build spans between each label.
1664 const MCSymbol *StartSym = List[0].Sym;
1665 for (size_t n = 1, e = List.size(); n < e; n++) {
1666 const SymbolCU &Prev = List[n - 1];
1667 const SymbolCU &Cur = List[n];
1669 // Try and build the longest span we can within the same CU.
1670 if (Cur.CU != Prev.CU) {
1672 Span.Start = StartSym;
1675 Spans[Prev.CU].push_back(Span);
1681 // Start the dwarf aranges section.
1682 Asm->OutStreamer->SwitchSection(
1683 Asm->getObjFileLowering().getDwarfARangesSection());
1685 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1687 // Build a list of CUs used.
1688 std::vector<DwarfCompileUnit *> CUs;
1689 for (const auto &it : Spans) {
1690 DwarfCompileUnit *CU = it.first;
1694 // Sort the CU list (again, to ensure consistent output order).
1695 std::sort(CUs.begin(), CUs.end(),
1696 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1697 return A->getUniqueID() < B->getUniqueID();
1700 // Emit an arange table for each CU we used.
1701 for (DwarfCompileUnit *CU : CUs) {
1702 std::vector<ArangeSpan> &List = Spans[CU];
1704 // Describe the skeleton CU's offset and length, not the dwo file's.
1705 if (auto *Skel = CU->getSkeleton())
1708 // Emit size of content not including length itself.
1709 unsigned ContentSize =
1710 sizeof(int16_t) + // DWARF ARange version number
1711 sizeof(int32_t) + // Offset of CU in the .debug_info section
1712 sizeof(int8_t) + // Pointer Size (in bytes)
1713 sizeof(int8_t); // Segment Size (in bytes)
1715 unsigned TupleSize = PtrSize * 2;
1717 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1719 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1721 ContentSize += Padding;
1722 ContentSize += (List.size() + 1) * TupleSize;
1724 // For each compile unit, write the list of spans it covers.
1725 Asm->OutStreamer->AddComment("Length of ARange Set");
1726 Asm->EmitInt32(ContentSize);
1727 Asm->OutStreamer->AddComment("DWARF Arange version number");
1728 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1729 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1730 Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1731 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1732 Asm->EmitInt8(PtrSize);
1733 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1736 Asm->OutStreamer->emitFill(Padding, 0xff);
1738 for (const ArangeSpan &Span : List) {
1739 Asm->EmitLabelReference(Span.Start, PtrSize);
1741 // Calculate the size as being from the span start to it's end.
1743 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1745 // For symbols without an end marker (e.g. common), we
1746 // write a single arange entry containing just that one symbol.
1747 uint64_t Size = SymSize[Span.Start];
1751 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1755 Asm->OutStreamer->AddComment("ARange terminator");
1756 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1757 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1761 /// Emit address ranges into a debug ranges section.
1762 void DwarfDebug::emitDebugRanges() {
1763 // Start the dwarf ranges section.
1764 Asm->OutStreamer->SwitchSection(
1765 Asm->getObjFileLowering().getDwarfRangesSection());
1767 // Size for our labels.
1768 unsigned char Size = Asm->getDataLayout().getPointerSize();
1770 // Grab the specific ranges for the compile units in the module.
1771 for (const auto &I : CUMap) {
1772 DwarfCompileUnit *TheCU = I.second;
1774 if (auto *Skel = TheCU->getSkeleton())
1777 // Iterate over the misc ranges for the compile units in the module.
1778 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1779 // Emit our symbol so we can find the beginning of the range.
1780 Asm->OutStreamer->EmitLabel(List.getSym());
1782 for (const RangeSpan &Range : List.getRanges()) {
1783 const MCSymbol *Begin = Range.getStart();
1784 const MCSymbol *End = Range.getEnd();
1785 assert(Begin && "Range without a begin symbol?");
1786 assert(End && "Range without an end symbol?");
1787 if (auto *Base = TheCU->getBaseAddress()) {
1788 Asm->EmitLabelDifference(Begin, Base, Size);
1789 Asm->EmitLabelDifference(End, Base, Size);
1791 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1792 Asm->OutStreamer->EmitSymbolValue(End, Size);
1796 // And terminate the list with two 0 values.
1797 Asm->OutStreamer->EmitIntValue(0, Size);
1798 Asm->OutStreamer->EmitIntValue(0, Size);
1803 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
1804 for (auto *MN : Nodes) {
1805 if (auto *M = dyn_cast<DIMacro>(MN))
1807 else if (auto *F = dyn_cast<DIMacroFile>(MN))
1808 emitMacroFile(*F, U);
1810 llvm_unreachable("Unexpected DI type!");
1814 void DwarfDebug::emitMacro(DIMacro &M) {
1815 Asm->EmitULEB128(M.getMacinfoType());
1816 Asm->EmitULEB128(M.getLine());
1817 StringRef Name = M.getName();
1818 StringRef Value = M.getValue();
1819 Asm->OutStreamer->EmitBytes(Name);
1820 if (!Value.empty()) {
1821 // There should be one space between macro name and macro value.
1823 Asm->OutStreamer->EmitBytes(Value);
1825 Asm->EmitInt8('\0');
1828 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
1829 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1830 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
1831 Asm->EmitULEB128(F.getLine());
1832 DIFile *File = F.getFile();
1834 U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
1835 Asm->EmitULEB128(FID);
1836 handleMacroNodes(F.getElements(), U);
1837 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
1840 /// Emit macros into a debug macinfo section.
1841 void DwarfDebug::emitDebugMacinfo() {
1842 // Start the dwarf macinfo section.
1843 Asm->OutStreamer->SwitchSection(
1844 Asm->getObjFileLowering().getDwarfMacinfoSection());
1846 for (const auto &P : CUMap) {
1847 auto &TheCU = *P.second;
1848 auto *SkCU = TheCU.getSkeleton();
1849 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1850 auto *CUNode = cast<DICompileUnit>(P.first);
1851 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
1852 handleMacroNodes(CUNode->getMacros(), U);
1854 Asm->OutStreamer->AddComment("End Of Macro List Mark");
1858 // DWARF5 Experimental Separate Dwarf emitters.
1860 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1861 std::unique_ptr<DwarfCompileUnit> NewU) {
1862 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1863 U.getCUNode()->getSplitDebugFilename());
1865 if (!CompilationDir.empty())
1866 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1868 addGnuPubAttributes(*NewU, Die);
1870 SkeletonHolder.addUnit(std::move(NewU));
1873 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1874 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1875 // DW_AT_addr_base, DW_AT_ranges_base.
1876 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1878 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1879 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1880 DwarfCompileUnit &NewCU = *OwnedUnit;
1881 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1883 NewCU.initStmtList();
1885 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1890 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1891 // compile units that would normally be in debug_info.
1892 void DwarfDebug::emitDebugInfoDWO() {
1893 assert(useSplitDwarf() && "No split dwarf debug info?");
1894 // Don't emit relocations into the dwo file.
1895 InfoHolder.emitUnits(/* UseOffsets */ true);
1898 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1899 // abbreviations for the .debug_info.dwo section.
1900 void DwarfDebug::emitDebugAbbrevDWO() {
1901 assert(useSplitDwarf() && "No split dwarf?");
1902 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1905 void DwarfDebug::emitDebugLineDWO() {
1906 assert(useSplitDwarf() && "No split dwarf?");
1907 Asm->OutStreamer->SwitchSection(
1908 Asm->getObjFileLowering().getDwarfLineDWOSection());
1909 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
1912 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1913 // string section and is identical in format to traditional .debug_str
1915 void DwarfDebug::emitDebugStrDWO() {
1916 assert(useSplitDwarf() && "No split dwarf?");
1917 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1918 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1922 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1923 if (!useSplitDwarf())
1926 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
1927 return &SplitTypeUnitFileTable;
1930 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
1932 Hash.update(Identifier);
1933 // ... take the least significant 8 bytes and return those. Our MD5
1934 // implementation always returns its results in little endian, swap bytes
1936 MD5::MD5Result Result;
1938 return support::endian::read64le(Result + 8);
1941 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1942 StringRef Identifier, DIE &RefDie,
1943 const DICompositeType *CTy) {
1944 // Fast path if we're building some type units and one has already used the
1945 // address pool we know we're going to throw away all this work anyway, so
1946 // don't bother building dependent types.
1947 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1950 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
1952 CU.addDIETypeSignature(RefDie, Ins.first->second);
1956 bool TopLevelType = TypeUnitsUnderConstruction.empty();
1957 AddrPool.resetUsedFlag();
1959 auto OwnedUnit = make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
1960 getDwoLineTable(CU));
1961 DwarfTypeUnit &NewTU = *OwnedUnit;
1962 DIE &UnitDie = NewTU.getUnitDie();
1963 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
1965 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1968 uint64_t Signature = makeTypeSignature(Identifier);
1969 NewTU.setTypeSignature(Signature);
1970 Ins.first->second = Signature;
1972 if (useSplitDwarf())
1973 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1975 CU.applyStmtList(UnitDie);
1976 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1979 NewTU.setType(NewTU.createTypeDIE(CTy));
1982 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1983 TypeUnitsUnderConstruction.clear();
1985 // Types referencing entries in the address table cannot be placed in type
1987 if (AddrPool.hasBeenUsed()) {
1989 // Remove all the types built while building this type.
1990 // This is pessimistic as some of these types might not be dependent on
1991 // the type that used an address.
1992 for (const auto &TU : TypeUnitsToAdd)
1993 TypeSignatures.erase(TU.second);
1995 // Construct this type in the CU directly.
1996 // This is inefficient because all the dependent types will be rebuilt
1997 // from scratch, including building them in type units, discovering that
1998 // they depend on addresses, throwing them out and rebuilding them.
1999 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2003 // If the type wasn't dependent on fission addresses, finish adding the type
2004 // and all its dependent types.
2005 for (auto &TU : TypeUnitsToAdd) {
2006 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2007 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2010 CU.addDIETypeSignature(RefDie, Signature);
2013 // Accelerator table mutators - add each name along with its companion
2014 // DIE to the proper table while ensuring that the name that we're going
2015 // to reference is in the string table. We do this since the names we
2016 // add may not only be identical to the names in the DIE.
2017 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2018 if (!useDwarfAccelTables())
2020 AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2023 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2024 if (!useDwarfAccelTables())
2026 AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2029 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2030 if (!useDwarfAccelTables())
2032 AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2035 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2036 if (!useDwarfAccelTables())
2038 AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2041 uint16_t DwarfDebug::getDwarfVersion() const {
2042 return Asm->OutStreamer->getContext().getDwarfVersion();