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"
18 #include "DwarfAccelTable.h"
19 #include "DwarfCompileUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
67 GenerateCUHash("generate-cu-hash", cl::Hidden,
68 cl::desc("Add the CU hash as the dwo_id."),
79 static cl::opt<DefaultOnOff>
80 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
81 cl::desc("Output prototype dwarf accelerator tables."),
82 cl::values(clEnumVal(Default, "Default for platform"),
83 clEnumVal(Enable, "Enabled"),
84 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 static cl::opt<DefaultOnOff>
88 DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
89 cl::desc("Compatibility with Darwin gdb."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 SplitDwarf("split-dwarf", cl::Hidden,
97 cl::desc("Output prototype dwarf split debug info."),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static cl::opt<DefaultOnOff>
104 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
105 cl::desc("Generate DWARF pubnames and pubtypes sections"),
106 cl::values(clEnumVal(Default, "Default for platform"),
107 clEnumVal(Enable, "Enabled"),
108 clEnumVal(Disable, "Disabled"), clEnumValEnd),
111 static const char *const DWARFGroupName = "DWARF Emission";
112 static const char *const DbgTimerName = "DWARF Debug Writer";
114 //===----------------------------------------------------------------------===//
116 // Configuration values for initial hash set sizes (log2).
118 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
122 DIType DbgVariable::getType() const {
123 DIType Ty = Var.getType();
124 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
125 // addresses instead.
126 if (Var.isBlockByrefVariable()) {
127 /* Byref variables, in Blocks, are declared by the programmer as
128 "SomeType VarName;", but the compiler creates a
129 __Block_byref_x_VarName struct, and gives the variable VarName
130 either the struct, or a pointer to the struct, as its type. This
131 is necessary for various behind-the-scenes things the compiler
132 needs to do with by-reference variables in blocks.
134 However, as far as the original *programmer* is concerned, the
135 variable should still have type 'SomeType', as originally declared.
137 The following function dives into the __Block_byref_x_VarName
138 struct to find the original type of the variable. This will be
139 passed back to the code generating the type for the Debug
140 Information Entry for the variable 'VarName'. 'VarName' will then
141 have the original type 'SomeType' in its debug information.
143 The original type 'SomeType' will be the type of the field named
144 'VarName' inside the __Block_byref_x_VarName struct.
146 NOTE: In order for this to not completely fail on the debugger
147 side, the Debug Information Entry for the variable VarName needs to
148 have a DW_AT_location that tells the debugger how to unwind through
149 the pointers and __Block_byref_x_VarName struct to find the actual
150 value of the variable. The function addBlockByrefType does this. */
152 uint16_t tag = Ty.getTag();
154 if (tag == dwarf::DW_TAG_pointer_type) {
155 DIDerivedType DTy = DIDerivedType(Ty);
156 subType = DTy.getTypeDerivedFrom();
159 DICompositeType blockStruct = DICompositeType(subType);
160 DIArray Elements = blockStruct.getTypeArray();
162 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
163 DIDescriptor Element = Elements.getElement(i);
164 DIDerivedType DT = DIDerivedType(Element);
165 if (getName() == DT.getName())
166 return (DT.getTypeDerivedFrom());
172 } // end llvm namespace
174 /// Return Dwarf Version by checking module flags.
175 static unsigned getDwarfVersionFromModule(const Module *M) {
176 Value *Val = M->getModuleFlag("Dwarf Version");
178 return dwarf::DWARF_VERSION;
179 return cast<ConstantInt>(Val)->getZExtValue();
182 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
183 : Asm(A), MMI(Asm->MMI), FirstCU(0),
184 AbbreviationsSet(InitAbbreviationsSetSize),
185 SourceIdMap(DIEValueAllocator),
186 PrevLabel(NULL), GlobalCUIndexCount(0),
187 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
189 SkeletonAbbrevSet(InitAbbreviationsSetSize),
190 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
193 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
194 DwarfStrSectionSym = TextSectionSym = 0;
195 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
196 DwarfAddrSectionSym = 0;
197 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
198 FunctionBeginSym = FunctionEndSym = 0;
200 // Turn on accelerator tables and older gdb compatibility
201 // for Darwin by default, pubnames by default for non-Darwin,
202 // and handle split dwarf.
203 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
205 if (DarwinGDBCompat == Default)
206 IsDarwinGDBCompat = IsDarwin;
208 IsDarwinGDBCompat = DarwinGDBCompat == Enable;
210 if (DwarfAccelTables == Default)
211 HasDwarfAccelTables = IsDarwin;
213 HasDwarfAccelTables = DwarfAccelTables == Enable;
215 if (SplitDwarf == Default)
216 HasSplitDwarf = false;
218 HasSplitDwarf = SplitDwarf == Enable;
220 if (DwarfPubSections == Default)
221 HasDwarfPubSections = !IsDarwin;
223 HasDwarfPubSections = DwarfPubSections == Enable;
225 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
228 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
232 DwarfDebug::~DwarfDebug() {
235 // Switch to the specified MCSection and emit an assembler
236 // temporary label to it if SymbolStem is specified.
237 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
238 const char *SymbolStem = 0) {
239 Asm->OutStreamer.SwitchSection(Section);
240 if (!SymbolStem) return 0;
242 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
243 Asm->OutStreamer.EmitLabel(TmpSym);
247 MCSymbol *DwarfUnits::getStringPoolSym() {
248 return Asm->GetTempSymbol(StringPref);
251 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
252 std::pair<MCSymbol*, unsigned> &Entry =
253 StringPool.GetOrCreateValue(Str).getValue();
254 if (Entry.first) return Entry.first;
256 Entry.second = NextStringPoolNumber++;
257 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
260 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
261 std::pair<MCSymbol*, unsigned> &Entry =
262 StringPool.GetOrCreateValue(Str).getValue();
263 if (Entry.first) return Entry.second;
265 Entry.second = NextStringPoolNumber++;
266 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
270 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
271 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
274 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
275 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
276 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
278 ++NextAddrPoolNumber;
279 return P.first->second;
282 // Define a unique number for the abbreviation.
284 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
285 // Check the set for priors.
286 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
288 // If it's newly added.
289 if (InSet == &Abbrev) {
290 // Add to abbreviation list.
291 Abbreviations->push_back(&Abbrev);
293 // Assign the vector position + 1 as its number.
294 Abbrev.setNumber(Abbreviations->size());
296 // Assign existing abbreviation number.
297 Abbrev.setNumber(InSet->getNumber());
301 static bool isObjCClass(StringRef Name) {
302 return Name.startswith("+") || Name.startswith("-");
305 static bool hasObjCCategory(StringRef Name) {
306 if (!isObjCClass(Name)) return false;
308 return Name.find(") ") != StringRef::npos;
311 static void getObjCClassCategory(StringRef In, StringRef &Class,
312 StringRef &Category) {
313 if (!hasObjCCategory(In)) {
314 Class = In.slice(In.find('[') + 1, In.find(' '));
319 Class = In.slice(In.find('[') + 1, In.find('('));
320 Category = In.slice(In.find('[') + 1, In.find(' '));
324 static StringRef getObjCMethodName(StringRef In) {
325 return In.slice(In.find(' ') + 1, In.find(']'));
328 // Add the various names to the Dwarf accelerator table names.
329 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
331 if (!SP.isDefinition()) return;
333 TheCU->addAccelName(SP.getName(), Die);
335 // If the linkage name is different than the name, go ahead and output
336 // that as well into the name table.
337 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
338 TheCU->addAccelName(SP.getLinkageName(), Die);
340 // If this is an Objective-C selector name add it to the ObjC accelerator
342 if (isObjCClass(SP.getName())) {
343 StringRef Class, Category;
344 getObjCClassCategory(SP.getName(), Class, Category);
345 TheCU->addAccelObjC(Class, Die);
347 TheCU->addAccelObjC(Category, Die);
348 // Also add the base method name to the name table.
349 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
353 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
354 // and DW_AT_high_pc attributes. If there are global variables in this
355 // scope then create and insert DIEs for these variables.
356 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
357 const MDNode *SPNode) {
358 DIE *SPDie = SPCU->getDIE(SPNode);
360 assert(SPDie && "Unable to find subprogram DIE!");
361 DISubprogram SP(SPNode);
363 // If we're updating an abstract DIE, then we will be adding the children and
364 // object pointer later on. But what we don't want to do is process the
365 // concrete DIE twice.
366 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
368 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
369 // Pick up abstract subprogram DIE.
370 SPDie = new DIE(dwarf::DW_TAG_subprogram);
371 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
373 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
374 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
378 DISubprogram SPDecl = SP.getFunctionDeclaration();
379 if (!SPDecl.isSubprogram()) {
380 // There is not any need to generate specification DIE for a function
381 // defined at compile unit level. If a function is defined inside another
382 // function then gdb prefers the definition at top level and but does not
383 // expect specification DIE in parent function. So avoid creating
384 // specification DIE for a function defined inside a function.
385 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
386 !SP.getContext().isFile() &&
387 !isSubprogramContext(SP.getContext())) {
388 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
391 DICompositeType SPTy = SP.getType();
392 DIArray Args = SPTy.getTypeArray();
393 uint16_t SPTag = SPTy.getTag();
394 if (SPTag == dwarf::DW_TAG_subroutine_type)
395 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
396 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
397 DIType ATy = DIType(Args.getElement(i));
398 SPCU->addType(Arg, ATy);
399 if (ATy.isArtificial())
400 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
401 if (ATy.isObjectPointer())
402 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
403 dwarf::DW_FORM_ref4, Arg);
404 SPDie->addChild(Arg);
406 DIE *SPDeclDie = SPDie;
407 SPDie = new DIE(dwarf::DW_TAG_subprogram);
408 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
409 dwarf::DW_FORM_ref4, SPDeclDie);
415 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
416 Asm->GetTempSymbol("func_begin",
417 Asm->getFunctionNumber()));
418 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
419 Asm->GetTempSymbol("func_end",
420 Asm->getFunctionNumber()));
421 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
422 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
423 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
425 // Add name to the name table, we do this here because we're guaranteed
426 // to have concrete versions of our DW_TAG_subprogram nodes.
427 addSubprogramNames(SPCU, SP, SPDie);
432 // Construct new DW_TAG_lexical_block for this scope and attach
433 // DW_AT_low_pc/DW_AT_high_pc labels.
434 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
435 LexicalScope *Scope) {
436 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
437 if (Scope->isAbstractScope())
440 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
444 // If we have multiple ranges, emit them into the range section.
445 if (Ranges.size() > 1) {
446 // .debug_range section has not been laid out yet. Emit offset in
447 // .debug_range as a uint, size 4, for now. emitDIE will handle
448 // DW_AT_ranges appropriately.
449 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
450 DebugRangeSymbols.size()
451 * Asm->getDataLayout().getPointerSize());
452 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
453 RE = Ranges.end(); RI != RE; ++RI) {
454 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
455 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
458 // Terminate the range list.
459 DebugRangeSymbols.push_back(NULL);
460 DebugRangeSymbols.push_back(NULL);
464 // Construct the address range for this DIE.
465 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
466 MCSymbol *Start = getLabelBeforeInsn(RI->first);
467 MCSymbol *End = getLabelAfterInsn(RI->second);
469 if (End == 0) return 0;
471 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
472 assert(End->isDefined() && "Invalid end label for an inlined scope!");
474 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
475 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
480 // This scope represents inlined body of a function. Construct DIE to
481 // represent this concrete inlined copy of the function.
482 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
483 LexicalScope *Scope) {
484 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
485 assert(Ranges.empty() == false &&
486 "LexicalScope does not have instruction markers!");
488 if (!Scope->getScopeNode())
490 DIScope DS(Scope->getScopeNode());
491 DISubprogram InlinedSP = getDISubprogram(DS);
492 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
494 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
498 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
499 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
500 dwarf::DW_FORM_ref4, OriginDIE);
502 if (Ranges.size() > 1) {
503 // .debug_range section has not been laid out yet. Emit offset in
504 // .debug_range as a uint, size 4, for now. emitDIE will handle
505 // DW_AT_ranges appropriately.
506 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
507 DebugRangeSymbols.size()
508 * Asm->getDataLayout().getPointerSize());
509 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
510 RE = Ranges.end(); RI != RE; ++RI) {
511 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
512 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
514 DebugRangeSymbols.push_back(NULL);
515 DebugRangeSymbols.push_back(NULL);
517 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
518 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
519 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
521 if (StartLabel == 0 || EndLabel == 0)
522 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
524 assert(StartLabel->isDefined() &&
525 "Invalid starting label for an inlined scope!");
526 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
528 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
529 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
532 InlinedSubprogramDIEs.insert(OriginDIE);
534 // Add the call site information to the DIE.
535 DILocation DL(Scope->getInlinedAt());
536 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
537 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
538 TheCU->getUniqueID()));
539 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
541 // Add name to the name table, we do this here because we're guaranteed
542 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
543 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
548 // Construct a DIE for this scope.
549 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
550 if (!Scope || !Scope->getScopeNode())
553 DIScope DS(Scope->getScopeNode());
554 // Early return to avoid creating dangling variable|scope DIEs.
555 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
559 SmallVector<DIE *, 8> Children;
560 DIE *ObjectPointer = NULL;
562 // Collect arguments for current function.
563 if (LScopes.isCurrentFunctionScope(Scope))
564 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
565 if (DbgVariable *ArgDV = CurrentFnArguments[i])
567 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
568 Children.push_back(Arg);
569 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
572 // Collect lexical scope children first.
573 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
574 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
576 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
577 Children.push_back(Variable);
578 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
580 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
581 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
582 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
583 Children.push_back(Nested);
584 DIE *ScopeDIE = NULL;
585 if (Scope->getInlinedAt())
586 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
587 else if (DS.isSubprogram()) {
588 ProcessedSPNodes.insert(DS);
589 if (Scope->isAbstractScope()) {
590 ScopeDIE = TheCU->getDIE(DS);
591 // Note down abstract DIE.
593 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
596 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
599 // There is no need to emit empty lexical block DIE.
600 std::pair<ImportedEntityMap::const_iterator,
601 ImportedEntityMap::const_iterator> Range = std::equal_range(
602 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
603 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
605 if (Children.empty() && Range.first == Range.second)
607 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
608 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
610 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
614 std::for_each(Children.begin(), Children.end(), deleter<DIE>);
619 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
620 E = Children.end(); I != E; ++I)
621 ScopeDIE->addChild(*I);
623 if (DS.isSubprogram() && ObjectPointer != NULL)
624 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
625 dwarf::DW_FORM_ref4, ObjectPointer);
627 if (DS.isSubprogram())
628 TheCU->addPubTypes(DISubprogram(DS));
633 // Look up the source id with the given directory and source file names.
634 // If none currently exists, create a new id and insert it in the
635 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
637 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
638 StringRef DirName, unsigned CUID) {
639 // If we use .loc in assembly, we can't separate .file entries according to
640 // compile units. Thus all files will belong to the default compile unit.
641 if (Asm->TM.hasMCUseLoc() &&
642 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
645 // If FE did not provide a file name, then assume stdin.
646 if (FileName.empty())
647 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
649 // TODO: this might not belong here. See if we can factor this better.
650 if (DirName == CompilationDir)
653 // FileIDCUMap stores the current ID for the given compile unit.
654 unsigned SrcId = FileIDCUMap[CUID] + 1;
656 // We look up the CUID/file/dir by concatenating them with a zero byte.
657 SmallString<128> NamePair;
658 NamePair += utostr(CUID);
661 NamePair += '\0'; // Zero bytes are not allowed in paths.
662 NamePair += FileName;
664 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
665 if (Ent.getValue() != SrcId)
666 return Ent.getValue();
668 FileIDCUMap[CUID] = SrcId;
669 // Print out a .file directive to specify files for .loc directives.
670 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
675 // Create new CompileUnit for the given metadata node with tag
676 // DW_TAG_compile_unit.
677 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
678 DICompileUnit DIUnit(N);
679 StringRef FN = DIUnit.getFilename();
680 CompilationDir = DIUnit.getDirectory();
682 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
684 new CompileUnit(GlobalCUIndexCount++, Die, N, Asm, this, &InfoHolder);
686 FileIDCUMap[NewCU->getUniqueID()] = 0;
687 // Call this to emit a .file directive if it wasn't emitted for the source
688 // file this CU comes from yet.
689 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
691 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
692 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
693 DIUnit.getLanguage());
694 NewCU->addString(Die, dwarf::DW_AT_name, FN);
696 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
697 // into an entity. We're using 0 (or a NULL label) for this. For
698 // split dwarf it's in the skeleton CU so omit it here.
699 if (!useSplitDwarf())
700 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
702 // Define start line table label for each Compile Unit.
703 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
704 NewCU->getUniqueID());
705 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
706 NewCU->getUniqueID());
708 // Use a single line table if we are using .loc and generating assembly.
710 (Asm->TM.hasMCUseLoc() &&
711 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
712 (NewCU->getUniqueID() == 0);
714 // DW_AT_stmt_list is a offset of line number information for this
715 // compile unit in debug_line section. For split dwarf this is
716 // left in the skeleton CU and so not included.
717 // The line table entries are not always emitted in assembly, so it
718 // is not okay to use line_table_start here.
719 if (!useSplitDwarf()) {
720 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
721 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
723 Asm->GetTempSymbol("section_line") : LineTableStartSym);
724 else if (UseTheFirstCU)
725 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
727 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
728 LineTableStartSym, DwarfLineSectionSym);
731 // If we're using split dwarf the compilation dir is going to be in the
732 // skeleton CU and so we don't need to duplicate it here.
733 if (!useSplitDwarf() && !CompilationDir.empty())
734 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
735 if (DIUnit.isOptimized())
736 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
738 StringRef Flags = DIUnit.getFlags();
740 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
742 if (unsigned RVer = DIUnit.getRunTimeVersion())
743 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
744 dwarf::DW_FORM_data1, RVer);
749 InfoHolder.addUnit(NewCU);
751 CUMap.insert(std::make_pair(N, NewCU));
755 // Construct subprogram DIE.
756 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
758 CompileUnit *&CURef = SPMap[N];
764 if (!SP.isDefinition())
765 // This is a method declaration which will be handled while constructing
769 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
772 TheCU->insertDIE(N, SubprogramDie);
774 // Add to context owner.
775 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
777 // Expose as global, if requested.
778 if (HasDwarfPubSections)
779 TheCU->addGlobalName(SP.getName(), SubprogramDie);
782 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
784 DIImportedEntity Module(N);
785 if (!Module.Verify())
787 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
788 constructImportedEntityDIE(TheCU, Module, D);
791 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
793 DIImportedEntity Module(N);
794 if (!Module.Verify())
796 return constructImportedEntityDIE(TheCU, Module, Context);
799 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
800 const DIImportedEntity &Module,
802 assert(Module.Verify() &&
803 "Use one of the MDNode * overloads to handle invalid metadata");
804 assert(Context && "Should always have a context for an imported_module");
805 DIE *IMDie = new DIE(Module.getTag());
806 TheCU->insertDIE(Module, IMDie);
808 DIDescriptor Entity = Module.getEntity();
809 if (Entity.isNameSpace())
810 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
811 else if (Entity.isSubprogram())
812 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
813 else if (Entity.isType())
814 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
816 EntityDie = TheCU->getDIE(Entity);
817 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
818 Module.getContext().getDirectory(),
819 TheCU->getUniqueID());
820 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
821 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
822 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
824 StringRef Name = Module.getName();
826 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
827 Context->addChild(IMDie);
830 // Emit all Dwarf sections that should come prior to the content. Create
831 // global DIEs and emit initial debug info sections. This is invoked by
832 // the target AsmPrinter.
833 void DwarfDebug::beginModule() {
834 if (DisableDebugInfoPrinting)
837 const Module *M = MMI->getModule();
839 // If module has named metadata anchors then use them, otherwise scan the
840 // module using debug info finder to collect debug info.
841 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
845 // Emit initial sections so we can reference labels later.
848 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
849 DICompileUnit CUNode(CU_Nodes->getOperand(i));
850 CompileUnit *CU = constructCompileUnit(CUNode);
851 DIArray ImportedEntities = CUNode.getImportedEntities();
852 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
853 ScopesWithImportedEntities.push_back(std::make_pair(
854 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
855 ImportedEntities.getElement(i)));
856 std::sort(ScopesWithImportedEntities.begin(),
857 ScopesWithImportedEntities.end(), less_first());
858 DIArray GVs = CUNode.getGlobalVariables();
859 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
860 CU->createGlobalVariableDIE(GVs.getElement(i));
861 DIArray SPs = CUNode.getSubprograms();
862 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
863 constructSubprogramDIE(CU, SPs.getElement(i));
864 DIArray EnumTypes = CUNode.getEnumTypes();
865 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
866 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
867 DIArray RetainedTypes = CUNode.getRetainedTypes();
868 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
869 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
870 // Emit imported_modules last so that the relevant context is already
872 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
873 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
876 // Tell MMI that we have debug info.
877 MMI->setDebugInfoAvailability(true);
879 // Prime section data.
880 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
883 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
884 void DwarfDebug::computeInlinedDIEs() {
885 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
886 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
887 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
889 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
891 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
892 AE = AbstractSPDies.end(); AI != AE; ++AI) {
893 DIE *ISP = AI->second;
894 if (InlinedSubprogramDIEs.count(ISP))
896 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
900 // Collect info for variables that were optimized out.
901 void DwarfDebug::collectDeadVariables() {
902 const Module *M = MMI->getModule();
903 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
905 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
906 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
907 DICompileUnit TheCU(CU_Nodes->getOperand(i));
908 DIArray Subprograms = TheCU.getSubprograms();
909 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
910 DISubprogram SP(Subprograms.getElement(i));
911 if (ProcessedSPNodes.count(SP) != 0) continue;
912 if (!SP.isSubprogram()) continue;
913 if (!SP.isDefinition()) continue;
914 DIArray Variables = SP.getVariables();
915 if (Variables.getNumElements() == 0) continue;
917 LexicalScope *Scope =
918 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
919 DeadFnScopeMap[SP] = Scope;
921 // Construct subprogram DIE and add variables DIEs.
922 CompileUnit *SPCU = CUMap.lookup(TheCU);
923 assert(SPCU && "Unable to find Compile Unit!");
924 constructSubprogramDIE(SPCU, SP);
925 DIE *ScopeDIE = SPCU->getDIE(SP);
926 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
927 DIVariable DV(Variables.getElement(vi));
928 if (!DV.isVariable()) continue;
929 DbgVariable NewVar(DV, NULL);
930 if (DIE *VariableDIE =
931 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
932 ScopeDIE->addChild(VariableDIE);
937 DeleteContainerSeconds(DeadFnScopeMap);
940 // Type Signature [7.27] and ODR Hash code.
942 /// \brief Grabs the string in whichever attribute is passed in and returns
943 /// a reference to it. Returns "" if the attribute doesn't exist.
944 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
945 DIEValue *V = Die->findAttribute(Attr);
947 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
948 return S->getString();
950 return StringRef("");
953 /// Return true if the current DIE is contained within an anonymous namespace.
954 static bool isContainedInAnonNamespace(DIE *Die) {
955 DIE *Parent = Die->getParent();
958 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
959 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
961 Parent = Parent->getParent();
967 /// Test if the current CU language is C++ and that we have
968 /// a named type that is not contained in an anonymous namespace.
969 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
970 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
971 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
972 !isContainedInAnonNamespace(Die);
975 void DwarfDebug::finalizeModuleInfo() {
976 // Collect info for variables that were optimized out.
977 collectDeadVariables();
979 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
980 computeInlinedDIEs();
982 // Split out type units and conditionally add an ODR tag to the split
984 // FIXME: Do type splitting.
985 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
986 DIE *Die = TypeUnits[i];
988 // If we've requested ODR hashes and it's applicable for an ODR hash then
989 // add the ODR signature now.
990 // FIXME: This should be added onto the type unit, not the type, but this
991 // works as an intermediate stage.
992 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
993 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
994 dwarf::DW_FORM_data8,
995 Hash.computeDIEODRSignature(Die));
998 // Handle anything that needs to be done on a per-cu basis.
999 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1001 CUI != CUE; ++CUI) {
1002 CompileUnit *TheCU = CUI->second;
1003 // Emit DW_AT_containing_type attribute to connect types with their
1004 // vtable holding type.
1005 TheCU->constructContainingTypeDIEs();
1007 // If we're splitting the dwarf out now that we've got the entire
1008 // CU then construct a skeleton CU based upon it.
1009 if (useSplitDwarf()) {
1011 if (GenerateCUHash) {
1013 ID = CUHash.computeCUSignature(TheCU->getCUDie());
1015 // This should be a unique identifier when we want to build .dwp files.
1016 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1017 dwarf::DW_FORM_data8, ID);
1018 // Now construct the skeleton CU associated.
1019 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1020 // This should be a unique identifier when we want to build .dwp files.
1021 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1022 dwarf::DW_FORM_data8, ID);
1026 // Compute DIE offsets and sizes.
1027 InfoHolder.computeSizeAndOffsets();
1028 if (useSplitDwarf())
1029 SkeletonHolder.computeSizeAndOffsets();
1032 void DwarfDebug::endSections() {
1033 // Standard sections final addresses.
1034 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1035 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1036 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1037 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1039 // End text sections.
1040 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1041 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1042 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1046 // Emit all Dwarf sections that should come after the content.
1047 void DwarfDebug::endModule() {
1049 if (!FirstCU) return;
1051 // End any existing sections.
1052 // TODO: Does this need to happen?
1055 // Finalize the debug info for the module.
1056 finalizeModuleInfo();
1058 if (!useSplitDwarf()) {
1059 // Emit all the DIEs into a debug info section.
1062 // Corresponding abbreviations into a abbrev section.
1063 emitAbbreviations();
1065 // Emit info into a debug loc section.
1068 // Emit info into a debug aranges section.
1071 // Emit info into a debug ranges section.
1074 // Emit info into a debug macinfo section.
1078 // TODO: Fill this in for separated debug sections and separate
1079 // out information into new sections.
1081 // Emit the debug info section and compile units.
1085 // Corresponding abbreviations into a abbrev section.
1086 emitAbbreviations();
1087 emitDebugAbbrevDWO();
1089 // Emit info into a debug loc section.
1092 // Emit info into a debug aranges section.
1095 // Emit info into a debug ranges section.
1098 // Emit info into a debug macinfo section.
1101 // Emit DWO addresses.
1102 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1106 // Emit info into the dwarf accelerator table sections.
1107 if (useDwarfAccelTables()) {
1110 emitAccelNamespaces();
1114 // Emit info into a debug pubnames section, if requested.
1115 if (HasDwarfPubSections)
1116 emitDebugPubnames();
1118 // Emit info into a debug pubtypes section.
1119 // TODO: When we don't need the option anymore we can
1120 // remove all of the code that adds to the table.
1121 if (useDarwinGDBCompat() || HasDwarfPubSections)
1122 emitDebugPubTypes();
1124 // Finally emit string information into a string table.
1126 if (useSplitDwarf())
1131 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1132 E = CUMap.end(); I != E; ++I)
1135 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1136 E = SkeletonCUs.end(); I != E; ++I)
1139 // Reset these for the next Module if we have one.
1143 // Find abstract variable, if any, associated with Var.
1144 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1145 DebugLoc ScopeLoc) {
1146 LLVMContext &Ctx = DV->getContext();
1147 // More then one inlined variable corresponds to one abstract variable.
1148 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1149 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1151 return AbsDbgVariable;
1153 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1157 AbsDbgVariable = new DbgVariable(Var, NULL);
1158 addScopeVariable(Scope, AbsDbgVariable);
1159 AbstractVariables[Var] = AbsDbgVariable;
1160 return AbsDbgVariable;
1163 // If Var is a current function argument then add it to CurrentFnArguments list.
1164 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1165 DbgVariable *Var, LexicalScope *Scope) {
1166 if (!LScopes.isCurrentFunctionScope(Scope))
1168 DIVariable DV = Var->getVariable();
1169 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1171 unsigned ArgNo = DV.getArgNumber();
1175 size_t Size = CurrentFnArguments.size();
1177 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1178 // llvm::Function argument size is not good indicator of how many
1179 // arguments does the function have at source level.
1181 CurrentFnArguments.resize(ArgNo * 2);
1182 CurrentFnArguments[ArgNo - 1] = Var;
1186 // Collect variable information from side table maintained by MMI.
1188 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1189 SmallPtrSet<const MDNode *, 16> &Processed) {
1190 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1191 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1192 VE = VMap.end(); VI != VE; ++VI) {
1193 const MDNode *Var = VI->first;
1195 Processed.insert(Var);
1197 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1199 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1201 // If variable scope is not found then skip this variable.
1205 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1206 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1207 RegVar->setFrameIndex(VP.first);
1208 if (!addCurrentFnArgument(MF, RegVar, Scope))
1209 addScopeVariable(Scope, RegVar);
1211 AbsDbgVariable->setFrameIndex(VP.first);
1215 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1217 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1218 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1219 return MI->getNumOperands() == 3 &&
1220 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1221 (MI->getOperand(1).isImm() ||
1222 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1225 // Get .debug_loc entry for the instruction range starting at MI.
1226 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1227 const MCSymbol *FLabel,
1228 const MCSymbol *SLabel,
1229 const MachineInstr *MI) {
1230 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1232 assert(MI->getNumOperands() == 3);
1233 if (MI->getOperand(0).isReg()) {
1234 MachineLocation MLoc;
1235 // If the second operand is an immediate, this is a
1236 // register-indirect address.
1237 if (!MI->getOperand(1).isImm())
1238 MLoc.set(MI->getOperand(0).getReg());
1240 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1241 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1243 if (MI->getOperand(0).isImm())
1244 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1245 if (MI->getOperand(0).isFPImm())
1246 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1247 if (MI->getOperand(0).isCImm())
1248 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1250 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1253 // Find variables for each lexical scope.
1255 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1256 SmallPtrSet<const MDNode *, 16> &Processed) {
1258 // Grab the variable info that was squirreled away in the MMI side-table.
1259 collectVariableInfoFromMMITable(MF, Processed);
1261 for (SmallVectorImpl<const MDNode*>::const_iterator
1262 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1264 const MDNode *Var = *UVI;
1265 if (Processed.count(Var))
1268 // History contains relevant DBG_VALUE instructions for Var and instructions
1270 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1271 if (History.empty())
1273 const MachineInstr *MInsn = History.front();
1276 LexicalScope *Scope = NULL;
1277 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1278 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1279 Scope = LScopes.getCurrentFunctionScope();
1280 else if (MDNode *IA = DV.getInlinedAt())
1281 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1283 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1284 // If variable scope is not found then skip this variable.
1288 Processed.insert(DV);
1289 assert(MInsn->isDebugValue() && "History must begin with debug value");
1290 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1291 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1292 if (!addCurrentFnArgument(MF, RegVar, Scope))
1293 addScopeVariable(Scope, RegVar);
1295 AbsVar->setMInsn(MInsn);
1297 // Simplify ranges that are fully coalesced.
1298 if (History.size() <= 1 || (History.size() == 2 &&
1299 MInsn->isIdenticalTo(History.back()))) {
1300 RegVar->setMInsn(MInsn);
1304 // Handle multiple DBG_VALUE instructions describing one variable.
1305 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1307 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1308 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1309 const MachineInstr *Begin = *HI;
1310 assert(Begin->isDebugValue() && "Invalid History entry");
1312 // Check if DBG_VALUE is truncating a range.
1313 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1314 && !Begin->getOperand(0).getReg())
1317 // Compute the range for a register location.
1318 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1319 const MCSymbol *SLabel = 0;
1322 // If Begin is the last instruction in History then its value is valid
1323 // until the end of the function.
1324 SLabel = FunctionEndSym;
1326 const MachineInstr *End = HI[1];
1327 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1328 << "\t" << *Begin << "\t" << *End << "\n");
1329 if (End->isDebugValue())
1330 SLabel = getLabelBeforeInsn(End);
1332 // End is a normal instruction clobbering the range.
1333 SLabel = getLabelAfterInsn(End);
1334 assert(SLabel && "Forgot label after clobber instruction");
1339 // The value is valid until the next DBG_VALUE or clobber.
1340 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1343 DotDebugLocEntries.push_back(DotDebugLocEntry());
1346 // Collect info for variables that were optimized out.
1347 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1348 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1349 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1350 DIVariable DV(Variables.getElement(i));
1351 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1353 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1354 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1358 // Return Label preceding the instruction.
1359 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1360 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1361 assert(Label && "Didn't insert label before instruction");
1365 // Return Label immediately following the instruction.
1366 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1367 return LabelsAfterInsn.lookup(MI);
1370 // Process beginning of an instruction.
1371 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1372 // Check if source location changes, but ignore DBG_VALUE locations.
1373 if (!MI->isDebugValue()) {
1374 DebugLoc DL = MI->getDebugLoc();
1375 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1378 if (DL == PrologEndLoc) {
1379 Flags |= DWARF2_FLAG_PROLOGUE_END;
1380 PrologEndLoc = DebugLoc();
1382 if (PrologEndLoc.isUnknown())
1383 Flags |= DWARF2_FLAG_IS_STMT;
1385 if (!DL.isUnknown()) {
1386 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1387 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1389 recordSourceLine(0, 0, 0, 0);
1393 // Insert labels where requested.
1394 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1395 LabelsBeforeInsn.find(MI);
1398 if (I == LabelsBeforeInsn.end())
1401 // Label already assigned.
1406 PrevLabel = MMI->getContext().CreateTempSymbol();
1407 Asm->OutStreamer.EmitLabel(PrevLabel);
1409 I->second = PrevLabel;
1412 // Process end of an instruction.
1413 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1414 // Don't create a new label after DBG_VALUE instructions.
1415 // They don't generate code.
1416 if (!MI->isDebugValue())
1419 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1420 LabelsAfterInsn.find(MI);
1423 if (I == LabelsAfterInsn.end())
1426 // Label already assigned.
1430 // We need a label after this instruction.
1432 PrevLabel = MMI->getContext().CreateTempSymbol();
1433 Asm->OutStreamer.EmitLabel(PrevLabel);
1435 I->second = PrevLabel;
1438 // Each LexicalScope has first instruction and last instruction to mark
1439 // beginning and end of a scope respectively. Create an inverse map that list
1440 // scopes starts (and ends) with an instruction. One instruction may start (or
1441 // end) multiple scopes. Ignore scopes that are not reachable.
1442 void DwarfDebug::identifyScopeMarkers() {
1443 SmallVector<LexicalScope *, 4> WorkList;
1444 WorkList.push_back(LScopes.getCurrentFunctionScope());
1445 while (!WorkList.empty()) {
1446 LexicalScope *S = WorkList.pop_back_val();
1448 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1449 if (!Children.empty())
1450 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1451 SE = Children.end(); SI != SE; ++SI)
1452 WorkList.push_back(*SI);
1454 if (S->isAbstractScope())
1457 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1460 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1461 RE = Ranges.end(); RI != RE; ++RI) {
1462 assert(RI->first && "InsnRange does not have first instruction!");
1463 assert(RI->second && "InsnRange does not have second instruction!");
1464 requestLabelBeforeInsn(RI->first);
1465 requestLabelAfterInsn(RI->second);
1470 // Get MDNode for DebugLoc's scope.
1471 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1472 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1473 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1474 return DL.getScope(Ctx);
1477 // Walk up the scope chain of given debug loc and find line number info
1478 // for the function.
1479 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1480 const MDNode *Scope = getScopeNode(DL, Ctx);
1481 DISubprogram SP = getDISubprogram(Scope);
1482 if (SP.isSubprogram()) {
1483 // Check for number of operands since the compatibility is
1485 if (SP->getNumOperands() > 19)
1486 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1488 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1494 // Gather pre-function debug information. Assumes being called immediately
1495 // after the function entry point has been emitted.
1496 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1497 if (!MMI->hasDebugInfo()) return;
1498 LScopes.initialize(*MF);
1499 if (LScopes.empty()) return;
1500 identifyScopeMarkers();
1502 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1504 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1505 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1506 assert(TheCU && "Unable to find compile unit!");
1507 if (Asm->TM.hasMCUseLoc() &&
1508 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1509 // Use a single line table if we are using .loc and generating assembly.
1510 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1512 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1514 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1515 Asm->getFunctionNumber());
1516 // Assumes in correct section after the entry point.
1517 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1519 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1521 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1522 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1523 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1525 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1527 bool AtBlockEntry = true;
1528 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1530 const MachineInstr *MI = II;
1532 if (MI->isDebugValue()) {
1533 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1535 // Keep track of user variables.
1537 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1539 // Variable is in a register, we need to check for clobbers.
1540 if (isDbgValueInDefinedReg(MI))
1541 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1543 // Check the history of this variable.
1544 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1545 if (History.empty()) {
1546 UserVariables.push_back(Var);
1547 // The first mention of a function argument gets the FunctionBeginSym
1548 // label, so arguments are visible when breaking at function entry.
1550 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1551 DISubprogram(getDISubprogram(DV.getContext()))
1552 .describes(MF->getFunction()))
1553 LabelsBeforeInsn[MI] = FunctionBeginSym;
1555 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1556 const MachineInstr *Prev = History.back();
1557 if (Prev->isDebugValue()) {
1558 // Coalesce identical entries at the end of History.
1559 if (History.size() >= 2 &&
1560 Prev->isIdenticalTo(History[History.size() - 2])) {
1561 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1563 << "\t" << *History[History.size() - 2] << "\n");
1567 // Terminate old register assignments that don't reach MI;
1568 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1569 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1570 isDbgValueInDefinedReg(Prev)) {
1571 // Previous register assignment needs to terminate at the end of
1573 MachineBasicBlock::const_iterator LastMI =
1574 PrevMBB->getLastNonDebugInstr();
1575 if (LastMI == PrevMBB->end()) {
1576 // Drop DBG_VALUE for empty range.
1577 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1578 << "\t" << *Prev << "\n");
1580 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1581 // Terminate after LastMI.
1582 History.push_back(LastMI);
1586 History.push_back(MI);
1588 // Not a DBG_VALUE instruction.
1590 AtBlockEntry = false;
1592 // First known non-DBG_VALUE and non-frame setup location marks
1593 // the beginning of the function body.
1594 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1595 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1596 PrologEndLoc = MI->getDebugLoc();
1598 // Check if the instruction clobbers any registers with debug vars.
1599 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1600 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1601 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1603 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1604 AI.isValid(); ++AI) {
1606 const MDNode *Var = LiveUserVar[Reg];
1609 // Reg is now clobbered.
1610 LiveUserVar[Reg] = 0;
1612 // Was MD last defined by a DBG_VALUE referring to Reg?
1613 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1614 if (HistI == DbgValues.end())
1616 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1617 if (History.empty())
1619 const MachineInstr *Prev = History.back();
1620 // Sanity-check: Register assignments are terminated at the end of
1622 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1624 // Is the variable still in Reg?
1625 if (!isDbgValueInDefinedReg(Prev) ||
1626 Prev->getOperand(0).getReg() != Reg)
1628 // Var is clobbered. Make sure the next instruction gets a label.
1629 History.push_back(MI);
1636 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1638 SmallVectorImpl<const MachineInstr*> &History = I->second;
1639 if (History.empty())
1642 // Make sure the final register assignments are terminated.
1643 const MachineInstr *Prev = History.back();
1644 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1645 const MachineBasicBlock *PrevMBB = Prev->getParent();
1646 MachineBasicBlock::const_iterator LastMI =
1647 PrevMBB->getLastNonDebugInstr();
1648 if (LastMI == PrevMBB->end())
1649 // Drop DBG_VALUE for empty range.
1651 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1652 // Terminate after LastMI.
1653 History.push_back(LastMI);
1656 // Request labels for the full history.
1657 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1658 const MachineInstr *MI = History[i];
1659 if (MI->isDebugValue())
1660 requestLabelBeforeInsn(MI);
1662 requestLabelAfterInsn(MI);
1666 PrevInstLoc = DebugLoc();
1667 PrevLabel = FunctionBeginSym;
1669 // Record beginning of function.
1670 if (!PrologEndLoc.isUnknown()) {
1671 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1672 MF->getFunction()->getContext());
1673 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1674 FnStartDL.getScope(MF->getFunction()->getContext()),
1675 // We'd like to list the prologue as "not statements" but GDB behaves
1676 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1677 DWARF2_FLAG_IS_STMT);
1681 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1682 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1683 DIVariable DV = Var->getVariable();
1684 // Variables with positive arg numbers are parameters.
1685 if (unsigned ArgNum = DV.getArgNumber()) {
1686 // Keep all parameters in order at the start of the variable list to ensure
1687 // function types are correct (no out-of-order parameters)
1689 // This could be improved by only doing it for optimized builds (unoptimized
1690 // builds have the right order to begin with), searching from the back (this
1691 // would catch the unoptimized case quickly), or doing a binary search
1692 // rather than linear search.
1693 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1694 while (I != Vars.end()) {
1695 unsigned CurNum = (*I)->getVariable().getArgNumber();
1696 // A local (non-parameter) variable has been found, insert immediately
1700 // A later indexed parameter has been found, insert immediately before it.
1701 if (CurNum > ArgNum)
1705 Vars.insert(I, Var);
1709 Vars.push_back(Var);
1712 // Gather and emit post-function debug information.
1713 void DwarfDebug::endFunction(const MachineFunction *MF) {
1714 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1716 // Define end label for subprogram.
1717 FunctionEndSym = Asm->GetTempSymbol("func_end",
1718 Asm->getFunctionNumber());
1719 // Assumes in correct section after the entry point.
1720 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1721 // Set DwarfCompileUnitID in MCContext to default value.
1722 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1724 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1725 collectVariableInfo(MF, ProcessedVars);
1727 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1728 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1729 assert(TheCU && "Unable to find compile unit!");
1731 // Construct abstract scopes.
1732 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1733 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1734 LexicalScope *AScope = AList[i];
1735 DISubprogram SP(AScope->getScopeNode());
1736 if (SP.isSubprogram()) {
1737 // Collect info for variables that were optimized out.
1738 DIArray Variables = SP.getVariables();
1739 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1740 DIVariable DV(Variables.getElement(i));
1741 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1743 // Check that DbgVariable for DV wasn't created earlier, when
1744 // findAbstractVariable() was called for inlined instance of DV.
1745 LLVMContext &Ctx = DV->getContext();
1746 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1747 if (AbstractVariables.lookup(CleanDV))
1749 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1750 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1753 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1754 constructScopeDIE(TheCU, AScope);
1757 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1759 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1760 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1763 for (ScopeVariablesMap::iterator
1764 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1765 DeleteContainerPointers(I->second);
1766 ScopeVariables.clear();
1767 DeleteContainerPointers(CurrentFnArguments);
1768 UserVariables.clear();
1770 AbstractVariables.clear();
1771 LabelsBeforeInsn.clear();
1772 LabelsAfterInsn.clear();
1776 // Register a source line with debug info. Returns the unique label that was
1777 // emitted and which provides correspondence to the source line list.
1778 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1784 DIDescriptor Scope(S);
1786 if (Scope.isCompileUnit()) {
1787 DICompileUnit CU(S);
1788 Fn = CU.getFilename();
1789 Dir = CU.getDirectory();
1790 } else if (Scope.isFile()) {
1792 Fn = F.getFilename();
1793 Dir = F.getDirectory();
1794 } else if (Scope.isSubprogram()) {
1796 Fn = SP.getFilename();
1797 Dir = SP.getDirectory();
1798 } else if (Scope.isLexicalBlockFile()) {
1799 DILexicalBlockFile DBF(S);
1800 Fn = DBF.getFilename();
1801 Dir = DBF.getDirectory();
1802 } else if (Scope.isLexicalBlock()) {
1803 DILexicalBlock DB(S);
1804 Fn = DB.getFilename();
1805 Dir = DB.getDirectory();
1807 llvm_unreachable("Unexpected scope info");
1809 Src = getOrCreateSourceID(Fn, Dir,
1810 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1812 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1815 //===----------------------------------------------------------------------===//
1817 //===----------------------------------------------------------------------===//
1819 // Compute the size and offset of a DIE.
1821 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1822 // Get the children.
1823 const std::vector<DIE *> &Children = Die->getChildren();
1825 // Record the abbreviation.
1826 assignAbbrevNumber(Die->getAbbrev());
1828 // Get the abbreviation for this DIE.
1829 unsigned AbbrevNumber = Die->getAbbrevNumber();
1830 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1833 Die->setOffset(Offset);
1835 // Start the size with the size of abbreviation code.
1836 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1838 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1839 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1841 // Size the DIE attribute values.
1842 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1843 // Size attribute value.
1844 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1846 // Size the DIE children if any.
1847 if (!Children.empty()) {
1848 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1849 "Children flag not set");
1851 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1852 Offset = computeSizeAndOffset(Children[j], Offset);
1854 // End of children marker.
1855 Offset += sizeof(int8_t);
1858 Die->setSize(Offset - Die->getOffset());
1862 // Compute the size and offset of all the DIEs.
1863 void DwarfUnits::computeSizeAndOffsets() {
1864 // Offset from the beginning of debug info section.
1865 unsigned SecOffset = 0;
1866 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1867 E = CUs.end(); I != E; ++I) {
1868 (*I)->setDebugInfoOffset(SecOffset);
1870 sizeof(int32_t) + // Length of Compilation Unit Info
1871 sizeof(int16_t) + // DWARF version number
1872 sizeof(int32_t) + // Offset Into Abbrev. Section
1873 sizeof(int8_t); // Pointer Size (in bytes)
1875 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1876 SecOffset += EndOffset;
1880 // Emit initial Dwarf sections with a label at the start of each one.
1881 void DwarfDebug::emitSectionLabels() {
1882 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1884 // Dwarf sections base addresses.
1885 DwarfInfoSectionSym =
1886 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1887 DwarfAbbrevSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1889 if (useSplitDwarf())
1890 DwarfAbbrevDWOSectionSym =
1891 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1892 "section_abbrev_dwo");
1893 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1895 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1896 emitSectionSym(Asm, MacroInfo);
1898 DwarfLineSectionSym =
1899 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1900 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1901 if (HasDwarfPubSections)
1902 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1903 if (useDarwinGDBCompat() || HasDwarfPubSections)
1904 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1905 DwarfStrSectionSym =
1906 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1907 if (useSplitDwarf()) {
1908 DwarfStrDWOSectionSym =
1909 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1910 DwarfAddrSectionSym =
1911 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1913 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1916 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1917 "section_debug_loc");
1919 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1920 emitSectionSym(Asm, TLOF.getDataSection());
1923 // Recursively emits a debug information entry.
1924 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1925 // Get the abbreviation for this DIE.
1926 unsigned AbbrevNumber = Die->getAbbrevNumber();
1927 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1929 // Emit the code (index) for the abbreviation.
1930 if (Asm->isVerbose())
1931 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1932 Twine::utohexstr(Die->getOffset()) + ":0x" +
1933 Twine::utohexstr(Die->getSize()) + " " +
1934 dwarf::TagString(Abbrev->getTag()));
1935 Asm->EmitULEB128(AbbrevNumber);
1937 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1938 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1940 // Emit the DIE attribute values.
1941 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1942 unsigned Attr = AbbrevData[i].getAttribute();
1943 unsigned Form = AbbrevData[i].getForm();
1944 assert(Form && "Too many attributes for DIE (check abbreviation)");
1946 if (Asm->isVerbose())
1947 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1950 case dwarf::DW_AT_abstract_origin: {
1951 DIEEntry *E = cast<DIEEntry>(Values[i]);
1952 DIE *Origin = E->getEntry();
1953 unsigned Addr = Origin->getOffset();
1954 if (Form == dwarf::DW_FORM_ref_addr) {
1955 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1956 // section. Origin->getOffset() returns the offset from start of the
1958 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1959 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1961 Asm->OutStreamer.EmitIntValue(Addr,
1962 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1965 case dwarf::DW_AT_ranges: {
1966 // DW_AT_range Value encodes offset in debug_range section.
1967 DIEInteger *V = cast<DIEInteger>(Values[i]);
1969 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1970 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1974 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1976 DwarfDebugRangeSectionSym,
1981 case dwarf::DW_AT_location: {
1982 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1983 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1984 Asm->EmitLabelReference(L->getValue(), 4);
1986 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1988 Values[i]->EmitValue(Asm, Form);
1992 case dwarf::DW_AT_accessibility: {
1993 if (Asm->isVerbose()) {
1994 DIEInteger *V = cast<DIEInteger>(Values[i]);
1995 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1997 Values[i]->EmitValue(Asm, Form);
2001 // Emit an attribute using the defined form.
2002 Values[i]->EmitValue(Asm, Form);
2007 // Emit the DIE children if any.
2008 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2009 const std::vector<DIE *> &Children = Die->getChildren();
2011 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2012 emitDIE(Children[j], Abbrevs);
2014 if (Asm->isVerbose())
2015 Asm->OutStreamer.AddComment("End Of Children Mark");
2020 // Emit the various dwarf units to the unit section USection with
2021 // the abbreviations going into ASection.
2022 void DwarfUnits::emitUnits(DwarfDebug *DD,
2023 const MCSection *USection,
2024 const MCSection *ASection,
2025 const MCSymbol *ASectionSym) {
2026 Asm->OutStreamer.SwitchSection(USection);
2027 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2028 E = CUs.end(); I != E; ++I) {
2029 CompileUnit *TheCU = *I;
2030 DIE *Die = TheCU->getCUDie();
2032 // Emit the compile units header.
2034 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2035 TheCU->getUniqueID()));
2037 // Emit size of content not including length itself
2038 unsigned ContentSize = Die->getSize() +
2039 sizeof(int16_t) + // DWARF version number
2040 sizeof(int32_t) + // Offset Into Abbrev. Section
2041 sizeof(int8_t); // Pointer Size (in bytes)
2043 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2044 Asm->EmitInt32(ContentSize);
2045 Asm->OutStreamer.AddComment("DWARF version number");
2046 Asm->EmitInt16(DD->getDwarfVersion());
2047 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2048 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2050 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2051 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2053 DD->emitDIE(Die, Abbreviations);
2054 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2055 TheCU->getUniqueID()));
2059 /// For a given compile unit DIE, returns offset from beginning of debug info.
2060 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2061 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2062 "Input DIE should be compile unit in getCUOffset.");
2063 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2065 CompileUnit *TheCU = *I;
2066 if (TheCU->getCUDie() == Die)
2067 return TheCU->getDebugInfoOffset();
2069 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2072 // Emit the debug info section.
2073 void DwarfDebug::emitDebugInfo() {
2074 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2076 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2077 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2078 DwarfAbbrevSectionSym);
2081 // Emit the abbreviation section.
2082 void DwarfDebug::emitAbbreviations() {
2083 if (!useSplitDwarf())
2084 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2087 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2090 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2091 std::vector<DIEAbbrev *> *Abbrevs) {
2092 // Check to see if it is worth the effort.
2093 if (!Abbrevs->empty()) {
2094 // Start the debug abbrev section.
2095 Asm->OutStreamer.SwitchSection(Section);
2097 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2098 Asm->OutStreamer.EmitLabel(Begin);
2100 // For each abbrevation.
2101 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2102 // Get abbreviation data
2103 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2105 // Emit the abbrevations code (base 1 index.)
2106 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2108 // Emit the abbreviations data.
2112 // Mark end of abbreviations.
2113 Asm->EmitULEB128(0, "EOM(3)");
2115 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2116 Asm->OutStreamer.EmitLabel(End);
2120 // Emit the last address of the section and the end of the line matrix.
2121 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2122 // Define last address of section.
2123 Asm->OutStreamer.AddComment("Extended Op");
2126 Asm->OutStreamer.AddComment("Op size");
2127 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2128 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2129 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2131 Asm->OutStreamer.AddComment("Section end label");
2133 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2134 Asm->getDataLayout().getPointerSize());
2136 // Mark end of matrix.
2137 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2143 // Emit visible names into a hashed accelerator table section.
2144 void DwarfDebug::emitAccelNames() {
2145 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2146 dwarf::DW_FORM_data4));
2147 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2148 E = CUMap.end(); I != E; ++I) {
2149 CompileUnit *TheCU = I->second;
2150 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2151 for (StringMap<std::vector<DIE*> >::const_iterator
2152 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2153 StringRef Name = GI->getKey();
2154 const std::vector<DIE *> &Entities = GI->second;
2155 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2156 DE = Entities.end(); DI != DE; ++DI)
2157 AT.AddName(Name, (*DI));
2161 AT.FinalizeTable(Asm, "Names");
2162 Asm->OutStreamer.SwitchSection(
2163 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2164 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2165 Asm->OutStreamer.EmitLabel(SectionBegin);
2167 // Emit the full data.
2168 AT.Emit(Asm, SectionBegin, &InfoHolder);
2171 // Emit objective C classes and categories into a hashed accelerator table
2173 void DwarfDebug::emitAccelObjC() {
2174 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2175 dwarf::DW_FORM_data4));
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<DIE*> > &Names = TheCU->getAccelObjC();
2180 for (StringMap<std::vector<DIE*> >::const_iterator
2181 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2182 StringRef Name = GI->getKey();
2183 const std::vector<DIE *> &Entities = GI->second;
2184 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2185 DE = Entities.end(); DI != DE; ++DI)
2186 AT.AddName(Name, (*DI));
2190 AT.FinalizeTable(Asm, "ObjC");
2191 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2192 .getDwarfAccelObjCSection());
2193 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2194 Asm->OutStreamer.EmitLabel(SectionBegin);
2196 // Emit the full data.
2197 AT.Emit(Asm, SectionBegin, &InfoHolder);
2200 // Emit namespace dies into a hashed accelerator table.
2201 void DwarfDebug::emitAccelNamespaces() {
2202 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2203 dwarf::DW_FORM_data4));
2204 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2205 E = CUMap.end(); I != E; ++I) {
2206 CompileUnit *TheCU = I->second;
2207 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2208 for (StringMap<std::vector<DIE*> >::const_iterator
2209 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2210 StringRef Name = GI->getKey();
2211 const std::vector<DIE *> &Entities = GI->second;
2212 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2213 DE = Entities.end(); DI != DE; ++DI)
2214 AT.AddName(Name, (*DI));
2218 AT.FinalizeTable(Asm, "namespac");
2219 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2220 .getDwarfAccelNamespaceSection());
2221 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2222 Asm->OutStreamer.EmitLabel(SectionBegin);
2224 // Emit the full data.
2225 AT.Emit(Asm, SectionBegin, &InfoHolder);
2228 // Emit type dies into a hashed accelerator table.
2229 void DwarfDebug::emitAccelTypes() {
2230 std::vector<DwarfAccelTable::Atom> Atoms;
2231 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2232 dwarf::DW_FORM_data4));
2233 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2234 dwarf::DW_FORM_data2));
2235 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2236 dwarf::DW_FORM_data1));
2237 DwarfAccelTable AT(Atoms);
2238 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2239 E = CUMap.end(); I != E; ++I) {
2240 CompileUnit *TheCU = I->second;
2241 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2242 = TheCU->getAccelTypes();
2243 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2244 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2245 StringRef Name = GI->getKey();
2246 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2247 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2248 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2249 AT.AddName(Name, (*DI).first, (*DI).second);
2253 AT.FinalizeTable(Asm, "types");
2254 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2255 .getDwarfAccelTypesSection());
2256 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2257 Asm->OutStreamer.EmitLabel(SectionBegin);
2259 // Emit the full data.
2260 AT.Emit(Asm, SectionBegin, &InfoHolder);
2263 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2265 void DwarfDebug::emitDebugPubnames() {
2266 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2268 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2269 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2270 CompileUnit *TheCU = I->second;
2271 unsigned ID = TheCU->getUniqueID();
2273 if (TheCU->getGlobalNames().empty())
2276 // Start the dwarf pubnames section.
2278 .SwitchSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
2280 Asm->OutStreamer.AddComment("Length of Public Names Info");
2281 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2282 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2284 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2286 Asm->OutStreamer.AddComment("DWARF Version");
2287 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2289 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2290 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2291 DwarfInfoSectionSym);
2293 Asm->OutStreamer.AddComment("Compilation Unit Length");
2294 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2295 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2298 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2299 for (StringMap<DIE*>::const_iterator
2300 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2301 const char *Name = GI->getKeyData();
2302 const DIE *Entity = GI->second;
2304 Asm->OutStreamer.AddComment("DIE offset");
2305 Asm->EmitInt32(Entity->getOffset());
2307 if (Asm->isVerbose())
2308 Asm->OutStreamer.AddComment("External Name");
2309 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2312 Asm->OutStreamer.AddComment("End Mark");
2314 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2318 void DwarfDebug::emitDebugPubTypes() {
2319 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2320 E = CUMap.end(); I != E; ++I) {
2321 CompileUnit *TheCU = I->second;
2322 // Start the dwarf pubtypes section.
2323 Asm->OutStreamer.SwitchSection(
2324 Asm->getObjFileLowering().getDwarfPubTypesSection());
2325 Asm->OutStreamer.AddComment("Length of Public Types Info");
2326 Asm->EmitLabelDifference(
2327 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2328 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2330 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2331 TheCU->getUniqueID()));
2333 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2334 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2336 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2337 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2338 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2339 TheCU->getUniqueID()),
2340 DwarfInfoSectionSym);
2342 Asm->OutStreamer.AddComment("Compilation Unit Length");
2343 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2344 TheCU->getUniqueID()),
2345 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2346 TheCU->getUniqueID()),
2349 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2350 for (StringMap<DIE*>::const_iterator
2351 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2352 const char *Name = GI->getKeyData();
2353 DIE *Entity = GI->second;
2355 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2356 Asm->EmitInt32(Entity->getOffset());
2358 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2359 // Emit the name with a terminating null byte.
2360 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2363 Asm->OutStreamer.AddComment("End Mark");
2365 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2366 TheCU->getUniqueID()));
2370 // Emit strings into a string section.
2371 void DwarfUnits::emitStrings(const MCSection *StrSection,
2372 const MCSection *OffsetSection = NULL,
2373 const MCSymbol *StrSecSym = NULL) {
2375 if (StringPool.empty()) return;
2377 // Start the dwarf str section.
2378 Asm->OutStreamer.SwitchSection(StrSection);
2380 // Get all of the string pool entries and put them in an array by their ID so
2381 // we can sort them.
2382 SmallVector<std::pair<unsigned,
2383 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2385 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2386 I = StringPool.begin(), E = StringPool.end();
2388 Entries.push_back(std::make_pair(I->second.second, &*I));
2390 array_pod_sort(Entries.begin(), Entries.end());
2392 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2393 // Emit a label for reference from debug information entries.
2394 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2396 // Emit the string itself with a terminating null byte.
2397 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2398 Entries[i].second->getKeyLength()+1));
2401 // If we've got an offset section go ahead and emit that now as well.
2402 if (OffsetSection) {
2403 Asm->OutStreamer.SwitchSection(OffsetSection);
2404 unsigned offset = 0;
2405 unsigned size = 4; // FIXME: DWARF64 is 8.
2406 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2407 Asm->OutStreamer.EmitIntValue(offset, size);
2408 offset += Entries[i].second->getKeyLength() + 1;
2413 // Emit strings into a string section.
2414 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2416 if (AddressPool.empty()) return;
2418 // Start the dwarf addr section.
2419 Asm->OutStreamer.SwitchSection(AddrSection);
2421 // Order the address pool entries by ID
2422 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2424 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2425 E = AddressPool.end();
2427 Entries[I->second] = I->first;
2429 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2430 // Emit an expression for reference from debug information entries.
2431 if (const MCExpr *Expr = Entries[i])
2432 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2434 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2439 // Emit visible names into a debug str section.
2440 void DwarfDebug::emitDebugStr() {
2441 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2442 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2445 // Emit locations into the debug loc section.
2446 void DwarfDebug::emitDebugLoc() {
2447 if (DotDebugLocEntries.empty())
2450 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2451 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2453 DotDebugLocEntry &Entry = *I;
2454 if (I + 1 != DotDebugLocEntries.end())
2458 // Start the dwarf loc section.
2459 Asm->OutStreamer.SwitchSection(
2460 Asm->getObjFileLowering().getDwarfLocSection());
2461 unsigned char Size = Asm->getDataLayout().getPointerSize();
2462 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2464 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2465 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2466 I != E; ++I, ++index) {
2467 DotDebugLocEntry &Entry = *I;
2468 if (Entry.isMerged()) continue;
2469 if (Entry.isEmpty()) {
2470 Asm->OutStreamer.EmitIntValue(0, Size);
2471 Asm->OutStreamer.EmitIntValue(0, Size);
2472 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2474 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2475 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2476 DIVariable DV(Entry.getVariable());
2477 Asm->OutStreamer.AddComment("Loc expr size");
2478 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2479 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2480 Asm->EmitLabelDifference(end, begin, 2);
2481 Asm->OutStreamer.EmitLabel(begin);
2482 if (Entry.isInt()) {
2483 DIBasicType BTy(DV.getType());
2485 (BTy.getEncoding() == dwarf::DW_ATE_signed
2486 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2487 Asm->OutStreamer.AddComment("DW_OP_consts");
2488 Asm->EmitInt8(dwarf::DW_OP_consts);
2489 Asm->EmitSLEB128(Entry.getInt());
2491 Asm->OutStreamer.AddComment("DW_OP_constu");
2492 Asm->EmitInt8(dwarf::DW_OP_constu);
2493 Asm->EmitULEB128(Entry.getInt());
2495 } else if (Entry.isLocation()) {
2496 MachineLocation Loc = Entry.getLoc();
2497 if (!DV.hasComplexAddress())
2499 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2501 // Complex address entry.
2502 unsigned N = DV.getNumAddrElements();
2504 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2505 if (Loc.getOffset()) {
2507 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2508 Asm->OutStreamer.AddComment("DW_OP_deref");
2509 Asm->EmitInt8(dwarf::DW_OP_deref);
2510 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2511 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2512 Asm->EmitSLEB128(DV.getAddrElement(1));
2514 // If first address element is OpPlus then emit
2515 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2516 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2517 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2521 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2524 // Emit remaining complex address elements.
2525 for (; i < N; ++i) {
2526 uint64_t Element = DV.getAddrElement(i);
2527 if (Element == DIBuilder::OpPlus) {
2528 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2529 Asm->EmitULEB128(DV.getAddrElement(++i));
2530 } else if (Element == DIBuilder::OpDeref) {
2532 Asm->EmitInt8(dwarf::DW_OP_deref);
2534 llvm_unreachable("unknown Opcode found in complex address");
2538 // else ... ignore constant fp. There is not any good way to
2539 // to represent them here in dwarf.
2540 Asm->OutStreamer.EmitLabel(end);
2545 // Emit visible names into a debug aranges section.
2546 void DwarfDebug::emitDebugARanges() {
2547 // Start the dwarf aranges section.
2549 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2552 // Emit visible names into a debug ranges section.
2553 void DwarfDebug::emitDebugRanges() {
2554 // Start the dwarf ranges section.
2556 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2557 unsigned char Size = Asm->getDataLayout().getPointerSize();
2558 for (SmallVectorImpl<const MCSymbol *>::iterator
2559 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2562 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2564 Asm->OutStreamer.EmitIntValue(0, Size);
2568 // Emit visible names into a debug macinfo section.
2569 void DwarfDebug::emitDebugMacInfo() {
2570 if (const MCSection *LineInfo =
2571 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2572 // Start the dwarf macinfo section.
2573 Asm->OutStreamer.SwitchSection(LineInfo);
2577 // DWARF5 Experimental Separate Dwarf emitters.
2579 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2580 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2581 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2582 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2583 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2585 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2586 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2587 Asm, this, &SkeletonHolder);
2589 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2590 DICompileUnit(CU->getNode()).getSplitDebugFilename());
2592 // Relocate to the beginning of the addr_base section, else 0 for the
2593 // beginning of the one for this compile unit.
2594 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2595 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2596 DwarfAddrSectionSym);
2598 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2599 dwarf::DW_FORM_sec_offset, 0);
2601 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2602 // into an entity. We're using 0, or a NULL label for this.
2603 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2605 // DW_AT_stmt_list is a offset of line number information for this
2606 // compile unit in debug_line section.
2607 // FIXME: Should handle multiple compile units.
2608 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2609 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2610 DwarfLineSectionSym);
2612 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2614 if (!CompilationDir.empty())
2615 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2617 SkeletonHolder.addUnit(NewCU);
2618 SkeletonCUs.push_back(NewCU);
2623 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2624 assert(useSplitDwarf() && "No split dwarf debug info?");
2625 emitAbbrevs(Section, &SkeletonAbbrevs);
2628 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2629 // compile units that would normally be in debug_info.
2630 void DwarfDebug::emitDebugInfoDWO() {
2631 assert(useSplitDwarf() && "No split dwarf debug info?");
2632 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2633 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2634 DwarfAbbrevDWOSectionSym);
2637 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2638 // abbreviations for the .debug_info.dwo section.
2639 void DwarfDebug::emitDebugAbbrevDWO() {
2640 assert(useSplitDwarf() && "No split dwarf?");
2641 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2645 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2646 // string section and is identical in format to traditional .debug_str
2648 void DwarfDebug::emitDebugStrDWO() {
2649 assert(useSplitDwarf() && "No split dwarf?");
2650 const MCSection *OffSec = Asm->getObjFileLowering()
2651 .getDwarfStrOffDWOSection();
2652 const MCSymbol *StrSym = DwarfStrSectionSym;
2653 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),