1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/DIBuilder.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
51 cl::desc("Disable debug info printing"));
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54 cl::desc("Make an absence of debug location information explicit."),
57 static cl::opt<bool> GenerateDwarfPubNamesSection("generate-dwarf-pubnames",
58 cl::Hidden, cl::init(false),
59 cl::desc("Generate DWARF pubnames section"));
63 Default, Enable, Disable
67 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
68 cl::desc("Output prototype dwarf accelerator tables."),
70 clEnumVal(Default, "Default for platform"),
71 clEnumVal(Enable, "Enabled"),
72 clEnumVal(Disable, "Disabled"),
76 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
77 cl::desc("Compatibility with Darwin gdb."),
79 clEnumVal(Default, "Default for platform"),
80 clEnumVal(Enable, "Enabled"),
81 clEnumVal(Disable, "Disabled"),
85 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
86 cl::desc("Output prototype dwarf split debug info."),
88 clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"),
95 const char *DWARFGroupName = "DWARF Emission";
96 const char *DbgTimerName = "DWARF Debug Writer";
99 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
100 return lhs.first < rhs.first;
103 } // end anonymous namespace
105 //===----------------------------------------------------------------------===//
107 // Configuration values for initial hash set sizes (log2).
109 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
113 DIType DbgVariable::getType() const {
114 DIType Ty = Var.getType();
115 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
116 // addresses instead.
117 if (Var.isBlockByrefVariable()) {
118 /* Byref variables, in Blocks, are declared by the programmer as
119 "SomeType VarName;", but the compiler creates a
120 __Block_byref_x_VarName struct, and gives the variable VarName
121 either the struct, or a pointer to the struct, as its type. This
122 is necessary for various behind-the-scenes things the compiler
123 needs to do with by-reference variables in blocks.
125 However, as far as the original *programmer* is concerned, the
126 variable should still have type 'SomeType', as originally declared.
128 The following function dives into the __Block_byref_x_VarName
129 struct to find the original type of the variable. This will be
130 passed back to the code generating the type for the Debug
131 Information Entry for the variable 'VarName'. 'VarName' will then
132 have the original type 'SomeType' in its debug information.
134 The original type 'SomeType' will be the type of the field named
135 'VarName' inside the __Block_byref_x_VarName struct.
137 NOTE: In order for this to not completely fail on the debugger
138 side, the Debug Information Entry for the variable VarName needs to
139 have a DW_AT_location that tells the debugger how to unwind through
140 the pointers and __Block_byref_x_VarName struct to find the actual
141 value of the variable. The function addBlockByrefType does this. */
143 unsigned tag = Ty.getTag();
145 if (tag == dwarf::DW_TAG_pointer_type) {
146 DIDerivedType DTy = DIDerivedType(Ty);
147 subType = DTy.getTypeDerivedFrom();
150 DICompositeType blockStruct = DICompositeType(subType);
151 DIArray Elements = blockStruct.getTypeArray();
153 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
154 DIDescriptor Element = Elements.getElement(i);
155 DIDerivedType DT = DIDerivedType(Element);
156 if (getName() == DT.getName())
157 return (DT.getTypeDerivedFrom());
163 } // end llvm namespace
165 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
166 : Asm(A), MMI(Asm->MMI), FirstCU(0),
167 AbbreviationsSet(InitAbbreviationsSetSize),
168 SourceIdMap(DIEValueAllocator),
169 PrevLabel(NULL), GlobalCUIndexCount(0),
170 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
172 SkeletonAbbrevSet(InitAbbreviationsSetSize),
173 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
176 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
177 DwarfStrSectionSym = TextSectionSym = 0;
178 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
179 DwarfAddrSectionSym = 0;
180 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
181 FunctionBeginSym = FunctionEndSym = 0;
183 // Turn on accelerator tables and older gdb compatibility
185 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
186 if (DarwinGDBCompat == Default) {
188 IsDarwinGDBCompat = true;
190 IsDarwinGDBCompat = false;
192 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
194 if (DwarfAccelTables == Default) {
196 HasDwarfAccelTables = true;
198 HasDwarfAccelTables = false;
200 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable ? true : false;
208 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
212 DwarfDebug::~DwarfDebug() {
215 // Switch to the specified MCSection and emit an assembler
216 // temporary label to it if SymbolStem is specified.
217 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
218 const char *SymbolStem = 0) {
219 Asm->OutStreamer.SwitchSection(Section);
220 if (!SymbolStem) return 0;
222 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
223 Asm->OutStreamer.EmitLabel(TmpSym);
227 MCSymbol *DwarfUnits::getStringPoolSym() {
228 return Asm->GetTempSymbol(StringPref);
231 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
232 std::pair<MCSymbol*, unsigned> &Entry =
233 StringPool.GetOrCreateValue(Str).getValue();
234 if (Entry.first) return Entry.first;
236 Entry.second = NextStringPoolNumber++;
237 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
240 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
241 std::pair<MCSymbol*, unsigned> &Entry =
242 StringPool.GetOrCreateValue(Str).getValue();
243 if (Entry.first) return Entry.second;
245 Entry.second = NextStringPoolNumber++;
246 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
250 unsigned DwarfUnits::getAddrPoolIndex(MCSymbol *Sym) {
251 std::pair<MCSymbol*, unsigned> &Entry = AddressPool[Sym];
252 if (Entry.first) return Entry.second;
254 Entry.second = NextAddrPoolNumber++;
259 // Define a unique number for the abbreviation.
261 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
262 // Check the set for priors.
263 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
265 // If it's newly added.
266 if (InSet == &Abbrev) {
267 // Add to abbreviation list.
268 Abbreviations->push_back(&Abbrev);
270 // Assign the vector position + 1 as its number.
271 Abbrev.setNumber(Abbreviations->size());
273 // Assign existing abbreviation number.
274 Abbrev.setNumber(InSet->getNumber());
278 static bool isObjCClass(StringRef Name) {
279 return Name.startswith("+") || Name.startswith("-");
282 static bool hasObjCCategory(StringRef Name) {
283 if (!isObjCClass(Name)) return false;
285 size_t pos = Name.find(')');
286 if (pos != std::string::npos) {
287 if (Name[pos+1] != ' ') return false;
293 static void getObjCClassCategory(StringRef In, StringRef &Class,
294 StringRef &Category) {
295 if (!hasObjCCategory(In)) {
296 Class = In.slice(In.find('[') + 1, In.find(' '));
301 Class = In.slice(In.find('[') + 1, In.find('('));
302 Category = In.slice(In.find('[') + 1, In.find(' '));
306 static StringRef getObjCMethodName(StringRef In) {
307 return In.slice(In.find(' ') + 1, In.find(']'));
310 // Add the various names to the Dwarf accelerator table names.
311 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
313 if (!SP.isDefinition()) return;
315 TheCU->addAccelName(SP.getName(), Die);
317 // If the linkage name is different than the name, go ahead and output
318 // that as well into the name table.
319 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
320 TheCU->addAccelName(SP.getLinkageName(), Die);
322 // If this is an Objective-C selector name add it to the ObjC accelerator
324 if (isObjCClass(SP.getName())) {
325 StringRef Class, Category;
326 getObjCClassCategory(SP.getName(), Class, Category);
327 TheCU->addAccelObjC(Class, Die);
329 TheCU->addAccelObjC(Category, Die);
330 // Also add the base method name to the name table.
331 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
335 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
336 // and DW_AT_high_pc attributes. If there are global variables in this
337 // scope then create and insert DIEs for these variables.
338 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
339 const MDNode *SPNode) {
340 DIE *SPDie = SPCU->getDIE(SPNode);
342 assert(SPDie && "Unable to find subprogram DIE!");
343 DISubprogram SP(SPNode);
345 // If we're updating an abstract DIE, then we will be adding the children and
346 // object pointer later on. But what we don't want to do is process the
347 // concrete DIE twice.
348 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
350 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
351 // Pick up abstract subprogram DIE.
352 SPDie = new DIE(dwarf::DW_TAG_subprogram);
353 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
355 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
356 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
360 DISubprogram SPDecl = SP.getFunctionDeclaration();
361 if (!SPDecl.isSubprogram()) {
362 // There is not any need to generate specification DIE for a function
363 // defined at compile unit level. If a function is defined inside another
364 // function then gdb prefers the definition at top level and but does not
365 // expect specification DIE in parent function. So avoid creating
366 // specification DIE for a function defined inside a function.
367 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
368 !SP.getContext().isFile() &&
369 !isSubprogramContext(SP.getContext())) {
370 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
373 DICompositeType SPTy = SP.getType();
374 DIArray Args = SPTy.getTypeArray();
375 unsigned SPTag = SPTy.getTag();
376 if (SPTag == dwarf::DW_TAG_subroutine_type)
377 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
378 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
379 DIType ATy = DIType(Args.getElement(i));
380 SPCU->addType(Arg, ATy);
381 if (ATy.isArtificial())
382 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
383 if (ATy.isObjectPointer())
384 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
385 dwarf::DW_FORM_ref4, Arg);
386 SPDie->addChild(Arg);
388 DIE *SPDeclDie = SPDie;
389 SPDie = new DIE(dwarf::DW_TAG_subprogram);
390 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
391 dwarf::DW_FORM_ref4, SPDeclDie);
397 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
398 Asm->GetTempSymbol("func_begin",
399 Asm->getFunctionNumber()));
400 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
401 Asm->GetTempSymbol("func_end",
402 Asm->getFunctionNumber()));
403 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
404 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
405 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
407 // Add name to the name table, we do this here because we're guaranteed
408 // to have concrete versions of our DW_TAG_subprogram nodes.
409 addSubprogramNames(SPCU, SP, SPDie);
414 // Construct new DW_TAG_lexical_block for this scope and attach
415 // DW_AT_low_pc/DW_AT_high_pc labels.
416 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
417 LexicalScope *Scope) {
418 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
419 if (Scope->isAbstractScope())
422 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
426 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
427 if (Ranges.size() > 1) {
428 // .debug_range section has not been laid out yet. Emit offset in
429 // .debug_range as a uint, size 4, for now. emitDIE will handle
430 // DW_AT_ranges appropriately.
431 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
432 DebugRangeSymbols.size()
433 * Asm->getDataLayout().getPointerSize());
434 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
435 RE = Ranges.end(); RI != RE; ++RI) {
436 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
437 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
439 DebugRangeSymbols.push_back(NULL);
440 DebugRangeSymbols.push_back(NULL);
444 MCSymbol *Start = getLabelBeforeInsn(RI->first);
445 MCSymbol *End = getLabelAfterInsn(RI->second);
447 if (End == 0) return 0;
449 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
450 assert(End->isDefined() && "Invalid end label for an inlined scope!");
452 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
453 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
458 // This scope represents inlined body of a function. Construct DIE to
459 // represent this concrete inlined copy of the function.
460 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
461 LexicalScope *Scope) {
462 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
463 assert(Ranges.empty() == false &&
464 "LexicalScope does not have instruction markers!");
466 if (!Scope->getScopeNode())
468 DIScope DS(Scope->getScopeNode());
469 DISubprogram InlinedSP = getDISubprogram(DS);
470 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
472 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
476 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
477 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
478 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
480 if (StartLabel == 0 || EndLabel == 0) {
481 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
483 assert(StartLabel->isDefined() &&
484 "Invalid starting label for an inlined scope!");
485 assert(EndLabel->isDefined() &&
486 "Invalid end label for an inlined scope!");
488 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
489 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
490 dwarf::DW_FORM_ref4, OriginDIE);
492 if (Ranges.size() > 1) {
493 // .debug_range section has not been laid out yet. Emit offset in
494 // .debug_range as a uint, size 4, for now. emitDIE will handle
495 // DW_AT_ranges appropriately.
496 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
497 DebugRangeSymbols.size()
498 * Asm->getDataLayout().getPointerSize());
499 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
500 RE = Ranges.end(); RI != RE; ++RI) {
501 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
502 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
504 DebugRangeSymbols.push_back(NULL);
505 DebugRangeSymbols.push_back(NULL);
507 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
508 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
511 InlinedSubprogramDIEs.insert(OriginDIE);
513 // Track the start label for this inlined function.
514 //.debug_inlined section specification does not clearly state how
515 // to emit inlined scope that is split into multiple instruction ranges.
516 // For now, use first instruction range and emit low_pc/high_pc pair and
517 // corresponding .debug_inlined section entry for this pair.
518 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
519 I = InlineInfo.find(InlinedSP);
521 if (I == InlineInfo.end()) {
522 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
523 InlinedSPNodes.push_back(InlinedSP);
525 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
527 DILocation DL(Scope->getInlinedAt());
528 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
529 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
530 TheCU->getUniqueID()));
531 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
533 // Add name to the name table, we do this here because we're guaranteed
534 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
535 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
540 // Construct a DIE for this scope.
541 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
542 if (!Scope || !Scope->getScopeNode())
545 DIScope DS(Scope->getScopeNode());
546 // Early return to avoid creating dangling variable|scope DIEs.
547 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
551 SmallVector<DIE *, 8> Children;
552 DIE *ObjectPointer = NULL;
554 // Collect arguments for current function.
555 if (LScopes.isCurrentFunctionScope(Scope))
556 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
557 if (DbgVariable *ArgDV = CurrentFnArguments[i])
559 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
560 Children.push_back(Arg);
561 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
564 // Collect lexical scope children first.
565 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
566 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
568 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
569 Children.push_back(Variable);
570 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
572 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
573 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
574 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
575 Children.push_back(Nested);
576 DIE *ScopeDIE = NULL;
577 if (Scope->getInlinedAt())
578 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
579 else if (DS.isSubprogram()) {
580 ProcessedSPNodes.insert(DS);
581 if (Scope->isAbstractScope()) {
582 ScopeDIE = TheCU->getDIE(DS);
583 // Note down abstract DIE.
585 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
588 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
591 // There is no need to emit empty lexical block DIE.
592 std::pair<ImportedEntityMap::const_iterator,
593 ImportedEntityMap::const_iterator> Range = std::equal_range(
594 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
595 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
597 if (Children.empty() && Range.first == Range.second)
599 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
600 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
602 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
605 if (!ScopeDIE) return NULL;
608 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
609 E = Children.end(); I != E; ++I)
610 ScopeDIE->addChild(*I);
612 if (DS.isSubprogram() && ObjectPointer != NULL)
613 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
614 dwarf::DW_FORM_ref4, ObjectPointer);
616 if (DS.isSubprogram())
617 TheCU->addPubTypes(DISubprogram(DS));
622 // Look up the source id with the given directory and source file names.
623 // If none currently exists, create a new id and insert it in the
624 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
626 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
627 StringRef DirName, unsigned CUID) {
628 // If we use .loc in assembly, we can't separate .file entries according to
629 // compile units. Thus all files will belong to the default compile unit.
630 if (Asm->TM.hasMCUseLoc() &&
631 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
634 // If FE did not provide a file name, then assume stdin.
635 if (FileName.empty())
636 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
638 // TODO: this might not belong here. See if we can factor this better.
639 if (DirName == CompilationDir)
642 // FileIDCUMap stores the current ID for the given compile unit.
643 unsigned SrcId = FileIDCUMap[CUID] + 1;
645 // We look up the CUID/file/dir by concatenating them with a zero byte.
646 SmallString<128> NamePair;
647 NamePair += utostr(CUID);
650 NamePair += '\0'; // Zero bytes are not allowed in paths.
651 NamePair += FileName;
653 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
654 if (Ent.getValue() != SrcId)
655 return Ent.getValue();
657 FileIDCUMap[CUID] = SrcId;
658 // Print out a .file directive to specify files for .loc directives.
659 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
664 // Create new CompileUnit for the given metadata node with tag
665 // DW_TAG_compile_unit.
666 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
667 DICompileUnit DIUnit(N);
668 StringRef FN = DIUnit.getFilename();
669 CompilationDir = DIUnit.getDirectory();
671 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
672 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
673 DIUnit.getLanguage(), Die, N, Asm,
676 FileIDCUMap[NewCU->getUniqueID()] = 0;
677 // Call this to emit a .file directive if it wasn't emitted for the source
678 // file this CU comes from yet.
679 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
681 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
682 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
683 DIUnit.getLanguage());
684 NewCU->addString(Die, dwarf::DW_AT_name, FN);
686 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
687 // into an entity. We're using 0 (or a NULL label) for this. For
688 // split dwarf it's in the skeleton CU so omit it here.
689 if (!useSplitDwarf())
690 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
692 // Define start line table label for each Compile Unit.
693 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
694 NewCU->getUniqueID());
695 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
696 NewCU->getUniqueID());
698 // Use a single line table if we are using .loc and generating assembly.
700 (Asm->TM.hasMCUseLoc() &&
701 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
702 (NewCU->getUniqueID() == 0);
704 // DW_AT_stmt_list is a offset of line number information for this
705 // compile unit in debug_line section. For split dwarf this is
706 // left in the skeleton CU and so not included.
707 // The line table entries are not always emitted in assembly, so it
708 // is not okay to use line_table_start here.
709 if (!useSplitDwarf()) {
710 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
711 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
713 Asm->GetTempSymbol("section_line") : LineTableStartSym);
714 else if (UseTheFirstCU)
715 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
717 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
718 LineTableStartSym, DwarfLineSectionSym);
721 // If we're using split dwarf the compilation dir is going to be in the
722 // skeleton CU and so we don't need to duplicate it here.
723 if (!useSplitDwarf() && !CompilationDir.empty())
724 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
725 if (DIUnit.isOptimized())
726 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
728 StringRef Flags = DIUnit.getFlags();
730 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
732 if (unsigned RVer = DIUnit.getRunTimeVersion())
733 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
734 dwarf::DW_FORM_data1, RVer);
739 InfoHolder.addUnit(NewCU);
741 CUMap.insert(std::make_pair(N, NewCU));
745 // Construct subprogram DIE.
746 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
748 CompileUnit *&CURef = SPMap[N];
754 if (!SP.isDefinition())
755 // This is a method declaration which will be handled while constructing
759 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
762 TheCU->insertDIE(N, SubprogramDie);
764 // Add to context owner.
765 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
767 // Expose as global, if requested.
768 if (GenerateDwarfPubNamesSection)
769 TheCU->addGlobalName(SP.getName(), SubprogramDie);
772 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
774 DIImportedEntity Module(N);
775 if (!Module.Verify())
777 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
778 constructImportedEntityDIE(TheCU, Module, D);
781 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
783 DIImportedEntity Module(N);
784 if (!Module.Verify())
786 return constructImportedEntityDIE(TheCU, Module, Context);
789 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
790 const DIImportedEntity &Module,
792 assert(Module.Verify() &&
793 "Use one of the MDNode * overloads to handle invalid metadata");
794 assert(Context && "Should always have a context for an imported_module");
795 DIE *IMDie = new DIE(Module.getTag());
796 TheCU->insertDIE(Module, IMDie);
798 DIDescriptor Entity = Module.getEntity();
799 if (Entity.isNameSpace())
800 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
801 else if (Entity.isSubprogram())
802 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
803 else if (Entity.isType())
804 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
806 EntityDie = TheCU->getDIE(Entity);
807 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
808 Module.getContext().getDirectory(),
809 TheCU->getUniqueID());
810 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
811 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
812 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
814 StringRef Name = Module.getName();
816 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
817 Context->addChild(IMDie);
820 // Emit all Dwarf sections that should come prior to the content. Create
821 // global DIEs and emit initial debug info sections. This is invoked by
822 // the target AsmPrinter.
823 void DwarfDebug::beginModule() {
824 if (DisableDebugInfoPrinting)
827 const Module *M = MMI->getModule();
829 // If module has named metadata anchors then use them, otherwise scan the
830 // module using debug info finder to collect debug info.
831 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
835 // Emit initial sections so we can reference labels later.
838 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
839 DICompileUnit CUNode(CU_Nodes->getOperand(i));
840 CompileUnit *CU = constructCompileUnit(CUNode);
841 DIArray ImportedEntities = CUNode.getImportedEntities();
842 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
843 ScopesWithImportedEntities.push_back(std::make_pair(
844 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
845 ImportedEntities.getElement(i)));
846 std::sort(ScopesWithImportedEntities.begin(),
847 ScopesWithImportedEntities.end(), CompareFirst());
848 DIArray GVs = CUNode.getGlobalVariables();
849 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
850 CU->createGlobalVariableDIE(GVs.getElement(i));
851 DIArray SPs = CUNode.getSubprograms();
852 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
853 constructSubprogramDIE(CU, SPs.getElement(i));
854 DIArray EnumTypes = CUNode.getEnumTypes();
855 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
856 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
857 DIArray RetainedTypes = CUNode.getRetainedTypes();
858 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
859 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
860 // Emit imported_modules last so that the relevant context is already
862 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
863 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
864 // If we're splitting the dwarf out now that we've got the entire
865 // CU then construct a skeleton CU based upon it.
866 if (useSplitDwarf()) {
867 // This should be a unique identifier when we want to build .dwp files.
868 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
869 dwarf::DW_FORM_data8, 0);
870 // Now construct the skeleton CU associated.
871 constructSkeletonCU(CUNode);
875 // Tell MMI that we have debug info.
876 MMI->setDebugInfoAvailability(true);
878 // Prime section data.
879 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
882 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
883 void DwarfDebug::computeInlinedDIEs() {
884 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
885 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
886 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
888 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
890 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
891 AE = AbstractSPDies.end(); AI != AE; ++AI) {
892 DIE *ISP = AI->second;
893 if (InlinedSubprogramDIEs.count(ISP))
895 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
899 // Collect info for variables that were optimized out.
900 void DwarfDebug::collectDeadVariables() {
901 const Module *M = MMI->getModule();
902 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
904 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
905 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
906 DICompileUnit TheCU(CU_Nodes->getOperand(i));
907 DIArray Subprograms = TheCU.getSubprograms();
908 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
909 DISubprogram SP(Subprograms.getElement(i));
910 if (ProcessedSPNodes.count(SP) != 0) continue;
911 if (!SP.Verify()) continue;
912 if (!SP.isDefinition()) continue;
913 DIArray Variables = SP.getVariables();
914 if (Variables.getNumElements() == 0) continue;
916 LexicalScope *Scope =
917 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
918 DeadFnScopeMap[SP] = Scope;
920 // Construct subprogram DIE and add variables DIEs.
921 CompileUnit *SPCU = CUMap.lookup(TheCU);
922 assert(SPCU && "Unable to find Compile Unit!");
923 constructSubprogramDIE(SPCU, SP);
924 DIE *ScopeDIE = SPCU->getDIE(SP);
925 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
926 DIVariable DV(Variables.getElement(vi));
927 if (!DV.Verify()) continue;
928 DbgVariable *NewVar = new DbgVariable(DV, NULL);
929 if (DIE *VariableDIE =
930 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
931 ScopeDIE->addChild(VariableDIE);
936 DeleteContainerSeconds(DeadFnScopeMap);
939 void DwarfDebug::finalizeModuleInfo() {
940 // Collect info for variables that were optimized out.
941 collectDeadVariables();
943 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
944 computeInlinedDIEs();
946 // Emit DW_AT_containing_type attribute to connect types with their
947 // vtable holding type.
948 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
949 CUE = CUMap.end(); CUI != CUE; ++CUI) {
950 CompileUnit *TheCU = CUI->second;
951 TheCU->constructContainingTypeDIEs();
954 // Compute DIE offsets and sizes.
955 InfoHolder.computeSizeAndOffsets();
957 SkeletonHolder.computeSizeAndOffsets();
960 void DwarfDebug::endSections() {
961 // Standard sections final addresses.
962 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
963 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
964 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
965 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
967 // End text sections.
968 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
969 Asm->OutStreamer.SwitchSection(SectionMap[I]);
970 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
974 // Emit all Dwarf sections that should come after the content.
975 void DwarfDebug::endModule() {
977 if (!FirstCU) return;
979 // End any existing sections.
980 // TODO: Does this need to happen?
983 // Finalize the debug info for the module.
984 finalizeModuleInfo();
986 if (!useSplitDwarf()) {
987 // Emit all the DIEs into a debug info section.
990 // Corresponding abbreviations into a abbrev section.
993 // Emit info into a debug loc section.
996 // Emit info into a debug aranges section.
999 // Emit info into a debug ranges section.
1002 // Emit info into a debug macinfo section.
1005 // Emit inline info.
1006 // TODO: When we don't need the option anymore we
1007 // can remove all of the code that this section
1009 if (useDarwinGDBCompat())
1010 emitDebugInlineInfo();
1012 // TODO: Fill this in for separated debug sections and separate
1013 // out information into new sections.
1015 // Emit the debug info section and compile units.
1019 // Corresponding abbreviations into a abbrev section.
1020 emitAbbreviations();
1021 emitDebugAbbrevDWO();
1023 // Emit info into a debug loc section.
1026 // Emit info into a debug aranges section.
1029 // Emit info into a debug ranges section.
1032 // Emit info into a debug macinfo section.
1035 // Emit DWO addresses.
1036 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1038 // Emit inline info.
1039 // TODO: When we don't need the option anymore we
1040 // can remove all of the code that this section
1042 if (useDarwinGDBCompat())
1043 emitDebugInlineInfo();
1046 // Emit info into the dwarf accelerator table sections.
1047 if (useDwarfAccelTables()) {
1050 emitAccelNamespaces();
1054 // Emit info into a debug pubnames section, if requested.
1055 if (GenerateDwarfPubNamesSection)
1056 emitDebugPubnames();
1058 // Emit info into a debug pubtypes section.
1059 // TODO: When we don't need the option anymore we can
1060 // remove all of the code that adds to the table.
1061 if (useDarwinGDBCompat())
1062 emitDebugPubTypes();
1064 // Finally emit string information into a string table.
1066 if (useSplitDwarf())
1071 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1072 E = CUMap.end(); I != E; ++I)
1075 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1076 E = SkeletonCUs.end(); I != E; ++I)
1079 // Reset these for the next Module if we have one.
1083 // Find abstract variable, if any, associated with Var.
1084 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1085 DebugLoc ScopeLoc) {
1086 LLVMContext &Ctx = DV->getContext();
1087 // More then one inlined variable corresponds to one abstract variable.
1088 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1089 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1091 return AbsDbgVariable;
1093 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1097 AbsDbgVariable = new DbgVariable(Var, NULL);
1098 addScopeVariable(Scope, AbsDbgVariable);
1099 AbstractVariables[Var] = AbsDbgVariable;
1100 return AbsDbgVariable;
1103 // If Var is a current function argument then add it to CurrentFnArguments list.
1104 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1105 DbgVariable *Var, LexicalScope *Scope) {
1106 if (!LScopes.isCurrentFunctionScope(Scope))
1108 DIVariable DV = Var->getVariable();
1109 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1111 unsigned ArgNo = DV.getArgNumber();
1115 size_t Size = CurrentFnArguments.size();
1117 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1118 // llvm::Function argument size is not good indicator of how many
1119 // arguments does the function have at source level.
1121 CurrentFnArguments.resize(ArgNo * 2);
1122 CurrentFnArguments[ArgNo - 1] = Var;
1126 // Collect variable information from side table maintained by MMI.
1128 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1129 SmallPtrSet<const MDNode *, 16> &Processed) {
1130 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1131 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1132 VE = VMap.end(); VI != VE; ++VI) {
1133 const MDNode *Var = VI->first;
1135 Processed.insert(Var);
1137 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1139 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1141 // If variable scope is not found then skip this variable.
1145 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1146 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1147 RegVar->setFrameIndex(VP.first);
1148 if (!addCurrentFnArgument(MF, RegVar, Scope))
1149 addScopeVariable(Scope, RegVar);
1151 AbsDbgVariable->setFrameIndex(VP.first);
1155 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1157 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1158 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1159 return MI->getNumOperands() == 3 &&
1160 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1161 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1164 // Get .debug_loc entry for the instruction range starting at MI.
1165 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1166 const MCSymbol *FLabel,
1167 const MCSymbol *SLabel,
1168 const MachineInstr *MI) {
1169 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1171 assert(MI->getNumOperands() == 3);
1172 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1173 MachineLocation MLoc;
1174 // TODO: Currently an offset of 0 in a DBG_VALUE means
1175 // we need to generate a direct register value.
1176 // There is no way to specify an indirect value with offset 0.
1177 if (MI->getOperand(1).getImm() == 0)
1178 MLoc.set(MI->getOperand(0).getReg());
1180 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1181 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1183 if (MI->getOperand(0).isImm())
1184 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1185 if (MI->getOperand(0).isFPImm())
1186 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1187 if (MI->getOperand(0).isCImm())
1188 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1190 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1193 // Find variables for each lexical scope.
1195 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1196 SmallPtrSet<const MDNode *, 16> &Processed) {
1198 // collection info from MMI table.
1199 collectVariableInfoFromMMITable(MF, Processed);
1201 for (SmallVectorImpl<const MDNode*>::const_iterator
1202 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1204 const MDNode *Var = *UVI;
1205 if (Processed.count(Var))
1208 // History contains relevant DBG_VALUE instructions for Var and instructions
1210 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1211 if (History.empty())
1213 const MachineInstr *MInsn = History.front();
1216 LexicalScope *Scope = NULL;
1217 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1218 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1219 Scope = LScopes.getCurrentFunctionScope();
1220 else if (MDNode *IA = DV.getInlinedAt())
1221 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1223 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1224 // If variable scope is not found then skip this variable.
1228 Processed.insert(DV);
1229 assert(MInsn->isDebugValue() && "History must begin with debug value");
1230 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1231 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1232 if (!addCurrentFnArgument(MF, RegVar, Scope))
1233 addScopeVariable(Scope, RegVar);
1235 AbsVar->setMInsn(MInsn);
1237 // Simplify ranges that are fully coalesced.
1238 if (History.size() <= 1 || (History.size() == 2 &&
1239 MInsn->isIdenticalTo(History.back()))) {
1240 RegVar->setMInsn(MInsn);
1244 // Handle multiple DBG_VALUE instructions describing one variable.
1245 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1247 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1248 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1249 const MachineInstr *Begin = *HI;
1250 assert(Begin->isDebugValue() && "Invalid History entry");
1252 // Check if DBG_VALUE is truncating a range.
1253 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1254 && !Begin->getOperand(0).getReg())
1257 // Compute the range for a register location.
1258 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1259 const MCSymbol *SLabel = 0;
1262 // If Begin is the last instruction in History then its value is valid
1263 // until the end of the function.
1264 SLabel = FunctionEndSym;
1266 const MachineInstr *End = HI[1];
1267 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1268 << "\t" << *Begin << "\t" << *End << "\n");
1269 if (End->isDebugValue())
1270 SLabel = getLabelBeforeInsn(End);
1272 // End is a normal instruction clobbering the range.
1273 SLabel = getLabelAfterInsn(End);
1274 assert(SLabel && "Forgot label after clobber instruction");
1279 // The value is valid until the next DBG_VALUE or clobber.
1280 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1283 DotDebugLocEntries.push_back(DotDebugLocEntry());
1286 // Collect info for variables that were optimized out.
1287 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1288 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1289 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1290 DIVariable DV(Variables.getElement(i));
1291 if (!DV || !DV.Verify() || !Processed.insert(DV))
1293 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1294 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1298 // Return Label preceding the instruction.
1299 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1300 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1301 assert(Label && "Didn't insert label before instruction");
1305 // Return Label immediately following the instruction.
1306 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1307 return LabelsAfterInsn.lookup(MI);
1310 // Process beginning of an instruction.
1311 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1312 // Check if source location changes, but ignore DBG_VALUE locations.
1313 if (!MI->isDebugValue()) {
1314 DebugLoc DL = MI->getDebugLoc();
1315 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1318 if (DL == PrologEndLoc) {
1319 Flags |= DWARF2_FLAG_PROLOGUE_END;
1320 PrologEndLoc = DebugLoc();
1322 if (PrologEndLoc.isUnknown())
1323 Flags |= DWARF2_FLAG_IS_STMT;
1325 if (!DL.isUnknown()) {
1326 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1327 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1329 recordSourceLine(0, 0, 0, 0);
1333 // Insert labels where requested.
1334 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1335 LabelsBeforeInsn.find(MI);
1338 if (I == LabelsBeforeInsn.end())
1341 // Label already assigned.
1346 PrevLabel = MMI->getContext().CreateTempSymbol();
1347 Asm->OutStreamer.EmitLabel(PrevLabel);
1349 I->second = PrevLabel;
1352 // Process end of an instruction.
1353 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1354 // Don't create a new label after DBG_VALUE instructions.
1355 // They don't generate code.
1356 if (!MI->isDebugValue())
1359 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1360 LabelsAfterInsn.find(MI);
1363 if (I == LabelsAfterInsn.end())
1366 // Label already assigned.
1370 // We need a label after this instruction.
1372 PrevLabel = MMI->getContext().CreateTempSymbol();
1373 Asm->OutStreamer.EmitLabel(PrevLabel);
1375 I->second = PrevLabel;
1378 // Each LexicalScope has first instruction and last instruction to mark
1379 // beginning and end of a scope respectively. Create an inverse map that list
1380 // scopes starts (and ends) with an instruction. One instruction may start (or
1381 // end) multiple scopes. Ignore scopes that are not reachable.
1382 void DwarfDebug::identifyScopeMarkers() {
1383 SmallVector<LexicalScope *, 4> WorkList;
1384 WorkList.push_back(LScopes.getCurrentFunctionScope());
1385 while (!WorkList.empty()) {
1386 LexicalScope *S = WorkList.pop_back_val();
1388 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1389 if (!Children.empty())
1390 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1391 SE = Children.end(); SI != SE; ++SI)
1392 WorkList.push_back(*SI);
1394 if (S->isAbstractScope())
1397 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1400 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1401 RE = Ranges.end(); RI != RE; ++RI) {
1402 assert(RI->first && "InsnRange does not have first instruction!");
1403 assert(RI->second && "InsnRange does not have second instruction!");
1404 requestLabelBeforeInsn(RI->first);
1405 requestLabelAfterInsn(RI->second);
1410 // Get MDNode for DebugLoc's scope.
1411 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1412 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1413 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1414 return DL.getScope(Ctx);
1417 // Walk up the scope chain of given debug loc and find line number info
1418 // for the function.
1419 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1420 const MDNode *Scope = getScopeNode(DL, Ctx);
1421 DISubprogram SP = getDISubprogram(Scope);
1423 // Check for number of operands since the compatibility is
1425 if (SP->getNumOperands() > 19)
1426 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1428 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1434 // Gather pre-function debug information. Assumes being called immediately
1435 // after the function entry point has been emitted.
1436 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1437 if (!MMI->hasDebugInfo()) return;
1438 LScopes.initialize(*MF);
1439 if (LScopes.empty()) return;
1440 identifyScopeMarkers();
1442 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1444 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1445 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1446 assert(TheCU && "Unable to find compile unit!");
1447 if (Asm->TM.hasMCUseLoc() &&
1448 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1449 // Use a single line table if we are using .loc and generating assembly.
1450 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1452 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1454 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1455 Asm->getFunctionNumber());
1456 // Assumes in correct section after the entry point.
1457 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1459 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1461 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1462 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1463 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1465 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1467 bool AtBlockEntry = true;
1468 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1470 const MachineInstr *MI = II;
1472 if (MI->isDebugValue()) {
1473 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1475 // Keep track of user variables.
1477 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1479 // Variable is in a register, we need to check for clobbers.
1480 if (isDbgValueInDefinedReg(MI))
1481 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1483 // Check the history of this variable.
1484 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1485 if (History.empty()) {
1486 UserVariables.push_back(Var);
1487 // The first mention of a function argument gets the FunctionBeginSym
1488 // label, so arguments are visible when breaking at function entry.
1490 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1491 DISubprogram(getDISubprogram(DV.getContext()))
1492 .describes(MF->getFunction()))
1493 LabelsBeforeInsn[MI] = FunctionBeginSym;
1495 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1496 const MachineInstr *Prev = History.back();
1497 if (Prev->isDebugValue()) {
1498 // Coalesce identical entries at the end of History.
1499 if (History.size() >= 2 &&
1500 Prev->isIdenticalTo(History[History.size() - 2])) {
1501 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1503 << "\t" << *History[History.size() - 2] << "\n");
1507 // Terminate old register assignments that don't reach MI;
1508 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1509 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1510 isDbgValueInDefinedReg(Prev)) {
1511 // Previous register assignment needs to terminate at the end of
1513 MachineBasicBlock::const_iterator LastMI =
1514 PrevMBB->getLastNonDebugInstr();
1515 if (LastMI == PrevMBB->end()) {
1516 // Drop DBG_VALUE for empty range.
1517 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1518 << "\t" << *Prev << "\n");
1520 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1521 // Terminate after LastMI.
1522 History.push_back(LastMI);
1526 History.push_back(MI);
1528 // Not a DBG_VALUE instruction.
1530 AtBlockEntry = false;
1532 // First known non-DBG_VALUE and non-frame setup location marks
1533 // the beginning of the function body.
1534 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1535 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1536 PrologEndLoc = MI->getDebugLoc();
1538 // Check if the instruction clobbers any registers with debug vars.
1539 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1540 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1541 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1543 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1544 AI.isValid(); ++AI) {
1546 const MDNode *Var = LiveUserVar[Reg];
1549 // Reg is now clobbered.
1550 LiveUserVar[Reg] = 0;
1552 // Was MD last defined by a DBG_VALUE referring to Reg?
1553 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1554 if (HistI == DbgValues.end())
1556 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1557 if (History.empty())
1559 const MachineInstr *Prev = History.back();
1560 // Sanity-check: Register assignments are terminated at the end of
1562 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1564 // Is the variable still in Reg?
1565 if (!isDbgValueInDefinedReg(Prev) ||
1566 Prev->getOperand(0).getReg() != Reg)
1568 // Var is clobbered. Make sure the next instruction gets a label.
1569 History.push_back(MI);
1576 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1578 SmallVectorImpl<const MachineInstr*> &History = I->second;
1579 if (History.empty())
1582 // Make sure the final register assignments are terminated.
1583 const MachineInstr *Prev = History.back();
1584 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1585 const MachineBasicBlock *PrevMBB = Prev->getParent();
1586 MachineBasicBlock::const_iterator LastMI =
1587 PrevMBB->getLastNonDebugInstr();
1588 if (LastMI == PrevMBB->end())
1589 // Drop DBG_VALUE for empty range.
1591 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1592 // Terminate after LastMI.
1593 History.push_back(LastMI);
1596 // Request labels for the full history.
1597 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1598 const MachineInstr *MI = History[i];
1599 if (MI->isDebugValue())
1600 requestLabelBeforeInsn(MI);
1602 requestLabelAfterInsn(MI);
1606 PrevInstLoc = DebugLoc();
1607 PrevLabel = FunctionBeginSym;
1609 // Record beginning of function.
1610 if (!PrologEndLoc.isUnknown()) {
1611 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1612 MF->getFunction()->getContext());
1613 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1614 FnStartDL.getScope(MF->getFunction()->getContext()),
1615 // We'd like to list the prologue as "not statements" but GDB behaves
1616 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1617 DWARF2_FLAG_IS_STMT);
1621 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1622 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1623 DIVariable DV = Var->getVariable();
1624 // Variables with positive arg numbers are parameters.
1625 if (unsigned ArgNum = DV.getArgNumber()) {
1626 // Keep all parameters in order at the start of the variable list to ensure
1627 // function types are correct (no out-of-order parameters)
1629 // This could be improved by only doing it for optimized builds (unoptimized
1630 // builds have the right order to begin with), searching from the back (this
1631 // would catch the unoptimized case quickly), or doing a binary search
1632 // rather than linear search.
1633 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1634 while (I != Vars.end()) {
1635 unsigned CurNum = (*I)->getVariable().getArgNumber();
1636 // A local (non-parameter) variable has been found, insert immediately
1640 // A later indexed parameter has been found, insert immediately before it.
1641 if (CurNum > ArgNum)
1645 Vars.insert(I, Var);
1649 Vars.push_back(Var);
1652 // Gather and emit post-function debug information.
1653 void DwarfDebug::endFunction(const MachineFunction *MF) {
1654 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1656 // Define end label for subprogram.
1657 FunctionEndSym = Asm->GetTempSymbol("func_end",
1658 Asm->getFunctionNumber());
1659 // Assumes in correct section after the entry point.
1660 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1661 // Set DwarfCompileUnitID in MCContext to default value.
1662 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1664 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1665 collectVariableInfo(MF, ProcessedVars);
1667 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1668 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1669 assert(TheCU && "Unable to find compile unit!");
1671 // Construct abstract scopes.
1672 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1673 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1674 LexicalScope *AScope = AList[i];
1675 DISubprogram SP(AScope->getScopeNode());
1677 // Collect info for variables that were optimized out.
1678 DIArray Variables = SP.getVariables();
1679 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1680 DIVariable DV(Variables.getElement(i));
1681 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1683 // Check that DbgVariable for DV wasn't created earlier, when
1684 // findAbstractVariable() was called for inlined instance of DV.
1685 LLVMContext &Ctx = DV->getContext();
1686 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1687 if (AbstractVariables.lookup(CleanDV))
1689 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1690 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1693 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1694 constructScopeDIE(TheCU, AScope);
1697 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1699 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1700 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1703 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1704 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1705 DeleteContainerPointers(I->second);
1706 ScopeVariables.clear();
1707 DeleteContainerPointers(CurrentFnArguments);
1708 UserVariables.clear();
1710 AbstractVariables.clear();
1711 LabelsBeforeInsn.clear();
1712 LabelsAfterInsn.clear();
1716 // Register a source line with debug info. Returns the unique label that was
1717 // emitted and which provides correspondence to the source line list.
1718 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1724 DIDescriptor Scope(S);
1726 if (Scope.isCompileUnit()) {
1727 DICompileUnit CU(S);
1728 Fn = CU.getFilename();
1729 Dir = CU.getDirectory();
1730 } else if (Scope.isFile()) {
1732 Fn = F.getFilename();
1733 Dir = F.getDirectory();
1734 } else if (Scope.isSubprogram()) {
1736 Fn = SP.getFilename();
1737 Dir = SP.getDirectory();
1738 } else if (Scope.isLexicalBlockFile()) {
1739 DILexicalBlockFile DBF(S);
1740 Fn = DBF.getFilename();
1741 Dir = DBF.getDirectory();
1742 } else if (Scope.isLexicalBlock()) {
1743 DILexicalBlock DB(S);
1744 Fn = DB.getFilename();
1745 Dir = DB.getDirectory();
1747 llvm_unreachable("Unexpected scope info");
1749 Src = getOrCreateSourceID(Fn, Dir,
1750 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1752 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1755 //===----------------------------------------------------------------------===//
1757 //===----------------------------------------------------------------------===//
1759 // Compute the size and offset of a DIE.
1761 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1762 // Get the children.
1763 const std::vector<DIE *> &Children = Die->getChildren();
1765 // Record the abbreviation.
1766 assignAbbrevNumber(Die->getAbbrev());
1768 // Get the abbreviation for this DIE.
1769 unsigned AbbrevNumber = Die->getAbbrevNumber();
1770 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1773 Die->setOffset(Offset);
1775 // Start the size with the size of abbreviation code.
1776 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1778 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1779 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1781 // Size the DIE attribute values.
1782 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1783 // Size attribute value.
1784 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1786 // Size the DIE children if any.
1787 if (!Children.empty()) {
1788 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1789 "Children flag not set");
1791 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1792 Offset = computeSizeAndOffset(Children[j], Offset);
1794 // End of children marker.
1795 Offset += sizeof(int8_t);
1798 Die->setSize(Offset - Die->getOffset());
1802 // Compute the size and offset of all the DIEs.
1803 void DwarfUnits::computeSizeAndOffsets() {
1804 // Offset from the beginning of debug info section.
1805 unsigned SecOffset = 0;
1806 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1807 E = CUs.end(); I != E; ++I) {
1808 (*I)->setDebugInfoOffset(SecOffset);
1810 sizeof(int32_t) + // Length of Compilation Unit Info
1811 sizeof(int16_t) + // DWARF version number
1812 sizeof(int32_t) + // Offset Into Abbrev. Section
1813 sizeof(int8_t); // Pointer Size (in bytes)
1815 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1816 SecOffset += EndOffset;
1820 // Emit initial Dwarf sections with a label at the start of each one.
1821 void DwarfDebug::emitSectionLabels() {
1822 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1824 // Dwarf sections base addresses.
1825 DwarfInfoSectionSym =
1826 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1827 DwarfAbbrevSectionSym =
1828 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1829 if (useSplitDwarf())
1830 DwarfAbbrevDWOSectionSym =
1831 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1832 "section_abbrev_dwo");
1833 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1835 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1836 emitSectionSym(Asm, MacroInfo);
1838 DwarfLineSectionSym =
1839 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1840 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1841 if (GenerateDwarfPubNamesSection)
1842 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1843 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1844 DwarfStrSectionSym =
1845 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1846 if (useSplitDwarf()) {
1847 DwarfStrDWOSectionSym =
1848 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1849 DwarfAddrSectionSym =
1850 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1852 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1855 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1856 "section_debug_loc");
1858 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1859 emitSectionSym(Asm, TLOF.getDataSection());
1862 // Recursively emits a debug information entry.
1863 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1864 // Get the abbreviation for this DIE.
1865 unsigned AbbrevNumber = Die->getAbbrevNumber();
1866 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1868 // Emit the code (index) for the abbreviation.
1869 if (Asm->isVerbose())
1870 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1871 Twine::utohexstr(Die->getOffset()) + ":0x" +
1872 Twine::utohexstr(Die->getSize()) + " " +
1873 dwarf::TagString(Abbrev->getTag()));
1874 Asm->EmitULEB128(AbbrevNumber);
1876 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1877 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1879 // Emit the DIE attribute values.
1880 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1881 unsigned Attr = AbbrevData[i].getAttribute();
1882 unsigned Form = AbbrevData[i].getForm();
1883 assert(Form && "Too many attributes for DIE (check abbreviation)");
1885 if (Asm->isVerbose())
1886 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1889 case dwarf::DW_AT_abstract_origin: {
1890 DIEEntry *E = cast<DIEEntry>(Values[i]);
1891 DIE *Origin = E->getEntry();
1892 unsigned Addr = Origin->getOffset();
1893 if (Form == dwarf::DW_FORM_ref_addr) {
1894 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1895 // section. Origin->getOffset() returns the offset from start of the
1897 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1898 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1900 Asm->EmitInt32(Addr);
1903 case dwarf::DW_AT_ranges: {
1904 // DW_AT_range Value encodes offset in debug_range section.
1905 DIEInteger *V = cast<DIEInteger>(Values[i]);
1907 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1908 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1912 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1914 DwarfDebugRangeSectionSym,
1919 case dwarf::DW_AT_location: {
1920 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1921 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1922 Asm->EmitLabelReference(L->getValue(), 4);
1924 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1926 Values[i]->EmitValue(Asm, Form);
1930 case dwarf::DW_AT_accessibility: {
1931 if (Asm->isVerbose()) {
1932 DIEInteger *V = cast<DIEInteger>(Values[i]);
1933 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1935 Values[i]->EmitValue(Asm, Form);
1939 // Emit an attribute using the defined form.
1940 Values[i]->EmitValue(Asm, Form);
1945 // Emit the DIE children if any.
1946 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1947 const std::vector<DIE *> &Children = Die->getChildren();
1949 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1950 emitDIE(Children[j], Abbrevs);
1952 if (Asm->isVerbose())
1953 Asm->OutStreamer.AddComment("End Of Children Mark");
1958 // Emit the various dwarf units to the unit section USection with
1959 // the abbreviations going into ASection.
1960 void DwarfUnits::emitUnits(DwarfDebug *DD,
1961 const MCSection *USection,
1962 const MCSection *ASection,
1963 const MCSymbol *ASectionSym) {
1964 Asm->OutStreamer.SwitchSection(USection);
1965 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1966 E = CUs.end(); I != E; ++I) {
1967 CompileUnit *TheCU = *I;
1968 DIE *Die = TheCU->getCUDie();
1970 // Emit the compile units header.
1972 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1973 TheCU->getUniqueID()));
1975 // Emit size of content not including length itself
1976 unsigned ContentSize = Die->getSize() +
1977 sizeof(int16_t) + // DWARF version number
1978 sizeof(int32_t) + // Offset Into Abbrev. Section
1979 sizeof(int8_t); // Pointer Size (in bytes)
1981 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1982 Asm->EmitInt32(ContentSize);
1983 Asm->OutStreamer.AddComment("DWARF version number");
1984 Asm->EmitInt16(dwarf::DWARF_VERSION);
1985 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1986 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1988 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1989 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1991 DD->emitDIE(Die, Abbreviations);
1992 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1993 TheCU->getUniqueID()));
1997 /// For a given compile unit DIE, returns offset from beginning of debug info.
1998 unsigned DwarfUnits::getCUOffset(DIE *Die) {
1999 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2000 "Input DIE should be compile unit in getCUOffset.");
2001 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2002 E = CUs.end(); I != E; ++I) {
2003 CompileUnit *TheCU = *I;
2004 if (TheCU->getCUDie() == Die)
2005 return TheCU->getDebugInfoOffset();
2007 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2010 // Emit the debug info section.
2011 void DwarfDebug::emitDebugInfo() {
2012 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2014 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2015 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2016 DwarfAbbrevSectionSym);
2019 // Emit the abbreviation section.
2020 void DwarfDebug::emitAbbreviations() {
2021 if (!useSplitDwarf())
2022 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2025 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2028 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2029 std::vector<DIEAbbrev *> *Abbrevs) {
2030 // Check to see if it is worth the effort.
2031 if (!Abbrevs->empty()) {
2032 // Start the debug abbrev section.
2033 Asm->OutStreamer.SwitchSection(Section);
2035 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2036 Asm->OutStreamer.EmitLabel(Begin);
2038 // For each abbrevation.
2039 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2040 // Get abbreviation data
2041 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2043 // Emit the abbrevations code (base 1 index.)
2044 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2046 // Emit the abbreviations data.
2050 // Mark end of abbreviations.
2051 Asm->EmitULEB128(0, "EOM(3)");
2053 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2054 Asm->OutStreamer.EmitLabel(End);
2058 // Emit the last address of the section and the end of the line matrix.
2059 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2060 // Define last address of section.
2061 Asm->OutStreamer.AddComment("Extended Op");
2064 Asm->OutStreamer.AddComment("Op size");
2065 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2066 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2067 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2069 Asm->OutStreamer.AddComment("Section end label");
2071 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2072 Asm->getDataLayout().getPointerSize());
2074 // Mark end of matrix.
2075 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2081 // Emit visible names into a hashed accelerator table section.
2082 void DwarfDebug::emitAccelNames() {
2083 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2084 dwarf::DW_FORM_data4));
2085 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2086 E = CUMap.end(); I != E; ++I) {
2087 CompileUnit *TheCU = I->second;
2088 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2089 for (StringMap<std::vector<DIE*> >::const_iterator
2090 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2091 StringRef Name = GI->getKey();
2092 const std::vector<DIE *> &Entities = GI->second;
2093 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2094 DE = Entities.end(); DI != DE; ++DI)
2095 AT.AddName(Name, (*DI));
2099 AT.FinalizeTable(Asm, "Names");
2100 Asm->OutStreamer.SwitchSection(
2101 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2102 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2103 Asm->OutStreamer.EmitLabel(SectionBegin);
2105 // Emit the full data.
2106 AT.Emit(Asm, SectionBegin, &InfoHolder);
2109 // Emit objective C classes and categories into a hashed accelerator table
2111 void DwarfDebug::emitAccelObjC() {
2112 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2113 dwarf::DW_FORM_data4));
2114 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2115 E = CUMap.end(); I != E; ++I) {
2116 CompileUnit *TheCU = I->second;
2117 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2118 for (StringMap<std::vector<DIE*> >::const_iterator
2119 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2120 StringRef Name = GI->getKey();
2121 const std::vector<DIE *> &Entities = GI->second;
2122 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2123 DE = Entities.end(); DI != DE; ++DI)
2124 AT.AddName(Name, (*DI));
2128 AT.FinalizeTable(Asm, "ObjC");
2129 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2130 .getDwarfAccelObjCSection());
2131 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2132 Asm->OutStreamer.EmitLabel(SectionBegin);
2134 // Emit the full data.
2135 AT.Emit(Asm, SectionBegin, &InfoHolder);
2138 // Emit namespace dies into a hashed accelerator table.
2139 void DwarfDebug::emitAccelNamespaces() {
2140 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2141 dwarf::DW_FORM_data4));
2142 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2143 E = CUMap.end(); I != E; ++I) {
2144 CompileUnit *TheCU = I->second;
2145 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2146 for (StringMap<std::vector<DIE*> >::const_iterator
2147 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2148 StringRef Name = GI->getKey();
2149 const std::vector<DIE *> &Entities = GI->second;
2150 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2151 DE = Entities.end(); DI != DE; ++DI)
2152 AT.AddName(Name, (*DI));
2156 AT.FinalizeTable(Asm, "namespac");
2157 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2158 .getDwarfAccelNamespaceSection());
2159 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2160 Asm->OutStreamer.EmitLabel(SectionBegin);
2162 // Emit the full data.
2163 AT.Emit(Asm, SectionBegin, &InfoHolder);
2166 // Emit type dies into a hashed accelerator table.
2167 void DwarfDebug::emitAccelTypes() {
2168 std::vector<DwarfAccelTable::Atom> Atoms;
2169 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2170 dwarf::DW_FORM_data4));
2171 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2172 dwarf::DW_FORM_data2));
2173 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2174 dwarf::DW_FORM_data1));
2175 DwarfAccelTable AT(Atoms);
2176 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2177 E = CUMap.end(); I != E; ++I) {
2178 CompileUnit *TheCU = I->second;
2179 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2180 = TheCU->getAccelTypes();
2181 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2182 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2183 StringRef Name = GI->getKey();
2184 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2185 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2186 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2187 AT.AddName(Name, (*DI).first, (*DI).second);
2191 AT.FinalizeTable(Asm, "types");
2192 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2193 .getDwarfAccelTypesSection());
2194 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2195 Asm->OutStreamer.EmitLabel(SectionBegin);
2197 // Emit the full data.
2198 AT.Emit(Asm, SectionBegin, &InfoHolder);
2201 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2203 void DwarfDebug::emitDebugPubnames() {
2204 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2206 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2207 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2208 CompileUnit *TheCU = I->second;
2209 unsigned ID = TheCU->getUniqueID();
2211 if (TheCU->getGlobalNames().empty())
2214 // Start the dwarf pubnames section.
2215 Asm->OutStreamer.SwitchSection(
2216 Asm->getObjFileLowering().getDwarfPubNamesSection());
2218 Asm->OutStreamer.AddComment("Length of Public Names Info");
2219 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2220 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2222 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2224 Asm->OutStreamer.AddComment("DWARF Version");
2225 Asm->EmitInt16(dwarf::DWARF_VERSION);
2227 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2228 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2229 DwarfInfoSectionSym);
2231 Asm->OutStreamer.AddComment("Compilation Unit Length");
2232 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2233 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2236 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2237 for (StringMap<DIE*>::const_iterator
2238 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2239 const char *Name = GI->getKeyData();
2240 const DIE *Entity = GI->second;
2242 Asm->OutStreamer.AddComment("DIE offset");
2243 Asm->EmitInt32(Entity->getOffset());
2245 if (Asm->isVerbose())
2246 Asm->OutStreamer.AddComment("External Name");
2247 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2250 Asm->OutStreamer.AddComment("End Mark");
2252 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2256 void DwarfDebug::emitDebugPubTypes() {
2257 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2258 E = CUMap.end(); I != E; ++I) {
2259 CompileUnit *TheCU = I->second;
2260 // Start the dwarf pubtypes section.
2261 Asm->OutStreamer.SwitchSection(
2262 Asm->getObjFileLowering().getDwarfPubTypesSection());
2263 Asm->OutStreamer.AddComment("Length of Public Types Info");
2264 Asm->EmitLabelDifference(
2265 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2266 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2268 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2269 TheCU->getUniqueID()));
2271 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2272 Asm->EmitInt16(dwarf::DWARF_VERSION);
2274 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2275 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2276 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2277 TheCU->getUniqueID()),
2278 DwarfInfoSectionSym);
2280 Asm->OutStreamer.AddComment("Compilation Unit Length");
2281 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2282 TheCU->getUniqueID()),
2283 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2284 TheCU->getUniqueID()),
2287 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2288 for (StringMap<DIE*>::const_iterator
2289 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2290 const char *Name = GI->getKeyData();
2291 DIE *Entity = GI->second;
2293 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2294 Asm->EmitInt32(Entity->getOffset());
2296 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2297 // Emit the name with a terminating null byte.
2298 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2301 Asm->OutStreamer.AddComment("End Mark");
2303 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2304 TheCU->getUniqueID()));
2308 // Emit strings into a string section.
2309 void DwarfUnits::emitStrings(const MCSection *StrSection,
2310 const MCSection *OffsetSection = NULL,
2311 const MCSymbol *StrSecSym = NULL) {
2313 if (StringPool.empty()) return;
2315 // Start the dwarf str section.
2316 Asm->OutStreamer.SwitchSection(StrSection);
2318 // Get all of the string pool entries and put them in an array by their ID so
2319 // we can sort them.
2320 SmallVector<std::pair<unsigned,
2321 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2323 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2324 I = StringPool.begin(), E = StringPool.end();
2326 Entries.push_back(std::make_pair(I->second.second, &*I));
2328 array_pod_sort(Entries.begin(), Entries.end());
2330 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2331 // Emit a label for reference from debug information entries.
2332 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2334 // Emit the string itself with a terminating null byte.
2335 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2336 Entries[i].second->getKeyLength()+1));
2339 // If we've got an offset section go ahead and emit that now as well.
2340 if (OffsetSection) {
2341 Asm->OutStreamer.SwitchSection(OffsetSection);
2342 unsigned offset = 0;
2343 unsigned size = 4; // FIXME: DWARF64 is 8.
2344 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2345 Asm->OutStreamer.EmitIntValue(offset, size);
2346 offset += Entries[i].second->getKeyLength() + 1;
2351 // Emit strings into a string section.
2352 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2354 if (AddressPool.empty()) return;
2356 // Start the dwarf addr section.
2357 Asm->OutStreamer.SwitchSection(AddrSection);
2359 // Get all of the string pool entries and put them in an array by their ID so
2360 // we can sort them.
2361 SmallVector<std::pair<unsigned,
2362 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2364 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2365 I = AddressPool.begin(), E = AddressPool.end();
2367 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2369 array_pod_sort(Entries.begin(), Entries.end());
2371 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2372 // Emit a label for reference from debug information entries.
2373 MCSymbol *Sym = Entries[i].second->first;
2375 Asm->EmitLabelReference(Entries[i].second->first,
2376 Asm->getDataLayout().getPointerSize());
2378 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2383 // Emit visible names into a debug str section.
2384 void DwarfDebug::emitDebugStr() {
2385 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2386 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2389 // Emit visible names into a debug loc section.
2390 void DwarfDebug::emitDebugLoc() {
2391 if (DotDebugLocEntries.empty())
2394 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2395 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2397 DotDebugLocEntry &Entry = *I;
2398 if (I + 1 != DotDebugLocEntries.end())
2402 // Start the dwarf loc section.
2403 Asm->OutStreamer.SwitchSection(
2404 Asm->getObjFileLowering().getDwarfLocSection());
2405 unsigned char Size = Asm->getDataLayout().getPointerSize();
2406 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2408 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2409 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2410 I != E; ++I, ++index) {
2411 DotDebugLocEntry &Entry = *I;
2412 if (Entry.isMerged()) continue;
2413 if (Entry.isEmpty()) {
2414 Asm->OutStreamer.EmitIntValue(0, Size);
2415 Asm->OutStreamer.EmitIntValue(0, Size);
2416 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2418 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2419 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2420 DIVariable DV(Entry.Variable);
2421 Asm->OutStreamer.AddComment("Loc expr size");
2422 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2423 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2424 Asm->EmitLabelDifference(end, begin, 2);
2425 Asm->OutStreamer.EmitLabel(begin);
2426 if (Entry.isInt()) {
2427 DIBasicType BTy(DV.getType());
2429 (BTy.getEncoding() == dwarf::DW_ATE_signed
2430 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2431 Asm->OutStreamer.AddComment("DW_OP_consts");
2432 Asm->EmitInt8(dwarf::DW_OP_consts);
2433 Asm->EmitSLEB128(Entry.getInt());
2435 Asm->OutStreamer.AddComment("DW_OP_constu");
2436 Asm->EmitInt8(dwarf::DW_OP_constu);
2437 Asm->EmitULEB128(Entry.getInt());
2439 } else if (Entry.isLocation()) {
2440 if (!DV.hasComplexAddress())
2442 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2444 // Complex address entry.
2445 unsigned N = DV.getNumAddrElements();
2447 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2448 if (Entry.Loc.getOffset()) {
2450 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2451 Asm->OutStreamer.AddComment("DW_OP_deref");
2452 Asm->EmitInt8(dwarf::DW_OP_deref);
2453 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2454 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2455 Asm->EmitSLEB128(DV.getAddrElement(1));
2457 // If first address element is OpPlus then emit
2458 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2459 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2460 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2464 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2467 // Emit remaining complex address elements.
2468 for (; i < N; ++i) {
2469 uint64_t Element = DV.getAddrElement(i);
2470 if (Element == DIBuilder::OpPlus) {
2471 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2472 Asm->EmitULEB128(DV.getAddrElement(++i));
2473 } else if (Element == DIBuilder::OpDeref) {
2474 if (!Entry.Loc.isReg())
2475 Asm->EmitInt8(dwarf::DW_OP_deref);
2477 llvm_unreachable("unknown Opcode found in complex address");
2481 // else ... ignore constant fp. There is not any good way to
2482 // to represent them here in dwarf.
2483 Asm->OutStreamer.EmitLabel(end);
2488 // Emit visible names into a debug aranges section.
2489 void DwarfDebug::emitDebugARanges() {
2490 // Start the dwarf aranges section.
2491 Asm->OutStreamer.SwitchSection(
2492 Asm->getObjFileLowering().getDwarfARangesSection());
2495 // Emit visible names into a debug ranges section.
2496 void DwarfDebug::emitDebugRanges() {
2497 // Start the dwarf ranges section.
2498 Asm->OutStreamer.SwitchSection(
2499 Asm->getObjFileLowering().getDwarfRangesSection());
2500 unsigned char Size = Asm->getDataLayout().getPointerSize();
2501 for (SmallVectorImpl<const MCSymbol *>::iterator
2502 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2505 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2507 Asm->OutStreamer.EmitIntValue(0, Size);
2511 // Emit visible names into a debug macinfo section.
2512 void DwarfDebug::emitDebugMacInfo() {
2513 if (const MCSection *LineInfo =
2514 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2515 // Start the dwarf macinfo section.
2516 Asm->OutStreamer.SwitchSection(LineInfo);
2520 // Emit inline info using following format.
2522 // 1. length of section
2523 // 2. Dwarf version number
2526 // Entries (one "entry" for each function that was inlined):
2528 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2529 // otherwise offset into __debug_str for regular function name.
2530 // 2. offset into __debug_str section for regular function name.
2531 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2532 // instances for the function.
2534 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2535 // inlined instance; the die_offset points to the inlined_subroutine die in the
2536 // __debug_info section, and the low_pc is the starting address for the
2537 // inlining instance.
2538 void DwarfDebug::emitDebugInlineInfo() {
2539 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2545 Asm->OutStreamer.SwitchSection(
2546 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2548 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2549 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2550 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2552 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2554 Asm->OutStreamer.AddComment("Dwarf Version");
2555 Asm->EmitInt16(dwarf::DWARF_VERSION);
2556 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2557 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2559 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2560 E = InlinedSPNodes.end(); I != E; ++I) {
2562 const MDNode *Node = *I;
2563 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2564 = InlineInfo.find(Node);
2565 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2566 DISubprogram SP(Node);
2567 StringRef LName = SP.getLinkageName();
2568 StringRef Name = SP.getName();
2570 Asm->OutStreamer.AddComment("MIPS linkage name");
2572 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2573 DwarfStrSectionSym);
2575 Asm->EmitSectionOffset(
2576 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2577 DwarfStrSectionSym);
2579 Asm->OutStreamer.AddComment("Function name");
2580 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2581 DwarfStrSectionSym);
2582 Asm->EmitULEB128(Labels.size(), "Inline count");
2584 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2585 LE = Labels.end(); LI != LE; ++LI) {
2586 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2587 Asm->EmitInt32(LI->second->getOffset());
2589 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2590 Asm->OutStreamer.EmitSymbolValue(LI->first,
2591 Asm->getDataLayout().getPointerSize());
2595 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2598 // DWARF5 Experimental Separate Dwarf emitters.
2600 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2601 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2602 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2603 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2604 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2605 DICompileUnit DIUnit(N);
2606 CompilationDir = DIUnit.getDirectory();
2608 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2609 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2610 DIUnit.getLanguage(), Die, N, Asm,
2611 this, &SkeletonHolder);
2613 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2614 DIUnit.getSplitDebugFilename());
2616 // This should be a unique identifier when we want to build .dwp files.
2617 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2619 // Relocate to the beginning of the addr_base section, else 0 for the
2620 // beginning of the one for this compile unit.
2621 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2622 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2623 DwarfAddrSectionSym);
2625 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2626 dwarf::DW_FORM_sec_offset, 0);
2628 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2629 // into an entity. We're using 0, or a NULL label for this.
2630 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2632 // DW_AT_stmt_list is a offset of line number information for this
2633 // compile unit in debug_line section.
2634 // FIXME: Should handle multiple compile units.
2635 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2636 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2637 DwarfLineSectionSym);
2639 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2641 if (!CompilationDir.empty())
2642 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2644 SkeletonHolder.addUnit(NewCU);
2645 SkeletonCUs.push_back(NewCU);
2650 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2651 assert(useSplitDwarf() && "No split dwarf debug info?");
2652 emitAbbrevs(Section, &SkeletonAbbrevs);
2655 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2656 // compile units that would normally be in debug_info.
2657 void DwarfDebug::emitDebugInfoDWO() {
2658 assert(useSplitDwarf() && "No split dwarf debug info?");
2659 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2660 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2661 DwarfAbbrevDWOSectionSym);
2664 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2665 // abbreviations for the .debug_info.dwo section.
2666 void DwarfDebug::emitDebugAbbrevDWO() {
2667 assert(useSplitDwarf() && "No split dwarf?");
2668 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2672 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2673 // string section and is identical in format to traditional .debug_str
2675 void DwarfDebug::emitDebugStrDWO() {
2676 assert(useSplitDwarf() && "No split dwarf?");
2677 const MCSection *OffSec = Asm->getObjFileLowering()
2678 .getDwarfStrOffDWOSection();
2679 const MCSymbol *StrSym = DwarfStrSectionSym;
2680 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),