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/LEB128.h"
42 #include "llvm/Support/MD5.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/ValueHandle.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 using namespace llvm;
53 static cl::opt<bool>
54 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
55 cl::desc("Disable debug info printing"));
57 static cl::opt<bool> UnknownLocations(
58 "use-unknown-locations", cl::Hidden,
59 cl::desc("Make an absence of debug location information explicit."),
60 cl::init(false));
62 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
63 cl::desc("Add the CU hash as the dwo_id."),
64 cl::init(false));
66 static cl::opt<bool>
67 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
68 cl::desc("Generate GNU-style pubnames and pubtypes"),
69 cl::init(false));
71 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
72 cl::Hidden,
73 cl::desc("Generate dwarf aranges"),
74 cl::init(false));
76 namespace {
77 enum DefaultOnOff { Default, Enable, Disable };
78 }
80 static cl::opt<DefaultOnOff>
81 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
82 cl::desc("Output prototype dwarf accelerator tables."),
83 cl::values(clEnumVal(Default, "Default for platform"),
84 clEnumVal(Enable, "Enabled"),
85 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 cl::init(Default));
88 static cl::opt<DefaultOnOff>
89 SplitDwarf("split-dwarf", cl::Hidden,
90 cl::desc("Output DWARF5 split debug info."),
91 cl::values(clEnumVal(Default, "Default for platform"),
92 clEnumVal(Enable, "Enabled"),
93 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 cl::init(Default));
96 static cl::opt<DefaultOnOff>
97 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
98 cl::desc("Generate DWARF pubnames and pubtypes sections"),
99 cl::values(clEnumVal(Default, "Default for platform"),
100 clEnumVal(Enable, "Enabled"),
101 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 cl::init(Default));
104 static cl::opt<unsigned>
105 DwarfVersionNumber("dwarf-version", cl::Hidden,
106 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
108 static cl::opt<bool>
109 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
110 cl::desc("Generate DW_AT_ranges for compile units"),
111 cl::init(false));
113 static const char *const DWARFGroupName = "DWARF Emission";
114 static const char *const DbgTimerName = "DWARF Debug Writer";
116 //===----------------------------------------------------------------------===//
118 namespace llvm {
120 /// resolve - Look in the DwarfDebug map for the MDNode that
121 /// corresponds to the reference.
122 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
123 return DD->resolve(Ref);
124 }
126 DIType DbgVariable::getType() const {
127 DIType Ty = Var.getType();
128 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
129 // addresses instead.
130 if (Var.isBlockByrefVariable()) {
131 /* Byref variables, in Blocks, are declared by the programmer as
132 "SomeType VarName;", but the compiler creates a
133 __Block_byref_x_VarName struct, and gives the variable VarName
134 either the struct, or a pointer to the struct, as its type. This
135 is necessary for various behind-the-scenes things the compiler
136 needs to do with by-reference variables in blocks.
138 However, as far as the original *programmer* is concerned, the
139 variable should still have type 'SomeType', as originally declared.
141 The following function dives into the __Block_byref_x_VarName
142 struct to find the original type of the variable. This will be
143 passed back to the code generating the type for the Debug
144 Information Entry for the variable 'VarName'. 'VarName' will then
145 have the original type 'SomeType' in its debug information.
147 The original type 'SomeType' will be the type of the field named
148 'VarName' inside the __Block_byref_x_VarName struct.
150 NOTE: In order for this to not completely fail on the debugger
151 side, the Debug Information Entry for the variable VarName needs to
152 have a DW_AT_location that tells the debugger how to unwind through
153 the pointers and __Block_byref_x_VarName struct to find the actual
154 value of the variable. The function addBlockByrefType does this. */
155 DIType subType = Ty;
156 uint16_t tag = Ty.getTag();
158 if (tag == dwarf::DW_TAG_pointer_type)
159 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
161 DIArray Elements = DICompositeType(subType).getTypeArray();
162 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
163 DIDerivedType DT(Elements.getElement(i));
164 if (getName() == DT.getName())
165 return (resolve(DT.getTypeDerivedFrom()));
166 }
167 }
168 return Ty;
169 }
171 } // end llvm namespace
173 /// Return Dwarf Version by checking module flags.
174 static unsigned getDwarfVersionFromModule(const Module *M) {
175 Value *Val = M->getModuleFlag("Dwarf Version");
176 if (!Val)
177 return dwarf::DWARF_VERSION;
178 return cast<ConstantInt>(Val)->getZExtValue();
179 }
181 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
182 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
183 PrevLabel(NULL), GlobalRangeCount(0),
184 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
185 UsedNonDefaultText(false),
186 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
188 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
189 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
190 DwarfAddrSectionSym = 0;
191 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
192 FunctionBeginSym = FunctionEndSym = 0;
193 CurFn = 0;
194 CurMI = 0;
196 // Turn on accelerator tables for Darwin by default, pubnames by
197 // default for non-Darwin, and handle split dwarf.
198 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
200 if (DwarfAccelTables == Default)
201 HasDwarfAccelTables = IsDarwin;
202 else
203 HasDwarfAccelTables = DwarfAccelTables == Enable;
205 if (SplitDwarf == Default)
206 HasSplitDwarf = false;
207 else
208 HasSplitDwarf = SplitDwarf == Enable;
210 if (DwarfPubSections == Default)
211 HasDwarfPubSections = !IsDarwin;
212 else
213 HasDwarfPubSections = DwarfPubSections == Enable;
215 DwarfVersion = DwarfVersionNumber
216 ? DwarfVersionNumber
217 : getDwarfVersionFromModule(MMI->getModule());
219 {
220 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
221 beginModule();
222 }
223 }
225 // Switch to the specified MCSection and emit an assembler
226 // temporary label to it if SymbolStem is specified.
227 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
228 const char *SymbolStem = 0) {
229 Asm->OutStreamer.SwitchSection(Section);
230 if (!SymbolStem)
231 return 0;
233 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
234 Asm->OutStreamer.EmitLabel(TmpSym);
235 return TmpSym;
236 }
238 DwarfFile::~DwarfFile() {
239 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
240 I != E; ++I)
241 delete *I;
242 }
244 MCSymbol *DwarfFile::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
246 }
248 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
251 if (Entry.first)
252 return Entry.first;
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
256 }
258 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol *, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
261 if (Entry.first)
262 return Entry.second;
264 Entry.second = NextStringPoolNumber++;
265 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
266 return Entry.second;
267 }
269 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
270 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
271 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
272 if (P.second)
273 ++NextAddrPoolNumber;
274 return P.first->second.Number;
275 }
277 // Define a unique number for the abbreviation.
278 //
279 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
280 // Check the set for priors.
281 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
283 // If it's newly added.
284 if (InSet == &Abbrev) {
285 // Add to abbreviation list.
286 Abbreviations.push_back(&Abbrev);
288 // Assign the vector position + 1 as its number.
289 Abbrev.setNumber(Abbreviations.size());
290 } else {
291 // Assign existing abbreviation number.
292 Abbrev.setNumber(InSet->getNumber());
293 }
294 }
296 static bool isObjCClass(StringRef Name) {
297 return Name.startswith("+") || Name.startswith("-");
298 }
300 static bool hasObjCCategory(StringRef Name) {
301 if (!isObjCClass(Name))
302 return false;
304 return Name.find(") ") != StringRef::npos;
305 }
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308 StringRef &Category) {
309 if (!hasObjCCategory(In)) {
310 Class = In.slice(In.find('[') + 1, In.find(' '));
311 Category = "";
312 return;
313 }
315 Class = In.slice(In.find('[') + 1, In.find('('));
316 Category = In.slice(In.find('[') + 1, In.find(' '));
317 return;
318 }
320 static StringRef getObjCMethodName(StringRef In) {
321 return In.slice(In.find(' ') + 1, In.find(']'));
322 }
324 // Helper for sorting sections into a stable output order.
325 static bool SectionSort(const MCSection *A, const MCSection *B) {
326 std::string LA = (A ? A->getLabelBeginName() : "");
327 std::string LB = (B ? B->getLabelBeginName() : "");
328 return LA < LB;
329 }
331 // Add the various names to the Dwarf accelerator table names.
332 // TODO: Determine whether or not we should add names for programs
333 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
334 // is only slightly different than the lookup of non-standard ObjC names.
335 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
336 if (!SP.isDefinition())
337 return;
338 TheU->addAccelName(SP.getName(), Die);
340 // If the linkage name is different than the name, go ahead and output
341 // that as well into the name table.
342 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
343 TheU->addAccelName(SP.getLinkageName(), Die);
345 // If this is an Objective-C selector name add it to the ObjC accelerator
346 // too.
347 if (isObjCClass(SP.getName())) {
348 StringRef Class, Category;
349 getObjCClassCategory(SP.getName(), Class, Category);
350 TheU->addAccelObjC(Class, Die);
351 if (Category != "")
352 TheU->addAccelObjC(Category, Die);
353 // Also add the base method name to the name table.
354 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
355 }
356 }
358 /// isSubprogramContext - Return true if Context is either a subprogram
359 /// or another context nested inside a subprogram.
360 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
361 if (!Context)
362 return false;
363 DIDescriptor D(Context);
364 if (D.isSubprogram())
365 return true;
366 if (D.isType())
367 return isSubprogramContext(resolve(DIType(Context).getContext()));
368 return false;
369 }
371 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
372 // and DW_AT_high_pc attributes. If there are global variables in this
373 // scope then create and insert DIEs for these variables.
374 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
375 DISubprogram SP) {
376 DIE *SPDie = SPCU->getDIE(SP);
378 assert(SPDie && "Unable to find subprogram DIE!");
380 // If we're updating an abstract DIE, then we will be adding the children and
381 // object pointer later on. But what we don't want to do is process the
382 // concrete DIE twice.
383 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
384 // Pick up abstract subprogram DIE.
385 SPDie =
386 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
387 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
388 } else {
389 DISubprogram SPDecl = SP.getFunctionDeclaration();
390 if (!SPDecl.isSubprogram()) {
391 // There is not any need to generate specification DIE for a function
392 // defined at compile unit level. If a function is defined inside another
393 // function then gdb prefers the definition at top level and but does not
394 // expect specification DIE in parent function. So avoid creating
395 // specification DIE for a function defined inside a function.
396 DIScope SPContext = resolve(SP.getContext());
397 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
399 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
401 // Add arguments.
402 DICompositeType SPTy = SP.getType();
403 DIArray Args = SPTy.getTypeArray();
404 uint16_t SPTag = SPTy.getTag();
405 if (SPTag == dwarf::DW_TAG_subroutine_type)
406 // FIXME: Use DwarfUnit::constructSubprogramArguments() here.
407 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
408 DIType ATy(Args.getElement(i));
409 if (ATy.isUnspecifiedParameter()) {
410 assert(i == N-1 && "ellipsis must be the last argument");
411 SPCU->createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, *SPDie);
412 } else {
413 DIE *Arg =
414 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
415 SPCU->addType(Arg, ATy);
416 if (ATy.isArtificial())
417 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
418 if (ATy.isObjectPointer())
419 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
420 }
421 }
422 DIE *SPDeclDie = SPDie;
423 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
424 *SPCU->getUnitDie());
425 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
426 }
427 }
428 }
430 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
431 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
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 // Create the unspecified parameter that marks a function as variadic.
602 DISubprogram SP(Scope->getScopeNode());
603 assert(SP.Verify());
604 DIArray FnArgs = SP.getType().getTypeArray();
605 if (FnArgs.getElement(FnArgs.getNumElements()-1).isUnspecifiedParameter()) {
606 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
607 Children.push_back(Ellipsis);
608 }
609 }
611 // Collect lexical scope children first.
612 const SmallVectorImpl<DbgVariable *> &Variables =
613 ScopeVariables.lookup(Scope);
614 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
615 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
616 Scope->isAbstractScope())) {
617 Children.push_back(Variable);
618 if (Variables[i]->isObjectPointer())
619 ObjectPointer = Variable;
620 }
621 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
622 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
623 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
624 Children.push_back(Nested);
625 return ObjectPointer;
626 }
628 // Construct a DIE for this scope.
629 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
630 LexicalScope *Scope) {
631 if (!Scope || !Scope->getScopeNode())
632 return NULL;
634 DIScope DS(Scope->getScopeNode());
636 SmallVector<DIE *, 8> Children;
637 DIE *ObjectPointer = NULL;
638 bool ChildrenCreated = false;
640 // We try to create the scope DIE first, then the children DIEs. This will
641 // avoid creating un-used children then removing them later when we find out
642 // the scope DIE is null.
643 DIE *ScopeDIE = NULL;
644 if (Scope->getInlinedAt())
645 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
646 else if (DS.isSubprogram()) {
647 ProcessedSPNodes.insert(DS);
648 if (Scope->isAbstractScope()) {
649 ScopeDIE = TheCU->getDIE(DS);
650 // Note down abstract DIE.
651 if (ScopeDIE)
652 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
653 } else
654 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
655 } else {
656 // Early exit when we know the scope DIE is going to be null.
657 if (isLexicalScopeDIENull(Scope))
658 return NULL;
660 // We create children here when we know the scope DIE is not going to be
661 // null and the children will be added to the scope DIE.
662 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
663 ChildrenCreated = true;
665 // There is no need to emit empty lexical block DIE.
666 std::pair<ImportedEntityMap::const_iterator,
667 ImportedEntityMap::const_iterator> Range =
668 std::equal_range(
669 ScopesWithImportedEntities.begin(),
670 ScopesWithImportedEntities.end(),
671 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
672 less_first());
673 if (Children.empty() && Range.first == Range.second)
674 return NULL;
675 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
676 assert(ScopeDIE && "Scope DIE should not be null.");
677 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
678 ++i)
679 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
680 }
682 if (!ScopeDIE) {
683 assert(Children.empty() &&
684 "We create children only when the scope DIE is not null.");
685 return NULL;
686 }
687 if (!ChildrenCreated)
688 // We create children when the scope DIE is not null.
689 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
691 // Add children
692 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
693 E = Children.end();
694 I != E; ++I)
695 ScopeDIE->addChild(*I);
697 if (DS.isSubprogram() && ObjectPointer != NULL)
698 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
700 return ScopeDIE;
701 }
703 // Look up the source id with the given directory and source file names.
704 // If none currently exists, create a new id and insert it in the
705 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
706 // as well.
707 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
708 unsigned CUID) {
709 // If we print assembly, we can't separate .file entries according to
710 // compile units. Thus all files will belong to the default compile unit.
712 // FIXME: add a better feature test than hasRawTextSupport. Even better,
713 // extend .file to support this.
714 if (Asm->OutStreamer.hasRawTextSupport())
715 CUID = 0;
717 // If FE did not provide a file name, then assume stdin.
718 if (FileName.empty())
719 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
721 // TODO: this might not belong here. See if we can factor this better.
722 if (DirName == CompilationDir)
723 DirName = "";
725 // FileIDCUMap stores the current ID for the given compile unit.
726 unsigned SrcId = FileIDCUMap[CUID] + 1;
728 // We look up the CUID/file/dir by concatenating them with a zero byte.
729 SmallString<128> NamePair;
730 NamePair += utostr(CUID);
731 NamePair += '\0';
732 NamePair += DirName;
733 NamePair += '\0'; // Zero bytes are not allowed in paths.
734 NamePair += FileName;
736 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
737 if (Ent.getValue() != SrcId)
738 return Ent.getValue();
740 FileIDCUMap[CUID] = SrcId;
741 // Print out a .file directive to specify files for .loc directives.
742 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
744 return SrcId;
745 }
747 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
748 if (!GenerateGnuPubSections)
749 return;
751 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
752 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
753 DwarfGnuPubNamesSectionSym);
755 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
756 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
757 DwarfGnuPubTypesSectionSym);
758 }
760 // Create new DwarfCompileUnit for the given metadata node with tag
761 // DW_TAG_compile_unit.
762 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
763 StringRef FN = DIUnit.getFilename();
764 CompilationDir = DIUnit.getDirectory();
766 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
767 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
768 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
769 InfoHolder.addUnit(NewCU);
771 FileIDCUMap[NewCU->getUniqueID()] = 0;
773 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
774 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
775 DIUnit.getLanguage());
776 NewCU->addString(Die, dwarf::DW_AT_name, FN);
779 if (!useSplitDwarf()) {
780 NewCU->initStmtList(DwarfLineSectionSym);
782 // If we're using split dwarf the compilation dir is going to be in the
783 // skeleton CU and so we don't need to duplicate it here.
784 if (!CompilationDir.empty())
785 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
787 addGnuPubAttributes(NewCU, Die);
788 }
790 if (DIUnit.isOptimized())
791 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
793 StringRef Flags = DIUnit.getFlags();
794 if (!Flags.empty())
795 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
797 if (unsigned RVer = DIUnit.getRunTimeVersion())
798 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
799 dwarf::DW_FORM_data1, RVer);
801 if (!FirstCU)
802 FirstCU = NewCU;
804 if (useSplitDwarf()) {
805 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
806 DwarfInfoDWOSectionSym);
807 NewCU->setSkeleton(constructSkeletonCU(NewCU));
808 } else
809 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
810 DwarfInfoSectionSym);
812 CUMap.insert(std::make_pair(DIUnit, NewCU));
813 CUDieMap.insert(std::make_pair(Die, NewCU));
814 return NewCU;
815 }
817 // Construct subprogram DIE.
818 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
819 const MDNode *N) {
820 // FIXME: We should only call this routine once, however, during LTO if a
821 // program is defined in multiple CUs we could end up calling it out of
822 // beginModule as we walk the CUs.
824 DwarfCompileUnit *&CURef = SPMap[N];
825 if (CURef)
826 return;
827 CURef = TheCU;
829 DISubprogram SP(N);
830 if (!SP.isDefinition())
831 // This is a method declaration which will be handled while constructing
832 // class type.
833 return;
835 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
837 // Expose as a global name.
838 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
839 }
841 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
842 const MDNode *N) {
843 DIImportedEntity Module(N);
844 assert(Module.Verify());
845 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
846 constructImportedEntityDIE(TheCU, Module, D);
847 }
849 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
850 const MDNode *N, DIE *Context) {
851 DIImportedEntity Module(N);
852 assert(Module.Verify());
853 return constructImportedEntityDIE(TheCU, Module, Context);
854 }
856 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
857 const DIImportedEntity &Module,
858 DIE *Context) {
859 assert(Module.Verify() &&
860 "Use one of the MDNode * overloads to handle invalid metadata");
861 assert(Context && "Should always have a context for an imported_module");
862 DIE *IMDie = new DIE(Module.getTag());
863 TheCU->insertDIE(Module, IMDie);
864 DIE *EntityDie;
865 DIDescriptor Entity = Module.getEntity();
866 if (Entity.isNameSpace())
867 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
868 else if (Entity.isSubprogram())
869 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
870 else if (Entity.isType())
871 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
872 else
873 EntityDie = TheCU->getDIE(Entity);
874 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
875 Module.getContext().getDirectory(),
876 TheCU->getUniqueID());
877 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
878 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
879 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
880 StringRef Name = Module.getName();
881 if (!Name.empty())
882 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
883 Context->addChild(IMDie);
884 }
886 // Emit all Dwarf sections that should come prior to the content. Create
887 // global DIEs and emit initial debug info sections. This is invoked by
888 // the target AsmPrinter.
889 void DwarfDebug::beginModule() {
890 if (DisableDebugInfoPrinting)
891 return;
893 const Module *M = MMI->getModule();
895 // If module has named metadata anchors then use them, otherwise scan the
896 // module using debug info finder to collect debug info.
897 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
898 if (!CU_Nodes)
899 return;
900 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
902 // Emit initial sections so we can reference labels later.
903 emitSectionLabels();
905 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
906 DICompileUnit CUNode(CU_Nodes->getOperand(i));
907 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
908 DIArray ImportedEntities = CUNode.getImportedEntities();
909 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
910 ScopesWithImportedEntities.push_back(std::make_pair(
911 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
912 ImportedEntities.getElement(i)));
913 std::sort(ScopesWithImportedEntities.begin(),
914 ScopesWithImportedEntities.end(), less_first());
915 DIArray GVs = CUNode.getGlobalVariables();
916 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
917 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
918 DIArray SPs = CUNode.getSubprograms();
919 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
920 constructSubprogramDIE(CU, SPs.getElement(i));
921 DIArray EnumTypes = CUNode.getEnumTypes();
922 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
923 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
924 DIArray RetainedTypes = CUNode.getRetainedTypes();
925 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
926 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
927 // Emit imported_modules last so that the relevant context is already
928 // available.
929 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
930 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
931 }
933 // Tell MMI that we have debug info.
934 MMI->setDebugInfoAvailability(true);
936 // Prime section data.
937 SectionMap[Asm->getObjFileLowering().getTextSection()];
938 }
940 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
941 void DwarfDebug::computeInlinedDIEs() {
942 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
943 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
944 AE = InlinedSubprogramDIEs.end();
945 AI != AE; ++AI) {
946 DIE *ISP = *AI;
947 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
948 }
949 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
950 AE = AbstractSPDies.end();
951 AI != AE; ++AI) {
952 DIE *ISP = AI->second;
953 if (InlinedSubprogramDIEs.count(ISP))
954 continue;
955 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
956 }
957 }
959 // Collect info for variables that were optimized out.
960 void DwarfDebug::collectDeadVariables() {
961 const Module *M = MMI->getModule();
963 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
964 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
965 DICompileUnit TheCU(CU_Nodes->getOperand(i));
966 DIArray Subprograms = TheCU.getSubprograms();
967 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
968 DISubprogram SP(Subprograms.getElement(i));
969 if (ProcessedSPNodes.count(SP) != 0)
970 continue;
971 if (!SP.isSubprogram())
972 continue;
973 if (!SP.isDefinition())
974 continue;
975 DIArray Variables = SP.getVariables();
976 if (Variables.getNumElements() == 0)
977 continue;
979 // Construct subprogram DIE and add variables DIEs.
980 DwarfCompileUnit *SPCU =
981 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
982 assert(SPCU && "Unable to find Compile Unit!");
983 // FIXME: See the comment in constructSubprogramDIE about duplicate
984 // subprogram DIEs.
985 constructSubprogramDIE(SPCU, SP);
986 DIE *SPDIE = SPCU->getDIE(SP);
987 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
988 DIVariable DV(Variables.getElement(vi));
989 if (!DV.isVariable())
990 continue;
991 DbgVariable NewVar(DV, NULL, this);
992 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
993 SPDIE->addChild(VariableDIE);
994 }
995 }
996 }
997 }
998 }
1000 void DwarfDebug::finalizeModuleInfo() {
1001 // Collect info for variables that were optimized out.
1002 collectDeadVariables();
1004 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1005 computeInlinedDIEs();
1007 // Handle anything that needs to be done on a per-unit basis after
1008 // all other generation.
1009 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1010 E = getUnits().end();
1011 I != E; ++I) {
1012 DwarfUnit *TheU = *I;
1013 // Emit DW_AT_containing_type attribute to connect types with their
1014 // vtable holding type.
1015 TheU->constructContainingTypeDIEs();
1017 // Add CU specific attributes if we need to add any.
1018 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1019 // If we're splitting the dwarf out now that we've got the entire
1020 // CU then add the dwo id to it.
1021 DwarfCompileUnit *SkCU =
1022 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1023 if (useSplitDwarf()) {
1024 // This should be a unique identifier when we want to build .dwp files.
1025 uint64_t ID = 0;
1026 if (GenerateCUHash) {
1027 DIEHash CUHash(Asm);
1028 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1029 }
1030 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1031 dwarf::DW_FORM_data8, ID);
1032 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1033 dwarf::DW_FORM_data8, ID);
1034 }
1036 // If we have code split among multiple sections or we've requested
1037 // it then emit a DW_AT_ranges attribute on the unit that will remain
1038 // in the .o file, otherwise add a DW_AT_low_pc.
1039 // FIXME: Also add a high pc if we can.
1040 // FIXME: We should use ranges if we have multiple compile units or
1041 // allow reordering of code ala .subsections_via_symbols in mach-o.
1042 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1043 if (useCURanges() && TheU->getRanges().size()) {
1044 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1045 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1046 DwarfDebugRangeSectionSym);
1048 // A DW_AT_low_pc attribute may also be specified in combination with
1049 // DW_AT_ranges to specify the default base address for use in location
1050 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1051 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1052 0);
1053 } else
1054 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1055 0);
1056 }
1057 }
1059 // Compute DIE offsets and sizes.
1060 InfoHolder.computeSizeAndOffsets();
1061 if (useSplitDwarf())
1062 SkeletonHolder.computeSizeAndOffsets();
1063 }
1065 void DwarfDebug::endSections() {
1066 // Filter labels by section.
1067 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1068 const SymbolCU &SCU = ArangeLabels[n];
1069 if (SCU.Sym->isInSection()) {
1070 // Make a note of this symbol and it's section.
1071 const MCSection *Section = &SCU.Sym->getSection();
1072 if (!Section->getKind().isMetadata())
1073 SectionMap[Section].push_back(SCU);
1074 } else {
1075 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1076 // appear in the output. This sucks as we rely on sections to build
1077 // arange spans. We can do it without, but it's icky.
1078 SectionMap[NULL].push_back(SCU);
1079 }
1080 }
1082 // Build a list of sections used.
1083 std::vector<const MCSection *> Sections;
1084 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1085 it++) {
1086 const MCSection *Section = it->first;
1087 Sections.push_back(Section);
1088 }
1090 // Sort the sections into order.
1091 // This is only done to ensure consistent output order across different runs.
1092 std::sort(Sections.begin(), Sections.end(), SectionSort);
1094 // Add terminating symbols for each section.
1095 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1096 const MCSection *Section = Sections[ID];
1097 MCSymbol *Sym = NULL;
1099 if (Section) {
1100 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1101 // if we know the section name up-front. For user-created sections, the
1102 // resulting label may not be valid to use as a label. (section names can
1103 // use a greater set of characters on some systems)
1104 Sym = Asm->GetTempSymbol("debug_end", ID);
1105 Asm->OutStreamer.SwitchSection(Section);
1106 Asm->OutStreamer.EmitLabel(Sym);
1107 }
1109 // Insert a final terminator.
1110 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1111 }
1113 // For now only turn on CU ranges if we've explicitly asked for it,
1114 // we have -ffunction-sections enabled, we've emitted a function
1115 // into a unique section, or we're using LTO. If we're using LTO then
1116 // we can't know that any particular function in the module is correlated
1117 // to a particular CU and so we need to be conservative. At this point all
1118 // sections should be finalized except for dwarf sections.
1119 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1120 TargetMachine::getFunctionSections();
1121 }
1123 // Emit all Dwarf sections that should come after the content.
1124 void DwarfDebug::endModule() {
1125 assert(CurFn == 0);
1126 assert(CurMI == 0);
1128 if (!FirstCU)
1129 return;
1131 // End any existing sections.
1132 // TODO: Does this need to happen?
1133 endSections();
1135 // Finalize the debug info for the module.
1136 finalizeModuleInfo();
1138 emitDebugStr();
1140 // Emit all the DIEs into a debug info section.
1141 emitDebugInfo();
1143 // Corresponding abbreviations into a abbrev section.
1144 emitAbbreviations();
1146 // Emit info into a debug loc section.
1147 emitDebugLoc();
1149 // Emit info into a debug aranges section.
1150 if (GenerateARangeSection)
1151 emitDebugARanges();
1153 // Emit info into a debug ranges section.
1154 emitDebugRanges();
1156 if (useSplitDwarf()) {
1157 emitDebugStrDWO();
1158 emitDebugInfoDWO();
1159 emitDebugAbbrevDWO();
1160 // Emit DWO addresses.
1161 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1162 }
1164 // Emit info into the dwarf accelerator table sections.
1165 if (useDwarfAccelTables()) {
1166 emitAccelNames();
1167 emitAccelObjC();
1168 emitAccelNamespaces();
1169 emitAccelTypes();
1170 }
1172 // Emit the pubnames and pubtypes sections if requested.
1173 if (HasDwarfPubSections) {
1174 emitDebugPubNames(GenerateGnuPubSections);
1175 emitDebugPubTypes(GenerateGnuPubSections);
1176 }
1178 // clean up.
1179 SPMap.clear();
1181 // Reset these for the next Module if we have one.
1182 FirstCU = NULL;
1183 }
1185 // Find abstract variable, if any, associated with Var.
1186 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1187 DebugLoc ScopeLoc) {
1188 LLVMContext &Ctx = DV->getContext();
1189 // More then one inlined variable corresponds to one abstract variable.
1190 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1191 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1192 if (AbsDbgVariable)
1193 return AbsDbgVariable;
1195 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1196 if (!Scope)
1197 return NULL;
1199 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1200 addScopeVariable(Scope, AbsDbgVariable);
1201 AbstractVariables[Var] = AbsDbgVariable;
1202 return AbsDbgVariable;
1203 }
1205 // If Var is a current function argument then add it to CurrentFnArguments list.
1206 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1207 if (!LScopes.isCurrentFunctionScope(Scope))
1208 return false;
1209 DIVariable DV = Var->getVariable();
1210 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1211 return false;
1212 unsigned ArgNo = DV.getArgNumber();
1213 if (ArgNo == 0)
1214 return false;
1216 size_t Size = CurrentFnArguments.size();
1217 if (Size == 0)
1218 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1219 // llvm::Function argument size is not good indicator of how many
1220 // arguments does the function have at source level.
1221 if (ArgNo > Size)
1222 CurrentFnArguments.resize(ArgNo * 2);
1223 CurrentFnArguments[ArgNo - 1] = Var;
1224 return true;
1225 }
1227 // Collect variable information from side table maintained by MMI.
1228 void DwarfDebug::collectVariableInfoFromMMITable(
1229 SmallPtrSet<const MDNode *, 16> &Processed) {
1230 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1231 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1232 VE = VMap.end();
1233 VI != VE; ++VI) {
1234 const MDNode *Var = VI->first;
1235 if (!Var)
1236 continue;
1237 Processed.insert(Var);
1238 DIVariable DV(Var);
1239 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1241 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1243 // If variable scope is not found then skip this variable.
1244 if (Scope == 0)
1245 continue;
1247 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1248 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1249 RegVar->setFrameIndex(VP.first);
1250 if (!addCurrentFnArgument(RegVar, Scope))
1251 addScopeVariable(Scope, RegVar);
1252 if (AbsDbgVariable)
1253 AbsDbgVariable->setFrameIndex(VP.first);
1254 }
1255 }
1257 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1258 // defined reg.
1259 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1260 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1261 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1262 MI->getOperand(0).getReg() &&
1263 (MI->getOperand(1).isImm() ||
1264 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1265 }
1267 // Get .debug_loc entry for the instruction range starting at MI.
1268 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1269 const MCSymbol *FLabel,
1270 const MCSymbol *SLabel,
1271 const MachineInstr *MI) {
1272 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1274 assert(MI->getNumOperands() == 3);
1275 if (MI->getOperand(0).isReg()) {
1276 MachineLocation MLoc;
1277 // If the second operand is an immediate, this is a
1278 // register-indirect address.
1279 if (!MI->getOperand(1).isImm())
1280 MLoc.set(MI->getOperand(0).getReg());
1281 else
1282 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1283 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1284 }
1285 if (MI->getOperand(0).isImm())
1286 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1287 if (MI->getOperand(0).isFPImm())
1288 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1289 if (MI->getOperand(0).isCImm())
1290 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1292 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1293 }
1295 // Find variables for each lexical scope.
1296 void
1297 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1299 // Grab the variable info that was squirreled away in the MMI side-table.
1300 collectVariableInfoFromMMITable(Processed);
1302 for (SmallVectorImpl<const MDNode *>::const_iterator
1303 UVI = UserVariables.begin(),
1304 UVE = UserVariables.end();
1305 UVI != UVE; ++UVI) {
1306 const MDNode *Var = *UVI;
1307 if (Processed.count(Var))
1308 continue;
1310 // History contains relevant DBG_VALUE instructions for Var and instructions
1311 // clobbering it.
1312 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1313 if (History.empty())
1314 continue;
1315 const MachineInstr *MInsn = History.front();
1317 DIVariable DV(Var);
1318 LexicalScope *Scope = NULL;
1319 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1320 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1321 Scope = LScopes.getCurrentFunctionScope();
1322 else if (MDNode *IA = DV.getInlinedAt())
1323 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1324 else
1325 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1326 // If variable scope is not found then skip this variable.
1327 if (!Scope)
1328 continue;
1330 Processed.insert(DV);
1331 assert(MInsn->isDebugValue() && "History must begin with debug value");
1332 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1333 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1334 if (!addCurrentFnArgument(RegVar, Scope))
1335 addScopeVariable(Scope, RegVar);
1336 if (AbsVar)
1337 AbsVar->setMInsn(MInsn);
1339 // Simplify ranges that are fully coalesced.
1340 if (History.size() <= 1 ||
1341 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1342 RegVar->setMInsn(MInsn);
1343 continue;
1344 }
1346 // Handle multiple DBG_VALUE instructions describing one variable.
1347 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1349 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1350 HI = History.begin(),
1351 HE = History.end();
1352 HI != HE; ++HI) {
1353 const MachineInstr *Begin = *HI;
1354 assert(Begin->isDebugValue() && "Invalid History entry");
1356 // Check if DBG_VALUE is truncating a range.
1357 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1358 !Begin->getOperand(0).getReg())
1359 continue;
1361 // Compute the range for a register location.
1362 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1363 const MCSymbol *SLabel = 0;
1365 if (HI + 1 == HE)
1366 // If Begin is the last instruction in History then its value is valid
1367 // until the end of the function.
1368 SLabel = FunctionEndSym;
1369 else {
1370 const MachineInstr *End = HI[1];
1371 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1372 << "\t" << *Begin << "\t" << *End << "\n");
1373 if (End->isDebugValue())
1374 SLabel = getLabelBeforeInsn(End);
1375 else {
1376 // End is a normal instruction clobbering the range.
1377 SLabel = getLabelAfterInsn(End);
1378 assert(SLabel && "Forgot label after clobber instruction");
1379 ++HI;
1380 }
1381 }
1383 // The value is valid until the next DBG_VALUE or clobber.
1384 DotDebugLocEntries.push_back(
1385 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1386 }
1387 DotDebugLocEntries.push_back(DotDebugLocEntry());
1388 }
1390 // Collect info for variables that were optimized out.
1391 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1392 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1393 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1394 DIVariable DV(Variables.getElement(i));
1395 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1396 continue;
1397 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1398 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1399 }
1400 }
1402 // Return Label preceding the instruction.
1403 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1404 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1405 assert(Label && "Didn't insert label before instruction");
1406 return Label;
1407 }
1409 // Return Label immediately following the instruction.
1410 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1411 return LabelsAfterInsn.lookup(MI);
1412 }
1414 // Process beginning of an instruction.
1415 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1416 assert(CurMI == 0);
1417 CurMI = MI;
1418 // Check if source location changes, but ignore DBG_VALUE locations.
1419 if (!MI->isDebugValue()) {
1420 DebugLoc DL = MI->getDebugLoc();
1421 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1422 unsigned Flags = 0;
1423 PrevInstLoc = DL;
1424 if (DL == PrologEndLoc) {
1425 Flags |= DWARF2_FLAG_PROLOGUE_END;
1426 PrologEndLoc = DebugLoc();
1427 }
1428 if (PrologEndLoc.isUnknown())
1429 Flags |= DWARF2_FLAG_IS_STMT;
1431 if (!DL.isUnknown()) {
1432 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1433 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1434 } else
1435 recordSourceLine(0, 0, 0, 0);
1436 }
1437 }
1439 // Insert labels where requested.
1440 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1441 LabelsBeforeInsn.find(MI);
1443 // No label needed.
1444 if (I == LabelsBeforeInsn.end())
1445 return;
1447 // Label already assigned.
1448 if (I->second)
1449 return;
1451 if (!PrevLabel) {
1452 PrevLabel = MMI->getContext().CreateTempSymbol();
1453 Asm->OutStreamer.EmitLabel(PrevLabel);
1454 }
1455 I->second = PrevLabel;
1456 }
1458 // Process end of an instruction.
1459 void DwarfDebug::endInstruction() {
1460 assert(CurMI != 0);
1461 // Don't create a new label after DBG_VALUE instructions.
1462 // They don't generate code.
1463 if (!CurMI->isDebugValue())
1464 PrevLabel = 0;
1466 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1467 LabelsAfterInsn.find(CurMI);
1468 CurMI = 0;
1470 // No label needed.
1471 if (I == LabelsAfterInsn.end())
1472 return;
1474 // Label already assigned.
1475 if (I->second)
1476 return;
1478 // We need a label after this instruction.
1479 if (!PrevLabel) {
1480 PrevLabel = MMI->getContext().CreateTempSymbol();
1481 Asm->OutStreamer.EmitLabel(PrevLabel);
1482 }
1483 I->second = PrevLabel;
1484 }
1486 // Each LexicalScope has first instruction and last instruction to mark
1487 // beginning and end of a scope respectively. Create an inverse map that list
1488 // scopes starts (and ends) with an instruction. One instruction may start (or
1489 // end) multiple scopes. Ignore scopes that are not reachable.
1490 void DwarfDebug::identifyScopeMarkers() {
1491 SmallVector<LexicalScope *, 4> WorkList;
1492 WorkList.push_back(LScopes.getCurrentFunctionScope());
1493 while (!WorkList.empty()) {
1494 LexicalScope *S = WorkList.pop_back_val();
1496 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1497 if (!Children.empty())
1498 for (SmallVectorImpl<LexicalScope *>::const_iterator
1499 SI = Children.begin(),
1500 SE = Children.end();
1501 SI != SE; ++SI)
1502 WorkList.push_back(*SI);
1504 if (S->isAbstractScope())
1505 continue;
1507 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1508 if (Ranges.empty())
1509 continue;
1510 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1511 RE = Ranges.end();
1512 RI != RE; ++RI) {
1513 assert(RI->first && "InsnRange does not have first instruction!");
1514 assert(RI->second && "InsnRange does not have second instruction!");
1515 requestLabelBeforeInsn(RI->first);
1516 requestLabelAfterInsn(RI->second);
1517 }
1518 }
1519 }
1521 // Gather pre-function debug information. Assumes being called immediately
1522 // after the function entry point has been emitted.
1523 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1524 CurFn = MF;
1526 // If there's no debug info for the function we're not going to do anything.
1527 if (!MMI->hasDebugInfo())
1528 return;
1530 // Grab the lexical scopes for the function, if we don't have any of those
1531 // then we're not going to be able to do anything.
1532 LScopes.initialize(*MF);
1533 if (LScopes.empty())
1534 return;
1536 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1538 // Make sure that each lexical scope will have a begin/end label.
1539 identifyScopeMarkers();
1541 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1542 // belongs to so that we add to the correct per-cu line table in the
1543 // non-asm case.
1544 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1545 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1546 assert(TheCU && "Unable to find compile unit!");
1547 if (Asm->OutStreamer.hasRawTextSupport())
1548 // Use a single line table if we are generating assembly.
1549 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1550 else
1551 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1553 // Check the current section against the standard text section. If different
1554 // keep track so that we will know when we're emitting functions into multiple
1555 // sections.
1556 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1557 UsedNonDefaultText = true;
1559 // Emit a label for the function so that we have a beginning address.
1560 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1561 // Assumes in correct section after the entry point.
1562 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1564 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1565 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1566 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1568 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1569 ++I) {
1570 bool AtBlockEntry = true;
1571 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1572 II != IE; ++II) {
1573 const MachineInstr *MI = II;
1575 if (MI->isDebugValue()) {
1576 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1578 // Keep track of user variables.
1579 const MDNode *Var =
1580 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1582 // Variable is in a register, we need to check for clobbers.
1583 if (isDbgValueInDefinedReg(MI))
1584 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1586 // Check the history of this variable.
1587 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1588 if (History.empty()) {
1589 UserVariables.push_back(Var);
1590 // The first mention of a function argument gets the FunctionBeginSym
1591 // label, so arguments are visible when breaking at function entry.
1592 DIVariable DV(Var);
1593 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1594 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1595 LabelsBeforeInsn[MI] = FunctionBeginSym;
1596 } else {
1597 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1598 const MachineInstr *Prev = History.back();
1599 if (Prev->isDebugValue()) {
1600 // Coalesce identical entries at the end of History.
1601 if (History.size() >= 2 &&
1602 Prev->isIdenticalTo(History[History.size() - 2])) {
1603 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1604 << "\t" << *Prev << "\t"
1605 << *History[History.size() - 2] << "\n");
1606 History.pop_back();
1607 }
1609 // Terminate old register assignments that don't reach MI;
1610 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1611 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1612 isDbgValueInDefinedReg(Prev)) {
1613 // Previous register assignment needs to terminate at the end of
1614 // its basic block.
1615 MachineBasicBlock::const_iterator LastMI =
1616 PrevMBB->getLastNonDebugInstr();
1617 if (LastMI == PrevMBB->end()) {
1618 // Drop DBG_VALUE for empty range.
1619 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1620 << "\t" << *Prev << "\n");
1621 History.pop_back();
1622 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1623 // Terminate after LastMI.
1624 History.push_back(LastMI);
1625 }
1626 }
1627 }
1628 History.push_back(MI);
1629 } else {
1630 // Not a DBG_VALUE instruction.
1631 if (!MI->isLabel())
1632 AtBlockEntry = false;
1634 // First known non-DBG_VALUE and non-frame setup location marks
1635 // the beginning of the function body.
1636 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1637 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1638 PrologEndLoc = MI->getDebugLoc();
1640 // Check if the instruction clobbers any registers with debug vars.
1641 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1642 MOE = MI->operands_end();
1643 MOI != MOE; ++MOI) {
1644 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1645 continue;
1646 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1647 ++AI) {
1648 unsigned Reg = *AI;
1649 const MDNode *Var = LiveUserVar[Reg];
1650 if (!Var)
1651 continue;
1652 // Reg is now clobbered.
1653 LiveUserVar[Reg] = 0;
1655 // Was MD last defined by a DBG_VALUE referring to Reg?
1656 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1657 if (HistI == DbgValues.end())
1658 continue;
1659 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1660 if (History.empty())
1661 continue;
1662 const MachineInstr *Prev = History.back();
1663 // Sanity-check: Register assignments are terminated at the end of
1664 // their block.
1665 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1666 continue;
1667 // Is the variable still in Reg?
1668 if (!isDbgValueInDefinedReg(Prev) ||
1669 Prev->getOperand(0).getReg() != Reg)
1670 continue;
1671 // Var is clobbered. Make sure the next instruction gets a label.
1672 History.push_back(MI);
1673 }
1674 }
1675 }
1676 }
1677 }
1679 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1680 I != E; ++I) {
1681 SmallVectorImpl<const MachineInstr *> &History = I->second;
1682 if (History.empty())
1683 continue;
1685 // Make sure the final register assignments are terminated.
1686 const MachineInstr *Prev = History.back();
1687 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1688 const MachineBasicBlock *PrevMBB = Prev->getParent();
1689 MachineBasicBlock::const_iterator LastMI =
1690 PrevMBB->getLastNonDebugInstr();
1691 if (LastMI == PrevMBB->end())
1692 // Drop DBG_VALUE for empty range.
1693 History.pop_back();
1694 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1695 // Terminate after LastMI.
1696 History.push_back(LastMI);
1697 }
1698 }
1699 // Request labels for the full history.
1700 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1701 const MachineInstr *MI = History[i];
1702 if (MI->isDebugValue())
1703 requestLabelBeforeInsn(MI);
1704 else
1705 requestLabelAfterInsn(MI);
1706 }
1707 }
1709 PrevInstLoc = DebugLoc();
1710 PrevLabel = FunctionBeginSym;
1712 // Record beginning of function.
1713 if (!PrologEndLoc.isUnknown()) {
1714 DebugLoc FnStartDL =
1715 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1716 recordSourceLine(
1717 FnStartDL.getLine(), FnStartDL.getCol(),
1718 FnStartDL.getScope(MF->getFunction()->getContext()),
1719 // We'd like to list the prologue as "not statements" but GDB behaves
1720 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1721 DWARF2_FLAG_IS_STMT);
1722 }
1723 }
1725 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1726 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1727 DIVariable DV = Var->getVariable();
1728 // Variables with positive arg numbers are parameters.
1729 if (unsigned ArgNum = DV.getArgNumber()) {
1730 // Keep all parameters in order at the start of the variable list to ensure
1731 // function types are correct (no out-of-order parameters)
1732 //
1733 // This could be improved by only doing it for optimized builds (unoptimized
1734 // builds have the right order to begin with), searching from the back (this
1735 // would catch the unoptimized case quickly), or doing a binary search
1736 // rather than linear search.
1737 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1738 while (I != Vars.end()) {
1739 unsigned CurNum = (*I)->getVariable().getArgNumber();
1740 // A local (non-parameter) variable has been found, insert immediately
1741 // before it.
1742 if (CurNum == 0)
1743 break;
1744 // A later indexed parameter has been found, insert immediately before it.
1745 if (CurNum > ArgNum)
1746 break;
1747 ++I;
1748 }
1749 Vars.insert(I, Var);
1750 return;
1751 }
1753 Vars.push_back(Var);
1754 }
1756 // Gather and emit post-function debug information.
1757 void DwarfDebug::endFunction(const MachineFunction *MF) {
1758 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1759 // though the beginFunction may not be called at all.
1760 // We should handle both cases.
1761 if (CurFn == 0)
1762 CurFn = MF;
1763 else
1764 assert(CurFn == MF);
1765 assert(CurFn != 0);
1767 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1768 CurFn = 0;
1769 return;
1770 }
1772 // Define end label for subprogram.
1773 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1774 // Assumes in correct section after the entry point.
1775 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1777 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1778 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1780 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1781 collectVariableInfo(ProcessedVars);
1783 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1784 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1785 assert(TheCU && "Unable to find compile unit!");
1787 // Construct abstract scopes.
1788 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1789 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1790 LexicalScope *AScope = AList[i];
1791 DISubprogram SP(AScope->getScopeNode());
1792 if (SP.isSubprogram()) {
1793 // Collect info for variables that were optimized out.
1794 DIArray Variables = SP.getVariables();
1795 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1796 DIVariable DV(Variables.getElement(i));
1797 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1798 continue;
1799 // Check that DbgVariable for DV wasn't created earlier, when
1800 // findAbstractVariable() was called for inlined instance of DV.
1801 LLVMContext &Ctx = DV->getContext();
1802 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1803 if (AbstractVariables.lookup(CleanDV))
1804 continue;
1805 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1806 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1807 }
1808 }
1809 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1810 constructScopeDIE(TheCU, AScope);
1811 }
1813 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1814 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1815 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1817 // Add the range of this function to the list of ranges for the CU.
1818 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1819 TheCU->addRange(llvm_move(Span));
1821 // Clear debug info
1822 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1823 E = ScopeVariables.end();
1824 I != E; ++I)
1825 DeleteContainerPointers(I->second);
1826 ScopeVariables.clear();
1827 DeleteContainerPointers(CurrentFnArguments);
1828 UserVariables.clear();
1829 DbgValues.clear();
1830 AbstractVariables.clear();
1831 LabelsBeforeInsn.clear();
1832 LabelsAfterInsn.clear();
1833 PrevLabel = NULL;
1834 CurFn = 0;
1835 }
1837 // Register a source line with debug info. Returns the unique label that was
1838 // emitted and which provides correspondence to the source line list.
1839 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1840 unsigned Flags) {
1841 StringRef Fn;
1842 StringRef Dir;
1843 unsigned Src = 1;
1844 if (S) {
1845 DIDescriptor Scope(S);
1847 if (Scope.isCompileUnit()) {
1848 DICompileUnit CU(S);
1849 Fn = CU.getFilename();
1850 Dir = CU.getDirectory();
1851 } else if (Scope.isFile()) {
1852 DIFile F(S);
1853 Fn = F.getFilename();
1854 Dir = F.getDirectory();
1855 } else if (Scope.isSubprogram()) {
1856 DISubprogram SP(S);
1857 Fn = SP.getFilename();
1858 Dir = SP.getDirectory();
1859 } else if (Scope.isLexicalBlockFile()) {
1860 DILexicalBlockFile DBF(S);
1861 Fn = DBF.getFilename();
1862 Dir = DBF.getDirectory();
1863 } else if (Scope.isLexicalBlock()) {
1864 DILexicalBlock DB(S);
1865 Fn = DB.getFilename();
1866 Dir = DB.getDirectory();
1867 } else
1868 llvm_unreachable("Unexpected scope info");
1870 Src = getOrCreateSourceID(
1871 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1872 }
1873 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1874 }
1876 //===----------------------------------------------------------------------===//
1877 // Emit Methods
1878 //===----------------------------------------------------------------------===//
1880 // Compute the size and offset of a DIE. The offset is relative to start of the
1881 // CU. It returns the offset after laying out the DIE.
1882 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1883 // Get the children.
1884 const std::vector<DIE *> &Children = Die->getChildren();
1886 // Record the abbreviation.
1887 assignAbbrevNumber(Die->getAbbrev());
1889 // Get the abbreviation for this DIE.
1890 const DIEAbbrev &Abbrev = Die->getAbbrev();
1892 // Set DIE offset
1893 Die->setOffset(Offset);
1895 // Start the size with the size of abbreviation code.
1896 Offset += getULEB128Size(Die->getAbbrevNumber());
1898 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1899 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1901 // Size the DIE attribute values.
1902 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1903 // Size attribute value.
1904 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1906 // Size the DIE children if any.
1907 if (!Children.empty()) {
1908 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1909 "Children flag not set");
1911 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1912 Offset = computeSizeAndOffset(Children[j], Offset);
1914 // End of children marker.
1915 Offset += sizeof(int8_t);
1916 }
1918 Die->setSize(Offset - Die->getOffset());
1919 return Offset;
1920 }
1922 // Compute the size and offset for each DIE.
1923 void DwarfFile::computeSizeAndOffsets() {
1924 // Offset from the first CU in the debug info section is 0 initially.
1925 unsigned SecOffset = 0;
1927 // Iterate over each compile unit and set the size and offsets for each
1928 // DIE within each compile unit. All offsets are CU relative.
1929 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1930 E = CUs.end();
1931 I != E; ++I) {
1932 (*I)->setDebugInfoOffset(SecOffset);
1934 // CU-relative offset is reset to 0 here.
1935 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1936 (*I)->getHeaderSize(); // Unit-specific headers
1938 // EndOffset here is CU-relative, after laying out
1939 // all of the CU DIE.
1940 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1941 SecOffset += EndOffset;
1942 }
1943 }
1945 // Emit initial Dwarf sections with a label at the start of each one.
1946 void DwarfDebug::emitSectionLabels() {
1947 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1949 // Dwarf sections base addresses.
1950 DwarfInfoSectionSym =
1951 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1952 if (useSplitDwarf())
1953 DwarfInfoDWOSectionSym =
1954 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1955 DwarfAbbrevSectionSym =
1956 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1957 if (useSplitDwarf())
1958 DwarfAbbrevDWOSectionSym = emitSectionSym(
1959 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1960 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1962 DwarfLineSectionSym =
1963 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1964 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1965 if (GenerateGnuPubSections) {
1966 DwarfGnuPubNamesSectionSym =
1967 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1968 DwarfGnuPubTypesSectionSym =
1969 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1970 } else if (HasDwarfPubSections) {
1971 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1972 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1973 }
1975 DwarfStrSectionSym =
1976 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1977 if (useSplitDwarf()) {
1978 DwarfStrDWOSectionSym =
1979 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1980 DwarfAddrSectionSym =
1981 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1982 }
1983 DwarfDebugRangeSectionSym =
1984 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1986 DwarfDebugLocSectionSym =
1987 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1988 }
1990 // Recursively emits a debug information entry.
1991 void DwarfDebug::emitDIE(DIE *Die) {
1992 // Get the abbreviation for this DIE.
1993 const DIEAbbrev &Abbrev = Die->getAbbrev();
1995 // Emit the code (index) for the abbreviation.
1996 if (Asm->isVerbose())
1997 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1998 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1999 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2000 dwarf::TagString(Abbrev.getTag()));
2001 Asm->EmitULEB128(Abbrev.getNumber());
2003 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2004 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2006 // Emit the DIE attribute values.
2007 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2008 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2009 dwarf::Form Form = AbbrevData[i].getForm();
2010 assert(Form && "Too many attributes for DIE (check abbreviation)");
2012 if (Asm->isVerbose())
2013 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2015 switch (Attr) {
2016 case dwarf::DW_AT_abstract_origin:
2017 case dwarf::DW_AT_type:
2018 case dwarf::DW_AT_friend:
2019 case dwarf::DW_AT_specification:
2020 case dwarf::DW_AT_import:
2021 case dwarf::DW_AT_containing_type: {
2022 DIEEntry *E = cast<DIEEntry>(Values[i]);
2023 DIE *Origin = E->getEntry();
2024 unsigned Addr = Origin->getOffset();
2025 if (Form == dwarf::DW_FORM_ref_addr) {
2026 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2027 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2028 // section. Origin->getOffset() returns the offset from start of the
2029 // compile unit.
2030 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2031 assert(CU && "CUDie should belong to a CU.");
2032 Addr += CU->getDebugInfoOffset();
2033 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2034 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2035 DIEEntry::getRefAddrSize(Asm));
2036 else
2037 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2038 CU->getSectionSym(),
2039 DIEEntry::getRefAddrSize(Asm));
2040 } else {
2041 // Make sure Origin belong to the same CU.
2042 assert(Die->getUnit() == Origin->getUnit() &&
2043 "The referenced DIE should belong to the same CU in ref4");
2044 Asm->EmitInt32(Addr);
2045 }
2046 break;
2047 }
2048 case dwarf::DW_AT_location: {
2049 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2050 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2051 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2052 else
2053 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2054 } else {
2055 Values[i]->EmitValue(Asm, Form);
2056 }
2057 break;
2058 }
2059 case dwarf::DW_AT_accessibility: {
2060 if (Asm->isVerbose()) {
2061 DIEInteger *V = cast<DIEInteger>(Values[i]);
2062 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2063 }
2064 Values[i]->EmitValue(Asm, Form);
2065 break;
2066 }
2067 default:
2068 // Emit an attribute using the defined form.
2069 Values[i]->EmitValue(Asm, Form);
2070 break;
2071 }
2072 }
2074 // Emit the DIE children if any.
2075 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2076 const std::vector<DIE *> &Children = Die->getChildren();
2078 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2079 emitDIE(Children[j]);
2081 Asm->OutStreamer.AddComment("End Of Children Mark");
2082 Asm->EmitInt8(0);
2083 }
2084 }
2086 // Emit the various dwarf units to the unit section USection with
2087 // the abbreviations going into ASection.
2088 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2089 const MCSymbol *ASectionSym) {
2090 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2091 I != E; ++I) {
2092 DwarfUnit *TheU = *I;
2093 DIE *Die = TheU->getUnitDie();
2094 const MCSection *USection = TheU->getSection();
2095 Asm->OutStreamer.SwitchSection(USection);
2097 // Emit the compile units header.
2098 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2100 // Emit size of content not including length itself
2101 Asm->OutStreamer.AddComment("Length of Unit");
2102 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2104 TheU->emitHeader(ASection, ASectionSym);
2106 DD->emitDIE(Die);
2107 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2108 }
2109 }
2111 // Emit the debug info section.
2112 void DwarfDebug::emitDebugInfo() {
2113 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2115 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2116 DwarfAbbrevSectionSym);
2117 }
2119 // Emit the abbreviation section.
2120 void DwarfDebug::emitAbbreviations() {
2121 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2123 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2124 }
2126 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2127 // Check to see if it is worth the effort.
2128 if (!Abbreviations.empty()) {
2129 // Start the debug abbrev section.
2130 Asm->OutStreamer.SwitchSection(Section);
2132 // For each abbrevation.
2133 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2134 // Get abbreviation data
2135 const DIEAbbrev *Abbrev = Abbreviations[i];
2137 // Emit the abbrevations code (base 1 index.)
2138 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2140 // Emit the abbreviations data.
2141 Abbrev->Emit(Asm);
2142 }
2144 // Mark end of abbreviations.
2145 Asm->EmitULEB128(0, "EOM(3)");
2146 }
2147 }
2149 // Emit the last address of the section and the end of the line matrix.
2150 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2151 // Define last address of section.
2152 Asm->OutStreamer.AddComment("Extended Op");
2153 Asm->EmitInt8(0);
2155 Asm->OutStreamer.AddComment("Op size");
2156 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2157 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2158 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2160 Asm->OutStreamer.AddComment("Section end label");
2162 Asm->OutStreamer.EmitSymbolValue(
2163 Asm->GetTempSymbol("section_end", SectionEnd),
2164 Asm->getDataLayout().getPointerSize());
2166 // Mark end of matrix.
2167 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2168 Asm->EmitInt8(0);
2169 Asm->EmitInt8(1);
2170 Asm->EmitInt8(1);
2171 }
2173 // Emit visible names into a hashed accelerator table section.
2174 void DwarfDebug::emitAccelNames() {
2175 DwarfAccelTable AT(
2176 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2177 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2178 E = getUnits().end();
2179 I != E; ++I) {
2180 DwarfUnit *TheU = *I;
2181 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2182 for (StringMap<std::vector<const DIE *> >::const_iterator
2183 GI = Names.begin(),
2184 GE = Names.end();
2185 GI != GE; ++GI) {
2186 StringRef Name = GI->getKey();
2187 const std::vector<const DIE *> &Entities = GI->second;
2188 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2189 DE = Entities.end();
2190 DI != DE; ++DI)
2191 AT.AddName(Name, *DI);
2192 }
2193 }
2195 AT.FinalizeTable(Asm, "Names");
2196 Asm->OutStreamer.SwitchSection(
2197 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2198 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2199 Asm->OutStreamer.EmitLabel(SectionBegin);
2201 // Emit the full data.
2202 AT.Emit(Asm, SectionBegin, &InfoHolder);
2203 }
2205 // Emit objective C classes and categories into a hashed accelerator table
2206 // section.
2207 void DwarfDebug::emitAccelObjC() {
2208 DwarfAccelTable AT(
2209 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2210 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2211 E = getUnits().end();
2212 I != E; ++I) {
2213 DwarfUnit *TheU = *I;
2214 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2215 for (StringMap<std::vector<const DIE *> >::const_iterator
2216 GI = Names.begin(),
2217 GE = Names.end();
2218 GI != GE; ++GI) {
2219 StringRef Name = GI->getKey();
2220 const std::vector<const DIE *> &Entities = GI->second;
2221 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2222 DE = Entities.end();
2223 DI != DE; ++DI)
2224 AT.AddName(Name, *DI);
2225 }
2226 }
2228 AT.FinalizeTable(Asm, "ObjC");
2229 Asm->OutStreamer.SwitchSection(
2230 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2231 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2232 Asm->OutStreamer.EmitLabel(SectionBegin);
2234 // Emit the full data.
2235 AT.Emit(Asm, SectionBegin, &InfoHolder);
2236 }
2238 // Emit namespace dies into a hashed accelerator table.
2239 void DwarfDebug::emitAccelNamespaces() {
2240 DwarfAccelTable AT(
2241 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2242 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2243 E = getUnits().end();
2244 I != E; ++I) {
2245 DwarfUnit *TheU = *I;
2246 const StringMap<std::vector<const DIE *> > &Names =
2247 TheU->getAccelNamespace();
2248 for (StringMap<std::vector<const DIE *> >::const_iterator
2249 GI = Names.begin(),
2250 GE = Names.end();
2251 GI != GE; ++GI) {
2252 StringRef Name = GI->getKey();
2253 const std::vector<const DIE *> &Entities = GI->second;
2254 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2255 DE = Entities.end();
2256 DI != DE; ++DI)
2257 AT.AddName(Name, *DI);
2258 }
2259 }
2261 AT.FinalizeTable(Asm, "namespac");
2262 Asm->OutStreamer.SwitchSection(
2263 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2264 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2265 Asm->OutStreamer.EmitLabel(SectionBegin);
2267 // Emit the full data.
2268 AT.Emit(Asm, SectionBegin, &InfoHolder);
2269 }
2271 // Emit type dies into a hashed accelerator table.
2272 void DwarfDebug::emitAccelTypes() {
2273 std::vector<DwarfAccelTable::Atom> Atoms;
2274 Atoms.push_back(
2275 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2276 Atoms.push_back(
2277 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2278 Atoms.push_back(
2279 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2280 DwarfAccelTable AT(Atoms);
2281 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2282 E = getUnits().end();
2283 I != E; ++I) {
2284 DwarfUnit *TheU = *I;
2285 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2286 TheU->getAccelTypes();
2287 for (StringMap<
2288 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2289 GI = Names.begin(),
2290 GE = Names.end();
2291 GI != GE; ++GI) {
2292 StringRef Name = GI->getKey();
2293 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2294 GI->second;
2295 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2296 DI = Entities.begin(),
2297 DE = Entities.end();
2298 DI != DE; ++DI)
2299 AT.AddName(Name, DI->first, DI->second);
2300 }
2301 }
2303 AT.FinalizeTable(Asm, "types");
2304 Asm->OutStreamer.SwitchSection(
2305 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2306 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2307 Asm->OutStreamer.EmitLabel(SectionBegin);
2309 // Emit the full data.
2310 AT.Emit(Asm, SectionBegin, &InfoHolder);
2311 }
2313 // Public name handling.
2314 // The format for the various pubnames:
2315 //
2316 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2317 // for the DIE that is named.
2318 //
2319 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2320 // into the CU and the index value is computed according to the type of value
2321 // for the DIE that is named.
2322 //
2323 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2324 // it's the offset within the debug_info/debug_types dwo section, however, the
2325 // reference in the pubname header doesn't change.
2327 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2328 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2329 const DIE *Die) {
2330 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2332 // We could have a specification DIE that has our most of our knowledge,
2333 // look for that now.
2334 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2335 if (SpecVal) {
2336 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2337 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2338 Linkage = dwarf::GIEL_EXTERNAL;
2339 } else if (Die->findAttribute(dwarf::DW_AT_external))
2340 Linkage = dwarf::GIEL_EXTERNAL;
2342 switch (Die->getTag()) {
2343 case dwarf::DW_TAG_class_type:
2344 case dwarf::DW_TAG_structure_type:
2345 case dwarf::DW_TAG_union_type:
2346 case dwarf::DW_TAG_enumeration_type:
2347 return dwarf::PubIndexEntryDescriptor(
2348 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2349 ? dwarf::GIEL_STATIC
2350 : dwarf::GIEL_EXTERNAL);
2351 case dwarf::DW_TAG_typedef:
2352 case dwarf::DW_TAG_base_type:
2353 case dwarf::DW_TAG_subrange_type:
2354 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2355 case dwarf::DW_TAG_namespace:
2356 return dwarf::GIEK_TYPE;
2357 case dwarf::DW_TAG_subprogram:
2358 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2359 case dwarf::DW_TAG_constant:
2360 case dwarf::DW_TAG_variable:
2361 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2362 case dwarf::DW_TAG_enumerator:
2363 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2364 dwarf::GIEL_STATIC);
2365 default:
2366 return dwarf::GIEK_NONE;
2367 }
2368 }
2370 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2371 ///
2372 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2373 const MCSection *PSec =
2374 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2375 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2377 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2378 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2379 for (unsigned i = 0; i != Units.size(); ++i) {
2380 DwarfUnit *TheU = Units[i];
2381 unsigned ID = TheU->getUniqueID();
2383 // Start the dwarf pubnames section.
2384 Asm->OutStreamer.SwitchSection(PSec);
2386 // Emit a label so we can reference the beginning of this pubname section.
2387 if (GnuStyle)
2388 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2390 // Emit the header.
2391 Asm->OutStreamer.AddComment("Length of Public Names Info");
2392 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2393 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2394 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2396 Asm->OutStreamer.EmitLabel(BeginLabel);
2398 Asm->OutStreamer.AddComment("DWARF Version");
2399 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2401 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2402 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2404 Asm->OutStreamer.AddComment("Compilation Unit Length");
2405 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2407 // Emit the pubnames for this compilation unit.
2408 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2409 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2410 GE = Globals.end();
2411 GI != GE; ++GI) {
2412 const char *Name = GI->getKeyData();
2413 const DIE *Entity = GI->second;
2415 Asm->OutStreamer.AddComment("DIE offset");
2416 Asm->EmitInt32(Entity->getOffset());
2418 if (GnuStyle) {
2419 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2420 Asm->OutStreamer.AddComment(
2421 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2422 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2423 Asm->EmitInt8(Desc.toBits());
2424 }
2426 Asm->OutStreamer.AddComment("External Name");
2427 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2428 }
2430 Asm->OutStreamer.AddComment("End Mark");
2431 Asm->EmitInt32(0);
2432 Asm->OutStreamer.EmitLabel(EndLabel);
2433 }
2434 }
2436 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2437 const MCSection *PSec =
2438 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2439 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2441 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2442 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2443 for (unsigned i = 0; i != Units.size(); ++i) {
2444 DwarfUnit *TheU = Units[i];
2445 unsigned ID = TheU->getUniqueID();
2447 // Start the dwarf pubtypes section.
2448 Asm->OutStreamer.SwitchSection(PSec);
2450 // Emit a label so we can reference the beginning of this pubtype section.
2451 if (GnuStyle)
2452 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2454 // Emit the header.
2455 Asm->OutStreamer.AddComment("Length of Public Types Info");
2456 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2457 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2458 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2460 Asm->OutStreamer.EmitLabel(BeginLabel);
2462 Asm->OutStreamer.AddComment("DWARF Version");
2463 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2465 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2466 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2468 Asm->OutStreamer.AddComment("Compilation Unit Length");
2469 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2471 // Emit the pubtypes.
2472 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2473 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2474 GE = Globals.end();
2475 GI != GE; ++GI) {
2476 const char *Name = GI->getKeyData();
2477 const DIE *Entity = GI->second;
2479 Asm->OutStreamer.AddComment("DIE offset");
2480 Asm->EmitInt32(Entity->getOffset());
2482 if (GnuStyle) {
2483 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2484 Asm->OutStreamer.AddComment(
2485 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2486 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2487 Asm->EmitInt8(Desc.toBits());
2488 }
2490 Asm->OutStreamer.AddComment("External Name");
2492 // Emit the name with a terminating null byte.
2493 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2494 }
2496 Asm->OutStreamer.AddComment("End Mark");
2497 Asm->EmitInt32(0);
2498 Asm->OutStreamer.EmitLabel(EndLabel);
2499 }
2500 }
2502 // Emit strings into a string section.
2503 void DwarfFile::emitStrings(const MCSection *StrSection,
2504 const MCSection *OffsetSection = NULL,
2505 const MCSymbol *StrSecSym = NULL) {
2507 if (StringPool.empty())
2508 return;
2510 // Start the dwarf str section.
2511 Asm->OutStreamer.SwitchSection(StrSection);
2513 // Get all of the string pool entries and put them in an array by their ID so
2514 // we can sort them.
2515 SmallVector<
2516 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2517 64> Entries;
2519 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2520 I = StringPool.begin(),
2521 E = StringPool.end();
2522 I != E; ++I)
2523 Entries.push_back(std::make_pair(I->second.second, &*I));
2525 array_pod_sort(Entries.begin(), Entries.end());
2527 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2528 // Emit a label for reference from debug information entries.
2529 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2531 // Emit the string itself with a terminating null byte.
2532 Asm->OutStreamer.EmitBytes(
2533 StringRef(Entries[i].second->getKeyData(),
2534 Entries[i].second->getKeyLength() + 1));
2535 }
2537 // If we've got an offset section go ahead and emit that now as well.
2538 if (OffsetSection) {
2539 Asm->OutStreamer.SwitchSection(OffsetSection);
2540 unsigned offset = 0;
2541 unsigned size = 4; // FIXME: DWARF64 is 8.
2542 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2543 Asm->OutStreamer.EmitIntValue(offset, size);
2544 offset += Entries[i].second->getKeyLength() + 1;
2545 }
2546 }
2547 }
2549 // Emit addresses into the section given.
2550 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2552 if (AddressPool.empty())
2553 return;
2555 // Start the dwarf addr section.
2556 Asm->OutStreamer.SwitchSection(AddrSection);
2558 // Order the address pool entries by ID
2559 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2561 for (AddrPool::iterator I = AddressPool.begin(), E = AddressPool.end();
2562 I != E; ++I)
2563 Entries[I->second.Number] =
2564 I->second.TLS
2565 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I->first)
2566 : MCSymbolRefExpr::Create(I->first, Asm->OutContext);
2568 for (unsigned i = 0, e = Entries.size(); i != e; ++i)
2569 Asm->OutStreamer.EmitValue(Entries[i],
2570 Asm->getDataLayout().getPointerSize());
2571 }
2573 // Emit visible names into a debug str section.
2574 void DwarfDebug::emitDebugStr() {
2575 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2576 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2577 }
2579 // Emit locations into the debug loc section.
2580 void DwarfDebug::emitDebugLoc() {
2581 if (DotDebugLocEntries.empty())
2582 return;
2584 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2585 I = DotDebugLocEntries.begin(),
2586 E = DotDebugLocEntries.end();
2587 I != E; ++I) {
2588 DotDebugLocEntry &Entry = *I;
2589 if (I + 1 != DotDebugLocEntries.end())
2590 Entry.Merge(I + 1);
2591 }
2593 // Start the dwarf loc section.
2594 Asm->OutStreamer.SwitchSection(
2595 Asm->getObjFileLowering().getDwarfLocSection());
2596 unsigned char Size = Asm->getDataLayout().getPointerSize();
2597 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2598 unsigned index = 1;
2599 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2600 I = DotDebugLocEntries.begin(),
2601 E = DotDebugLocEntries.end();
2602 I != E; ++I, ++index) {
2603 DotDebugLocEntry &Entry = *I;
2604 if (Entry.isMerged())
2605 continue;
2606 if (Entry.isEmpty()) {
2607 Asm->OutStreamer.EmitIntValue(0, Size);
2608 Asm->OutStreamer.EmitIntValue(0, Size);
2609 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2610 } else {
2611 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2612 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2613 DIVariable DV(Entry.getVariable());
2614 Asm->OutStreamer.AddComment("Loc expr size");
2615 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2616 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2617 Asm->EmitLabelDifference(end, begin, 2);
2618 Asm->OutStreamer.EmitLabel(begin);
2619 if (Entry.isInt()) {
2620 DIBasicType BTy(DV.getType());
2621 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2622 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2623 Asm->OutStreamer.AddComment("DW_OP_consts");
2624 Asm->EmitInt8(dwarf::DW_OP_consts);
2625 Asm->EmitSLEB128(Entry.getInt());
2626 } else {
2627 Asm->OutStreamer.AddComment("DW_OP_constu");
2628 Asm->EmitInt8(dwarf::DW_OP_constu);
2629 Asm->EmitULEB128(Entry.getInt());
2630 }
2631 } else if (Entry.isLocation()) {
2632 MachineLocation Loc = Entry.getLoc();
2633 if (!DV.hasComplexAddress())
2634 // Regular entry.
2635 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2636 else {
2637 // Complex address entry.
2638 unsigned N = DV.getNumAddrElements();
2639 unsigned i = 0;
2640 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2641 if (Loc.getOffset()) {
2642 i = 2;
2643 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2644 Asm->OutStreamer.AddComment("DW_OP_deref");
2645 Asm->EmitInt8(dwarf::DW_OP_deref);
2646 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2647 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2648 Asm->EmitSLEB128(DV.getAddrElement(1));
2649 } else {
2650 // If first address element is OpPlus then emit
2651 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2652 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2653 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2654 i = 2;
2655 }
2656 } else {
2657 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2658 }
2660 // Emit remaining complex address elements.
2661 for (; i < N; ++i) {
2662 uint64_t Element = DV.getAddrElement(i);
2663 if (Element == DIBuilder::OpPlus) {
2664 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2665 Asm->EmitULEB128(DV.getAddrElement(++i));
2666 } else if (Element == DIBuilder::OpDeref) {
2667 if (!Loc.isReg())
2668 Asm->EmitInt8(dwarf::DW_OP_deref);
2669 } else
2670 llvm_unreachable("unknown Opcode found in complex address");
2671 }
2672 }
2673 }
2674 // else ... ignore constant fp. There is not any good way to
2675 // to represent them here in dwarf.
2676 Asm->OutStreamer.EmitLabel(end);
2677 }
2678 }
2679 }
2681 struct SymbolCUSorter {
2682 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2683 const MCStreamer &Streamer;
2685 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2686 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2687 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2689 // Symbols with no order assigned should be placed at the end.
2690 // (e.g. section end labels)
2691 if (IA == 0)
2692 IA = (unsigned)(-1);
2693 if (IB == 0)
2694 IB = (unsigned)(-1);
2695 return IA < IB;
2696 }
2697 };
2699 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2700 return (A->getUniqueID() < B->getUniqueID());
2701 }
2703 struct ArangeSpan {
2704 const MCSymbol *Start, *End;
2705 };
2707 // Emit a debug aranges section, containing a CU lookup for any
2708 // address we can tie back to a CU.
2709 void DwarfDebug::emitDebugARanges() {
2710 // Start the dwarf aranges section.
2711 Asm->OutStreamer.SwitchSection(
2712 Asm->getObjFileLowering().getDwarfARangesSection());
2714 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2716 SpansType Spans;
2718 // Build a list of sections used.
2719 std::vector<const MCSection *> Sections;
2720 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2721 it++) {
2722 const MCSection *Section = it->first;
2723 Sections.push_back(Section);
2724 }
2726 // Sort the sections into order.
2727 // This is only done to ensure consistent output order across different runs.
2728 std::sort(Sections.begin(), Sections.end(), SectionSort);
2730 // Build a set of address spans, sorted by CU.
2731 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2732 const MCSection *Section = Sections[SecIdx];
2733 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2734 if (List.size() < 2)
2735 continue;
2737 // Sort the symbols by offset within the section.
2738 SymbolCUSorter sorter(Asm->OutStreamer);
2739 std::sort(List.begin(), List.end(), sorter);
2741 // If we have no section (e.g. common), just write out
2742 // individual spans for each symbol.
2743 if (Section == NULL) {
2744 for (size_t n = 0; n < List.size(); n++) {
2745 const SymbolCU &Cur = List[n];
2747 ArangeSpan Span;
2748 Span.Start = Cur.Sym;
2749 Span.End = NULL;
2750 if (Cur.CU)
2751 Spans[Cur.CU].push_back(Span);
2752 }
2753 } else {
2754 // Build spans between each label.
2755 const MCSymbol *StartSym = List[0].Sym;
2756 for (size_t n = 1; n < List.size(); n++) {
2757 const SymbolCU &Prev = List[n - 1];
2758 const SymbolCU &Cur = List[n];
2760 // Try and build the longest span we can within the same CU.
2761 if (Cur.CU != Prev.CU) {
2762 ArangeSpan Span;
2763 Span.Start = StartSym;
2764 Span.End = Cur.Sym;
2765 Spans[Prev.CU].push_back(Span);
2766 StartSym = Cur.Sym;
2767 }
2768 }
2769 }
2770 }
2772 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2774 // Build a list of CUs used.
2775 std::vector<DwarfCompileUnit *> CUs;
2776 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2777 DwarfCompileUnit *CU = it->first;
2778 CUs.push_back(CU);
2779 }
2781 // Sort the CU list (again, to ensure consistent output order).
2782 std::sort(CUs.begin(), CUs.end(), CUSort);
2784 // Emit an arange table for each CU we used.
2785 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2786 DwarfCompileUnit *CU = CUs[CUIdx];
2787 std::vector<ArangeSpan> &List = Spans[CU];
2789 // Emit size of content not including length itself.
2790 unsigned ContentSize =
2791 sizeof(int16_t) + // DWARF ARange version number
2792 sizeof(int32_t) + // Offset of CU in the .debug_info section
2793 sizeof(int8_t) + // Pointer Size (in bytes)
2794 sizeof(int8_t); // Segment Size (in bytes)
2796 unsigned TupleSize = PtrSize * 2;
2798 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2799 unsigned Padding =
2800 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2802 ContentSize += Padding;
2803 ContentSize += (List.size() + 1) * TupleSize;
2805 // For each compile unit, write the list of spans it covers.
2806 Asm->OutStreamer.AddComment("Length of ARange Set");
2807 Asm->EmitInt32(ContentSize);
2808 Asm->OutStreamer.AddComment("DWARF Arange version number");
2809 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2810 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2811 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2812 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2813 Asm->EmitInt8(PtrSize);
2814 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2815 Asm->EmitInt8(0);
2817 Asm->OutStreamer.EmitFill(Padding, 0xff);
2819 for (unsigned n = 0; n < List.size(); n++) {
2820 const ArangeSpan &Span = List[n];
2821 Asm->EmitLabelReference(Span.Start, PtrSize);
2823 // Calculate the size as being from the span start to it's end.
2824 if (Span.End) {
2825 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2826 } else {
2827 // For symbols without an end marker (e.g. common), we
2828 // write a single arange entry containing just that one symbol.
2829 uint64_t Size = SymSize[Span.Start];
2830 if (Size == 0)
2831 Size = 1;
2833 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2834 }
2835 }
2837 Asm->OutStreamer.AddComment("ARange terminator");
2838 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2839 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2840 }
2841 }
2843 // Emit visible names into a debug ranges section.
2844 void DwarfDebug::emitDebugRanges() {
2845 // Start the dwarf ranges section.
2846 Asm->OutStreamer.SwitchSection(
2847 Asm->getObjFileLowering().getDwarfRangesSection());
2849 // Size for our labels.
2850 unsigned char Size = Asm->getDataLayout().getPointerSize();
2852 // Grab the specific ranges for the compile units in the module.
2853 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2854 I = CUMap.begin(),
2855 E = CUMap.end();
2856 I != E; ++I) {
2857 DwarfCompileUnit *TheCU = I->second;
2859 // Emit a symbol so we can find the beginning of our ranges.
2860 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2862 // Iterate over the misc ranges for the compile units in the module.
2863 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2864 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2865 E = RangeLists.end();
2866 I != E; ++I) {
2867 const RangeSpanList &List = *I;
2869 // Emit our symbol so we can find the beginning of the range.
2870 Asm->OutStreamer.EmitLabel(List.getSym());
2872 for (SmallVectorImpl<RangeSpan>::const_iterator
2873 RI = List.getRanges().begin(),
2874 RE = List.getRanges().end();
2875 RI != RE; ++RI) {
2876 const RangeSpan &Range = *RI;
2877 const MCSymbol *Begin = Range.getStart();
2878 const MCSymbol *End = Range.getEnd();
2879 assert(Begin && "Range without a begin symbol?");
2880 assert(End && "Range without an end symbol?");
2881 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2882 Asm->OutStreamer.EmitSymbolValue(End, Size);
2883 }
2885 // And terminate the list with two 0 values.
2886 Asm->OutStreamer.EmitIntValue(0, Size);
2887 Asm->OutStreamer.EmitIntValue(0, Size);
2888 }
2890 // Now emit a range for the CU itself.
2891 if (useCURanges()) {
2892 Asm->OutStreamer.EmitLabel(
2893 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2894 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2895 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2896 RangeSpan Range = Ranges[i];
2897 const MCSymbol *Begin = Range.getStart();
2898 const MCSymbol *End = Range.getEnd();
2899 assert(Begin && "Range without a begin symbol?");
2900 assert(End && "Range without an end symbol?");
2901 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2902 Asm->OutStreamer.EmitSymbolValue(End, Size);
2903 }
2904 // And terminate the list with two 0 values.
2905 Asm->OutStreamer.EmitIntValue(0, Size);
2906 Asm->OutStreamer.EmitIntValue(0, Size);
2907 }
2908 }
2909 }
2911 // DWARF5 Experimental Separate Dwarf emitters.
2913 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2914 DwarfUnit *NewU) {
2915 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2916 U->getCUNode().getSplitDebugFilename());
2918 // Relocate to the beginning of the addr_base section, else 0 for the
2919 // beginning of the one for this compile unit.
2920 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2921 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2922 else
2923 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2925 if (!CompilationDir.empty())
2926 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2928 addGnuPubAttributes(NewU, Die);
2930 SkeletonHolder.addUnit(NewU);
2931 }
2933 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2934 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2935 // DW_AT_ranges_base, DW_AT_addr_base.
2936 // TODO: Implement DW_AT_ranges_base.
2937 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2939 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2940 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2941 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2942 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2943 DwarfInfoSectionSym);
2945 NewCU->initStmtList(DwarfLineSectionSym);
2947 initSkeletonUnit(CU, Die, NewCU);
2949 return NewCU;
2950 }
2952 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2953 // DW_AT_addr_base.
2954 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2955 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2956 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2958 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2959 DwarfTypeUnit *NewTU =
2960 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2961 NewTU->setTypeSignature(TU->getTypeSignature());
2962 NewTU->setType(NULL);
2963 NewTU->initSection(
2964 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2965 CU.applyStmtList(*Die);
2967 initSkeletonUnit(TU, Die, NewTU);
2968 return NewTU;
2969 }
2971 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2972 // compile units that would normally be in debug_info.
2973 void DwarfDebug::emitDebugInfoDWO() {
2974 assert(useSplitDwarf() && "No split dwarf debug info?");
2975 InfoHolder.emitUnits(this,
2976 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2977 DwarfAbbrevDWOSectionSym);
2978 }
2980 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2981 // abbreviations for the .debug_info.dwo section.
2982 void DwarfDebug::emitDebugAbbrevDWO() {
2983 assert(useSplitDwarf() && "No split dwarf?");
2984 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2985 }
2987 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2988 // string section and is identical in format to traditional .debug_str
2989 // sections.
2990 void DwarfDebug::emitDebugStrDWO() {
2991 assert(useSplitDwarf() && "No split dwarf?");
2992 const MCSection *OffSec =
2993 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2994 const MCSymbol *StrSym = DwarfStrSectionSym;
2995 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2996 OffSec, StrSym);
2997 }
2999 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
3000 StringRef Identifier, DIE *RefDie,
3001 DICompositeType CTy) {
3002 // Flag the type unit reference as a declaration so that if it contains
3003 // members (implicit special members, static data member definitions, member
3004 // declarations for definitions in this CU, etc) consumers don't get confused
3005 // and think this is a full definition.
3006 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
3008 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3009 if (TU) {
3010 CU.addDIETypeSignature(RefDie, *TU);
3011 return;
3012 }
3014 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3015 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
3016 UnitDie, CU, Asm, this, &InfoHolder);
3017 TU = NewTU;
3018 InfoHolder.addUnit(NewTU);
3020 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3021 CU.getLanguage());
3023 MD5 Hash;
3024 Hash.update(Identifier);
3025 // ... take the least significant 8 bytes and return those. Our MD5
3026 // implementation always returns its results in little endian, swap bytes
3027 // appropriately.
3028 MD5::MD5Result Result;
3029 Hash.final(Result);
3030 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3031 NewTU->setTypeSignature(Signature);
3032 if (useSplitDwarf())
3033 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3034 else
3035 CU.applyStmtList(*UnitDie);
3037 NewTU->setType(NewTU->createTypeDIE(CTy));
3039 NewTU->initSection(
3040 useSplitDwarf()
3041 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3042 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3044 CU.addDIETypeSignature(RefDie, *NewTU);
3045 }