077af8c375619758e74b7450e5ed7e34e8295a76
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 "DwarfDebug.h"
16 #include "DIE.h"
17 #include "DIEHash.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 using namespace llvm;
52 static cl::opt<bool>
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
59 cl::init(false));
61 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
62 cl::desc("Add the CU hash as the dwo_id."),
63 cl::init(false));
65 static cl::opt<bool>
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 cl::init(false));
70 namespace {
71 enum DefaultOnOff {
72 Default,
73 Enable,
74 Disable
75 };
76 }
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
84 cl::init(Default));
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
92 cl::init(Default));
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
100 cl::init(Default));
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
106 static cl::opt<bool>
107 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
108 cl::desc("Generate DW_AT_ranges for compile units"),
109 cl::init(false));
111 static const char *const DWARFGroupName = "DWARF Emission";
112 static const char *const DbgTimerName = "DWARF Debug Writer";
114 //===----------------------------------------------------------------------===//
116 namespace llvm {
118 /// resolve - Look in the DwarfDebug map for the MDNode that
119 /// corresponds to the reference.
120 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
121 return DD->resolve(Ref);
122 }
124 DIType DbgVariable::getType() const {
125 DIType Ty = Var.getType();
126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
127 // addresses instead.
128 if (Var.isBlockByrefVariable()) {
129 /* Byref variables, in Blocks, are declared by the programmer as
130 "SomeType VarName;", but the compiler creates a
131 __Block_byref_x_VarName struct, and gives the variable VarName
132 either the struct, or a pointer to the struct, as its type. This
133 is necessary for various behind-the-scenes things the compiler
134 needs to do with by-reference variables in blocks.
136 However, as far as the original *programmer* is concerned, the
137 variable should still have type 'SomeType', as originally declared.
139 The following function dives into the __Block_byref_x_VarName
140 struct to find the original type of the variable. This will be
141 passed back to the code generating the type for the Debug
142 Information Entry for the variable 'VarName'. 'VarName' will then
143 have the original type 'SomeType' in its debug information.
145 The original type 'SomeType' will be the type of the field named
146 'VarName' inside the __Block_byref_x_VarName struct.
148 NOTE: In order for this to not completely fail on the debugger
149 side, the Debug Information Entry for the variable VarName needs to
150 have a DW_AT_location that tells the debugger how to unwind through
151 the pointers and __Block_byref_x_VarName struct to find the actual
152 value of the variable. The function addBlockByrefType does this. */
153 DIType subType = Ty;
154 uint16_t tag = Ty.getTag();
156 if (tag == dwarf::DW_TAG_pointer_type)
157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
159 DIArray Elements = DICompositeType(subType).getTypeArray();
160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
161 DIDerivedType DT(Elements.getElement(i));
162 if (getName() == DT.getName())
163 return (resolve(DT.getTypeDerivedFrom()));
164 }
165 }
166 return Ty;
167 }
169 } // end llvm namespace
171 /// Return Dwarf Version by checking module flags.
172 static unsigned getDwarfVersionFromModule(const Module *M) {
173 Value *Val = M->getModuleFlag("Dwarf Version");
174 if (!Val)
175 return dwarf::DWARF_VERSION;
176 return cast<ConstantInt>(Val)->getZExtValue();
177 }
179 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
180 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
181 PrevLabel(NULL), GlobalRangeCount(0),
182 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
183 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
187 DwarfAddrSectionSym = 0;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
189 FunctionBeginSym = FunctionEndSym = 0;
190 TextSectionBeginSym = TextSectionEndSym = 0;
191 CurFn = 0;
192 CurMI = 0;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
198 if (DwarfAccelTables == Default)
199 HasDwarfAccelTables = IsDarwin;
200 else
201 HasDwarfAccelTables = DwarfAccelTables == Enable;
203 if (SplitDwarf == Default)
204 HasSplitDwarf = false;
205 else
206 HasSplitDwarf = SplitDwarf == Enable;
208 if (DwarfPubSections == Default)
209 HasDwarfPubSections = !IsDarwin;
210 else
211 HasDwarfPubSections = DwarfPubSections == Enable;
213 DwarfVersion = DwarfVersionNumber
214 ? DwarfVersionNumber
215 : getDwarfVersionFromModule(MMI->getModule());
217 {
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
219 beginModule();
220 }
221 }
223 // Switch to the specified MCSection and emit an assembler
224 // temporary label to it if SymbolStem is specified.
225 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
226 const char *SymbolStem = 0) {
227 Asm->OutStreamer.SwitchSection(Section);
228 if (!SymbolStem)
229 return 0;
231 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
232 Asm->OutStreamer.EmitLabel(TmpSym);
233 return TmpSym;
234 }
236 DwarfFile::~DwarfFile() {
237 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
238 I != E; ++I)
239 delete *I;
240 }
242 MCSymbol *DwarfFile::getStringPoolSym() {
243 return Asm->GetTempSymbol(StringPref);
244 }
246 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
247 std::pair<MCSymbol *, unsigned> &Entry =
248 StringPool.GetOrCreateValue(Str).getValue();
249 if (Entry.first)
250 return Entry.first;
252 Entry.second = NextStringPoolNumber++;
253 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
254 }
256 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
257 std::pair<MCSymbol *, unsigned> &Entry =
258 StringPool.GetOrCreateValue(Str).getValue();
259 if (Entry.first)
260 return Entry.second;
262 Entry.second = NextStringPoolNumber++;
263 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
264 return Entry.second;
265 }
267 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
268 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
269 }
271 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
272 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
273 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
274 if (P.second)
275 ++NextAddrPoolNumber;
276 return P.first->second;
277 }
279 // Define a unique number for the abbreviation.
280 //
281 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
282 // Check the set for priors.
283 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
285 // If it's newly added.
286 if (InSet == &Abbrev) {
287 // Add to abbreviation list.
288 Abbreviations.push_back(&Abbrev);
290 // Assign the vector position + 1 as its number.
291 Abbrev.setNumber(Abbreviations.size());
292 } else {
293 // Assign existing abbreviation number.
294 Abbrev.setNumber(InSet->getNumber());
295 }
296 }
298 static bool isObjCClass(StringRef Name) {
299 return Name.startswith("+") || Name.startswith("-");
300 }
302 static bool hasObjCCategory(StringRef Name) {
303 if (!isObjCClass(Name))
304 return false;
306 return Name.find(") ") != StringRef::npos;
307 }
309 static void getObjCClassCategory(StringRef In, StringRef &Class,
310 StringRef &Category) {
311 if (!hasObjCCategory(In)) {
312 Class = In.slice(In.find('[') + 1, In.find(' '));
313 Category = "";
314 return;
315 }
317 Class = In.slice(In.find('[') + 1, In.find('('));
318 Category = In.slice(In.find('[') + 1, In.find(' '));
319 return;
320 }
322 static StringRef getObjCMethodName(StringRef In) {
323 return In.slice(In.find(' ') + 1, In.find(']'));
324 }
326 // Helper for sorting sections into a stable output order.
327 static bool SectionSort(const MCSection *A, const MCSection *B) {
328 std::string LA = (A ? A->getLabelBeginName() : "");
329 std::string LB = (B ? B->getLabelBeginName() : "");
330 return LA < LB;
331 }
333 // Add the various names to the Dwarf accelerator table names.
334 // TODO: Determine whether or not we should add names for programs
335 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
336 // is only slightly different than the lookup of non-standard ObjC names.
337 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
338 if (!SP.isDefinition())
339 return;
340 TheU->addAccelName(SP.getName(), Die);
342 // If the linkage name is different than the name, go ahead and output
343 // that as well into the name table.
344 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
345 TheU->addAccelName(SP.getLinkageName(), Die);
347 // If this is an Objective-C selector name add it to the ObjC accelerator
348 // too.
349 if (isObjCClass(SP.getName())) {
350 StringRef Class, Category;
351 getObjCClassCategory(SP.getName(), Class, Category);
352 TheU->addAccelObjC(Class, Die);
353 if (Category != "")
354 TheU->addAccelObjC(Category, Die);
355 // Also add the base method name to the name table.
356 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
357 }
358 }
360 /// isSubprogramContext - Return true if Context is either a subprogram
361 /// or another context nested inside a subprogram.
362 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
363 if (!Context)
364 return false;
365 DIDescriptor D(Context);
366 if (D.isSubprogram())
367 return true;
368 if (D.isType())
369 return isSubprogramContext(resolve(DIType(Context).getContext()));
370 return false;
371 }
373 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
374 // and DW_AT_high_pc attributes. If there are global variables in this
375 // scope then create and insert DIEs for these variables.
376 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
377 DISubprogram SP) {
378 DIE *SPDie = SPCU->getDIE(SP);
380 assert(SPDie && "Unable to find subprogram DIE!");
382 // If we're updating an abstract DIE, then we will be adding the children and
383 // object pointer later on. But what we don't want to do is process the
384 // concrete DIE twice.
385 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
386 // Pick up abstract subprogram DIE.
387 SPDie =
388 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
389 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
390 } else {
391 DISubprogram SPDecl = SP.getFunctionDeclaration();
392 if (!SPDecl.isSubprogram()) {
393 // There is not any need to generate specification DIE for a function
394 // defined at compile unit level. If a function is defined inside another
395 // function then gdb prefers the definition at top level and but does not
396 // expect specification DIE in parent function. So avoid creating
397 // specification DIE for a function defined inside a function.
398 DIScope SPContext = resolve(SP.getContext());
399 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
400 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
401 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
403 // Add arguments.
404 DICompositeType SPTy = SP.getType();
405 DIArray Args = SPTy.getTypeArray();
406 uint16_t SPTag = SPTy.getTag();
407 if (SPTag == dwarf::DW_TAG_subroutine_type)
408 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 DIE *Arg =
410 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
411 DIType ATy(Args.getElement(i));
412 SPCU->addType(Arg, ATy);
413 if (ATy.isArtificial())
414 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
415 if (ATy.isObjectPointer())
416 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
417 }
418 DIE *SPDeclDie = SPDie;
419 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
420 *SPCU->getUnitDie());
421 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
422 }
423 }
424 }
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
427 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
429 // Add this range to the list of ranges for the CU.
430 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
431 SPCU->addRange(llvm_move(Span));
433 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
434 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
435 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
437 // Add name to the name table, we do this here because we're guaranteed
438 // to have concrete versions of our DW_TAG_subprogram nodes.
439 addSubprogramNames(SPCU, SP, SPDie);
441 return SPDie;
442 }
444 /// Check whether we should create a DIE for the given Scope, return true
445 /// if we don't create a DIE (the corresponding DIE is null).
446 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
447 if (Scope->isAbstractScope())
448 return false;
450 // We don't create a DIE if there is no Range.
451 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
452 if (Ranges.empty())
453 return true;
455 if (Ranges.size() > 1)
456 return false;
458 // We don't create a DIE if we have a single Range and the end label
459 // is null.
460 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
461 MCSymbol *End = getLabelAfterInsn(RI->second);
462 return !End;
463 }
465 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
466 dwarf::Attribute A, const MCSymbol *L,
467 const MCSymbol *Sec) {
468 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
469 U->addSectionLabel(D, A, L);
470 else
471 U->addSectionDelta(D, A, L, Sec);
472 }
474 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
475 const SmallVectorImpl<InsnRange> &Range) {
476 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
477 // emitting it appropriately.
478 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
479 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
480 DwarfDebugRangeSectionSym);
482 RangeSpanList List(RangeSym);
483 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
484 RE = Range.end();
485 RI != RE; ++RI) {
486 RangeSpan Span(getLabelBeforeInsn(RI->first),
487 getLabelAfterInsn(RI->second));
488 List.addRange(llvm_move(Span));
489 }
491 // Add the range list to the set of ranges to be emitted.
492 TheCU->addRangeList(llvm_move(List));
493 }
495 // Construct new DW_TAG_lexical_block for this scope and attach
496 // DW_AT_low_pc/DW_AT_high_pc labels.
497 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
498 LexicalScope *Scope) {
499 if (isLexicalScopeDIENull(Scope))
500 return 0;
502 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
503 if (Scope->isAbstractScope())
504 return ScopeDIE;
506 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
508 // If we have multiple ranges, emit them into the range section.
509 if (ScopeRanges.size() > 1) {
510 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
511 return ScopeDIE;
512 }
514 // Construct the address range for this DIE.
515 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
516 MCSymbol *Start = getLabelBeforeInsn(RI->first);
517 MCSymbol *End = getLabelAfterInsn(RI->second);
518 assert(End && "End label should not be null!");
520 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
521 assert(End->isDefined() && "Invalid end label for an inlined scope!");
523 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
524 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
526 return ScopeDIE;
527 }
529 // This scope represents inlined body of a function. Construct DIE to
530 // represent this concrete inlined copy of the function.
531 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
532 LexicalScope *Scope) {
533 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
534 assert(!ScopeRanges.empty() &&
535 "LexicalScope does not have instruction markers!");
537 if (!Scope->getScopeNode())
538 return NULL;
539 DIScope DS(Scope->getScopeNode());
540 DISubprogram InlinedSP = getDISubprogram(DS);
541 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
542 if (!OriginDIE) {
543 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
544 return NULL;
545 }
547 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
548 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
550 // If we have multiple ranges, emit them into the range section.
551 if (ScopeRanges.size() > 1)
552 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
553 else {
554 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
555 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
556 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
558 if (StartLabel == 0 || EndLabel == 0)
559 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
561 assert(StartLabel->isDefined() &&
562 "Invalid starting label for an inlined scope!");
563 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
565 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
566 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
567 }
569 InlinedSubprogramDIEs.insert(OriginDIE);
571 // Add the call site information to the DIE.
572 DILocation DL(Scope->getInlinedAt());
573 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
574 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
575 TheCU->getUniqueID()));
576 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
578 // Add name to the name table, we do this here because we're guaranteed
579 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
580 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
582 return ScopeDIE;
583 }
585 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
586 LexicalScope *Scope,
587 SmallVectorImpl<DIE *> &Children) {
588 DIE *ObjectPointer = NULL;
590 // Collect arguments for current function.
591 if (LScopes.isCurrentFunctionScope(Scope))
592 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
593 if (DbgVariable *ArgDV = CurrentFnArguments[i])
594 if (DIE *Arg =
595 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
596 Children.push_back(Arg);
597 if (ArgDV->isObjectPointer())
598 ObjectPointer = Arg;
599 }
601 // Collect lexical scope children first.
602 const SmallVectorImpl<DbgVariable *> &Variables =
603 ScopeVariables.lookup(Scope);
604 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
605 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
606 Scope->isAbstractScope())) {
607 Children.push_back(Variable);
608 if (Variables[i]->isObjectPointer())
609 ObjectPointer = Variable;
610 }
611 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
612 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
613 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
614 Children.push_back(Nested);
615 return ObjectPointer;
616 }
618 // Construct a DIE for this scope.
619 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
620 LexicalScope *Scope) {
621 if (!Scope || !Scope->getScopeNode())
622 return NULL;
624 DIScope DS(Scope->getScopeNode());
626 SmallVector<DIE *, 8> Children;
627 DIE *ObjectPointer = NULL;
628 bool ChildrenCreated = false;
630 // We try to create the scope DIE first, then the children DIEs. This will
631 // avoid creating un-used children then removing them later when we find out
632 // the scope DIE is null.
633 DIE *ScopeDIE = NULL;
634 if (Scope->getInlinedAt())
635 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
636 else if (DS.isSubprogram()) {
637 ProcessedSPNodes.insert(DS);
638 if (Scope->isAbstractScope()) {
639 ScopeDIE = TheCU->getDIE(DS);
640 // Note down abstract DIE.
641 if (ScopeDIE)
642 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
643 } else
644 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
645 } else {
646 // Early exit when we know the scope DIE is going to be null.
647 if (isLexicalScopeDIENull(Scope))
648 return NULL;
650 // We create children here when we know the scope DIE is not going to be
651 // null and the children will be added to the scope DIE.
652 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
653 ChildrenCreated = true;
655 // There is no need to emit empty lexical block DIE.
656 std::pair<ImportedEntityMap::const_iterator,
657 ImportedEntityMap::const_iterator> Range =
658 std::equal_range(
659 ScopesWithImportedEntities.begin(),
660 ScopesWithImportedEntities.end(),
661 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
662 less_first());
663 if (Children.empty() && Range.first == Range.second)
664 return NULL;
665 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
666 assert(ScopeDIE && "Scope DIE should not be null.");
667 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
668 ++i)
669 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
670 }
672 if (!ScopeDIE) {
673 assert(Children.empty() &&
674 "We create children only when the scope DIE is not null.");
675 return NULL;
676 }
677 if (!ChildrenCreated)
678 // We create children when the scope DIE is not null.
679 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
681 // Add children
682 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
683 E = Children.end();
684 I != E; ++I)
685 ScopeDIE->addChild(*I);
687 if (DS.isSubprogram() && ObjectPointer != NULL)
688 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
690 return ScopeDIE;
691 }
693 // Look up the source id with the given directory and source file names.
694 // If none currently exists, create a new id and insert it in the
695 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
696 // as well.
697 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
698 unsigned CUID) {
699 // If we use .loc in assembly, we can't separate .file entries according to
700 // compile units. Thus all files will belong to the default compile unit.
702 // FIXME: add a better feature test than hasRawTextSupport. Even better,
703 // extend .file to support this.
704 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
705 CUID = 0;
707 // If FE did not provide a file name, then assume stdin.
708 if (FileName.empty())
709 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
711 // TODO: this might not belong here. See if we can factor this better.
712 if (DirName == CompilationDir)
713 DirName = "";
715 // FileIDCUMap stores the current ID for the given compile unit.
716 unsigned SrcId = FileIDCUMap[CUID] + 1;
718 // We look up the CUID/file/dir by concatenating them with a zero byte.
719 SmallString<128> NamePair;
720 NamePair += utostr(CUID);
721 NamePair += '\0';
722 NamePair += DirName;
723 NamePair += '\0'; // Zero bytes are not allowed in paths.
724 NamePair += FileName;
726 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
727 if (Ent.getValue() != SrcId)
728 return Ent.getValue();
730 FileIDCUMap[CUID] = SrcId;
731 // Print out a .file directive to specify files for .loc directives.
732 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
734 return SrcId;
735 }
737 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
738 if (!GenerateGnuPubSections)
739 return;
741 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
742 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
743 DwarfGnuPubNamesSectionSym);
745 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
746 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
747 DwarfGnuPubTypesSectionSym);
748 }
750 // Create new DwarfCompileUnit for the given metadata node with tag
751 // DW_TAG_compile_unit.
752 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
753 StringRef FN = DIUnit.getFilename();
754 CompilationDir = DIUnit.getDirectory();
756 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
757 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
758 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
759 InfoHolder.addUnit(NewCU);
761 FileIDCUMap[NewCU->getUniqueID()] = 0;
762 // Call this to emit a .file directive if it wasn't emitted for the source
763 // file this CU comes from yet.
764 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
766 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
767 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
768 DIUnit.getLanguage());
769 NewCU->addString(Die, dwarf::DW_AT_name, FN);
771 // Define start line table label for each Compile Unit.
772 MCSymbol *LineTableStartSym =
773 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
774 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
775 NewCU->getUniqueID());
777 // Use a single line table if we are using .loc and generating assembly.
778 bool UseTheFirstCU =
779 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
780 (NewCU->getUniqueID() == 0);
782 if (!useSplitDwarf()) {
783 // DW_AT_stmt_list is a offset of line number information for this
784 // compile unit in debug_line section. For split dwarf this is
785 // left in the skeleton CU and so not included.
786 // The line table entries are not always emitted in assembly, so it
787 // is not okay to use line_table_start here.
788 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
789 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
790 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
791 : LineTableStartSym);
792 else if (UseTheFirstCU)
793 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
794 else
795 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
796 DwarfLineSectionSym);
798 // If we're using split dwarf the compilation dir is going to be in the
799 // skeleton CU and so we don't need to duplicate it here.
800 if (!CompilationDir.empty())
801 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
803 addGnuPubAttributes(NewCU, Die);
804 }
806 if (DIUnit.isOptimized())
807 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
809 StringRef Flags = DIUnit.getFlags();
810 if (!Flags.empty())
811 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
813 if (unsigned RVer = DIUnit.getRunTimeVersion())
814 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
815 dwarf::DW_FORM_data1, RVer);
817 if (!FirstCU)
818 FirstCU = NewCU;
820 if (useSplitDwarf()) {
821 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
822 DwarfInfoDWOSectionSym);
823 NewCU->setSkeleton(constructSkeletonCU(NewCU));
824 } else
825 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
826 DwarfInfoSectionSym);
828 CUMap.insert(std::make_pair(DIUnit, NewCU));
829 CUDieMap.insert(std::make_pair(Die, NewCU));
830 return NewCU;
831 }
833 // Construct subprogram DIE.
834 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
835 const MDNode *N) {
836 // FIXME: We should only call this routine once, however, during LTO if a
837 // program is defined in multiple CUs we could end up calling it out of
838 // beginModule as we walk the CUs.
840 DwarfCompileUnit *&CURef = SPMap[N];
841 if (CURef)
842 return;
843 CURef = TheCU;
845 DISubprogram SP(N);
846 if (!SP.isDefinition())
847 // This is a method declaration which will be handled while constructing
848 // class type.
849 return;
851 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
853 // Expose as a global name.
854 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
855 }
857 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
858 const MDNode *N) {
859 DIImportedEntity Module(N);
860 if (!Module.Verify())
861 return;
862 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
863 constructImportedEntityDIE(TheCU, Module, D);
864 }
866 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
867 const MDNode *N, DIE *Context) {
868 DIImportedEntity Module(N);
869 if (!Module.Verify())
870 return;
871 return constructImportedEntityDIE(TheCU, Module, Context);
872 }
874 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
875 const DIImportedEntity &Module,
876 DIE *Context) {
877 assert(Module.Verify() &&
878 "Use one of the MDNode * overloads to handle invalid metadata");
879 assert(Context && "Should always have a context for an imported_module");
880 DIE *IMDie = new DIE(Module.getTag());
881 TheCU->insertDIE(Module, IMDie);
882 DIE *EntityDie;
883 DIDescriptor Entity = Module.getEntity();
884 if (Entity.isNameSpace())
885 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
886 else if (Entity.isSubprogram())
887 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
888 else if (Entity.isType())
889 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
890 else
891 EntityDie = TheCU->getDIE(Entity);
892 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
893 Module.getContext().getDirectory(),
894 TheCU->getUniqueID());
895 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
896 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
897 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
898 StringRef Name = Module.getName();
899 if (!Name.empty())
900 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
901 Context->addChild(IMDie);
902 }
904 // Emit all Dwarf sections that should come prior to the content. Create
905 // global DIEs and emit initial debug info sections. This is invoked by
906 // the target AsmPrinter.
907 void DwarfDebug::beginModule() {
908 if (DisableDebugInfoPrinting)
909 return;
911 const Module *M = MMI->getModule();
913 // If module has named metadata anchors then use them, otherwise scan the
914 // module using debug info finder to collect debug info.
915 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
916 if (!CU_Nodes)
917 return;
918 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
920 // Emit initial sections so we can reference labels later.
921 emitSectionLabels();
923 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
924 DICompileUnit CUNode(CU_Nodes->getOperand(i));
925 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
926 DIArray ImportedEntities = CUNode.getImportedEntities();
927 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
928 ScopesWithImportedEntities.push_back(std::make_pair(
929 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
930 ImportedEntities.getElement(i)));
931 std::sort(ScopesWithImportedEntities.begin(),
932 ScopesWithImportedEntities.end(), less_first());
933 DIArray GVs = CUNode.getGlobalVariables();
934 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
935 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
936 DIArray SPs = CUNode.getSubprograms();
937 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
938 constructSubprogramDIE(CU, SPs.getElement(i));
939 DIArray EnumTypes = CUNode.getEnumTypes();
940 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
941 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
942 DIArray RetainedTypes = CUNode.getRetainedTypes();
943 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
944 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
945 // Emit imported_modules last so that the relevant context is already
946 // available.
947 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
948 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
949 }
951 // Tell MMI that we have debug info.
952 MMI->setDebugInfoAvailability(true);
954 // Prime section data.
955 SectionMap[Asm->getObjFileLowering().getTextSection()];
956 }
958 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
959 void DwarfDebug::computeInlinedDIEs() {
960 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
961 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
962 AE = InlinedSubprogramDIEs.end();
963 AI != AE; ++AI) {
964 DIE *ISP = *AI;
965 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
966 }
967 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
968 AE = AbstractSPDies.end();
969 AI != AE; ++AI) {
970 DIE *ISP = AI->second;
971 if (InlinedSubprogramDIEs.count(ISP))
972 continue;
973 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
974 }
975 }
977 // Collect info for variables that were optimized out.
978 void DwarfDebug::collectDeadVariables() {
979 const Module *M = MMI->getModule();
981 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
982 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
983 DICompileUnit TheCU(CU_Nodes->getOperand(i));
984 DIArray Subprograms = TheCU.getSubprograms();
985 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
986 DISubprogram SP(Subprograms.getElement(i));
987 if (ProcessedSPNodes.count(SP) != 0)
988 continue;
989 if (!SP.isSubprogram())
990 continue;
991 if (!SP.isDefinition())
992 continue;
993 DIArray Variables = SP.getVariables();
994 if (Variables.getNumElements() == 0)
995 continue;
997 // Construct subprogram DIE and add variables DIEs.
998 DwarfCompileUnit *SPCU =
999 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
1000 assert(SPCU && "Unable to find Compile Unit!");
1001 // FIXME: See the comment in constructSubprogramDIE about duplicate
1002 // subprogram DIEs.
1003 constructSubprogramDIE(SPCU, SP);
1004 DIE *SPDIE = SPCU->getDIE(SP);
1005 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1006 DIVariable DV(Variables.getElement(vi));
1007 if (!DV.isVariable())
1008 continue;
1009 DbgVariable NewVar(DV, NULL, this);
1010 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1011 SPDIE->addChild(VariableDIE);
1012 }
1013 }
1014 }
1015 }
1016 }
1018 void DwarfDebug::finalizeModuleInfo() {
1019 // Collect info for variables that were optimized out.
1020 collectDeadVariables();
1022 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1023 computeInlinedDIEs();
1025 // Handle anything that needs to be done on a per-unit basis after
1026 // all other generation.
1027 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1028 E = getUnits().end();
1029 I != E; ++I) {
1030 DwarfUnit *TheU = *I;
1031 // Emit DW_AT_containing_type attribute to connect types with their
1032 // vtable holding type.
1033 TheU->constructContainingTypeDIEs();
1035 // Add CU specific attributes if we need to add any.
1036 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1037 // If we're splitting the dwarf out now that we've got the entire
1038 // CU then add the dwo id to it.
1039 DwarfCompileUnit *SkCU =
1040 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1041 if (useSplitDwarf()) {
1042 // This should be a unique identifier when we want to build .dwp files.
1043 uint64_t ID = 0;
1044 if (GenerateCUHash) {
1045 DIEHash CUHash;
1046 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1047 }
1048 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1049 dwarf::DW_FORM_data8, ID);
1050 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1051 dwarf::DW_FORM_data8, ID);
1052 }
1054 // If we have code split among multiple sections or we've requested
1055 // it then emit a DW_AT_ranges attribute on the unit that will remain
1056 // in the .o file, otherwise add a DW_AT_low_pc.
1057 // FIXME: Also add a high pc if we can.
1058 // FIXME: We should use ranges if we have multiple compile units or
1059 // allow reordering of code ala .subsections_via_symbols in mach-o.
1060 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1061 if (useCURanges() && TheU->getRanges().size())
1062 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1063 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1064 DwarfDebugRangeSectionSym);
1065 else {
1066 U->addLocalLabelAddress(U->getUnitDie(), dwarf::DW_AT_low_pc,
1067 TextSectionBeginSym);
1068 U->addLocalLabelAddress(U->getUnitDie(), dwarf::DW_AT_high_pc,
1069 TextSectionEndSym);
1070 }
1071 }
1072 }
1074 // Compute DIE offsets and sizes.
1075 InfoHolder.computeSizeAndOffsets();
1076 if (useSplitDwarf())
1077 SkeletonHolder.computeSizeAndOffsets();
1078 }
1080 void DwarfDebug::endSections() {
1081 // Filter labels by section.
1082 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1083 const SymbolCU &SCU = ArangeLabels[n];
1084 if (SCU.Sym->isInSection()) {
1085 // Make a note of this symbol and it's section.
1086 const MCSection *Section = &SCU.Sym->getSection();
1087 if (!Section->getKind().isMetadata())
1088 SectionMap[Section].push_back(SCU);
1089 } else {
1090 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1091 // appear in the output. This sucks as we rely on sections to build
1092 // arange spans. We can do it without, but it's icky.
1093 SectionMap[NULL].push_back(SCU);
1094 }
1095 }
1097 // Build a list of sections used.
1098 std::vector<const MCSection *> Sections;
1099 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1100 it++) {
1101 const MCSection *Section = it->first;
1102 Sections.push_back(Section);
1103 }
1105 // Sort the sections into order.
1106 // This is only done to ensure consistent output order across different runs.
1107 std::sort(Sections.begin(), Sections.end(), SectionSort);
1109 // Add terminating symbols for each section.
1110 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1111 const MCSection *Section = Sections[ID];
1112 MCSymbol *Sym = NULL;
1114 if (Section) {
1115 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1116 // if we know the section name up-front. For user-created sections, the
1117 // resulting
1118 // label may not be valid to use as a label. (section names can use a
1119 // greater
1120 // set of characters on some systems)
1121 Sym = Asm->GetTempSymbol("debug_end", ID);
1122 Asm->OutStreamer.SwitchSection(Section);
1123 Asm->OutStreamer.EmitLabel(Sym);
1124 // If this is the end of the text section keep track of where the end of
1125 // the section is so that we can use it later.
1126 if (Section == Asm->getObjFileLowering().getTextSection())
1127 TextSectionEndSym = Sym;
1128 }
1130 // Insert a final terminator.
1131 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1132 }
1134 // For now only turn on CU ranges if we've explicitly asked for it,
1135 // we have -ffunction-sections enabled, or we've emitted a function
1136 // into a unique section. At this point all sections should be finalized
1137 // except for dwarf sections.
1138 HasCURanges = DwarfCURanges || Asm->TM.debugUseUniqueSections() ||
1139 TargetMachine::getFunctionSections();
1140 }
1142 // Emit all Dwarf sections that should come after the content.
1143 void DwarfDebug::endModule() {
1144 assert(CurFn == 0);
1145 assert(CurMI == 0);
1147 if (!FirstCU)
1148 return;
1150 // End any existing sections.
1151 // TODO: Does this need to happen?
1152 endSections();
1154 // Finalize the debug info for the module.
1155 finalizeModuleInfo();
1157 emitDebugStr();
1159 // Emit all the DIEs into a debug info section.
1160 emitDebugInfo();
1162 // Corresponding abbreviations into a abbrev section.
1163 emitAbbreviations();
1165 // Emit info into a debug loc section.
1166 emitDebugLoc();
1168 // Emit info into a debug aranges section.
1169 emitDebugARanges();
1171 // Emit info into a debug ranges section.
1172 emitDebugRanges();
1174 if (useSplitDwarf()) {
1175 emitDebugStrDWO();
1176 emitDebugInfoDWO();
1177 emitDebugAbbrevDWO();
1178 // Emit DWO addresses.
1179 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1180 }
1182 // Emit info into the dwarf accelerator table sections.
1183 if (useDwarfAccelTables()) {
1184 emitAccelNames();
1185 emitAccelObjC();
1186 emitAccelNamespaces();
1187 emitAccelTypes();
1188 }
1190 // Emit the pubnames and pubtypes sections if requested.
1191 if (HasDwarfPubSections) {
1192 emitDebugPubNames(GenerateGnuPubSections);
1193 emitDebugPubTypes(GenerateGnuPubSections);
1194 }
1196 // clean up.
1197 SPMap.clear();
1199 // Reset these for the next Module if we have one.
1200 FirstCU = NULL;
1201 }
1203 // Find abstract variable, if any, associated with Var.
1204 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1205 DebugLoc ScopeLoc) {
1206 LLVMContext &Ctx = DV->getContext();
1207 // More then one inlined variable corresponds to one abstract variable.
1208 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1209 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1210 if (AbsDbgVariable)
1211 return AbsDbgVariable;
1213 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1214 if (!Scope)
1215 return NULL;
1217 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1218 addScopeVariable(Scope, AbsDbgVariable);
1219 AbstractVariables[Var] = AbsDbgVariable;
1220 return AbsDbgVariable;
1221 }
1223 // If Var is a current function argument then add it to CurrentFnArguments list.
1224 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1225 if (!LScopes.isCurrentFunctionScope(Scope))
1226 return false;
1227 DIVariable DV = Var->getVariable();
1228 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1229 return false;
1230 unsigned ArgNo = DV.getArgNumber();
1231 if (ArgNo == 0)
1232 return false;
1234 size_t Size = CurrentFnArguments.size();
1235 if (Size == 0)
1236 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1237 // llvm::Function argument size is not good indicator of how many
1238 // arguments does the function have at source level.
1239 if (ArgNo > Size)
1240 CurrentFnArguments.resize(ArgNo * 2);
1241 CurrentFnArguments[ArgNo - 1] = Var;
1242 return true;
1243 }
1245 // Collect variable information from side table maintained by MMI.
1246 void DwarfDebug::collectVariableInfoFromMMITable(
1247 SmallPtrSet<const MDNode *, 16> &Processed) {
1248 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1249 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1250 VE = VMap.end();
1251 VI != VE; ++VI) {
1252 const MDNode *Var = VI->first;
1253 if (!Var)
1254 continue;
1255 Processed.insert(Var);
1256 DIVariable DV(Var);
1257 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1259 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1261 // If variable scope is not found then skip this variable.
1262 if (Scope == 0)
1263 continue;
1265 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1266 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1267 RegVar->setFrameIndex(VP.first);
1268 if (!addCurrentFnArgument(RegVar, Scope))
1269 addScopeVariable(Scope, RegVar);
1270 if (AbsDbgVariable)
1271 AbsDbgVariable->setFrameIndex(VP.first);
1272 }
1273 }
1275 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1276 // defined reg.
1277 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1278 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1279 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1280 MI->getOperand(0).getReg() &&
1281 (MI->getOperand(1).isImm() ||
1282 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1283 }
1285 // Get .debug_loc entry for the instruction range starting at MI.
1286 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1287 const MCSymbol *FLabel,
1288 const MCSymbol *SLabel,
1289 const MachineInstr *MI) {
1290 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1292 assert(MI->getNumOperands() == 3);
1293 if (MI->getOperand(0).isReg()) {
1294 MachineLocation MLoc;
1295 // If the second operand is an immediate, this is a
1296 // register-indirect address.
1297 if (!MI->getOperand(1).isImm())
1298 MLoc.set(MI->getOperand(0).getReg());
1299 else
1300 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1301 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1302 }
1303 if (MI->getOperand(0).isImm())
1304 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1305 if (MI->getOperand(0).isFPImm())
1306 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1307 if (MI->getOperand(0).isCImm())
1308 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1310 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1311 }
1313 // Find variables for each lexical scope.
1314 void
1315 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1317 // Grab the variable info that was squirreled away in the MMI side-table.
1318 collectVariableInfoFromMMITable(Processed);
1320 for (SmallVectorImpl<const MDNode *>::const_iterator
1321 UVI = UserVariables.begin(),
1322 UVE = UserVariables.end();
1323 UVI != UVE; ++UVI) {
1324 const MDNode *Var = *UVI;
1325 if (Processed.count(Var))
1326 continue;
1328 // History contains relevant DBG_VALUE instructions for Var and instructions
1329 // clobbering it.
1330 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1331 if (History.empty())
1332 continue;
1333 const MachineInstr *MInsn = History.front();
1335 DIVariable DV(Var);
1336 LexicalScope *Scope = NULL;
1337 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1338 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1339 Scope = LScopes.getCurrentFunctionScope();
1340 else if (MDNode *IA = DV.getInlinedAt())
1341 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1342 else
1343 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1344 // If variable scope is not found then skip this variable.
1345 if (!Scope)
1346 continue;
1348 Processed.insert(DV);
1349 assert(MInsn->isDebugValue() && "History must begin with debug value");
1350 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1351 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1352 if (!addCurrentFnArgument(RegVar, Scope))
1353 addScopeVariable(Scope, RegVar);
1354 if (AbsVar)
1355 AbsVar->setMInsn(MInsn);
1357 // Simplify ranges that are fully coalesced.
1358 if (History.size() <= 1 ||
1359 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1360 RegVar->setMInsn(MInsn);
1361 continue;
1362 }
1364 // Handle multiple DBG_VALUE instructions describing one variable.
1365 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1367 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1368 HI = History.begin(),
1369 HE = History.end();
1370 HI != HE; ++HI) {
1371 const MachineInstr *Begin = *HI;
1372 assert(Begin->isDebugValue() && "Invalid History entry");
1374 // Check if DBG_VALUE is truncating a range.
1375 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1376 !Begin->getOperand(0).getReg())
1377 continue;
1379 // Compute the range for a register location.
1380 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1381 const MCSymbol *SLabel = 0;
1383 if (HI + 1 == HE)
1384 // If Begin is the last instruction in History then its value is valid
1385 // until the end of the function.
1386 SLabel = FunctionEndSym;
1387 else {
1388 const MachineInstr *End = HI[1];
1389 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1390 << "\t" << *Begin << "\t" << *End << "\n");
1391 if (End->isDebugValue())
1392 SLabel = getLabelBeforeInsn(End);
1393 else {
1394 // End is a normal instruction clobbering the range.
1395 SLabel = getLabelAfterInsn(End);
1396 assert(SLabel && "Forgot label after clobber instruction");
1397 ++HI;
1398 }
1399 }
1401 // The value is valid until the next DBG_VALUE or clobber.
1402 DotDebugLocEntries.push_back(
1403 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1404 }
1405 DotDebugLocEntries.push_back(DotDebugLocEntry());
1406 }
1408 // Collect info for variables that were optimized out.
1409 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1410 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1411 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1412 DIVariable DV(Variables.getElement(i));
1413 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1414 continue;
1415 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1416 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1417 }
1418 }
1420 // Return Label preceding the instruction.
1421 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1422 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1423 assert(Label && "Didn't insert label before instruction");
1424 return Label;
1425 }
1427 // Return Label immediately following the instruction.
1428 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1429 return LabelsAfterInsn.lookup(MI);
1430 }
1432 // Process beginning of an instruction.
1433 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1434 assert(CurMI == 0);
1435 CurMI = MI;
1436 // Check if source location changes, but ignore DBG_VALUE locations.
1437 if (!MI->isDebugValue()) {
1438 DebugLoc DL = MI->getDebugLoc();
1439 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1440 unsigned Flags = 0;
1441 PrevInstLoc = DL;
1442 if (DL == PrologEndLoc) {
1443 Flags |= DWARF2_FLAG_PROLOGUE_END;
1444 PrologEndLoc = DebugLoc();
1445 }
1446 if (PrologEndLoc.isUnknown())
1447 Flags |= DWARF2_FLAG_IS_STMT;
1449 if (!DL.isUnknown()) {
1450 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1451 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1452 } else
1453 recordSourceLine(0, 0, 0, 0);
1454 }
1455 }
1457 // Insert labels where requested.
1458 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1459 LabelsBeforeInsn.find(MI);
1461 // No label needed.
1462 if (I == LabelsBeforeInsn.end())
1463 return;
1465 // Label already assigned.
1466 if (I->second)
1467 return;
1469 if (!PrevLabel) {
1470 PrevLabel = MMI->getContext().CreateTempSymbol();
1471 Asm->OutStreamer.EmitLabel(PrevLabel);
1472 }
1473 I->second = PrevLabel;
1474 }
1476 // Process end of an instruction.
1477 void DwarfDebug::endInstruction() {
1478 assert(CurMI != 0);
1479 // Don't create a new label after DBG_VALUE instructions.
1480 // They don't generate code.
1481 if (!CurMI->isDebugValue())
1482 PrevLabel = 0;
1484 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1485 LabelsAfterInsn.find(CurMI);
1486 CurMI = 0;
1488 // No label needed.
1489 if (I == LabelsAfterInsn.end())
1490 return;
1492 // Label already assigned.
1493 if (I->second)
1494 return;
1496 // We need a label after this instruction.
1497 if (!PrevLabel) {
1498 PrevLabel = MMI->getContext().CreateTempSymbol();
1499 Asm->OutStreamer.EmitLabel(PrevLabel);
1500 }
1501 I->second = PrevLabel;
1502 }
1504 // Each LexicalScope has first instruction and last instruction to mark
1505 // beginning and end of a scope respectively. Create an inverse map that list
1506 // scopes starts (and ends) with an instruction. One instruction may start (or
1507 // end) multiple scopes. Ignore scopes that are not reachable.
1508 void DwarfDebug::identifyScopeMarkers() {
1509 SmallVector<LexicalScope *, 4> WorkList;
1510 WorkList.push_back(LScopes.getCurrentFunctionScope());
1511 while (!WorkList.empty()) {
1512 LexicalScope *S = WorkList.pop_back_val();
1514 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1515 if (!Children.empty())
1516 for (SmallVectorImpl<LexicalScope *>::const_iterator
1517 SI = Children.begin(),
1518 SE = Children.end();
1519 SI != SE; ++SI)
1520 WorkList.push_back(*SI);
1522 if (S->isAbstractScope())
1523 continue;
1525 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1526 if (Ranges.empty())
1527 continue;
1528 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1529 RE = Ranges.end();
1530 RI != RE; ++RI) {
1531 assert(RI->first && "InsnRange does not have first instruction!");
1532 assert(RI->second && "InsnRange does not have second instruction!");
1533 requestLabelBeforeInsn(RI->first);
1534 requestLabelAfterInsn(RI->second);
1535 }
1536 }
1537 }
1539 // Get MDNode for DebugLoc's scope.
1540 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1541 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1542 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1543 return DL.getScope(Ctx);
1544 }
1546 // Walk up the scope chain of given debug loc and find line number info
1547 // for the function.
1548 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1549 const MDNode *Scope = getScopeNode(DL, Ctx);
1550 DISubprogram SP = getDISubprogram(Scope);
1551 if (SP.isSubprogram()) {
1552 // Check for number of operands since the compatibility is
1553 // cheap here.
1554 if (SP->getNumOperands() > 19)
1555 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1556 else
1557 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1558 }
1560 return DebugLoc();
1561 }
1563 // Gather pre-function debug information. Assumes being called immediately
1564 // after the function entry point has been emitted.
1565 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1566 CurFn = MF;
1568 // If there's no debug info for the function we're not going to do anything.
1569 if (!MMI->hasDebugInfo())
1570 return;
1572 // Grab the lexical scopes for the function, if we don't have any of those
1573 // then we're not going to be able to do anything.
1574 LScopes.initialize(*MF);
1575 if (LScopes.empty())
1576 return;
1578 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1580 // Make sure that each lexical scope will have a begin/end label.
1581 identifyScopeMarkers();
1583 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1584 // belongs to so that we add to the correct per-cu line table in the
1585 // non-asm case.
1586 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1587 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1588 assert(TheCU && "Unable to find compile unit!");
1589 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1590 // Use a single line table if we are using .loc and generating assembly.
1591 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1592 else
1593 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1595 // Emit a label for the function so that we have a beginning address.
1596 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1597 // Assumes in correct section after the entry point.
1598 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1600 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1601 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1602 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1604 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1605 ++I) {
1606 bool AtBlockEntry = true;
1607 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1608 II != IE; ++II) {
1609 const MachineInstr *MI = II;
1611 if (MI->isDebugValue()) {
1612 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1614 // Keep track of user variables.
1615 const MDNode *Var =
1616 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1618 // Variable is in a register, we need to check for clobbers.
1619 if (isDbgValueInDefinedReg(MI))
1620 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1622 // Check the history of this variable.
1623 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1624 if (History.empty()) {
1625 UserVariables.push_back(Var);
1626 // The first mention of a function argument gets the FunctionBeginSym
1627 // label, so arguments are visible when breaking at function entry.
1628 DIVariable DV(Var);
1629 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1630 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1631 LabelsBeforeInsn[MI] = FunctionBeginSym;
1632 } else {
1633 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1634 const MachineInstr *Prev = History.back();
1635 if (Prev->isDebugValue()) {
1636 // Coalesce identical entries at the end of History.
1637 if (History.size() >= 2 &&
1638 Prev->isIdenticalTo(History[History.size() - 2])) {
1639 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1640 << "\t" << *Prev << "\t"
1641 << *History[History.size() - 2] << "\n");
1642 History.pop_back();
1643 }
1645 // Terminate old register assignments that don't reach MI;
1646 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1647 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1648 isDbgValueInDefinedReg(Prev)) {
1649 // Previous register assignment needs to terminate at the end of
1650 // its basic block.
1651 MachineBasicBlock::const_iterator LastMI =
1652 PrevMBB->getLastNonDebugInstr();
1653 if (LastMI == PrevMBB->end()) {
1654 // Drop DBG_VALUE for empty range.
1655 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1656 << "\t" << *Prev << "\n");
1657 History.pop_back();
1658 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1659 // Terminate after LastMI.
1660 History.push_back(LastMI);
1661 }
1662 }
1663 }
1664 History.push_back(MI);
1665 } else {
1666 // Not a DBG_VALUE instruction.
1667 if (!MI->isLabel())
1668 AtBlockEntry = false;
1670 // First known non-DBG_VALUE and non-frame setup location marks
1671 // the beginning of the function body.
1672 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1673 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1674 PrologEndLoc = MI->getDebugLoc();
1676 // Check if the instruction clobbers any registers with debug vars.
1677 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1678 MOE = MI->operands_end();
1679 MOI != MOE; ++MOI) {
1680 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1681 continue;
1682 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1683 ++AI) {
1684 unsigned Reg = *AI;
1685 const MDNode *Var = LiveUserVar[Reg];
1686 if (!Var)
1687 continue;
1688 // Reg is now clobbered.
1689 LiveUserVar[Reg] = 0;
1691 // Was MD last defined by a DBG_VALUE referring to Reg?
1692 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1693 if (HistI == DbgValues.end())
1694 continue;
1695 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1696 if (History.empty())
1697 continue;
1698 const MachineInstr *Prev = History.back();
1699 // Sanity-check: Register assignments are terminated at the end of
1700 // their block.
1701 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1702 continue;
1703 // Is the variable still in Reg?
1704 if (!isDbgValueInDefinedReg(Prev) ||
1705 Prev->getOperand(0).getReg() != Reg)
1706 continue;
1707 // Var is clobbered. Make sure the next instruction gets a label.
1708 History.push_back(MI);
1709 }
1710 }
1711 }
1712 }
1713 }
1715 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1716 I != E; ++I) {
1717 SmallVectorImpl<const MachineInstr *> &History = I->second;
1718 if (History.empty())
1719 continue;
1721 // Make sure the final register assignments are terminated.
1722 const MachineInstr *Prev = History.back();
1723 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1724 const MachineBasicBlock *PrevMBB = Prev->getParent();
1725 MachineBasicBlock::const_iterator LastMI =
1726 PrevMBB->getLastNonDebugInstr();
1727 if (LastMI == PrevMBB->end())
1728 // Drop DBG_VALUE for empty range.
1729 History.pop_back();
1730 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1731 // Terminate after LastMI.
1732 History.push_back(LastMI);
1733 }
1734 }
1735 // Request labels for the full history.
1736 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1737 const MachineInstr *MI = History[i];
1738 if (MI->isDebugValue())
1739 requestLabelBeforeInsn(MI);
1740 else
1741 requestLabelAfterInsn(MI);
1742 }
1743 }
1745 PrevInstLoc = DebugLoc();
1746 PrevLabel = FunctionBeginSym;
1748 // Record beginning of function.
1749 if (!PrologEndLoc.isUnknown()) {
1750 DebugLoc FnStartDL =
1751 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1752 recordSourceLine(
1753 FnStartDL.getLine(), FnStartDL.getCol(),
1754 FnStartDL.getScope(MF->getFunction()->getContext()),
1755 // We'd like to list the prologue as "not statements" but GDB behaves
1756 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1757 DWARF2_FLAG_IS_STMT);
1758 }
1759 }
1761 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1762 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1763 DIVariable DV = Var->getVariable();
1764 // Variables with positive arg numbers are parameters.
1765 if (unsigned ArgNum = DV.getArgNumber()) {
1766 // Keep all parameters in order at the start of the variable list to ensure
1767 // function types are correct (no out-of-order parameters)
1768 //
1769 // This could be improved by only doing it for optimized builds (unoptimized
1770 // builds have the right order to begin with), searching from the back (this
1771 // would catch the unoptimized case quickly), or doing a binary search
1772 // rather than linear search.
1773 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1774 while (I != Vars.end()) {
1775 unsigned CurNum = (*I)->getVariable().getArgNumber();
1776 // A local (non-parameter) variable has been found, insert immediately
1777 // before it.
1778 if (CurNum == 0)
1779 break;
1780 // A later indexed parameter has been found, insert immediately before it.
1781 if (CurNum > ArgNum)
1782 break;
1783 ++I;
1784 }
1785 Vars.insert(I, Var);
1786 return;
1787 }
1789 Vars.push_back(Var);
1790 }
1792 // Gather and emit post-function debug information.
1793 void DwarfDebug::endFunction(const MachineFunction *MF) {
1794 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1795 // though the beginFunction may not be called at all.
1796 // We should handle both cases.
1797 if (CurFn == 0)
1798 CurFn = MF;
1799 else
1800 assert(CurFn == MF);
1801 assert(CurFn != 0);
1803 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1804 CurFn = 0;
1805 return;
1806 }
1808 // Define end label for subprogram.
1809 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1810 // Assumes in correct section after the entry point.
1811 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1812 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1813 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1815 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1816 collectVariableInfo(ProcessedVars);
1818 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1819 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1820 assert(TheCU && "Unable to find compile unit!");
1822 // Construct abstract scopes.
1823 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1824 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1825 LexicalScope *AScope = AList[i];
1826 DISubprogram SP(AScope->getScopeNode());
1827 if (SP.isSubprogram()) {
1828 // Collect info for variables that were optimized out.
1829 DIArray Variables = SP.getVariables();
1830 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1831 DIVariable DV(Variables.getElement(i));
1832 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1833 continue;
1834 // Check that DbgVariable for DV wasn't created earlier, when
1835 // findAbstractVariable() was called for inlined instance of DV.
1836 LLVMContext &Ctx = DV->getContext();
1837 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1838 if (AbstractVariables.lookup(CleanDV))
1839 continue;
1840 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1841 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1842 }
1843 }
1844 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1845 constructScopeDIE(TheCU, AScope);
1846 }
1848 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1850 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1851 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1853 // Clear debug info
1854 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1855 E = ScopeVariables.end();
1856 I != E; ++I)
1857 DeleteContainerPointers(I->second);
1858 ScopeVariables.clear();
1859 DeleteContainerPointers(CurrentFnArguments);
1860 UserVariables.clear();
1861 DbgValues.clear();
1862 AbstractVariables.clear();
1863 LabelsBeforeInsn.clear();
1864 LabelsAfterInsn.clear();
1865 PrevLabel = NULL;
1866 CurFn = 0;
1867 }
1869 // Register a source line with debug info. Returns the unique label that was
1870 // emitted and which provides correspondence to the source line list.
1871 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1872 unsigned Flags) {
1873 StringRef Fn;
1874 StringRef Dir;
1875 unsigned Src = 1;
1876 if (S) {
1877 DIDescriptor Scope(S);
1879 if (Scope.isCompileUnit()) {
1880 DICompileUnit CU(S);
1881 Fn = CU.getFilename();
1882 Dir = CU.getDirectory();
1883 } else if (Scope.isFile()) {
1884 DIFile F(S);
1885 Fn = F.getFilename();
1886 Dir = F.getDirectory();
1887 } else if (Scope.isSubprogram()) {
1888 DISubprogram SP(S);
1889 Fn = SP.getFilename();
1890 Dir = SP.getDirectory();
1891 } else if (Scope.isLexicalBlockFile()) {
1892 DILexicalBlockFile DBF(S);
1893 Fn = DBF.getFilename();
1894 Dir = DBF.getDirectory();
1895 } else if (Scope.isLexicalBlock()) {
1896 DILexicalBlock DB(S);
1897 Fn = DB.getFilename();
1898 Dir = DB.getDirectory();
1899 } else
1900 llvm_unreachable("Unexpected scope info");
1902 Src = getOrCreateSourceID(
1903 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1904 }
1905 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1906 }
1908 //===----------------------------------------------------------------------===//
1909 // Emit Methods
1910 //===----------------------------------------------------------------------===//
1912 // Compute the size and offset of a DIE. The offset is relative to start of the
1913 // CU. It returns the offset after laying out the DIE.
1914 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1915 // Get the children.
1916 const std::vector<DIE *> &Children = Die->getChildren();
1918 // Record the abbreviation.
1919 assignAbbrevNumber(Die->getAbbrev());
1921 // Get the abbreviation for this DIE.
1922 const DIEAbbrev &Abbrev = Die->getAbbrev();
1924 // Set DIE offset
1925 Die->setOffset(Offset);
1927 // Start the size with the size of abbreviation code.
1928 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1930 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1931 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1933 // Size the DIE attribute values.
1934 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1935 // Size attribute value.
1936 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1938 // Size the DIE children if any.
1939 if (!Children.empty()) {
1940 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1941 "Children flag not set");
1943 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1944 Offset = computeSizeAndOffset(Children[j], Offset);
1946 // End of children marker.
1947 Offset += sizeof(int8_t);
1948 }
1950 Die->setSize(Offset - Die->getOffset());
1951 return Offset;
1952 }
1954 // Compute the size and offset for each DIE.
1955 void DwarfFile::computeSizeAndOffsets() {
1956 // Offset from the first CU in the debug info section is 0 initially.
1957 unsigned SecOffset = 0;
1959 // Iterate over each compile unit and set the size and offsets for each
1960 // DIE within each compile unit. All offsets are CU relative.
1961 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1962 E = CUs.end();
1963 I != E; ++I) {
1964 (*I)->setDebugInfoOffset(SecOffset);
1966 // CU-relative offset is reset to 0 here.
1967 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1968 (*I)->getHeaderSize(); // Unit-specific headers
1970 // EndOffset here is CU-relative, after laying out
1971 // all of the CU DIE.
1972 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1973 SecOffset += EndOffset;
1974 }
1975 }
1977 // Emit initial Dwarf sections with a label at the start of each one.
1978 void DwarfDebug::emitSectionLabels() {
1979 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1981 // Dwarf sections base addresses.
1982 DwarfInfoSectionSym =
1983 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1984 if (useSplitDwarf())
1985 DwarfInfoDWOSectionSym =
1986 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1987 DwarfAbbrevSectionSym =
1988 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1989 if (useSplitDwarf())
1990 DwarfAbbrevDWOSectionSym = emitSectionSym(
1991 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1992 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1994 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1995 emitSectionSym(Asm, MacroInfo);
1997 DwarfLineSectionSym =
1998 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1999 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2000 if (GenerateGnuPubSections) {
2001 DwarfGnuPubNamesSectionSym =
2002 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2003 DwarfGnuPubTypesSectionSym =
2004 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2005 } else if (HasDwarfPubSections) {
2006 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2007 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2008 }
2010 DwarfStrSectionSym =
2011 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2012 if (useSplitDwarf()) {
2013 DwarfStrDWOSectionSym =
2014 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2015 DwarfAddrSectionSym =
2016 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2017 }
2018 DwarfDebugRangeSectionSym =
2019 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2021 DwarfDebugLocSectionSym =
2022 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2024 TextSectionBeginSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2025 }
2027 // Recursively emits a debug information entry.
2028 void DwarfDebug::emitDIE(DIE *Die) {
2029 // Get the abbreviation for this DIE.
2030 const DIEAbbrev &Abbrev = Die->getAbbrev();
2032 // Emit the code (index) for the abbreviation.
2033 if (Asm->isVerbose())
2034 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2035 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2036 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2037 dwarf::TagString(Abbrev.getTag()));
2038 Asm->EmitULEB128(Abbrev.getNumber());
2040 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2041 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2043 // Emit the DIE attribute values.
2044 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2045 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2046 dwarf::Form Form = AbbrevData[i].getForm();
2047 assert(Form && "Too many attributes for DIE (check abbreviation)");
2049 if (Asm->isVerbose())
2050 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2052 switch (Attr) {
2053 case dwarf::DW_AT_abstract_origin:
2054 case dwarf::DW_AT_type:
2055 case dwarf::DW_AT_friend:
2056 case dwarf::DW_AT_specification:
2057 case dwarf::DW_AT_import:
2058 case dwarf::DW_AT_containing_type: {
2059 DIEEntry *E = cast<DIEEntry>(Values[i]);
2060 DIE *Origin = E->getEntry();
2061 unsigned Addr = Origin->getOffset();
2062 if (Form == dwarf::DW_FORM_ref_addr) {
2063 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2064 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2065 // section. Origin->getOffset() returns the offset from start of the
2066 // compile unit.
2067 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2068 assert(CU && "CUDie should belong to a CU.");
2069 Addr += CU->getDebugInfoOffset();
2070 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2071 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2072 DIEEntry::getRefAddrSize(Asm));
2073 else
2074 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2075 CU->getSectionSym(),
2076 DIEEntry::getRefAddrSize(Asm));
2077 } else {
2078 // Make sure Origin belong to the same CU.
2079 assert(Die->getUnit() == Origin->getUnit() &&
2080 "The referenced DIE should belong to the same CU in ref4");
2081 Asm->EmitInt32(Addr);
2082 }
2083 break;
2084 }
2085 case dwarf::DW_AT_location: {
2086 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2087 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2088 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2089 else
2090 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2091 } else {
2092 Values[i]->EmitValue(Asm, Form);
2093 }
2094 break;
2095 }
2096 case dwarf::DW_AT_accessibility: {
2097 if (Asm->isVerbose()) {
2098 DIEInteger *V = cast<DIEInteger>(Values[i]);
2099 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2100 }
2101 Values[i]->EmitValue(Asm, Form);
2102 break;
2103 }
2104 default:
2105 // Emit an attribute using the defined form.
2106 Values[i]->EmitValue(Asm, Form);
2107 break;
2108 }
2109 }
2111 // Emit the DIE children if any.
2112 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2113 const std::vector<DIE *> &Children = Die->getChildren();
2115 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2116 emitDIE(Children[j]);
2118 Asm->OutStreamer.AddComment("End Of Children Mark");
2119 Asm->EmitInt8(0);
2120 }
2121 }
2123 // Emit the various dwarf units to the unit section USection with
2124 // the abbreviations going into ASection.
2125 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2126 const MCSymbol *ASectionSym) {
2127 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2128 I != E; ++I) {
2129 DwarfUnit *TheU = *I;
2130 DIE *Die = TheU->getUnitDie();
2131 const MCSection *USection = TheU->getSection();
2132 Asm->OutStreamer.SwitchSection(USection);
2134 // Emit the compile units header.
2135 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2137 // Emit size of content not including length itself
2138 Asm->OutStreamer.AddComment("Length of Unit");
2139 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2141 TheU->emitHeader(ASection, ASectionSym);
2143 DD->emitDIE(Die);
2144 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2145 }
2146 }
2148 // Emit the debug info section.
2149 void DwarfDebug::emitDebugInfo() {
2150 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2152 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2153 DwarfAbbrevSectionSym);
2154 }
2156 // Emit the abbreviation section.
2157 void DwarfDebug::emitAbbreviations() {
2158 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2160 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2161 }
2163 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2164 // Check to see if it is worth the effort.
2165 if (!Abbreviations.empty()) {
2166 // Start the debug abbrev section.
2167 Asm->OutStreamer.SwitchSection(Section);
2169 // For each abbrevation.
2170 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2171 // Get abbreviation data
2172 const DIEAbbrev *Abbrev = Abbreviations[i];
2174 // Emit the abbrevations code (base 1 index.)
2175 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2177 // Emit the abbreviations data.
2178 Abbrev->Emit(Asm);
2179 }
2181 // Mark end of abbreviations.
2182 Asm->EmitULEB128(0, "EOM(3)");
2183 }
2184 }
2186 // Emit the last address of the section and the end of the line matrix.
2187 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2188 // Define last address of section.
2189 Asm->OutStreamer.AddComment("Extended Op");
2190 Asm->EmitInt8(0);
2192 Asm->OutStreamer.AddComment("Op size");
2193 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2194 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2195 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2197 Asm->OutStreamer.AddComment("Section end label");
2199 Asm->OutStreamer.EmitSymbolValue(
2200 Asm->GetTempSymbol("section_end", SectionEnd),
2201 Asm->getDataLayout().getPointerSize());
2203 // Mark end of matrix.
2204 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2205 Asm->EmitInt8(0);
2206 Asm->EmitInt8(1);
2207 Asm->EmitInt8(1);
2208 }
2210 // Emit visible names into a hashed accelerator table section.
2211 void DwarfDebug::emitAccelNames() {
2212 DwarfAccelTable AT(
2213 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2214 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2215 E = getUnits().end();
2216 I != E; ++I) {
2217 DwarfUnit *TheU = *I;
2218 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2219 for (StringMap<std::vector<const DIE *> >::const_iterator
2220 GI = Names.begin(),
2221 GE = Names.end();
2222 GI != GE; ++GI) {
2223 StringRef Name = GI->getKey();
2224 const std::vector<const DIE *> &Entities = GI->second;
2225 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2226 DE = Entities.end();
2227 DI != DE; ++DI)
2228 AT.AddName(Name, *DI);
2229 }
2230 }
2232 AT.FinalizeTable(Asm, "Names");
2233 Asm->OutStreamer.SwitchSection(
2234 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2235 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2236 Asm->OutStreamer.EmitLabel(SectionBegin);
2238 // Emit the full data.
2239 AT.Emit(Asm, SectionBegin, &InfoHolder);
2240 }
2242 // Emit objective C classes and categories into a hashed accelerator table
2243 // section.
2244 void DwarfDebug::emitAccelObjC() {
2245 DwarfAccelTable AT(
2246 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2247 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2248 E = getUnits().end();
2249 I != E; ++I) {
2250 DwarfUnit *TheU = *I;
2251 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2252 for (StringMap<std::vector<const DIE *> >::const_iterator
2253 GI = Names.begin(),
2254 GE = Names.end();
2255 GI != GE; ++GI) {
2256 StringRef Name = GI->getKey();
2257 const std::vector<const DIE *> &Entities = GI->second;
2258 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2259 DE = Entities.end();
2260 DI != DE; ++DI)
2261 AT.AddName(Name, *DI);
2262 }
2263 }
2265 AT.FinalizeTable(Asm, "ObjC");
2266 Asm->OutStreamer.SwitchSection(
2267 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2268 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2269 Asm->OutStreamer.EmitLabel(SectionBegin);
2271 // Emit the full data.
2272 AT.Emit(Asm, SectionBegin, &InfoHolder);
2273 }
2275 // Emit namespace dies into a hashed accelerator table.
2276 void DwarfDebug::emitAccelNamespaces() {
2277 DwarfAccelTable AT(
2278 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2279 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2280 E = getUnits().end();
2281 I != E; ++I) {
2282 DwarfUnit *TheU = *I;
2283 const StringMap<std::vector<const DIE *> > &Names =
2284 TheU->getAccelNamespace();
2285 for (StringMap<std::vector<const DIE *> >::const_iterator
2286 GI = Names.begin(),
2287 GE = Names.end();
2288 GI != GE; ++GI) {
2289 StringRef Name = GI->getKey();
2290 const std::vector<const DIE *> &Entities = GI->second;
2291 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2292 DE = Entities.end();
2293 DI != DE; ++DI)
2294 AT.AddName(Name, *DI);
2295 }
2296 }
2298 AT.FinalizeTable(Asm, "namespac");
2299 Asm->OutStreamer.SwitchSection(
2300 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2301 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2302 Asm->OutStreamer.EmitLabel(SectionBegin);
2304 // Emit the full data.
2305 AT.Emit(Asm, SectionBegin, &InfoHolder);
2306 }
2308 // Emit type dies into a hashed accelerator table.
2309 void DwarfDebug::emitAccelTypes() {
2310 std::vector<DwarfAccelTable::Atom> Atoms;
2311 Atoms.push_back(
2312 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2313 Atoms.push_back(
2314 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2315 Atoms.push_back(
2316 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2317 DwarfAccelTable AT(Atoms);
2318 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2319 E = getUnits().end();
2320 I != E; ++I) {
2321 DwarfUnit *TheU = *I;
2322 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2323 TheU->getAccelTypes();
2324 for (StringMap<
2325 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2326 GI = Names.begin(),
2327 GE = Names.end();
2328 GI != GE; ++GI) {
2329 StringRef Name = GI->getKey();
2330 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2331 GI->second;
2332 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2333 DI = Entities.begin(),
2334 DE = Entities.end();
2335 DI != DE; ++DI)
2336 AT.AddName(Name, DI->first, DI->second);
2337 }
2338 }
2340 AT.FinalizeTable(Asm, "types");
2341 Asm->OutStreamer.SwitchSection(
2342 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2343 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2344 Asm->OutStreamer.EmitLabel(SectionBegin);
2346 // Emit the full data.
2347 AT.Emit(Asm, SectionBegin, &InfoHolder);
2348 }
2350 // Public name handling.
2351 // The format for the various pubnames:
2352 //
2353 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2354 // for the DIE that is named.
2355 //
2356 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2357 // into the CU and the index value is computed according to the type of value
2358 // for the DIE that is named.
2359 //
2360 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2361 // it's the offset within the debug_info/debug_types dwo section, however, the
2362 // reference in the pubname header doesn't change.
2364 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2365 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2366 const DIE *Die) {
2367 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2369 // We could have a specification DIE that has our most of our knowledge,
2370 // look for that now.
2371 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2372 if (SpecVal) {
2373 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2374 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2375 Linkage = dwarf::GIEL_EXTERNAL;
2376 } else if (Die->findAttribute(dwarf::DW_AT_external))
2377 Linkage = dwarf::GIEL_EXTERNAL;
2379 switch (Die->getTag()) {
2380 case dwarf::DW_TAG_class_type:
2381 case dwarf::DW_TAG_structure_type:
2382 case dwarf::DW_TAG_union_type:
2383 case dwarf::DW_TAG_enumeration_type:
2384 return dwarf::PubIndexEntryDescriptor(
2385 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2386 ? dwarf::GIEL_STATIC
2387 : dwarf::GIEL_EXTERNAL);
2388 case dwarf::DW_TAG_typedef:
2389 case dwarf::DW_TAG_base_type:
2390 case dwarf::DW_TAG_subrange_type:
2391 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2392 case dwarf::DW_TAG_namespace:
2393 return dwarf::GIEK_TYPE;
2394 case dwarf::DW_TAG_subprogram:
2395 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2396 case dwarf::DW_TAG_constant:
2397 case dwarf::DW_TAG_variable:
2398 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2399 case dwarf::DW_TAG_enumerator:
2400 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2401 dwarf::GIEL_STATIC);
2402 default:
2403 return dwarf::GIEK_NONE;
2404 }
2405 }
2407 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2408 ///
2409 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2410 const MCSection *PSec =
2411 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2412 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2414 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2415 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2416 for (unsigned i = 0; i != Units.size(); ++i) {
2417 DwarfUnit *TheU = Units[i];
2418 unsigned ID = TheU->getUniqueID();
2420 // Start the dwarf pubnames section.
2421 Asm->OutStreamer.SwitchSection(PSec);
2423 // Emit a label so we can reference the beginning of this pubname section.
2424 if (GnuStyle)
2425 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2427 // Emit the header.
2428 Asm->OutStreamer.AddComment("Length of Public Names Info");
2429 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2430 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2431 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2433 Asm->OutStreamer.EmitLabel(BeginLabel);
2435 Asm->OutStreamer.AddComment("DWARF Version");
2436 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2438 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2439 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2441 Asm->OutStreamer.AddComment("Compilation Unit Length");
2442 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2444 // Emit the pubnames for this compilation unit.
2445 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2446 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2447 GE = Globals.end();
2448 GI != GE; ++GI) {
2449 const char *Name = GI->getKeyData();
2450 const DIE *Entity = GI->second;
2452 Asm->OutStreamer.AddComment("DIE offset");
2453 Asm->EmitInt32(Entity->getOffset());
2455 if (GnuStyle) {
2456 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2457 Asm->OutStreamer.AddComment(
2458 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2459 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2460 Asm->EmitInt8(Desc.toBits());
2461 }
2463 Asm->OutStreamer.AddComment("External Name");
2464 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2465 }
2467 Asm->OutStreamer.AddComment("End Mark");
2468 Asm->EmitInt32(0);
2469 Asm->OutStreamer.EmitLabel(EndLabel);
2470 }
2471 }
2473 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2474 const MCSection *PSec =
2475 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2476 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2478 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2479 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2480 for (unsigned i = 0; i != Units.size(); ++i) {
2481 DwarfUnit *TheU = Units[i];
2482 unsigned ID = TheU->getUniqueID();
2484 // Start the dwarf pubtypes section.
2485 Asm->OutStreamer.SwitchSection(PSec);
2487 // Emit a label so we can reference the beginning of this pubtype section.
2488 if (GnuStyle)
2489 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2491 // Emit the header.
2492 Asm->OutStreamer.AddComment("Length of Public Types Info");
2493 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2494 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2495 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2497 Asm->OutStreamer.EmitLabel(BeginLabel);
2499 Asm->OutStreamer.AddComment("DWARF Version");
2500 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2502 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2503 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2505 Asm->OutStreamer.AddComment("Compilation Unit Length");
2506 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2508 // Emit the pubtypes.
2509 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2510 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2511 GE = Globals.end();
2512 GI != GE; ++GI) {
2513 const char *Name = GI->getKeyData();
2514 const DIE *Entity = GI->second;
2516 Asm->OutStreamer.AddComment("DIE offset");
2517 Asm->EmitInt32(Entity->getOffset());
2519 if (GnuStyle) {
2520 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2521 Asm->OutStreamer.AddComment(
2522 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2523 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2524 Asm->EmitInt8(Desc.toBits());
2525 }
2527 Asm->OutStreamer.AddComment("External Name");
2529 // Emit the name with a terminating null byte.
2530 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2531 }
2533 Asm->OutStreamer.AddComment("End Mark");
2534 Asm->EmitInt32(0);
2535 Asm->OutStreamer.EmitLabel(EndLabel);
2536 }
2537 }
2539 // Emit strings into a string section.
2540 void DwarfFile::emitStrings(const MCSection *StrSection,
2541 const MCSection *OffsetSection = NULL,
2542 const MCSymbol *StrSecSym = NULL) {
2544 if (StringPool.empty())
2545 return;
2547 // Start the dwarf str section.
2548 Asm->OutStreamer.SwitchSection(StrSection);
2550 // Get all of the string pool entries and put them in an array by their ID so
2551 // we can sort them.
2552 SmallVector<
2553 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2554 64> Entries;
2556 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2557 I = StringPool.begin(),
2558 E = StringPool.end();
2559 I != E; ++I)
2560 Entries.push_back(std::make_pair(I->second.second, &*I));
2562 array_pod_sort(Entries.begin(), Entries.end());
2564 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2565 // Emit a label for reference from debug information entries.
2566 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2568 // Emit the string itself with a terminating null byte.
2569 Asm->OutStreamer.EmitBytes(
2570 StringRef(Entries[i].second->getKeyData(),
2571 Entries[i].second->getKeyLength() + 1));
2572 }
2574 // If we've got an offset section go ahead and emit that now as well.
2575 if (OffsetSection) {
2576 Asm->OutStreamer.SwitchSection(OffsetSection);
2577 unsigned offset = 0;
2578 unsigned size = 4; // FIXME: DWARF64 is 8.
2579 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2580 Asm->OutStreamer.EmitIntValue(offset, size);
2581 offset += Entries[i].second->getKeyLength() + 1;
2582 }
2583 }
2584 }
2586 // Emit addresses into the section given.
2587 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2589 if (AddressPool.empty())
2590 return;
2592 // Start the dwarf addr section.
2593 Asm->OutStreamer.SwitchSection(AddrSection);
2595 // Order the address pool entries by ID
2596 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2598 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2599 E = AddressPool.end();
2600 I != E; ++I)
2601 Entries[I->second] = I->first;
2603 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2604 // Emit an expression for reference from debug information entries.
2605 if (const MCExpr *Expr = Entries[i])
2606 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2607 else
2608 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2609 }
2610 }
2612 // Emit visible names into a debug str section.
2613 void DwarfDebug::emitDebugStr() {
2614 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2615 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2616 }
2618 // Emit locations into the debug loc section.
2619 void DwarfDebug::emitDebugLoc() {
2620 if (DotDebugLocEntries.empty())
2621 return;
2623 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2624 I = DotDebugLocEntries.begin(),
2625 E = DotDebugLocEntries.end();
2626 I != E; ++I) {
2627 DotDebugLocEntry &Entry = *I;
2628 if (I + 1 != DotDebugLocEntries.end())
2629 Entry.Merge(I + 1);
2630 }
2632 // Start the dwarf loc section.
2633 Asm->OutStreamer.SwitchSection(
2634 Asm->getObjFileLowering().getDwarfLocSection());
2635 unsigned char Size = Asm->getDataLayout().getPointerSize();
2636 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2637 unsigned index = 1;
2638 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2639 I = DotDebugLocEntries.begin(),
2640 E = DotDebugLocEntries.end();
2641 I != E; ++I, ++index) {
2642 DotDebugLocEntry &Entry = *I;
2643 if (Entry.isMerged())
2644 continue;
2645 if (Entry.isEmpty()) {
2646 Asm->OutStreamer.EmitIntValue(0, Size);
2647 Asm->OutStreamer.EmitIntValue(0, Size);
2648 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2649 } else {
2650 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2651 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2652 DIVariable DV(Entry.getVariable());
2653 Asm->OutStreamer.AddComment("Loc expr size");
2654 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2655 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2656 Asm->EmitLabelDifference(end, begin, 2);
2657 Asm->OutStreamer.EmitLabel(begin);
2658 if (Entry.isInt()) {
2659 DIBasicType BTy(DV.getType());
2660 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2661 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2662 Asm->OutStreamer.AddComment("DW_OP_consts");
2663 Asm->EmitInt8(dwarf::DW_OP_consts);
2664 Asm->EmitSLEB128(Entry.getInt());
2665 } else {
2666 Asm->OutStreamer.AddComment("DW_OP_constu");
2667 Asm->EmitInt8(dwarf::DW_OP_constu);
2668 Asm->EmitULEB128(Entry.getInt());
2669 }
2670 } else if (Entry.isLocation()) {
2671 MachineLocation Loc = Entry.getLoc();
2672 if (!DV.hasComplexAddress())
2673 // Regular entry.
2674 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2675 else {
2676 // Complex address entry.
2677 unsigned N = DV.getNumAddrElements();
2678 unsigned i = 0;
2679 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2680 if (Loc.getOffset()) {
2681 i = 2;
2682 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2683 Asm->OutStreamer.AddComment("DW_OP_deref");
2684 Asm->EmitInt8(dwarf::DW_OP_deref);
2685 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2686 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2687 Asm->EmitSLEB128(DV.getAddrElement(1));
2688 } else {
2689 // If first address element is OpPlus then emit
2690 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2691 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2692 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2693 i = 2;
2694 }
2695 } else {
2696 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2697 }
2699 // Emit remaining complex address elements.
2700 for (; i < N; ++i) {
2701 uint64_t Element = DV.getAddrElement(i);
2702 if (Element == DIBuilder::OpPlus) {
2703 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2704 Asm->EmitULEB128(DV.getAddrElement(++i));
2705 } else if (Element == DIBuilder::OpDeref) {
2706 if (!Loc.isReg())
2707 Asm->EmitInt8(dwarf::DW_OP_deref);
2708 } else
2709 llvm_unreachable("unknown Opcode found in complex address");
2710 }
2711 }
2712 }
2713 // else ... ignore constant fp. There is not any good way to
2714 // to represent them here in dwarf.
2715 Asm->OutStreamer.EmitLabel(end);
2716 }
2717 }
2718 }
2720 struct SymbolCUSorter {
2721 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2722 const MCStreamer &Streamer;
2724 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2725 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2726 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2728 // Symbols with no order assigned should be placed at the end.
2729 // (e.g. section end labels)
2730 if (IA == 0)
2731 IA = (unsigned)(-1);
2732 if (IB == 0)
2733 IB = (unsigned)(-1);
2734 return IA < IB;
2735 }
2736 };
2738 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2739 return (A->getUniqueID() < B->getUniqueID());
2740 }
2742 struct ArangeSpan {
2743 const MCSymbol *Start, *End;
2744 };
2746 // Emit a debug aranges section, containing a CU lookup for any
2747 // address we can tie back to a CU.
2748 void DwarfDebug::emitDebugARanges() {
2749 // Start the dwarf aranges section.
2750 Asm->OutStreamer.SwitchSection(
2751 Asm->getObjFileLowering().getDwarfARangesSection());
2753 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2755 SpansType Spans;
2757 // Build a list of sections used.
2758 std::vector<const MCSection *> Sections;
2759 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2760 it++) {
2761 const MCSection *Section = it->first;
2762 Sections.push_back(Section);
2763 }
2765 // Sort the sections into order.
2766 // This is only done to ensure consistent output order across different runs.
2767 std::sort(Sections.begin(), Sections.end(), SectionSort);
2769 // Build a set of address spans, sorted by CU.
2770 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2771 const MCSection *Section = Sections[SecIdx];
2772 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2773 if (List.size() < 2)
2774 continue;
2776 // Sort the symbols by offset within the section.
2777 SymbolCUSorter sorter(Asm->OutStreamer);
2778 std::sort(List.begin(), List.end(), sorter);
2780 // If we have no section (e.g. common), just write out
2781 // individual spans for each symbol.
2782 if (Section == NULL) {
2783 for (size_t n = 0; n < List.size(); n++) {
2784 const SymbolCU &Cur = List[n];
2786 ArangeSpan Span;
2787 Span.Start = Cur.Sym;
2788 Span.End = NULL;
2789 if (Cur.CU)
2790 Spans[Cur.CU].push_back(Span);
2791 }
2792 } else {
2793 // Build spans between each label.
2794 const MCSymbol *StartSym = List[0].Sym;
2795 for (size_t n = 1; n < List.size(); n++) {
2796 const SymbolCU &Prev = List[n - 1];
2797 const SymbolCU &Cur = List[n];
2799 // Try and build the longest span we can within the same CU.
2800 if (Cur.CU != Prev.CU) {
2801 ArangeSpan Span;
2802 Span.Start = StartSym;
2803 Span.End = Cur.Sym;
2804 Spans[Prev.CU].push_back(Span);
2805 StartSym = Cur.Sym;
2806 }
2807 }
2808 }
2809 }
2811 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2813 // Build a list of CUs used.
2814 std::vector<DwarfCompileUnit *> CUs;
2815 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2816 DwarfCompileUnit *CU = it->first;
2817 CUs.push_back(CU);
2818 }
2820 // Sort the CU list (again, to ensure consistent output order).
2821 std::sort(CUs.begin(), CUs.end(), CUSort);
2823 // Emit an arange table for each CU we used.
2824 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2825 DwarfCompileUnit *CU = CUs[CUIdx];
2826 std::vector<ArangeSpan> &List = Spans[CU];
2828 // Emit size of content not including length itself.
2829 unsigned ContentSize =
2830 sizeof(int16_t) + // DWARF ARange version number
2831 sizeof(int32_t) + // Offset of CU in the .debug_info section
2832 sizeof(int8_t) + // Pointer Size (in bytes)
2833 sizeof(int8_t); // Segment Size (in bytes)
2835 unsigned TupleSize = PtrSize * 2;
2837 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2838 unsigned Padding =
2839 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2841 ContentSize += Padding;
2842 ContentSize += (List.size() + 1) * TupleSize;
2844 // For each compile unit, write the list of spans it covers.
2845 Asm->OutStreamer.AddComment("Length of ARange Set");
2846 Asm->EmitInt32(ContentSize);
2847 Asm->OutStreamer.AddComment("DWARF Arange version number");
2848 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2849 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2850 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2851 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2852 Asm->EmitInt8(PtrSize);
2853 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2854 Asm->EmitInt8(0);
2856 Asm->OutStreamer.EmitFill(Padding, 0xff);
2858 for (unsigned n = 0; n < List.size(); n++) {
2859 const ArangeSpan &Span = List[n];
2860 Asm->EmitLabelReference(Span.Start, PtrSize);
2862 // Calculate the size as being from the span start to it's end.
2863 if (Span.End) {
2864 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2865 } else {
2866 // For symbols without an end marker (e.g. common), we
2867 // write a single arange entry containing just that one symbol.
2868 uint64_t Size = SymSize[Span.Start];
2869 if (Size == 0)
2870 Size = 1;
2872 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2873 }
2874 }
2876 Asm->OutStreamer.AddComment("ARange terminator");
2877 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2878 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2879 }
2880 }
2882 // Emit visible names into a debug ranges section.
2883 void DwarfDebug::emitDebugRanges() {
2884 // Start the dwarf ranges section.
2885 Asm->OutStreamer.SwitchSection(
2886 Asm->getObjFileLowering().getDwarfRangesSection());
2888 // Size for our labels.
2889 unsigned char Size = Asm->getDataLayout().getPointerSize();
2891 // Grab the specific ranges for the compile units in the module.
2892 for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2893 E = CUMap.end();
2894 I != E; ++I) {
2895 DwarfCompileUnit *TheCU = I->second;
2897 // Emit a symbol so we can find the beginning of our ranges.
2898 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2900 // Iterate over the misc ranges for the compile units in the module.
2901 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2902 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2903 E = RangeLists.end();
2904 I != E; ++I) {
2905 const RangeSpanList &List = *I;
2907 // Emit our symbol so we can find the beginning of the range.
2908 Asm->OutStreamer.EmitLabel(List.getSym());
2910 for (SmallVectorImpl<RangeSpan>::const_iterator
2911 RI = List.getRanges().begin(),
2912 RE = List.getRanges().end();
2913 RI != RE; ++RI) {
2914 const RangeSpan &Range = *RI;
2915 const MCSymbol *Begin = Range.getStart();
2916 const MCSymbol *End = Range.getEnd();
2917 assert(Begin && "Range without a begin symbol?");
2918 assert(End && "Range without an end symbol?");
2919 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2920 Asm->OutStreamer.EmitSymbolValue(End, Size);
2921 }
2923 // And terminate the list with two 0 values.
2924 Asm->OutStreamer.EmitIntValue(0, Size);
2925 Asm->OutStreamer.EmitIntValue(0, Size);
2926 }
2928 // Now emit a range for the CU itself.
2929 if (useCURanges()) {
2930 Asm->OutStreamer.EmitLabel(
2931 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2932 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2933 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2934 RangeSpan Range = Ranges[i];
2935 const MCSymbol *Begin = Range.getStart();
2936 const MCSymbol *End = Range.getEnd();
2937 assert(Begin && "Range without a begin symbol?");
2938 assert(End && "Range without an end symbol?");
2939 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2940 Asm->OutStreamer.EmitSymbolValue(End, Size);
2941 }
2942 // And terminate the list with two 0 values.
2943 Asm->OutStreamer.EmitIntValue(0, Size);
2944 Asm->OutStreamer.EmitIntValue(0, Size);
2945 }
2946 }
2947 }
2949 // DWARF5 Experimental Separate Dwarf emitters.
2951 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2952 DwarfUnit *NewU) {
2953 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2954 U->getCUNode().getSplitDebugFilename());
2956 // Relocate to the beginning of the addr_base section, else 0 for the
2957 // beginning of the one for this compile unit.
2958 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2959 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2960 else
2961 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2963 if (!CompilationDir.empty())
2964 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2966 addGnuPubAttributes(NewU, Die);
2968 SkeletonHolder.addUnit(NewU);
2969 }
2971 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2972 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2973 // DW_AT_ranges_base, DW_AT_addr_base.
2974 // TODO: Implement DW_AT_ranges_base.
2975 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2977 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2978 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2979 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2980 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2981 DwarfInfoSectionSym);
2983 // DW_AT_stmt_list is a offset of line number information for this
2984 // compile unit in debug_line section.
2985 // FIXME: Should handle multiple compile units.
2986 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2987 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2988 else
2989 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2991 initSkeletonUnit(CU, Die, NewCU);
2993 return NewCU;
2994 }
2996 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2997 // DW_AT_addr_base.
2998 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(const DwarfTypeUnit *TU) {
3000 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
3001 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3002 TU->getUniqueID(), Die, TU->getCUNode(), Asm, this, &SkeletonHolder);
3003 NewTU->setTypeSignature(TU->getTypeSignature());
3004 NewTU->setType(NULL);
3005 NewTU->initSection(
3006 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
3008 initSkeletonUnit(TU, Die, NewTU);
3009 return NewTU;
3010 }
3012 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3013 // compile units that would normally be in debug_info.
3014 void DwarfDebug::emitDebugInfoDWO() {
3015 assert(useSplitDwarf() && "No split dwarf debug info?");
3016 InfoHolder.emitUnits(this,
3017 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3018 DwarfAbbrevDWOSectionSym);
3019 }
3021 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3022 // abbreviations for the .debug_info.dwo section.
3023 void DwarfDebug::emitDebugAbbrevDWO() {
3024 assert(useSplitDwarf() && "No split dwarf?");
3025 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3026 }
3028 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3029 // string section and is identical in format to traditional .debug_str
3030 // sections.
3031 void DwarfDebug::emitDebugStrDWO() {
3032 assert(useSplitDwarf() && "No split dwarf?");
3033 const MCSection *OffSec =
3034 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3035 const MCSymbol *StrSym = DwarfStrSectionSym;
3036 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3037 OffSec, StrSym);
3038 }
3040 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3041 StringRef Identifier, DIE *RefDie,
3042 DICompositeType CTy) {
3044 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3045 if (TU) {
3046 CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);
3047 return;
3048 }
3050 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3051 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3052 InfoHolder.getUnits().size(), UnitDie, CUNode, Asm, this, &InfoHolder);
3053 TU = NewTU;
3054 InfoHolder.addUnit(NewTU);
3056 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3057 CUNode.getLanguage());
3059 MD5 Hash;
3060 Hash.update(Identifier);
3061 // ... take the least significant 8 bytes and return those. Our MD5
3062 // implementation always returns its results in little endian, swap bytes
3063 // appropriately.
3064 MD5::MD5Result Result;
3065 Hash.final(Result);
3066 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3067 NewTU->setTypeSignature(Signature);
3068 if (useSplitDwarf())
3069 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3071 NewTU->setType(NewTU->createTypeDIE(CTy));
3073 NewTU->initSection(
3074 useSplitDwarf()
3075 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3076 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3078 CUMap.begin()->second->addDIETypeSignature(RefDie, *NewTU);
3079 }