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 #define DEBUG_TYPE "dwarfdebug"
15 #include "ByteStreamer.h"
16 #include "DwarfDebug.h"
17 #include "DIE.h"
18 #include "DIEHash.h"
19 #include "DwarfAccelTable.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/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 using namespace llvm;
54 static cl::opt<bool>
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
61 cl::init(false));
63 static cl::opt<bool>
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
66 cl::init(false));
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
69 cl::Hidden,
70 cl::desc("Generate dwarf aranges"),
71 cl::init(false));
73 namespace {
74 enum DefaultOnOff { Default, Enable, Disable };
75 }
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
83 cl::init(Default));
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 cl::init(Default));
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 cl::init(Default));
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 namespace llvm {
112 /// resolve - Look in the DwarfDebug map for the MDNode that
113 /// corresponds to the reference.
114 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
115 return DD->resolve(Ref);
116 }
118 DIType DbgVariable::getType() const {
119 DIType Ty = Var.getType();
120 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
121 // addresses instead.
122 if (Var.isBlockByrefVariable()) {
123 /* Byref variables, in Blocks, are declared by the programmer as
124 "SomeType VarName;", but the compiler creates a
125 __Block_byref_x_VarName struct, and gives the variable VarName
126 either the struct, or a pointer to the struct, as its type. This
127 is necessary for various behind-the-scenes things the compiler
128 needs to do with by-reference variables in blocks.
130 However, as far as the original *programmer* is concerned, the
131 variable should still have type 'SomeType', as originally declared.
133 The following function dives into the __Block_byref_x_VarName
134 struct to find the original type of the variable. This will be
135 passed back to the code generating the type for the Debug
136 Information Entry for the variable 'VarName'. 'VarName' will then
137 have the original type 'SomeType' in its debug information.
139 The original type 'SomeType' will be the type of the field named
140 'VarName' inside the __Block_byref_x_VarName struct.
142 NOTE: In order for this to not completely fail on the debugger
143 side, the Debug Information Entry for the variable VarName needs to
144 have a DW_AT_location that tells the debugger how to unwind through
145 the pointers and __Block_byref_x_VarName struct to find the actual
146 value of the variable. The function addBlockByrefType does this. */
147 DIType subType = Ty;
148 uint16_t tag = Ty.getTag();
150 if (tag == dwarf::DW_TAG_pointer_type)
151 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
153 DIArray Elements = DICompositeType(subType).getTypeArray();
154 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
155 DIDerivedType DT(Elements.getElement(i));
156 if (getName() == DT.getName())
157 return (resolve(DT.getTypeDerivedFrom()));
158 }
159 }
160 return Ty;
161 }
163 } // end llvm namespace
165 /// Return Dwarf Version by checking module flags.
166 static unsigned getDwarfVersionFromModule(const Module *M) {
167 Value *Val = M->getModuleFlag("Dwarf Version");
168 if (!Val)
169 return dwarf::DWARF_VERSION;
170 return cast<ConstantInt>(Val)->getZExtValue();
171 }
173 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
174 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
175 PrevLabel(NULL), GlobalRangeCount(0),
176 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
177 UsedNonDefaultText(false),
178 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
180 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
181 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
182 DwarfAddrSectionSym = 0;
183 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
184 FunctionBeginSym = FunctionEndSym = 0;
185 CurFn = 0;
186 CurMI = 0;
188 // Turn on accelerator tables for Darwin by default, pubnames by
189 // default for non-Darwin, and handle split dwarf.
190 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
192 if (DwarfAccelTables == Default)
193 HasDwarfAccelTables = IsDarwin;
194 else
195 HasDwarfAccelTables = DwarfAccelTables == Enable;
197 if (SplitDwarf == Default)
198 HasSplitDwarf = false;
199 else
200 HasSplitDwarf = SplitDwarf == Enable;
202 if (DwarfPubSections == Default)
203 HasDwarfPubSections = !IsDarwin;
204 else
205 HasDwarfPubSections = DwarfPubSections == Enable;
207 DwarfVersion = DwarfVersionNumber
208 ? DwarfVersionNumber
209 : getDwarfVersionFromModule(MMI->getModule());
211 {
212 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
213 beginModule();
214 }
215 }
217 // Switch to the specified MCSection and emit an assembler
218 // temporary label to it if SymbolStem is specified.
219 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
220 const char *SymbolStem = 0) {
221 Asm->OutStreamer.SwitchSection(Section);
222 if (!SymbolStem)
223 return 0;
225 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
226 Asm->OutStreamer.EmitLabel(TmpSym);
227 return TmpSym;
228 }
230 DwarfFile::~DwarfFile() {
231 for (DwarfUnit *DU : CUs)
232 delete DU;
233 }
235 MCSymbol *DwarfFile::getStringPoolSym() {
236 return Asm->GetTempSymbol(StringPref);
237 }
239 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
240 std::pair<MCSymbol *, unsigned> &Entry =
241 StringPool.GetOrCreateValue(Str).getValue();
242 if (Entry.first)
243 return Entry.first;
245 Entry.second = NextStringPoolNumber++;
246 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
247 }
249 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
250 std::pair<MCSymbol *, unsigned> &Entry =
251 StringPool.GetOrCreateValue(Str).getValue();
252 if (Entry.first)
253 return Entry.second;
255 Entry.second = NextStringPoolNumber++;
256 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
257 return Entry.second;
258 }
260 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
261 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
262 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
263 if (P.second)
264 ++NextAddrPoolNumber;
265 return P.first->second.Number;
266 }
268 // Define a unique number for the abbreviation.
269 //
270 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
271 // Check the set for priors.
272 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
274 // If it's newly added.
275 if (InSet == &Abbrev) {
276 // Add to abbreviation list.
277 Abbreviations.push_back(&Abbrev);
279 // Assign the vector position + 1 as its number.
280 Abbrev.setNumber(Abbreviations.size());
281 } else {
282 // Assign existing abbreviation number.
283 Abbrev.setNumber(InSet->getNumber());
284 }
285 }
287 static bool isObjCClass(StringRef Name) {
288 return Name.startswith("+") || Name.startswith("-");
289 }
291 static bool hasObjCCategory(StringRef Name) {
292 if (!isObjCClass(Name))
293 return false;
295 return Name.find(") ") != StringRef::npos;
296 }
298 static void getObjCClassCategory(StringRef In, StringRef &Class,
299 StringRef &Category) {
300 if (!hasObjCCategory(In)) {
301 Class = In.slice(In.find('[') + 1, In.find(' '));
302 Category = "";
303 return;
304 }
306 Class = In.slice(In.find('[') + 1, In.find('('));
307 Category = In.slice(In.find('[') + 1, In.find(' '));
308 return;
309 }
311 static StringRef getObjCMethodName(StringRef In) {
312 return In.slice(In.find(' ') + 1, In.find(']'));
313 }
315 // Helper for sorting sections into a stable output order.
316 static bool SectionSort(const MCSection *A, const MCSection *B) {
317 std::string LA = (A ? A->getLabelBeginName() : "");
318 std::string LB = (B ? B->getLabelBeginName() : "");
319 return LA < LB;
320 }
322 // Add the various names to the Dwarf accelerator table names.
323 // TODO: Determine whether or not we should add names for programs
324 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
325 // is only slightly different than the lookup of non-standard ObjC names.
326 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
327 if (!SP.isDefinition())
328 return;
329 TheU->addAccelName(SP.getName(), Die);
331 // If the linkage name is different than the name, go ahead and output
332 // that as well into the name table.
333 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
334 TheU->addAccelName(SP.getLinkageName(), Die);
336 // If this is an Objective-C selector name add it to the ObjC accelerator
337 // too.
338 if (isObjCClass(SP.getName())) {
339 StringRef Class, Category;
340 getObjCClassCategory(SP.getName(), Class, Category);
341 TheU->addAccelObjC(Class, Die);
342 if (Category != "")
343 TheU->addAccelObjC(Category, Die);
344 // Also add the base method name to the name table.
345 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
346 }
347 }
349 /// isSubprogramContext - Return true if Context is either a subprogram
350 /// or another context nested inside a subprogram.
351 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
352 if (!Context)
353 return false;
354 DIDescriptor D(Context);
355 if (D.isSubprogram())
356 return true;
357 if (D.isType())
358 return isSubprogramContext(resolve(DIType(Context).getContext()));
359 return false;
360 }
362 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
363 // and DW_AT_high_pc attributes. If there are global variables in this
364 // scope then create and insert DIEs for these variables.
365 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
366 DISubprogram SP) {
367 SP = SPCU->getOdrUniqueSubprogram(resolve(SP.getContext()), SP);
368 DIE *SPDie = SPCU->getDIE(SP);
370 assert(SPDie && "Unable to find subprogram DIE!");
372 // If we're updating an abstract DIE, then we will be adding the children and
373 // object pointer later on. But what we don't want to do is process the
374 // concrete DIE twice.
375 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
376 // Pick up abstract subprogram DIE.
377 SPDie =
378 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
379 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
380 } else {
381 DISubprogram SPDecl = SP.getFunctionDeclaration();
382 if (!SPDecl.isSubprogram()) {
383 // There is not any need to generate specification DIE for a function
384 // defined at compile unit level. If a function is defined inside another
385 // function then gdb prefers the definition at top level and but does not
386 // expect specification DIE in parent function. So avoid creating
387 // specification DIE for a function defined inside a function.
388 DIScope SPContext = resolve(SP.getContext());
389 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
390 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
391 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
393 // Add arguments.
394 DICompositeType SPTy = SP.getType();
395 DIArray Args = SPTy.getTypeArray();
396 uint16_t SPTag = SPTy.getTag();
397 if (SPTag == dwarf::DW_TAG_subroutine_type)
398 SPCU->constructSubprogramArguments(*SPDie, Args);
399 DIE *SPDeclDie = SPDie;
400 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
401 *SPCU->getUnitDie());
402 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
403 }
404 }
405 }
407 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
409 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
410 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
411 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
413 // Add name to the name table, we do this here because we're guaranteed
414 // to have concrete versions of our DW_TAG_subprogram nodes.
415 addSubprogramNames(SPCU, SP, SPDie);
417 return SPDie;
418 }
420 /// Check whether we should create a DIE for the given Scope, return true
421 /// if we don't create a DIE (the corresponding DIE is null).
422 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
423 if (Scope->isAbstractScope())
424 return false;
426 // We don't create a DIE if there is no Range.
427 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
428 if (Ranges.empty())
429 return true;
431 if (Ranges.size() > 1)
432 return false;
434 // We don't create a DIE if we have a single Range and the end label
435 // is null.
436 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
437 MCSymbol *End = getLabelAfterInsn(RI->second);
438 return !End;
439 }
441 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
442 dwarf::Attribute A, const MCSymbol *L,
443 const MCSymbol *Sec) {
444 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
445 U->addSectionLabel(D, A, L);
446 else
447 U->addSectionDelta(D, A, L, Sec);
448 }
450 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
451 const SmallVectorImpl<InsnRange> &Range) {
452 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
453 // emitting it appropriately.
454 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
455 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
456 DwarfDebugRangeSectionSym);
458 RangeSpanList List(RangeSym);
459 for (const InsnRange &R : Range) {
460 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
461 List.addRange(std::move(Span));
462 }
464 // Add the range list to the set of ranges to be emitted.
465 TheCU->addRangeList(std::move(List));
466 }
468 // Construct new DW_TAG_lexical_block for this scope and attach
469 // DW_AT_low_pc/DW_AT_high_pc labels.
470 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
471 LexicalScope *Scope) {
472 if (isLexicalScopeDIENull(Scope))
473 return 0;
475 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
476 if (Scope->isAbstractScope())
477 return ScopeDIE;
479 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
481 // If we have multiple ranges, emit them into the range section.
482 if (ScopeRanges.size() > 1) {
483 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
484 return ScopeDIE;
485 }
487 // Construct the address range for this DIE.
488 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
489 MCSymbol *Start = getLabelBeforeInsn(RI->first);
490 MCSymbol *End = getLabelAfterInsn(RI->second);
491 assert(End && "End label should not be null!");
493 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
494 assert(End->isDefined() && "Invalid end label for an inlined scope!");
496 attachLowHighPC(TheCU, ScopeDIE, Start, End);
498 return ScopeDIE;
499 }
501 // This scope represents inlined body of a function. Construct DIE to
502 // represent this concrete inlined copy of the function.
503 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
504 LexicalScope *Scope) {
505 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
506 assert(!ScopeRanges.empty() &&
507 "LexicalScope does not have instruction markers!");
509 if (!Scope->getScopeNode())
510 return NULL;
511 DIScope DS(Scope->getScopeNode());
512 DISubprogram InlinedSP = getDISubprogram(DS);
513 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
514 if (!OriginDIE) {
515 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
516 return NULL;
517 }
519 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
520 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
522 // If we have multiple ranges, emit them into the range section.
523 if (ScopeRanges.size() > 1)
524 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
525 else {
526 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
527 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
528 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
530 if (StartLabel == 0 || EndLabel == 0)
531 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
533 assert(StartLabel->isDefined() &&
534 "Invalid starting label for an inlined scope!");
535 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
537 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
538 }
540 InlinedSubprogramDIEs.insert(OriginDIE);
542 // Add the call site information to the DIE.
543 DILocation DL(Scope->getInlinedAt());
544 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
545 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
546 TheCU->getUniqueID()));
547 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
549 // Add name to the name table, we do this here because we're guaranteed
550 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
551 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
553 return ScopeDIE;
554 }
556 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
557 LexicalScope *Scope,
558 SmallVectorImpl<DIE *> &Children) {
559 DIE *ObjectPointer = NULL;
561 // Collect arguments for current function.
562 if (LScopes.isCurrentFunctionScope(Scope)) {
563 for (DbgVariable *ArgDV : CurrentFnArguments)
564 if (ArgDV)
565 if (DIE *Arg =
566 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
567 Children.push_back(Arg);
568 if (ArgDV->isObjectPointer())
569 ObjectPointer = Arg;
570 }
572 // If this is a variadic function, add an unspecified parameter.
573 DISubprogram SP(Scope->getScopeNode());
574 DIArray FnArgs = SP.getType().getTypeArray();
575 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
576 .isUnspecifiedParameter()) {
577 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
578 Children.push_back(Ellipsis);
579 }
580 }
582 // Collect lexical scope children first.
583 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
584 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
585 Scope->isAbstractScope())) {
586 Children.push_back(Variable);
587 if (DV->isObjectPointer())
588 ObjectPointer = Variable;
589 }
590 for (LexicalScope *LS : Scope->getChildren())
591 if (DIE *Nested = constructScopeDIE(TheCU, LS))
592 Children.push_back(Nested);
593 return ObjectPointer;
594 }
596 // Construct a DIE for this scope.
597 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
598 LexicalScope *Scope) {
599 if (!Scope || !Scope->getScopeNode())
600 return NULL;
602 DIScope DS(Scope->getScopeNode());
604 SmallVector<DIE *, 8> Children;
605 DIE *ObjectPointer = NULL;
606 bool ChildrenCreated = false;
608 // We try to create the scope DIE first, then the children DIEs. This will
609 // avoid creating un-used children then removing them later when we find out
610 // the scope DIE is null.
611 DIE *ScopeDIE = NULL;
612 if (Scope->getInlinedAt())
613 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
614 else if (DS.isSubprogram()) {
615 ProcessedSPNodes.insert(DS);
616 if (Scope->isAbstractScope()) {
617 ScopeDIE = TheCU->getDIE(DS);
618 // Note down abstract DIE.
619 if (ScopeDIE)
620 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
621 } else
622 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
623 } else {
624 // Early exit when we know the scope DIE is going to be null.
625 if (isLexicalScopeDIENull(Scope))
626 return NULL;
628 // We create children here when we know the scope DIE is not going to be
629 // null and the children will be added to the scope DIE.
630 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
631 ChildrenCreated = true;
633 // There is no need to emit empty lexical block DIE.
634 std::pair<ImportedEntityMap::const_iterator,
635 ImportedEntityMap::const_iterator> Range =
636 std::equal_range(
637 ScopesWithImportedEntities.begin(),
638 ScopesWithImportedEntities.end(),
639 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
640 less_first());
641 if (Children.empty() && Range.first == Range.second)
642 return NULL;
643 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
644 assert(ScopeDIE && "Scope DIE should not be null.");
645 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
646 ++i)
647 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
648 }
650 if (!ScopeDIE) {
651 assert(Children.empty() &&
652 "We create children only when the scope DIE is not null.");
653 return NULL;
654 }
655 if (!ChildrenCreated)
656 // We create children when the scope DIE is not null.
657 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
659 // Add children
660 for (DIE *I : Children)
661 ScopeDIE->addChild(I);
663 if (DS.isSubprogram() && ObjectPointer != NULL)
664 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
666 return ScopeDIE;
667 }
669 // Look up the source id with the given directory and source file names.
670 // If none currently exists, create a new id and insert it in the
671 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
672 // as well.
673 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
674 unsigned CUID) {
675 // If we print assembly, we can't separate .file entries according to
676 // compile units. Thus all files will belong to the default compile unit.
678 // FIXME: add a better feature test than hasRawTextSupport. Even better,
679 // extend .file to support this.
680 if (Asm->OutStreamer.hasRawTextSupport())
681 CUID = 0;
683 // If FE did not provide a file name, then assume stdin.
684 if (FileName.empty()) {
685 FileName = "<stdin>";
686 DirName = "";
687 }
689 // TODO: this might not belong here. See if we can factor this better.
690 if (DirName == CompilationDir)
691 DirName = "";
693 // FileIDCUMap stores the current ID for the given compile unit.
694 unsigned SrcId = FileIDCUMap[CUID] + 1;
696 // We look up the CUID/file/dir by concatenating them with a zero byte.
697 SmallString<128> NamePair;
698 NamePair += utostr(CUID);
699 NamePair += '\0';
700 NamePair += DirName;
701 NamePair += '\0'; // Zero bytes are not allowed in paths.
702 NamePair += FileName;
704 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
705 if (Ent.getValue() != SrcId)
706 return Ent.getValue();
708 FileIDCUMap[CUID] = SrcId;
709 // Print out a .file directive to specify files for .loc directives.
710 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
712 return SrcId;
713 }
715 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
716 if (!GenerateGnuPubSections)
717 return;
719 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
720 }
722 // Create new DwarfCompileUnit for the given metadata node with tag
723 // DW_TAG_compile_unit.
724 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
725 StringRef FN = DIUnit.getFilename();
726 CompilationDir = DIUnit.getDirectory();
728 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
729 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
730 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
731 InfoHolder.addUnit(NewCU);
733 FileIDCUMap[NewCU->getUniqueID()] = 0;
735 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
736 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
737 DIUnit.getLanguage());
738 NewCU->addString(Die, dwarf::DW_AT_name, FN);
740 if (!useSplitDwarf()) {
741 NewCU->initStmtList(DwarfLineSectionSym);
743 // If we're using split dwarf the compilation dir is going to be in the
744 // skeleton CU and so we don't need to duplicate it here.
745 if (!CompilationDir.empty())
746 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
748 addGnuPubAttributes(NewCU, Die);
749 }
751 if (DIUnit.isOptimized())
752 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
754 StringRef Flags = DIUnit.getFlags();
755 if (!Flags.empty())
756 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
758 if (unsigned RVer = DIUnit.getRunTimeVersion())
759 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
760 dwarf::DW_FORM_data1, RVer);
762 if (!FirstCU)
763 FirstCU = NewCU;
765 if (useSplitDwarf()) {
766 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
767 DwarfInfoDWOSectionSym);
768 NewCU->setSkeleton(constructSkeletonCU(NewCU));
769 } else
770 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
771 DwarfInfoSectionSym);
773 CUMap.insert(std::make_pair(DIUnit, NewCU));
774 CUDieMap.insert(std::make_pair(Die, NewCU));
775 return NewCU;
776 }
778 // Construct subprogram DIE.
779 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
780 const MDNode *N) {
781 // FIXME: We should only call this routine once, however, during LTO if a
782 // program is defined in multiple CUs we could end up calling it out of
783 // beginModule as we walk the CUs.
785 DwarfCompileUnit *&CURef = SPMap[N];
786 if (CURef)
787 return;
788 CURef = TheCU;
790 DISubprogram SP(N);
791 if (!SP.isDefinition())
792 // This is a method declaration which will be handled while constructing
793 // class type.
794 return;
796 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
798 // Expose as a global name.
799 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
800 }
802 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
803 const MDNode *N) {
804 DIImportedEntity Module(N);
805 assert(Module.Verify());
806 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
807 constructImportedEntityDIE(TheCU, Module, D);
808 }
810 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
811 const MDNode *N, DIE *Context) {
812 DIImportedEntity Module(N);
813 assert(Module.Verify());
814 return constructImportedEntityDIE(TheCU, Module, Context);
815 }
817 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
818 const DIImportedEntity &Module,
819 DIE *Context) {
820 assert(Module.Verify() &&
821 "Use one of the MDNode * overloads to handle invalid metadata");
822 assert(Context && "Should always have a context for an imported_module");
823 DIE *IMDie = new DIE(Module.getTag());
824 TheCU->insertDIE(Module, IMDie);
825 DIE *EntityDie;
826 DIDescriptor Entity = Module.getEntity();
827 if (Entity.isNameSpace())
828 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
829 else if (Entity.isSubprogram())
830 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
831 else if (Entity.isType())
832 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
833 else
834 EntityDie = TheCU->getDIE(Entity);
835 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
836 Module.getContext().getFilename(),
837 Module.getContext().getDirectory());
838 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
839 StringRef Name = Module.getName();
840 if (!Name.empty())
841 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
842 Context->addChild(IMDie);
843 }
845 // Emit all Dwarf sections that should come prior to the content. Create
846 // global DIEs and emit initial debug info sections. This is invoked by
847 // the target AsmPrinter.
848 void DwarfDebug::beginModule() {
849 if (DisableDebugInfoPrinting)
850 return;
852 const Module *M = MMI->getModule();
854 // If module has named metadata anchors then use them, otherwise scan the
855 // module using debug info finder to collect debug info.
856 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
857 if (!CU_Nodes)
858 return;
859 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
861 // Emit initial sections so we can reference labels later.
862 emitSectionLabels();
864 for (MDNode *N : CU_Nodes->operands()) {
865 DICompileUnit CUNode(N);
866 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
867 DIArray ImportedEntities = CUNode.getImportedEntities();
868 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
869 ScopesWithImportedEntities.push_back(std::make_pair(
870 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
871 ImportedEntities.getElement(i)));
872 std::sort(ScopesWithImportedEntities.begin(),
873 ScopesWithImportedEntities.end(), less_first());
874 DIArray GVs = CUNode.getGlobalVariables();
875 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
876 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
877 DIArray SPs = CUNode.getSubprograms();
878 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
879 constructSubprogramDIE(CU, SPs.getElement(i));
880 DIArray EnumTypes = CUNode.getEnumTypes();
881 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
882 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
883 DIArray RetainedTypes = CUNode.getRetainedTypes();
884 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
885 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
886 // Emit imported_modules last so that the relevant context is already
887 // available.
888 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
889 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
890 }
892 // Tell MMI that we have debug info.
893 MMI->setDebugInfoAvailability(true);
895 // Prime section data.
896 SectionMap[Asm->getObjFileLowering().getTextSection()];
897 }
899 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
900 void DwarfDebug::computeInlinedDIEs() {
901 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
902 for (DIE *ISP : InlinedSubprogramDIEs)
903 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
905 for (const auto &AI : AbstractSPDies) {
906 DIE *ISP = AI.second;
907 if (InlinedSubprogramDIEs.count(ISP))
908 continue;
909 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
910 }
911 }
913 // Collect info for variables that were optimized out.
914 void DwarfDebug::collectDeadVariables() {
915 const Module *M = MMI->getModule();
917 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
918 for (MDNode *N : CU_Nodes->operands()) {
919 DICompileUnit TheCU(N);
920 DIArray Subprograms = TheCU.getSubprograms();
921 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
922 DISubprogram SP(Subprograms.getElement(i));
923 if (ProcessedSPNodes.count(SP) != 0)
924 continue;
925 if (!SP.isSubprogram())
926 continue;
927 if (!SP.isDefinition())
928 continue;
929 DIArray Variables = SP.getVariables();
930 if (Variables.getNumElements() == 0)
931 continue;
933 // Construct subprogram DIE and add variables DIEs.
934 DwarfCompileUnit *SPCU =
935 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
936 assert(SPCU && "Unable to find Compile Unit!");
937 // FIXME: See the comment in constructSubprogramDIE about duplicate
938 // subprogram DIEs.
939 constructSubprogramDIE(SPCU, SP);
940 DIE *SPDIE = SPCU->getDIE(SP);
941 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
942 DIVariable DV(Variables.getElement(vi));
943 if (!DV.isVariable())
944 continue;
945 DbgVariable NewVar(DV, NULL, this);
946 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
947 SPDIE->addChild(VariableDIE);
948 }
949 }
950 }
951 }
952 }
954 void DwarfDebug::finalizeModuleInfo() {
955 // Collect info for variables that were optimized out.
956 collectDeadVariables();
958 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
959 computeInlinedDIEs();
961 // Handle anything that needs to be done on a per-unit basis after
962 // all other generation.
963 for (DwarfUnit *TheU : getUnits()) {
964 // Emit DW_AT_containing_type attribute to connect types with their
965 // vtable holding type.
966 TheU->constructContainingTypeDIEs();
968 // Add CU specific attributes if we need to add any.
969 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
970 // If we're splitting the dwarf out now that we've got the entire
971 // CU then add the dwo id to it.
972 DwarfCompileUnit *SkCU =
973 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
974 if (useSplitDwarf()) {
975 // Emit a unique identifier for this CU.
976 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
977 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
978 dwarf::DW_FORM_data8, ID);
979 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
980 dwarf::DW_FORM_data8, ID);
981 }
983 // If we have code split among multiple sections or we've requested
984 // it then emit a DW_AT_ranges attribute on the unit that will remain
985 // in the .o file, otherwise add a DW_AT_low_pc.
986 // FIXME: Also add a high pc if we can.
987 // FIXME: We should use ranges if we have multiple compile units or
988 // allow reordering of code ala .subsections_via_symbols in mach-o.
989 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
990 if (useCURanges() && TheU->getRanges().size()) {
991 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
992 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
993 DwarfDebugRangeSectionSym);
995 // A DW_AT_low_pc attribute may also be specified in combination with
996 // DW_AT_ranges to specify the default base address for use in location
997 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
998 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
999 0);
1000 } else
1001 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1002 0);
1003 }
1004 }
1006 // Compute DIE offsets and sizes.
1007 InfoHolder.computeSizeAndOffsets();
1008 if (useSplitDwarf())
1009 SkeletonHolder.computeSizeAndOffsets();
1010 }
1012 void DwarfDebug::endSections() {
1013 // Filter labels by section.
1014 for (const SymbolCU &SCU : ArangeLabels) {
1015 if (SCU.Sym->isInSection()) {
1016 // Make a note of this symbol and it's section.
1017 const MCSection *Section = &SCU.Sym->getSection();
1018 if (!Section->getKind().isMetadata())
1019 SectionMap[Section].push_back(SCU);
1020 } else {
1021 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1022 // appear in the output. This sucks as we rely on sections to build
1023 // arange spans. We can do it without, but it's icky.
1024 SectionMap[NULL].push_back(SCU);
1025 }
1026 }
1028 // Build a list of sections used.
1029 std::vector<const MCSection *> Sections;
1030 for (const auto &it : SectionMap) {
1031 const MCSection *Section = it.first;
1032 Sections.push_back(Section);
1033 }
1035 // Sort the sections into order.
1036 // This is only done to ensure consistent output order across different runs.
1037 std::sort(Sections.begin(), Sections.end(), SectionSort);
1039 // Add terminating symbols for each section.
1040 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1041 const MCSection *Section = Sections[ID];
1042 MCSymbol *Sym = NULL;
1044 if (Section) {
1045 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1046 // if we know the section name up-front. For user-created sections, the
1047 // resulting label may not be valid to use as a label. (section names can
1048 // use a greater set of characters on some systems)
1049 Sym = Asm->GetTempSymbol("debug_end", ID);
1050 Asm->OutStreamer.SwitchSection(Section);
1051 Asm->OutStreamer.EmitLabel(Sym);
1052 }
1054 // Insert a final terminator.
1055 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1056 }
1058 // For now only turn on CU ranges if we have -ffunction-sections enabled,
1059 // we've emitted a function into a unique section, or we're using LTO. If
1060 // we're using LTO then we can't know that any particular function in the
1061 // module is correlated to a particular CU and so we need to be conservative.
1062 // At this point all sections should be finalized except for dwarf sections.
1063 HasCURanges = UsedNonDefaultText || (CUMap.size() > 1) ||
1064 TargetMachine::getFunctionSections();
1065 }
1067 // Emit all Dwarf sections that should come after the content.
1068 void DwarfDebug::endModule() {
1069 assert(CurFn == 0);
1070 assert(CurMI == 0);
1072 if (!FirstCU)
1073 return;
1075 // End any existing sections.
1076 // TODO: Does this need to happen?
1077 endSections();
1079 // Finalize the debug info for the module.
1080 finalizeModuleInfo();
1082 emitDebugStr();
1084 // Emit all the DIEs into a debug info section.
1085 emitDebugInfo();
1087 // Corresponding abbreviations into a abbrev section.
1088 emitAbbreviations();
1090 // Emit info into a debug loc section.
1091 emitDebugLoc();
1093 // Emit info into a debug aranges section.
1094 if (GenerateARangeSection)
1095 emitDebugARanges();
1097 // Emit info into a debug ranges section.
1098 emitDebugRanges();
1100 if (useSplitDwarf()) {
1101 emitDebugStrDWO();
1102 emitDebugInfoDWO();
1103 emitDebugAbbrevDWO();
1104 // Emit DWO addresses.
1105 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1106 }
1108 // Emit info into the dwarf accelerator table sections.
1109 if (useDwarfAccelTables()) {
1110 emitAccelNames();
1111 emitAccelObjC();
1112 emitAccelNamespaces();
1113 emitAccelTypes();
1114 }
1116 // Emit the pubnames and pubtypes sections if requested.
1117 if (HasDwarfPubSections) {
1118 emitDebugPubNames(GenerateGnuPubSections);
1119 emitDebugPubTypes(GenerateGnuPubSections);
1120 }
1122 // clean up.
1123 SPMap.clear();
1125 // Reset these for the next Module if we have one.
1126 FirstCU = NULL;
1127 }
1129 // Find abstract variable, if any, associated with Var.
1130 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1131 DebugLoc ScopeLoc) {
1132 LLVMContext &Ctx = DV->getContext();
1133 // More then one inlined variable corresponds to one abstract variable.
1134 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1135 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1136 if (AbsDbgVariable)
1137 return AbsDbgVariable;
1139 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1140 if (!Scope)
1141 return NULL;
1143 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1144 addScopeVariable(Scope, AbsDbgVariable);
1145 AbstractVariables[Var] = AbsDbgVariable;
1146 return AbsDbgVariable;
1147 }
1149 // If Var is a current function argument then add it to CurrentFnArguments list.
1150 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1151 if (!LScopes.isCurrentFunctionScope(Scope))
1152 return false;
1153 DIVariable DV = Var->getVariable();
1154 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1155 return false;
1156 unsigned ArgNo = DV.getArgNumber();
1157 if (ArgNo == 0)
1158 return false;
1160 size_t Size = CurrentFnArguments.size();
1161 if (Size == 0)
1162 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1163 // llvm::Function argument size is not good indicator of how many
1164 // arguments does the function have at source level.
1165 if (ArgNo > Size)
1166 CurrentFnArguments.resize(ArgNo * 2);
1167 CurrentFnArguments[ArgNo - 1] = Var;
1168 return true;
1169 }
1171 // Collect variable information from side table maintained by MMI.
1172 void DwarfDebug::collectVariableInfoFromMMITable(
1173 SmallPtrSet<const MDNode *, 16> &Processed) {
1174 for (const auto &VI : MMI->getVariableDbgInfo()) {
1175 if (!VI.Var)
1176 continue;
1177 Processed.insert(VI.Var);
1178 DIVariable DV(VI.Var);
1179 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1181 // If variable scope is not found then skip this variable.
1182 if (Scope == 0)
1183 continue;
1185 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1186 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1187 RegVar->setFrameIndex(VI.Slot);
1188 if (!addCurrentFnArgument(RegVar, Scope))
1189 addScopeVariable(Scope, RegVar);
1190 if (AbsDbgVariable)
1191 AbsDbgVariable->setFrameIndex(VI.Slot);
1192 }
1193 }
1195 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1196 // defined reg.
1197 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1198 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1199 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1200 MI->getOperand(0).getReg() &&
1201 (MI->getOperand(1).isImm() ||
1202 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1203 }
1205 // Get .debug_loc entry for the instruction range starting at MI.
1206 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1207 const MCSymbol *FLabel,
1208 const MCSymbol *SLabel,
1209 const MachineInstr *MI) {
1210 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1212 assert(MI->getNumOperands() == 3);
1213 if (MI->getOperand(0).isReg()) {
1214 MachineLocation MLoc;
1215 // If the second operand is an immediate, this is a
1216 // register-indirect address.
1217 if (!MI->getOperand(1).isImm())
1218 MLoc.set(MI->getOperand(0).getReg());
1219 else
1220 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1221 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1222 }
1223 if (MI->getOperand(0).isImm())
1224 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1225 if (MI->getOperand(0).isFPImm())
1226 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1227 if (MI->getOperand(0).isCImm())
1228 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1230 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1231 }
1233 // Find variables for each lexical scope.
1234 void
1235 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1237 // Grab the variable info that was squirreled away in the MMI side-table.
1238 collectVariableInfoFromMMITable(Processed);
1240 for (const MDNode *Var : UserVariables) {
1241 if (Processed.count(Var))
1242 continue;
1244 // History contains relevant DBG_VALUE instructions for Var and instructions
1245 // clobbering it.
1246 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1247 if (History.empty())
1248 continue;
1249 const MachineInstr *MInsn = History.front();
1251 DIVariable DV(Var);
1252 LexicalScope *Scope = NULL;
1253 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1254 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1255 Scope = LScopes.getCurrentFunctionScope();
1256 else if (MDNode *IA = DV.getInlinedAt())
1257 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1258 else
1259 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1260 // If variable scope is not found then skip this variable.
1261 if (!Scope)
1262 continue;
1264 Processed.insert(DV);
1265 assert(MInsn->isDebugValue() && "History must begin with debug value");
1266 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1267 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1268 if (!addCurrentFnArgument(RegVar, Scope))
1269 addScopeVariable(Scope, RegVar);
1270 if (AbsVar)
1271 AbsVar->setMInsn(MInsn);
1273 // Simplify ranges that are fully coalesced.
1274 if (History.size() <= 1 ||
1275 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1276 RegVar->setMInsn(MInsn);
1277 continue;
1278 }
1280 // Handle multiple DBG_VALUE instructions describing one variable.
1281 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1283 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1284 HI = History.begin(),
1285 HE = History.end();
1286 HI != HE; ++HI) {
1287 const MachineInstr *Begin = *HI;
1288 assert(Begin->isDebugValue() && "Invalid History entry");
1290 // Check if DBG_VALUE is truncating a range.
1291 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1292 !Begin->getOperand(0).getReg())
1293 continue;
1295 // Compute the range for a register location.
1296 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1297 const MCSymbol *SLabel = 0;
1299 if (HI + 1 == HE)
1300 // If Begin is the last instruction in History then its value is valid
1301 // until the end of the function.
1302 SLabel = FunctionEndSym;
1303 else {
1304 const MachineInstr *End = HI[1];
1305 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1306 << "\t" << *Begin << "\t" << *End << "\n");
1307 if (End->isDebugValue())
1308 SLabel = getLabelBeforeInsn(End);
1309 else {
1310 // End is a normal instruction clobbering the range.
1311 SLabel = getLabelAfterInsn(End);
1312 assert(SLabel && "Forgot label after clobber instruction");
1313 ++HI;
1314 }
1315 }
1317 // The value is valid until the next DBG_VALUE or clobber.
1318 DotDebugLocEntries.push_back(
1319 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1320 }
1321 DotDebugLocEntries.push_back(DotDebugLocEntry());
1322 }
1324 // Collect info for variables that were optimized out.
1325 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1326 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1327 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1328 DIVariable DV(Variables.getElement(i));
1329 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1330 continue;
1331 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1332 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1333 }
1334 }
1336 // Return Label preceding the instruction.
1337 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1338 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1339 assert(Label && "Didn't insert label before instruction");
1340 return Label;
1341 }
1343 // Return Label immediately following the instruction.
1344 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1345 return LabelsAfterInsn.lookup(MI);
1346 }
1348 // Process beginning of an instruction.
1349 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1350 assert(CurMI == 0);
1351 CurMI = MI;
1352 // Check if source location changes, but ignore DBG_VALUE locations.
1353 if (!MI->isDebugValue()) {
1354 DebugLoc DL = MI->getDebugLoc();
1355 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1356 unsigned Flags = 0;
1357 PrevInstLoc = DL;
1358 if (DL == PrologEndLoc) {
1359 Flags |= DWARF2_FLAG_PROLOGUE_END;
1360 PrologEndLoc = DebugLoc();
1361 }
1362 if (PrologEndLoc.isUnknown())
1363 Flags |= DWARF2_FLAG_IS_STMT;
1365 if (!DL.isUnknown()) {
1366 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1367 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1368 } else
1369 recordSourceLine(0, 0, 0, 0);
1370 }
1371 }
1373 // Insert labels where requested.
1374 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1375 LabelsBeforeInsn.find(MI);
1377 // No label needed.
1378 if (I == LabelsBeforeInsn.end())
1379 return;
1381 // Label already assigned.
1382 if (I->second)
1383 return;
1385 if (!PrevLabel) {
1386 PrevLabel = MMI->getContext().CreateTempSymbol();
1387 Asm->OutStreamer.EmitLabel(PrevLabel);
1388 }
1389 I->second = PrevLabel;
1390 }
1392 // Process end of an instruction.
1393 void DwarfDebug::endInstruction() {
1394 assert(CurMI != 0);
1395 // Don't create a new label after DBG_VALUE instructions.
1396 // They don't generate code.
1397 if (!CurMI->isDebugValue())
1398 PrevLabel = 0;
1400 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1401 LabelsAfterInsn.find(CurMI);
1402 CurMI = 0;
1404 // No label needed.
1405 if (I == LabelsAfterInsn.end())
1406 return;
1408 // Label already assigned.
1409 if (I->second)
1410 return;
1412 // We need a label after this instruction.
1413 if (!PrevLabel) {
1414 PrevLabel = MMI->getContext().CreateTempSymbol();
1415 Asm->OutStreamer.EmitLabel(PrevLabel);
1416 }
1417 I->second = PrevLabel;
1418 }
1420 // Each LexicalScope has first instruction and last instruction to mark
1421 // beginning and end of a scope respectively. Create an inverse map that list
1422 // scopes starts (and ends) with an instruction. One instruction may start (or
1423 // end) multiple scopes. Ignore scopes that are not reachable.
1424 void DwarfDebug::identifyScopeMarkers() {
1425 SmallVector<LexicalScope *, 4> WorkList;
1426 WorkList.push_back(LScopes.getCurrentFunctionScope());
1427 while (!WorkList.empty()) {
1428 LexicalScope *S = WorkList.pop_back_val();
1430 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1431 if (!Children.empty())
1432 WorkList.append(Children.begin(), Children.end());
1434 if (S->isAbstractScope())
1435 continue;
1437 for (const InsnRange &R : S->getRanges()) {
1438 assert(R.first && "InsnRange does not have first instruction!");
1439 assert(R.second && "InsnRange does not have second instruction!");
1440 requestLabelBeforeInsn(R.first);
1441 requestLabelAfterInsn(R.second);
1442 }
1443 }
1444 }
1446 // Gather pre-function debug information. Assumes being called immediately
1447 // after the function entry point has been emitted.
1448 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1449 CurFn = MF;
1451 // If there's no debug info for the function we're not going to do anything.
1452 if (!MMI->hasDebugInfo())
1453 return;
1455 // Grab the lexical scopes for the function, if we don't have any of those
1456 // then we're not going to be able to do anything.
1457 LScopes.initialize(*MF);
1458 if (LScopes.empty()) {
1459 UsedNonDefaultText = true;
1460 return;
1461 }
1463 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1465 // Make sure that each lexical scope will have a begin/end label.
1466 identifyScopeMarkers();
1468 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1469 // belongs to so that we add to the correct per-cu line table in the
1470 // non-asm case.
1471 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1472 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1473 assert(TheCU && "Unable to find compile unit!");
1474 if (Asm->OutStreamer.hasRawTextSupport())
1475 // Use a single line table if we are generating assembly.
1476 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1477 else
1478 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1480 // Check the current section against the standard text section. If different
1481 // keep track so that we will know when we're emitting functions into multiple
1482 // sections.
1483 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1484 UsedNonDefaultText = true;
1486 // Emit a label for the function so that we have a beginning address.
1487 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1488 // Assumes in correct section after the entry point.
1489 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1491 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1492 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1493 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1495 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1496 ++I) {
1497 bool AtBlockEntry = true;
1498 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1499 II != IE; ++II) {
1500 const MachineInstr *MI = II;
1502 if (MI->isDebugValue()) {
1503 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1505 // Keep track of user variables.
1506 const MDNode *Var =
1507 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1509 // Variable is in a register, we need to check for clobbers.
1510 if (isDbgValueInDefinedReg(MI))
1511 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1513 // Check the history of this variable.
1514 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1515 if (History.empty()) {
1516 UserVariables.push_back(Var);
1517 // The first mention of a function argument gets the FunctionBeginSym
1518 // label, so arguments are visible when breaking at function entry.
1519 DIVariable DV(Var);
1520 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1521 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1522 LabelsBeforeInsn[MI] = FunctionBeginSym;
1523 } else {
1524 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1525 const MachineInstr *Prev = History.back();
1526 if (Prev->isDebugValue()) {
1527 // Coalesce identical entries at the end of History.
1528 if (History.size() >= 2 &&
1529 Prev->isIdenticalTo(History[History.size() - 2])) {
1530 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1531 << "\t" << *Prev << "\t"
1532 << *History[History.size() - 2] << "\n");
1533 History.pop_back();
1534 }
1536 // Terminate old register assignments that don't reach MI;
1537 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1538 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1539 isDbgValueInDefinedReg(Prev)) {
1540 // Previous register assignment needs to terminate at the end of
1541 // its basic block.
1542 MachineBasicBlock::const_iterator LastMI =
1543 PrevMBB->getLastNonDebugInstr();
1544 if (LastMI == PrevMBB->end()) {
1545 // Drop DBG_VALUE for empty range.
1546 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1547 << "\t" << *Prev << "\n");
1548 History.pop_back();
1549 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1550 // Terminate after LastMI.
1551 History.push_back(LastMI);
1552 }
1553 }
1554 }
1555 History.push_back(MI);
1556 } else {
1557 // Not a DBG_VALUE instruction.
1558 if (!MI->isPosition())
1559 AtBlockEntry = false;
1561 // First known non-DBG_VALUE and non-frame setup location marks
1562 // the beginning of the function body.
1563 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1564 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1565 PrologEndLoc = MI->getDebugLoc();
1567 // Check if the instruction clobbers any registers with debug vars.
1568 for (const MachineOperand &MO : MI->operands()) {
1569 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1570 continue;
1571 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1572 ++AI) {
1573 unsigned Reg = *AI;
1574 const MDNode *Var = LiveUserVar[Reg];
1575 if (!Var)
1576 continue;
1577 // Reg is now clobbered.
1578 LiveUserVar[Reg] = 0;
1580 // Was MD last defined by a DBG_VALUE referring to Reg?
1581 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1582 if (HistI == DbgValues.end())
1583 continue;
1584 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1585 if (History.empty())
1586 continue;
1587 const MachineInstr *Prev = History.back();
1588 // Sanity-check: Register assignments are terminated at the end of
1589 // their block.
1590 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1591 continue;
1592 // Is the variable still in Reg?
1593 if (!isDbgValueInDefinedReg(Prev) ||
1594 Prev->getOperand(0).getReg() != Reg)
1595 continue;
1596 // Var is clobbered. Make sure the next instruction gets a label.
1597 History.push_back(MI);
1598 }
1599 }
1600 }
1601 }
1602 }
1604 for (auto &I : DbgValues) {
1605 SmallVectorImpl<const MachineInstr *> &History = I.second;
1606 if (History.empty())
1607 continue;
1609 // Make sure the final register assignments are terminated.
1610 const MachineInstr *Prev = History.back();
1611 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1612 const MachineBasicBlock *PrevMBB = Prev->getParent();
1613 MachineBasicBlock::const_iterator LastMI =
1614 PrevMBB->getLastNonDebugInstr();
1615 if (LastMI == PrevMBB->end())
1616 // Drop DBG_VALUE for empty range.
1617 History.pop_back();
1618 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1619 // Terminate after LastMI.
1620 History.push_back(LastMI);
1621 }
1622 }
1623 // Request labels for the full history.
1624 for (const MachineInstr *MI : History) {
1625 if (MI->isDebugValue())
1626 requestLabelBeforeInsn(MI);
1627 else
1628 requestLabelAfterInsn(MI);
1629 }
1630 }
1632 PrevInstLoc = DebugLoc();
1633 PrevLabel = FunctionBeginSym;
1635 // Record beginning of function.
1636 if (!PrologEndLoc.isUnknown()) {
1637 DebugLoc FnStartDL =
1638 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1639 recordSourceLine(
1640 FnStartDL.getLine(), FnStartDL.getCol(),
1641 FnStartDL.getScope(MF->getFunction()->getContext()),
1642 // We'd like to list the prologue as "not statements" but GDB behaves
1643 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1644 DWARF2_FLAG_IS_STMT);
1645 }
1646 }
1648 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1649 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1650 DIVariable DV = Var->getVariable();
1651 // Variables with positive arg numbers are parameters.
1652 if (unsigned ArgNum = DV.getArgNumber()) {
1653 // Keep all parameters in order at the start of the variable list to ensure
1654 // function types are correct (no out-of-order parameters)
1655 //
1656 // This could be improved by only doing it for optimized builds (unoptimized
1657 // builds have the right order to begin with), searching from the back (this
1658 // would catch the unoptimized case quickly), or doing a binary search
1659 // rather than linear search.
1660 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1661 while (I != Vars.end()) {
1662 unsigned CurNum = (*I)->getVariable().getArgNumber();
1663 // A local (non-parameter) variable has been found, insert immediately
1664 // before it.
1665 if (CurNum == 0)
1666 break;
1667 // A later indexed parameter has been found, insert immediately before it.
1668 if (CurNum > ArgNum)
1669 break;
1670 ++I;
1671 }
1672 Vars.insert(I, Var);
1673 return;
1674 }
1676 Vars.push_back(Var);
1677 }
1679 // Gather and emit post-function debug information.
1680 void DwarfDebug::endFunction(const MachineFunction *MF) {
1681 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1682 // though the beginFunction may not be called at all.
1683 // We should handle both cases.
1684 if (CurFn == 0)
1685 CurFn = MF;
1686 else
1687 assert(CurFn == MF);
1688 assert(CurFn != 0);
1690 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1691 CurFn = 0;
1692 return;
1693 }
1695 // Define end label for subprogram.
1696 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1697 // Assumes in correct section after the entry point.
1698 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1700 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1701 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1703 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1704 collectVariableInfo(ProcessedVars);
1706 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1707 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1708 assert(TheCU && "Unable to find compile unit!");
1710 // Construct abstract scopes.
1711 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1712 DISubprogram SP(AScope->getScopeNode());
1713 if (SP.isSubprogram()) {
1714 // Collect info for variables that were optimized out.
1715 DIArray Variables = SP.getVariables();
1716 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1717 DIVariable DV(Variables.getElement(i));
1718 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1719 continue;
1720 // Check that DbgVariable for DV wasn't created earlier, when
1721 // findAbstractVariable() was called for inlined instance of DV.
1722 LLVMContext &Ctx = DV->getContext();
1723 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1724 if (AbstractVariables.lookup(CleanDV))
1725 continue;
1726 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1727 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1728 }
1729 }
1730 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1731 constructScopeDIE(TheCU, AScope);
1732 }
1734 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1735 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1736 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1738 // Add the range of this function to the list of ranges for the CU.
1739 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1740 TheCU->addRange(std::move(Span));
1742 // Clear debug info
1743 for (auto &I : ScopeVariables)
1744 DeleteContainerPointers(I.second);
1745 ScopeVariables.clear();
1746 DeleteContainerPointers(CurrentFnArguments);
1747 UserVariables.clear();
1748 DbgValues.clear();
1749 AbstractVariables.clear();
1750 LabelsBeforeInsn.clear();
1751 LabelsAfterInsn.clear();
1752 PrevLabel = NULL;
1753 CurFn = 0;
1754 }
1756 // Register a source line with debug info. Returns the unique label that was
1757 // emitted and which provides correspondence to the source line list.
1758 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1759 unsigned Flags) {
1760 StringRef Fn;
1761 StringRef Dir;
1762 unsigned Src = 1;
1763 unsigned Discriminator = 0;
1764 if (S) {
1765 DIDescriptor Scope(S);
1767 if (Scope.isCompileUnit()) {
1768 DICompileUnit CU(S);
1769 Fn = CU.getFilename();
1770 Dir = CU.getDirectory();
1771 } else if (Scope.isFile()) {
1772 DIFile F(S);
1773 Fn = F.getFilename();
1774 Dir = F.getDirectory();
1775 } else if (Scope.isSubprogram()) {
1776 DISubprogram SP(S);
1777 Fn = SP.getFilename();
1778 Dir = SP.getDirectory();
1779 } else if (Scope.isLexicalBlockFile()) {
1780 DILexicalBlockFile DBF(S);
1781 Fn = DBF.getFilename();
1782 Dir = DBF.getDirectory();
1783 } else if (Scope.isLexicalBlock()) {
1784 DILexicalBlock DB(S);
1785 Fn = DB.getFilename();
1786 Dir = DB.getDirectory();
1787 Discriminator = DB.getDiscriminator();
1788 } else
1789 llvm_unreachable("Unexpected scope info");
1791 Src = getOrCreateSourceID(
1792 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1793 }
1794 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1795 Discriminator, Fn);
1796 }
1798 //===----------------------------------------------------------------------===//
1799 // Emit Methods
1800 //===----------------------------------------------------------------------===//
1802 // Compute the size and offset of a DIE. The offset is relative to start of the
1803 // CU. It returns the offset after laying out the DIE.
1804 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1805 // Record the abbreviation.
1806 assignAbbrevNumber(Die->getAbbrev());
1808 // Get the abbreviation for this DIE.
1809 const DIEAbbrev &Abbrev = Die->getAbbrev();
1811 // Set DIE offset
1812 Die->setOffset(Offset);
1814 // Start the size with the size of abbreviation code.
1815 Offset += getULEB128Size(Die->getAbbrevNumber());
1817 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1818 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1820 // Size the DIE attribute values.
1821 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1822 // Size attribute value.
1823 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1825 // Get the children.
1826 const std::vector<DIE *> &Children = Die->getChildren();
1828 // Size the DIE children if any.
1829 if (!Children.empty()) {
1830 assert(Abbrev.hasChildren() && "Children flag not set");
1832 for (DIE *Child : Children)
1833 Offset = computeSizeAndOffset(Child, Offset);
1835 // End of children marker.
1836 Offset += sizeof(int8_t);
1837 }
1839 Die->setSize(Offset - Die->getOffset());
1840 return Offset;
1841 }
1843 // Compute the size and offset for each DIE.
1844 void DwarfFile::computeSizeAndOffsets() {
1845 // Offset from the first CU in the debug info section is 0 initially.
1846 unsigned SecOffset = 0;
1848 // Iterate over each compile unit and set the size and offsets for each
1849 // DIE within each compile unit. All offsets are CU relative.
1850 for (DwarfUnit *TheU : CUs) {
1851 TheU->setDebugInfoOffset(SecOffset);
1853 // CU-relative offset is reset to 0 here.
1854 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1855 TheU->getHeaderSize(); // Unit-specific headers
1857 // EndOffset here is CU-relative, after laying out
1858 // all of the CU DIE.
1859 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1860 SecOffset += EndOffset;
1861 }
1862 }
1864 // Emit initial Dwarf sections with a label at the start of each one.
1865 void DwarfDebug::emitSectionLabels() {
1866 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1868 // Dwarf sections base addresses.
1869 DwarfInfoSectionSym =
1870 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1871 if (useSplitDwarf())
1872 DwarfInfoDWOSectionSym =
1873 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1874 DwarfAbbrevSectionSym =
1875 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1876 if (useSplitDwarf())
1877 DwarfAbbrevDWOSectionSym = emitSectionSym(
1878 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1879 if (GenerateARangeSection)
1880 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1882 DwarfLineSectionSym =
1883 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1884 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1885 if (GenerateGnuPubSections) {
1886 DwarfGnuPubNamesSectionSym =
1887 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1888 DwarfGnuPubTypesSectionSym =
1889 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1890 } else if (HasDwarfPubSections) {
1891 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1892 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1893 }
1895 DwarfStrSectionSym =
1896 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1897 if (useSplitDwarf()) {
1898 DwarfStrDWOSectionSym =
1899 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1900 DwarfAddrSectionSym =
1901 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1902 }
1903 DwarfDebugRangeSectionSym =
1904 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1906 DwarfDebugLocSectionSym =
1907 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1908 }
1910 // Recursively emits a debug information entry.
1911 void DwarfDebug::emitDIE(DIE *Die) {
1912 // Get the abbreviation for this DIE.
1913 const DIEAbbrev &Abbrev = Die->getAbbrev();
1915 // Emit the code (index) for the abbreviation.
1916 if (Asm->isVerbose())
1917 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1918 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1919 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1920 dwarf::TagString(Abbrev.getTag()));
1921 Asm->EmitULEB128(Abbrev.getNumber());
1923 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1924 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1926 // Emit the DIE attribute values.
1927 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1928 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1929 dwarf::Form Form = AbbrevData[i].getForm();
1930 assert(Form && "Too many attributes for DIE (check abbreviation)");
1932 if (Asm->isVerbose()) {
1933 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1934 if (Attr == dwarf::DW_AT_accessibility)
1935 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1936 cast<DIEInteger>(Values[i])->getValue()));
1937 }
1939 // Emit an attribute using the defined form.
1940 Values[i]->EmitValue(Asm, Form);
1941 }
1943 // Emit the DIE children if any.
1944 if (Abbrev.hasChildren()) {
1945 const std::vector<DIE *> &Children = Die->getChildren();
1947 for (DIE *Child : Children)
1948 emitDIE(Child);
1950 Asm->OutStreamer.AddComment("End Of Children Mark");
1951 Asm->EmitInt8(0);
1952 }
1953 }
1955 // Emit the various dwarf units to the unit section USection with
1956 // the abbreviations going into ASection.
1957 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1958 const MCSymbol *ASectionSym) {
1959 for (DwarfUnit *TheU : CUs) {
1960 DIE *Die = TheU->getUnitDie();
1961 const MCSection *USection = TheU->getSection();
1962 Asm->OutStreamer.SwitchSection(USection);
1964 // Emit the compile units header.
1965 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1967 // Emit size of content not including length itself
1968 Asm->OutStreamer.AddComment("Length of Unit");
1969 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1971 TheU->emitHeader(ASection, ASectionSym);
1973 DD->emitDIE(Die);
1974 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1975 }
1976 }
1978 // Emit the debug info section.
1979 void DwarfDebug::emitDebugInfo() {
1980 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1982 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1983 DwarfAbbrevSectionSym);
1984 }
1986 // Emit the abbreviation section.
1987 void DwarfDebug::emitAbbreviations() {
1988 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1990 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1991 }
1993 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1994 // Check to see if it is worth the effort.
1995 if (!Abbreviations.empty()) {
1996 // Start the debug abbrev section.
1997 Asm->OutStreamer.SwitchSection(Section);
1999 // For each abbrevation.
2000 for (const DIEAbbrev *Abbrev : Abbreviations) {
2001 // Emit the abbrevations code (base 1 index.)
2002 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2004 // Emit the abbreviations data.
2005 Abbrev->Emit(Asm);
2006 }
2008 // Mark end of abbreviations.
2009 Asm->EmitULEB128(0, "EOM(3)");
2010 }
2011 }
2013 // Emit the last address of the section and the end of the line matrix.
2014 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2015 // Define last address of section.
2016 Asm->OutStreamer.AddComment("Extended Op");
2017 Asm->EmitInt8(0);
2019 Asm->OutStreamer.AddComment("Op size");
2020 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2021 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2022 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2024 Asm->OutStreamer.AddComment("Section end label");
2026 Asm->OutStreamer.EmitSymbolValue(
2027 Asm->GetTempSymbol("section_end", SectionEnd),
2028 Asm->getDataLayout().getPointerSize());
2030 // Mark end of matrix.
2031 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2032 Asm->EmitInt8(0);
2033 Asm->EmitInt8(1);
2034 Asm->EmitInt8(1);
2035 }
2037 // Emit visible names into a hashed accelerator table section.
2038 void DwarfDebug::emitAccelNames() {
2039 DwarfAccelTable AT(
2040 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2041 for (DwarfUnit *TheU : getUnits()) {
2042 for (const auto &GI : TheU->getAccelNames()) {
2043 StringRef Name = GI.getKey();
2044 for (const DIE *D : GI.second)
2045 AT.AddName(Name, D);
2046 }
2047 }
2049 AT.FinalizeTable(Asm, "Names");
2050 Asm->OutStreamer.SwitchSection(
2051 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2052 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2053 Asm->OutStreamer.EmitLabel(SectionBegin);
2055 // Emit the full data.
2056 AT.Emit(Asm, SectionBegin, &InfoHolder);
2057 }
2059 // Emit objective C classes and categories into a hashed accelerator table
2060 // section.
2061 void DwarfDebug::emitAccelObjC() {
2062 DwarfAccelTable AT(
2063 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2064 for (DwarfUnit *TheU : getUnits()) {
2065 for (const auto &GI : TheU->getAccelObjC()) {
2066 StringRef Name = GI.getKey();
2067 for (const DIE *D : GI.second)
2068 AT.AddName(Name, D);
2069 }
2070 }
2072 AT.FinalizeTable(Asm, "ObjC");
2073 Asm->OutStreamer.SwitchSection(
2074 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2075 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2076 Asm->OutStreamer.EmitLabel(SectionBegin);
2078 // Emit the full data.
2079 AT.Emit(Asm, SectionBegin, &InfoHolder);
2080 }
2082 // Emit namespace dies into a hashed accelerator table.
2083 void DwarfDebug::emitAccelNamespaces() {
2084 DwarfAccelTable AT(
2085 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2086 for (DwarfUnit *TheU : getUnits()) {
2087 for (const auto &GI : TheU->getAccelNamespace()) {
2088 StringRef Name = GI.getKey();
2089 for (const DIE *D : GI.second)
2090 AT.AddName(Name, D);
2091 }
2092 }
2094 AT.FinalizeTable(Asm, "namespac");
2095 Asm->OutStreamer.SwitchSection(
2096 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2097 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2098 Asm->OutStreamer.EmitLabel(SectionBegin);
2100 // Emit the full data.
2101 AT.Emit(Asm, SectionBegin, &InfoHolder);
2102 }
2104 // Emit type dies into a hashed accelerator table.
2105 void DwarfDebug::emitAccelTypes() {
2106 std::vector<DwarfAccelTable::Atom> Atoms;
2107 Atoms.push_back(
2108 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2109 Atoms.push_back(
2110 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2111 Atoms.push_back(
2112 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2113 DwarfAccelTable AT(Atoms);
2114 for (DwarfUnit *TheU : getUnits()) {
2115 for (const auto &GI : TheU->getAccelTypes()) {
2116 StringRef Name = GI.getKey();
2117 for (const auto &DI : GI.second)
2118 AT.AddName(Name, DI.first, DI.second);
2119 }
2120 }
2122 AT.FinalizeTable(Asm, "types");
2123 Asm->OutStreamer.SwitchSection(
2124 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2125 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2126 Asm->OutStreamer.EmitLabel(SectionBegin);
2128 // Emit the full data.
2129 AT.Emit(Asm, SectionBegin, &InfoHolder);
2130 }
2132 // Public name handling.
2133 // The format for the various pubnames:
2134 //
2135 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2136 // for the DIE that is named.
2137 //
2138 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2139 // into the CU and the index value is computed according to the type of value
2140 // for the DIE that is named.
2141 //
2142 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2143 // it's the offset within the debug_info/debug_types dwo section, however, the
2144 // reference in the pubname header doesn't change.
2146 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2147 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2148 const DIE *Die) {
2149 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2151 // We could have a specification DIE that has our most of our knowledge,
2152 // look for that now.
2153 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2154 if (SpecVal) {
2155 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2156 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2157 Linkage = dwarf::GIEL_EXTERNAL;
2158 } else if (Die->findAttribute(dwarf::DW_AT_external))
2159 Linkage = dwarf::GIEL_EXTERNAL;
2161 switch (Die->getTag()) {
2162 case dwarf::DW_TAG_class_type:
2163 case dwarf::DW_TAG_structure_type:
2164 case dwarf::DW_TAG_union_type:
2165 case dwarf::DW_TAG_enumeration_type:
2166 return dwarf::PubIndexEntryDescriptor(
2167 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2168 ? dwarf::GIEL_STATIC
2169 : dwarf::GIEL_EXTERNAL);
2170 case dwarf::DW_TAG_typedef:
2171 case dwarf::DW_TAG_base_type:
2172 case dwarf::DW_TAG_subrange_type:
2173 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2174 case dwarf::DW_TAG_namespace:
2175 return dwarf::GIEK_TYPE;
2176 case dwarf::DW_TAG_subprogram:
2177 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2178 case dwarf::DW_TAG_constant:
2179 case dwarf::DW_TAG_variable:
2180 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2181 case dwarf::DW_TAG_enumerator:
2182 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2183 dwarf::GIEL_STATIC);
2184 default:
2185 return dwarf::GIEK_NONE;
2186 }
2187 }
2189 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2190 ///
2191 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2192 const MCSection *PSec =
2193 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2194 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2196 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2197 }
2199 void DwarfDebug::emitDebugPubSection(
2200 bool GnuStyle, const MCSection *PSec, StringRef Name,
2201 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2202 for (const auto &NU : CUMap) {
2203 DwarfCompileUnit *TheU = NU.second;
2205 const auto &Globals = (TheU->*Accessor)();
2207 if (Globals.empty())
2208 continue;
2210 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2211 TheU = Skeleton;
2212 unsigned ID = TheU->getUniqueID();
2214 // Start the dwarf pubnames section.
2215 Asm->OutStreamer.SwitchSection(PSec);
2217 // Emit the header.
2218 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2219 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2220 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2221 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2223 Asm->OutStreamer.EmitLabel(BeginLabel);
2225 Asm->OutStreamer.AddComment("DWARF Version");
2226 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2228 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2229 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2231 Asm->OutStreamer.AddComment("Compilation Unit Length");
2232 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2234 // Emit the pubnames for this compilation unit.
2235 for (const auto &GI : Globals) {
2236 const char *Name = GI.getKeyData();
2237 const DIE *Entity = GI.second;
2239 Asm->OutStreamer.AddComment("DIE offset");
2240 Asm->EmitInt32(Entity->getOffset());
2242 if (GnuStyle) {
2243 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2244 Asm->OutStreamer.AddComment(
2245 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2246 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2247 Asm->EmitInt8(Desc.toBits());
2248 }
2250 Asm->OutStreamer.AddComment("External Name");
2251 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2252 }
2254 Asm->OutStreamer.AddComment("End Mark");
2255 Asm->EmitInt32(0);
2256 Asm->OutStreamer.EmitLabel(EndLabel);
2257 }
2258 }
2260 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2261 const MCSection *PSec =
2262 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2263 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2265 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2266 }
2268 // Emit strings into a string section.
2269 void DwarfFile::emitStrings(const MCSection *StrSection,
2270 const MCSection *OffsetSection = NULL,
2271 const MCSymbol *StrSecSym = NULL) {
2273 if (StringPool.empty())
2274 return;
2276 // Start the dwarf str section.
2277 Asm->OutStreamer.SwitchSection(StrSection);
2279 // Get all of the string pool entries and put them in an array by their ID so
2280 // we can sort them.
2281 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2283 for (const auto &I : StringPool)
2284 Entries.push_back(std::make_pair(I.second.second, &I));
2286 array_pod_sort(Entries.begin(), Entries.end());
2288 for (const auto &Entry : Entries) {
2289 // Emit a label for reference from debug information entries.
2290 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2292 // Emit the string itself with a terminating null byte.
2293 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2294 Entry.second->getKeyLength() + 1));
2295 }
2297 // If we've got an offset section go ahead and emit that now as well.
2298 if (OffsetSection) {
2299 Asm->OutStreamer.SwitchSection(OffsetSection);
2300 unsigned offset = 0;
2301 unsigned size = 4; // FIXME: DWARF64 is 8.
2302 for (const auto &Entry : Entries) {
2303 Asm->OutStreamer.EmitIntValue(offset, size);
2304 offset += Entry.second->getKeyLength() + 1;
2305 }
2306 }
2307 }
2309 // Emit addresses into the section given.
2310 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2312 if (AddressPool.empty())
2313 return;
2315 // Start the dwarf addr section.
2316 Asm->OutStreamer.SwitchSection(AddrSection);
2318 // Order the address pool entries by ID
2319 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2321 for (const auto &I : AddressPool)
2322 Entries[I.second.Number] =
2323 I.second.TLS
2324 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2325 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2327 for (const MCExpr *Entry : Entries)
2328 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2329 }
2331 // Emit visible names into a debug str section.
2332 void DwarfDebug::emitDebugStr() {
2333 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2334 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2335 }
2337 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2338 const DotDebugLocEntry &Entry) {
2339 DIVariable DV(Entry.getVariable());
2340 if (Entry.isInt()) {
2341 DIBasicType BTy(DV.getType());
2342 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2343 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2344 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2345 Streamer.EmitSLEB128(Entry.getInt());
2346 } else {
2347 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2348 Streamer.EmitULEB128(Entry.getInt());
2349 }
2350 } else if (Entry.isLocation()) {
2351 MachineLocation Loc = Entry.getLoc();
2352 if (!DV.hasComplexAddress())
2353 // Regular entry.
2354 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2355 else {
2356 // Complex address entry.
2357 unsigned N = DV.getNumAddrElements();
2358 unsigned i = 0;
2359 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2360 if (Loc.getOffset()) {
2361 i = 2;
2362 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2363 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2364 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2365 Streamer.EmitSLEB128(DV.getAddrElement(1));
2366 } else {
2367 // If first address element is OpPlus then emit
2368 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2369 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2370 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2371 i = 2;
2372 }
2373 } else {
2374 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2375 }
2377 // Emit remaining complex address elements.
2378 for (; i < N; ++i) {
2379 uint64_t Element = DV.getAddrElement(i);
2380 if (Element == DIBuilder::OpPlus) {
2381 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2382 Streamer.EmitULEB128(DV.getAddrElement(++i));
2383 } else if (Element == DIBuilder::OpDeref) {
2384 if (!Loc.isReg())
2385 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2386 } else
2387 llvm_unreachable("unknown Opcode found in complex address");
2388 }
2389 }
2390 }
2391 // else ... ignore constant fp. There is not any good way to
2392 // to represent them here in dwarf.
2393 // FIXME: ^
2394 }
2396 // Emit locations into the debug loc section.
2397 void DwarfDebug::emitDebugLoc() {
2398 if (DotDebugLocEntries.empty())
2399 return;
2401 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2402 I = DotDebugLocEntries.begin(),
2403 E = DotDebugLocEntries.end();
2404 I != E; ++I) {
2405 DotDebugLocEntry &Entry = *I;
2406 if (I + 1 != DotDebugLocEntries.end())
2407 Entry.Merge(I + 1);
2408 }
2410 // Start the dwarf loc section.
2411 Asm->OutStreamer.SwitchSection(
2412 Asm->getObjFileLowering().getDwarfLocSection());
2413 unsigned char Size = Asm->getDataLayout().getPointerSize();
2414 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2415 unsigned index = 1;
2416 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2417 I = DotDebugLocEntries.begin(),
2418 E = DotDebugLocEntries.end();
2419 I != E; ++I, ++index) {
2420 const DotDebugLocEntry &Entry = *I;
2421 if (Entry.isMerged())
2422 continue;
2424 if (Entry.isEmpty()) {
2425 Asm->OutStreamer.EmitIntValue(0, Size);
2426 Asm->OutStreamer.EmitIntValue(0, Size);
2427 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2428 } else {
2429 // Set up the range.
2430 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2431 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2432 Asm->OutStreamer.AddComment("Loc expr size");
2433 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2434 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2435 Asm->EmitLabelDifference(end, begin, 2);
2436 Asm->OutStreamer.EmitLabel(begin);
2437 // Emit the entry.
2438 APByteStreamer Streamer(*Asm);
2439 emitDebugLocEntry(Streamer, Entry);
2440 // Close the range.
2441 Asm->OutStreamer.EmitLabel(end);
2442 }
2443 }
2444 }
2446 struct ArangeSpan {
2447 const MCSymbol *Start, *End;
2448 };
2450 // Emit a debug aranges section, containing a CU lookup for any
2451 // address we can tie back to a CU.
2452 void DwarfDebug::emitDebugARanges() {
2453 // Start the dwarf aranges section.
2454 Asm->OutStreamer.SwitchSection(
2455 Asm->getObjFileLowering().getDwarfARangesSection());
2457 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2459 SpansType Spans;
2461 // Build a list of sections used.
2462 std::vector<const MCSection *> Sections;
2463 for (const auto &it : SectionMap) {
2464 const MCSection *Section = it.first;
2465 Sections.push_back(Section);
2466 }
2468 // Sort the sections into order.
2469 // This is only done to ensure consistent output order across different runs.
2470 std::sort(Sections.begin(), Sections.end(), SectionSort);
2472 // Build a set of address spans, sorted by CU.
2473 for (const MCSection *Section : Sections) {
2474 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2475 if (List.size() < 2)
2476 continue;
2478 // Sort the symbols by offset within the section.
2479 std::sort(List.begin(), List.end(),
2480 [&](const SymbolCU &A, const SymbolCU &B) {
2481 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2482 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2484 // Symbols with no order assigned should be placed at the end.
2485 // (e.g. section end labels)
2486 if (IA == 0)
2487 return false;
2488 if (IB == 0)
2489 return true;
2490 return IA < IB;
2491 });
2493 // If we have no section (e.g. common), just write out
2494 // individual spans for each symbol.
2495 if (Section == NULL) {
2496 for (const SymbolCU &Cur : List) {
2497 ArangeSpan Span;
2498 Span.Start = Cur.Sym;
2499 Span.End = NULL;
2500 if (Cur.CU)
2501 Spans[Cur.CU].push_back(Span);
2502 }
2503 } else {
2504 // Build spans between each label.
2505 const MCSymbol *StartSym = List[0].Sym;
2506 for (size_t n = 1, e = List.size(); n < e; n++) {
2507 const SymbolCU &Prev = List[n - 1];
2508 const SymbolCU &Cur = List[n];
2510 // Try and build the longest span we can within the same CU.
2511 if (Cur.CU != Prev.CU) {
2512 ArangeSpan Span;
2513 Span.Start = StartSym;
2514 Span.End = Cur.Sym;
2515 Spans[Prev.CU].push_back(Span);
2516 StartSym = Cur.Sym;
2517 }
2518 }
2519 }
2520 }
2522 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2524 // Build a list of CUs used.
2525 std::vector<DwarfCompileUnit *> CUs;
2526 for (const auto &it : Spans) {
2527 DwarfCompileUnit *CU = it.first;
2528 CUs.push_back(CU);
2529 }
2531 // Sort the CU list (again, to ensure consistent output order).
2532 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2533 return A->getUniqueID() < B->getUniqueID();
2534 });
2536 // Emit an arange table for each CU we used.
2537 for (DwarfCompileUnit *CU : CUs) {
2538 std::vector<ArangeSpan> &List = Spans[CU];
2540 // Emit size of content not including length itself.
2541 unsigned ContentSize =
2542 sizeof(int16_t) + // DWARF ARange version number
2543 sizeof(int32_t) + // Offset of CU in the .debug_info section
2544 sizeof(int8_t) + // Pointer Size (in bytes)
2545 sizeof(int8_t); // Segment Size (in bytes)
2547 unsigned TupleSize = PtrSize * 2;
2549 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2550 unsigned Padding =
2551 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2553 ContentSize += Padding;
2554 ContentSize += (List.size() + 1) * TupleSize;
2556 // For each compile unit, write the list of spans it covers.
2557 Asm->OutStreamer.AddComment("Length of ARange Set");
2558 Asm->EmitInt32(ContentSize);
2559 Asm->OutStreamer.AddComment("DWARF Arange version number");
2560 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2561 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2562 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2563 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2564 Asm->EmitInt8(PtrSize);
2565 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2566 Asm->EmitInt8(0);
2568 Asm->OutStreamer.EmitFill(Padding, 0xff);
2570 for (const ArangeSpan &Span : List) {
2571 Asm->EmitLabelReference(Span.Start, PtrSize);
2573 // Calculate the size as being from the span start to it's end.
2574 if (Span.End) {
2575 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2576 } else {
2577 // For symbols without an end marker (e.g. common), we
2578 // write a single arange entry containing just that one symbol.
2579 uint64_t Size = SymSize[Span.Start];
2580 if (Size == 0)
2581 Size = 1;
2583 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2584 }
2585 }
2587 Asm->OutStreamer.AddComment("ARange terminator");
2588 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2589 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2590 }
2591 }
2593 // Emit visible names into a debug ranges section.
2594 void DwarfDebug::emitDebugRanges() {
2595 // Start the dwarf ranges section.
2596 Asm->OutStreamer.SwitchSection(
2597 Asm->getObjFileLowering().getDwarfRangesSection());
2599 // Size for our labels.
2600 unsigned char Size = Asm->getDataLayout().getPointerSize();
2602 // Grab the specific ranges for the compile units in the module.
2603 for (const auto &I : CUMap) {
2604 DwarfCompileUnit *TheCU = I.second;
2606 // Emit a symbol so we can find the beginning of our ranges.
2607 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2609 // Iterate over the misc ranges for the compile units in the module.
2610 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2611 // Emit our symbol so we can find the beginning of the range.
2612 Asm->OutStreamer.EmitLabel(List.getSym());
2614 for (const RangeSpan &Range : List.getRanges()) {
2615 const MCSymbol *Begin = Range.getStart();
2616 const MCSymbol *End = Range.getEnd();
2617 assert(Begin && "Range without a begin symbol?");
2618 assert(End && "Range without an end symbol?");
2619 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2620 Asm->OutStreamer.EmitSymbolValue(End, Size);
2621 }
2623 // And terminate the list with two 0 values.
2624 Asm->OutStreamer.EmitIntValue(0, Size);
2625 Asm->OutStreamer.EmitIntValue(0, Size);
2626 }
2628 // Now emit a range for the CU itself.
2629 if (useCURanges() && TheCU->getRanges().size()) {
2630 Asm->OutStreamer.EmitLabel(
2631 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2632 for (const RangeSpan &Range : TheCU->getRanges()) {
2633 const MCSymbol *Begin = Range.getStart();
2634 const MCSymbol *End = Range.getEnd();
2635 assert(Begin && "Range without a begin symbol?");
2636 assert(End && "Range without an end symbol?");
2637 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2638 Asm->OutStreamer.EmitSymbolValue(End, Size);
2639 }
2640 // And terminate the list with two 0 values.
2641 Asm->OutStreamer.EmitIntValue(0, Size);
2642 Asm->OutStreamer.EmitIntValue(0, Size);
2643 }
2644 }
2645 }
2647 // DWARF5 Experimental Separate Dwarf emitters.
2649 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2650 DwarfUnit *NewU) {
2651 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2652 U->getCUNode().getSplitDebugFilename());
2654 // Relocate to the beginning of the addr_base section, else 0 for the
2655 // beginning of the one for this compile unit.
2656 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2657 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2658 else
2659 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2661 if (!CompilationDir.empty())
2662 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2664 addGnuPubAttributes(NewU, Die);
2666 SkeletonHolder.addUnit(NewU);
2667 }
2669 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2670 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2671 // DW_AT_ranges_base, DW_AT_addr_base.
2672 // TODO: Implement DW_AT_ranges_base.
2673 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2675 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2676 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2677 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2678 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2679 DwarfInfoSectionSym);
2681 NewCU->initStmtList(DwarfLineSectionSym);
2683 initSkeletonUnit(CU, Die, NewCU);
2685 return NewCU;
2686 }
2688 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2689 // DW_AT_addr_base.
2690 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2691 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2692 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2694 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2695 DwarfTypeUnit *NewTU =
2696 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2697 NewTU->setTypeSignature(TU->getTypeSignature());
2698 NewTU->setType(NULL);
2699 NewTU->initSection(
2700 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2701 CU.applyStmtList(*Die);
2703 initSkeletonUnit(TU, Die, NewTU);
2704 return NewTU;
2705 }
2707 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2708 // compile units that would normally be in debug_info.
2709 void DwarfDebug::emitDebugInfoDWO() {
2710 assert(useSplitDwarf() && "No split dwarf debug info?");
2711 InfoHolder.emitUnits(this,
2712 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2713 DwarfAbbrevDWOSectionSym);
2714 }
2716 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2717 // abbreviations for the .debug_info.dwo section.
2718 void DwarfDebug::emitDebugAbbrevDWO() {
2719 assert(useSplitDwarf() && "No split dwarf?");
2720 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2721 }
2723 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2724 // string section and is identical in format to traditional .debug_str
2725 // sections.
2726 void DwarfDebug::emitDebugStrDWO() {
2727 assert(useSplitDwarf() && "No split dwarf?");
2728 const MCSection *OffSec =
2729 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2730 const MCSymbol *StrSym = DwarfStrSectionSym;
2731 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2732 OffSec, StrSym);
2733 }
2735 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2736 StringRef Identifier, DIE *RefDie,
2737 DICompositeType CTy) {
2738 // Flag the type unit reference as a declaration so that if it contains
2739 // members (implicit special members, static data member definitions, member
2740 // declarations for definitions in this CU, etc) consumers don't get confused
2741 // and think this is a full definition.
2742 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2744 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2745 if (TU) {
2746 CU.addDIETypeSignature(RefDie, *TU);
2747 return;
2748 }
2750 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2751 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2752 UnitDie, CU, Asm, this, &InfoHolder);
2753 TU = NewTU;
2754 InfoHolder.addUnit(NewTU);
2756 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2757 CU.getLanguage());
2759 MD5 Hash;
2760 Hash.update(Identifier);
2761 // ... take the least significant 8 bytes and return those. Our MD5
2762 // implementation always returns its results in little endian, swap bytes
2763 // appropriately.
2764 MD5::MD5Result Result;
2765 Hash.final(Result);
2766 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2767 NewTU->setTypeSignature(Signature);
2768 if (useSplitDwarf())
2769 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2770 else
2771 CU.applyStmtList(*UnitDie);
2773 NewTU->setType(NewTU->createTypeDIE(CTy));
2775 NewTU->initSection(
2776 useSplitDwarf()
2777 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2778 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2780 CU.addDIETypeSignature(RefDie, *NewTU);
2781 }
2783 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2784 MCSymbol *Begin, MCSymbol *End) {
2785 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2786 if (DwarfVersion < 4)
2787 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2788 else
2789 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2790 }