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 SplitDwarf("split-dwarf", cl::Hidden,
89 cl::desc("Output prototype dwarf split debug info."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
97 cl::desc("Generate DWARF pubnames and pubtypes sections"),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static const char *const DWARFGroupName = "DWARF Emission";
104 static const char *const DbgTimerName = "DWARF Debug Writer";
106 //===----------------------------------------------------------------------===//
108 // Configuration values for initial hash set sizes (log2).
110 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
114 DIType DbgVariable::getType() const {
115 DIType Ty = Var.getType();
116 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
117 // addresses instead.
118 if (Var.isBlockByrefVariable()) {
119 /* Byref variables, in Blocks, are declared by the programmer as
120 "SomeType VarName;", but the compiler creates a
121 __Block_byref_x_VarName struct, and gives the variable VarName
122 either the struct, or a pointer to the struct, as its type. This
123 is necessary for various behind-the-scenes things the compiler
124 needs to do with by-reference variables in blocks.
126 However, as far as the original *programmer* is concerned, the
127 variable should still have type 'SomeType', as originally declared.
129 The following function dives into the __Block_byref_x_VarName
130 struct to find the original type of the variable. This will be
131 passed back to the code generating the type for the Debug
132 Information Entry for the variable 'VarName'. 'VarName' will then
133 have the original type 'SomeType' in its debug information.
135 The original type 'SomeType' will be the type of the field named
136 'VarName' inside the __Block_byref_x_VarName struct.
138 NOTE: In order for this to not completely fail on the debugger
139 side, the Debug Information Entry for the variable VarName needs to
140 have a DW_AT_location that tells the debugger how to unwind through
141 the pointers and __Block_byref_x_VarName struct to find the actual
142 value of the variable. The function addBlockByrefType does this. */
144 uint16_t tag = Ty.getTag();
146 if (tag == dwarf::DW_TAG_pointer_type)
147 subType = DIDerivedType(Ty).getTypeDerivedFrom();
149 DIArray Elements = DICompositeType(subType).getTypeArray();
150 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
151 DIDerivedType DT = DIDerivedType(Elements.getElement(i));
152 if (getName() == DT.getName())
153 return (DT.getTypeDerivedFrom());
159 } // end llvm namespace
161 /// Return Dwarf Version by checking module flags.
162 static unsigned getDwarfVersionFromModule(const Module *M) {
163 Value *Val = M->getModuleFlag("Dwarf Version");
165 return dwarf::DWARF_VERSION;
166 return cast<ConstantInt>(Val)->getZExtValue();
169 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
170 : Asm(A), MMI(Asm->MMI), FirstCU(0),
171 AbbreviationsSet(InitAbbreviationsSetSize),
172 SourceIdMap(DIEValueAllocator),
173 PrevLabel(NULL), GlobalCUIndexCount(0),
174 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
176 SkeletonAbbrevSet(InitAbbreviationsSetSize),
177 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
180 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
181 DwarfStrSectionSym = TextSectionSym = 0;
182 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
183 DwarfAddrSectionSym = 0;
184 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
185 FunctionBeginSym = FunctionEndSym = 0;
187 // Turn on accelerator tables and older gdb compatibility
188 // for Darwin by default, pubnames by default for non-Darwin,
189 // and handle split dwarf.
190 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
192 if (DwarfAccelTables == Default)
193 HasDwarfAccelTables = IsDarwin;
195 HasDwarfAccelTables = DwarfAccelTables == Enable;
197 if (SplitDwarf == Default)
198 HasSplitDwarf = false;
200 HasSplitDwarf = SplitDwarf == Enable;
202 if (DwarfPubSections == Default)
203 HasDwarfPubSections = !IsDarwin;
205 HasDwarfPubSections = DwarfPubSections == Enable;
207 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
210 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
214 DwarfDebug::~DwarfDebug() {
217 // Switch to the specified MCSection and emit an assembler
218 // temporary label to it if SymbolStem is specified.
219 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
220 const char *SymbolStem = 0) {
221 Asm->OutStreamer.SwitchSection(Section);
222 if (!SymbolStem) return 0;
224 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
225 Asm->OutStreamer.EmitLabel(TmpSym);
229 MCSymbol *DwarfUnits::getStringPoolSym() {
230 return Asm->GetTempSymbol(StringPref);
233 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
234 std::pair<MCSymbol*, unsigned> &Entry =
235 StringPool.GetOrCreateValue(Str).getValue();
236 if (Entry.first) return Entry.first;
238 Entry.second = NextStringPoolNumber++;
239 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
242 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
243 std::pair<MCSymbol*, unsigned> &Entry =
244 StringPool.GetOrCreateValue(Str).getValue();
245 if (Entry.first) return Entry.second;
247 Entry.second = NextStringPoolNumber++;
248 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
252 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
253 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
256 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
257 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
258 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
260 ++NextAddrPoolNumber;
261 return P.first->second;
264 // Define a unique number for the abbreviation.
266 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
267 // Check the set for priors.
268 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
270 // If it's newly added.
271 if (InSet == &Abbrev) {
272 // Add to abbreviation list.
273 Abbreviations->push_back(&Abbrev);
275 // Assign the vector position + 1 as its number.
276 Abbrev.setNumber(Abbreviations->size());
278 // Assign existing abbreviation number.
279 Abbrev.setNumber(InSet->getNumber());
283 static bool isObjCClass(StringRef Name) {
284 return Name.startswith("+") || Name.startswith("-");
287 static bool hasObjCCategory(StringRef Name) {
288 if (!isObjCClass(Name)) return false;
290 return Name.find(") ") != StringRef::npos;
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 uint16_t 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 SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
426 // If we have multiple ranges, emit them into the range section.
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 (SmallVectorImpl<InsnRange>::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));
440 // Terminate the range list.
441 DebugRangeSymbols.push_back(NULL);
442 DebugRangeSymbols.push_back(NULL);
446 // Construct the address range for this DIE.
447 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
448 MCSymbol *Start = getLabelBeforeInsn(RI->first);
449 MCSymbol *End = getLabelAfterInsn(RI->second);
451 if (End == 0) return 0;
453 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
454 assert(End->isDefined() && "Invalid end label for an inlined scope!");
456 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
457 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
462 // This scope represents inlined body of a function. Construct DIE to
463 // represent this concrete inlined copy of the function.
464 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
465 LexicalScope *Scope) {
466 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
467 assert(Ranges.empty() == false &&
468 "LexicalScope does not have instruction markers!");
470 if (!Scope->getScopeNode())
472 DIScope DS(Scope->getScopeNode());
473 DISubprogram InlinedSP = getDISubprogram(DS);
474 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
476 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
480 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
481 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
482 dwarf::DW_FORM_ref4, OriginDIE);
484 if (Ranges.size() > 1) {
485 // .debug_range section has not been laid out yet. Emit offset in
486 // .debug_range as a uint, size 4, for now. emitDIE will handle
487 // DW_AT_ranges appropriately.
488 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
489 DebugRangeSymbols.size()
490 * Asm->getDataLayout().getPointerSize());
491 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
492 RE = Ranges.end(); RI != RE; ++RI) {
493 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
494 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
496 DebugRangeSymbols.push_back(NULL);
497 DebugRangeSymbols.push_back(NULL);
499 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
500 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
501 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
503 if (StartLabel == 0 || EndLabel == 0)
504 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
506 assert(StartLabel->isDefined() &&
507 "Invalid starting label for an inlined scope!");
508 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
510 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
511 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
514 InlinedSubprogramDIEs.insert(OriginDIE);
516 // Add the call site information to the DIE.
517 DILocation DL(Scope->getInlinedAt());
518 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
519 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
520 TheCU->getUniqueID()));
521 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
523 // Add name to the name table, we do this here because we're guaranteed
524 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
525 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
530 // Construct a DIE for this scope.
531 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
532 if (!Scope || !Scope->getScopeNode())
535 DIScope DS(Scope->getScopeNode());
536 // Early return to avoid creating dangling variable|scope DIEs.
537 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
541 SmallVector<DIE *, 8> Children;
542 DIE *ObjectPointer = NULL;
544 // Collect arguments for current function.
545 if (LScopes.isCurrentFunctionScope(Scope))
546 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
547 if (DbgVariable *ArgDV = CurrentFnArguments[i])
549 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
550 Children.push_back(Arg);
551 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
554 // Collect lexical scope children first.
555 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
556 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
558 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
559 Children.push_back(Variable);
560 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
562 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
563 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
564 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
565 Children.push_back(Nested);
566 DIE *ScopeDIE = NULL;
567 if (Scope->getInlinedAt())
568 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
569 else if (DS.isSubprogram()) {
570 ProcessedSPNodes.insert(DS);
571 if (Scope->isAbstractScope()) {
572 ScopeDIE = TheCU->getDIE(DS);
573 // Note down abstract DIE.
575 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
578 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
581 // There is no need to emit empty lexical block DIE.
582 std::pair<ImportedEntityMap::const_iterator,
583 ImportedEntityMap::const_iterator> Range = std::equal_range(
584 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
585 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
587 if (Children.empty() && Range.first == Range.second)
589 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
590 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
592 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
596 std::for_each(Children.begin(), Children.end(), deleter<DIE>);
601 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
602 E = Children.end(); I != E; ++I)
603 ScopeDIE->addChild(*I);
605 if (DS.isSubprogram() && ObjectPointer != NULL)
606 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
607 dwarf::DW_FORM_ref4, ObjectPointer);
609 if (DS.isSubprogram())
610 TheCU->addPubTypes(DISubprogram(DS));
615 // Look up the source id with the given directory and source file names.
616 // If none currently exists, create a new id and insert it in the
617 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
619 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
620 StringRef DirName, unsigned CUID) {
621 // If we use .loc in assembly, we can't separate .file entries according to
622 // compile units. Thus all files will belong to the default compile unit.
623 if (Asm->TM.hasMCUseLoc() &&
624 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
627 // If FE did not provide a file name, then assume stdin.
628 if (FileName.empty())
629 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
631 // TODO: this might not belong here. See if we can factor this better.
632 if (DirName == CompilationDir)
635 // FileIDCUMap stores the current ID for the given compile unit.
636 unsigned SrcId = FileIDCUMap[CUID] + 1;
638 // We look up the CUID/file/dir by concatenating them with a zero byte.
639 SmallString<128> NamePair;
640 NamePair += utostr(CUID);
643 NamePair += '\0'; // Zero bytes are not allowed in paths.
644 NamePair += FileName;
646 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
647 if (Ent.getValue() != SrcId)
648 return Ent.getValue();
650 FileIDCUMap[CUID] = SrcId;
651 // Print out a .file directive to specify files for .loc directives.
652 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
657 // Create new CompileUnit for the given metadata node with tag
658 // DW_TAG_compile_unit.
659 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
660 DICompileUnit DIUnit(N);
661 StringRef FN = DIUnit.getFilename();
662 CompilationDir = DIUnit.getDirectory();
664 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
666 new CompileUnit(GlobalCUIndexCount++, Die, N, Asm, this, &InfoHolder);
668 FileIDCUMap[NewCU->getUniqueID()] = 0;
669 // Call this to emit a .file directive if it wasn't emitted for the source
670 // file this CU comes from yet.
671 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
673 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
674 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
675 DIUnit.getLanguage());
676 NewCU->addString(Die, dwarf::DW_AT_name, FN);
678 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
679 // into an entity. We're using 0 (or a NULL label) for this. For
680 // split dwarf it's in the skeleton CU so omit it here.
681 if (!useSplitDwarf())
682 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
684 // Define start line table label for each Compile Unit.
685 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
686 NewCU->getUniqueID());
687 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
688 NewCU->getUniqueID());
690 // Use a single line table if we are using .loc and generating assembly.
692 (Asm->TM.hasMCUseLoc() &&
693 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
694 (NewCU->getUniqueID() == 0);
696 // DW_AT_stmt_list is a offset of line number information for this
697 // compile unit in debug_line section. For split dwarf this is
698 // left in the skeleton CU and so not included.
699 // The line table entries are not always emitted in assembly, so it
700 // is not okay to use line_table_start here.
701 if (!useSplitDwarf()) {
702 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
703 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
705 Asm->GetTempSymbol("section_line") : LineTableStartSym);
706 else if (UseTheFirstCU)
707 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
709 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
710 LineTableStartSym, DwarfLineSectionSym);
713 // If we're using split dwarf the compilation dir is going to be in the
714 // skeleton CU and so we don't need to duplicate it here.
715 if (!useSplitDwarf() && !CompilationDir.empty())
716 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
717 if (DIUnit.isOptimized())
718 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
720 StringRef Flags = DIUnit.getFlags();
722 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
724 if (unsigned RVer = DIUnit.getRunTimeVersion())
725 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
726 dwarf::DW_FORM_data1, RVer);
731 InfoHolder.addUnit(NewCU);
733 CUMap.insert(std::make_pair(N, NewCU));
737 // Construct subprogram DIE.
738 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
740 CompileUnit *&CURef = SPMap[N];
746 if (!SP.isDefinition())
747 // This is a method declaration which will be handled while constructing
751 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
754 TheCU->insertDIE(N, SubprogramDie);
756 // Add to context owner.
757 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
759 // Expose as global, if requested.
760 if (HasDwarfPubSections)
761 TheCU->addGlobalName(SP.getName(), SubprogramDie);
764 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
766 DIImportedEntity Module(N);
767 if (!Module.Verify())
769 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
770 constructImportedEntityDIE(TheCU, Module, D);
773 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
775 DIImportedEntity Module(N);
776 if (!Module.Verify())
778 return constructImportedEntityDIE(TheCU, Module, Context);
781 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
782 const DIImportedEntity &Module,
784 assert(Module.Verify() &&
785 "Use one of the MDNode * overloads to handle invalid metadata");
786 assert(Context && "Should always have a context for an imported_module");
787 DIE *IMDie = new DIE(Module.getTag());
788 TheCU->insertDIE(Module, IMDie);
790 DIDescriptor Entity = Module.getEntity();
791 if (Entity.isNameSpace())
792 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
793 else if (Entity.isSubprogram())
794 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
795 else if (Entity.isType())
796 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
798 EntityDie = TheCU->getDIE(Entity);
799 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
800 Module.getContext().getDirectory(),
801 TheCU->getUniqueID());
802 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
803 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
804 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
806 StringRef Name = Module.getName();
808 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
809 Context->addChild(IMDie);
812 // Emit all Dwarf sections that should come prior to the content. Create
813 // global DIEs and emit initial debug info sections. This is invoked by
814 // the target AsmPrinter.
815 void DwarfDebug::beginModule() {
816 if (DisableDebugInfoPrinting)
819 const Module *M = MMI->getModule();
821 // If module has named metadata anchors then use them, otherwise scan the
822 // module using debug info finder to collect debug info.
823 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
827 // Emit initial sections so we can reference labels later.
830 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
831 DICompileUnit CUNode(CU_Nodes->getOperand(i));
832 CompileUnit *CU = constructCompileUnit(CUNode);
833 DIArray ImportedEntities = CUNode.getImportedEntities();
834 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
835 ScopesWithImportedEntities.push_back(std::make_pair(
836 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
837 ImportedEntities.getElement(i)));
838 std::sort(ScopesWithImportedEntities.begin(),
839 ScopesWithImportedEntities.end(), less_first());
840 DIArray GVs = CUNode.getGlobalVariables();
841 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
842 CU->createGlobalVariableDIE(GVs.getElement(i));
843 DIArray SPs = CUNode.getSubprograms();
844 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
845 constructSubprogramDIE(CU, SPs.getElement(i));
846 DIArray EnumTypes = CUNode.getEnumTypes();
847 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
848 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
849 DIArray RetainedTypes = CUNode.getRetainedTypes();
850 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
851 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
852 // Emit imported_modules last so that the relevant context is already
854 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
855 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
858 // Tell MMI that we have debug info.
859 MMI->setDebugInfoAvailability(true);
861 // Prime section data.
862 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
865 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
866 void DwarfDebug::computeInlinedDIEs() {
867 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
868 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
869 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
871 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
873 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
874 AE = AbstractSPDies.end(); AI != AE; ++AI) {
875 DIE *ISP = AI->second;
876 if (InlinedSubprogramDIEs.count(ISP))
878 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
882 // Collect info for variables that were optimized out.
883 void DwarfDebug::collectDeadVariables() {
884 const Module *M = MMI->getModule();
885 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
887 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
888 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
889 DICompileUnit TheCU(CU_Nodes->getOperand(i));
890 DIArray Subprograms = TheCU.getSubprograms();
891 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
892 DISubprogram SP(Subprograms.getElement(i));
893 if (ProcessedSPNodes.count(SP) != 0) continue;
894 if (!SP.isSubprogram()) continue;
895 if (!SP.isDefinition()) continue;
896 DIArray Variables = SP.getVariables();
897 if (Variables.getNumElements() == 0) continue;
899 LexicalScope *Scope =
900 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
901 DeadFnScopeMap[SP] = Scope;
903 // Construct subprogram DIE and add variables DIEs.
904 CompileUnit *SPCU = CUMap.lookup(TheCU);
905 assert(SPCU && "Unable to find Compile Unit!");
906 constructSubprogramDIE(SPCU, SP);
907 DIE *ScopeDIE = SPCU->getDIE(SP);
908 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
909 DIVariable DV(Variables.getElement(vi));
910 if (!DV.isVariable()) continue;
911 DbgVariable NewVar(DV, NULL);
912 if (DIE *VariableDIE =
913 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
914 ScopeDIE->addChild(VariableDIE);
919 DeleteContainerSeconds(DeadFnScopeMap);
922 // Type Signature [7.27] and ODR Hash code.
924 /// \brief Grabs the string in whichever attribute is passed in and returns
925 /// a reference to it. Returns "" if the attribute doesn't exist.
926 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
927 DIEValue *V = Die->findAttribute(Attr);
929 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
930 return S->getString();
932 return StringRef("");
935 /// Return true if the current DIE is contained within an anonymous namespace.
936 static bool isContainedInAnonNamespace(DIE *Die) {
937 DIE *Parent = Die->getParent();
940 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
941 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
943 Parent = Parent->getParent();
949 /// Test if the current CU language is C++ and that we have
950 /// a named type that is not contained in an anonymous namespace.
951 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
952 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
953 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
954 !isContainedInAnonNamespace(Die);
957 void DwarfDebug::finalizeModuleInfo() {
958 // Collect info for variables that were optimized out.
959 collectDeadVariables();
961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962 computeInlinedDIEs();
964 // Split out type units and conditionally add an ODR tag to the split
966 // FIXME: Do type splitting.
967 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
968 DIE *Die = TypeUnits[i];
970 // If we've requested ODR hashes and it's applicable for an ODR hash then
971 // add the ODR signature now.
972 // FIXME: This should be added onto the type unit, not the type, but this
973 // works as an intermediate stage.
974 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
975 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
976 dwarf::DW_FORM_data8,
977 Hash.computeDIEODRSignature(Die));
980 // Handle anything that needs to be done on a per-cu basis.
981 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
984 CompileUnit *TheCU = CUI->second;
985 // Emit DW_AT_containing_type attribute to connect types with their
986 // vtable holding type.
987 TheCU->constructContainingTypeDIEs();
989 // If we're splitting the dwarf out now that we've got the entire
990 // CU then construct a skeleton CU based upon it.
991 if (useSplitDwarf()) {
993 if (GenerateCUHash) {
995 ID = CUHash.computeCUSignature(TheCU->getCUDie());
997 // This should be a unique identifier when we want to build .dwp files.
998 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
999 dwarf::DW_FORM_data8, ID);
1000 // Now construct the skeleton CU associated.
1001 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1002 // This should be a unique identifier when we want to build .dwp files.
1003 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1004 dwarf::DW_FORM_data8, ID);
1008 // Compute DIE offsets and sizes.
1009 InfoHolder.computeSizeAndOffsets();
1010 if (useSplitDwarf())
1011 SkeletonHolder.computeSizeAndOffsets();
1014 void DwarfDebug::endSections() {
1015 // Standard sections final addresses.
1016 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1017 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1018 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1019 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1021 // End text sections.
1022 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1023 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1024 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1028 // Emit all Dwarf sections that should come after the content.
1029 void DwarfDebug::endModule() {
1031 if (!FirstCU) return;
1033 // End any existing sections.
1034 // TODO: Does this need to happen?
1037 // Finalize the debug info for the module.
1038 finalizeModuleInfo();
1040 if (!useSplitDwarf()) {
1041 // Emit all the DIEs into a debug info section.
1044 // Corresponding abbreviations into a abbrev section.
1045 emitAbbreviations();
1047 // Emit info into a debug loc section.
1050 // Emit info into a debug aranges section.
1053 // Emit info into a debug ranges section.
1056 // Emit info into a debug macinfo section.
1060 // TODO: Fill this in for separated debug sections and separate
1061 // out information into new sections.
1063 // Emit the debug info section and compile units.
1067 // Corresponding abbreviations into a abbrev section.
1068 emitAbbreviations();
1069 emitDebugAbbrevDWO();
1071 // Emit info into a debug loc section.
1074 // Emit info into a debug aranges section.
1077 // Emit info into a debug ranges section.
1080 // Emit info into a debug macinfo section.
1083 // Emit DWO addresses.
1084 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1088 // Emit info into the dwarf accelerator table sections.
1089 if (useDwarfAccelTables()) {
1092 emitAccelNamespaces();
1096 // Emit the pubnames and pubtypes sections if requested.
1097 if (HasDwarfPubSections) {
1098 emitDebugPubnames();
1099 emitDebugPubTypes();
1102 // Finally emit string information into a string table.
1104 if (useSplitDwarf())
1109 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1110 E = CUMap.end(); I != E; ++I)
1113 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1114 E = SkeletonCUs.end(); I != E; ++I)
1117 // Reset these for the next Module if we have one.
1121 // Find abstract variable, if any, associated with Var.
1122 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1123 DebugLoc ScopeLoc) {
1124 LLVMContext &Ctx = DV->getContext();
1125 // More then one inlined variable corresponds to one abstract variable.
1126 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1127 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1129 return AbsDbgVariable;
1131 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1135 AbsDbgVariable = new DbgVariable(Var, NULL);
1136 addScopeVariable(Scope, AbsDbgVariable);
1137 AbstractVariables[Var] = AbsDbgVariable;
1138 return AbsDbgVariable;
1141 // If Var is a current function argument then add it to CurrentFnArguments list.
1142 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1143 DbgVariable *Var, LexicalScope *Scope) {
1144 if (!LScopes.isCurrentFunctionScope(Scope))
1146 DIVariable DV = Var->getVariable();
1147 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1149 unsigned ArgNo = DV.getArgNumber();
1153 size_t Size = CurrentFnArguments.size();
1155 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1156 // llvm::Function argument size is not good indicator of how many
1157 // arguments does the function have at source level.
1159 CurrentFnArguments.resize(ArgNo * 2);
1160 CurrentFnArguments[ArgNo - 1] = Var;
1164 // Collect variable information from side table maintained by MMI.
1166 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1167 SmallPtrSet<const MDNode *, 16> &Processed) {
1168 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1169 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1170 VE = VMap.end(); VI != VE; ++VI) {
1171 const MDNode *Var = VI->first;
1173 Processed.insert(Var);
1175 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1177 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1179 // If variable scope is not found then skip this variable.
1183 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1184 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1185 RegVar->setFrameIndex(VP.first);
1186 if (!addCurrentFnArgument(MF, RegVar, Scope))
1187 addScopeVariable(Scope, RegVar);
1189 AbsDbgVariable->setFrameIndex(VP.first);
1193 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1195 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1196 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1197 return MI->getNumOperands() == 3 &&
1198 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1199 (MI->getOperand(1).isImm() ||
1200 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1203 // Get .debug_loc entry for the instruction range starting at MI.
1204 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1205 const MCSymbol *FLabel,
1206 const MCSymbol *SLabel,
1207 const MachineInstr *MI) {
1208 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1210 assert(MI->getNumOperands() == 3);
1211 if (MI->getOperand(0).isReg()) {
1212 MachineLocation MLoc;
1213 // If the second operand is an immediate, this is a
1214 // register-indirect address.
1215 if (!MI->getOperand(1).isImm())
1216 MLoc.set(MI->getOperand(0).getReg());
1218 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1219 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1221 if (MI->getOperand(0).isImm())
1222 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1223 if (MI->getOperand(0).isFPImm())
1224 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1225 if (MI->getOperand(0).isCImm())
1226 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1228 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1231 // Find variables for each lexical scope.
1233 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1234 SmallPtrSet<const MDNode *, 16> &Processed) {
1236 // Grab the variable info that was squirreled away in the MMI side-table.
1237 collectVariableInfoFromMMITable(MF, Processed);
1239 for (SmallVectorImpl<const MDNode*>::const_iterator
1240 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1242 const MDNode *Var = *UVI;
1243 if (Processed.count(Var))
1246 // History contains relevant DBG_VALUE instructions for Var and instructions
1248 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1249 if (History.empty())
1251 const MachineInstr *MInsn = History.front();
1254 LexicalScope *Scope = NULL;
1255 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1256 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1257 Scope = LScopes.getCurrentFunctionScope();
1258 else if (MDNode *IA = DV.getInlinedAt())
1259 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1261 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1262 // If variable scope is not found then skip this variable.
1266 Processed.insert(DV);
1267 assert(MInsn->isDebugValue() && "History must begin with debug value");
1268 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1269 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1270 if (!addCurrentFnArgument(MF, RegVar, Scope))
1271 addScopeVariable(Scope, RegVar);
1273 AbsVar->setMInsn(MInsn);
1275 // Simplify ranges that are fully coalesced.
1276 if (History.size() <= 1 || (History.size() == 2 &&
1277 MInsn->isIdenticalTo(History.back()))) {
1278 RegVar->setMInsn(MInsn);
1282 // Handle multiple DBG_VALUE instructions describing one variable.
1283 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1285 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1286 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1287 const MachineInstr *Begin = *HI;
1288 assert(Begin->isDebugValue() && "Invalid History entry");
1290 // Check if DBG_VALUE is truncating a range.
1291 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1292 && !Begin->getOperand(0).getReg())
1295 // Compute the range for a register location.
1296 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1297 const MCSymbol *SLabel = 0;
1300 // If Begin is the last instruction in History then its value is valid
1301 // until the end of the function.
1302 SLabel = FunctionEndSym;
1304 const MachineInstr *End = HI[1];
1305 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1306 << "\t" << *Begin << "\t" << *End << "\n");
1307 if (End->isDebugValue())
1308 SLabel = getLabelBeforeInsn(End);
1310 // End is a normal instruction clobbering the range.
1311 SLabel = getLabelAfterInsn(End);
1312 assert(SLabel && "Forgot label after clobber instruction");
1317 // The value is valid until the next DBG_VALUE or clobber.
1318 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1321 DotDebugLocEntries.push_back(DotDebugLocEntry());
1324 // Collect info for variables that were optimized out.
1325 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1326 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1327 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1328 DIVariable DV(Variables.getElement(i));
1329 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1331 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1332 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1336 // Return Label preceding the instruction.
1337 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1338 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1339 assert(Label && "Didn't insert label before instruction");
1343 // Return Label immediately following the instruction.
1344 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1345 return LabelsAfterInsn.lookup(MI);
1348 // Process beginning of an instruction.
1349 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1350 // Check if source location changes, but ignore DBG_VALUE locations.
1351 if (!MI->isDebugValue()) {
1352 DebugLoc DL = MI->getDebugLoc();
1353 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1356 if (DL == PrologEndLoc) {
1357 Flags |= DWARF2_FLAG_PROLOGUE_END;
1358 PrologEndLoc = DebugLoc();
1360 if (PrologEndLoc.isUnknown())
1361 Flags |= DWARF2_FLAG_IS_STMT;
1363 if (!DL.isUnknown()) {
1364 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1365 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1367 recordSourceLine(0, 0, 0, 0);
1371 // Insert labels where requested.
1372 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1373 LabelsBeforeInsn.find(MI);
1376 if (I == LabelsBeforeInsn.end())
1379 // Label already assigned.
1384 PrevLabel = MMI->getContext().CreateTempSymbol();
1385 Asm->OutStreamer.EmitLabel(PrevLabel);
1387 I->second = PrevLabel;
1390 // Process end of an instruction.
1391 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1392 // Don't create a new label after DBG_VALUE instructions.
1393 // They don't generate code.
1394 if (!MI->isDebugValue())
1397 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1398 LabelsAfterInsn.find(MI);
1401 if (I == LabelsAfterInsn.end())
1404 // Label already assigned.
1408 // We need a label after this instruction.
1410 PrevLabel = MMI->getContext().CreateTempSymbol();
1411 Asm->OutStreamer.EmitLabel(PrevLabel);
1413 I->second = PrevLabel;
1416 // Each LexicalScope has first instruction and last instruction to mark
1417 // beginning and end of a scope respectively. Create an inverse map that list
1418 // scopes starts (and ends) with an instruction. One instruction may start (or
1419 // end) multiple scopes. Ignore scopes that are not reachable.
1420 void DwarfDebug::identifyScopeMarkers() {
1421 SmallVector<LexicalScope *, 4> WorkList;
1422 WorkList.push_back(LScopes.getCurrentFunctionScope());
1423 while (!WorkList.empty()) {
1424 LexicalScope *S = WorkList.pop_back_val();
1426 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1427 if (!Children.empty())
1428 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1429 SE = Children.end(); SI != SE; ++SI)
1430 WorkList.push_back(*SI);
1432 if (S->isAbstractScope())
1435 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1438 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1439 RE = Ranges.end(); RI != RE; ++RI) {
1440 assert(RI->first && "InsnRange does not have first instruction!");
1441 assert(RI->second && "InsnRange does not have second instruction!");
1442 requestLabelBeforeInsn(RI->first);
1443 requestLabelAfterInsn(RI->second);
1448 // Get MDNode for DebugLoc's scope.
1449 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1450 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1451 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1452 return DL.getScope(Ctx);
1455 // Walk up the scope chain of given debug loc and find line number info
1456 // for the function.
1457 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1458 const MDNode *Scope = getScopeNode(DL, Ctx);
1459 DISubprogram SP = getDISubprogram(Scope);
1460 if (SP.isSubprogram()) {
1461 // Check for number of operands since the compatibility is
1463 if (SP->getNumOperands() > 19)
1464 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1466 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1472 // Gather pre-function debug information. Assumes being called immediately
1473 // after the function entry point has been emitted.
1474 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1475 if (!MMI->hasDebugInfo()) return;
1476 LScopes.initialize(*MF);
1477 if (LScopes.empty()) return;
1478 identifyScopeMarkers();
1480 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1482 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1483 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1484 assert(TheCU && "Unable to find compile unit!");
1485 if (Asm->TM.hasMCUseLoc() &&
1486 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1487 // Use a single line table if we are using .loc and generating assembly.
1488 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1490 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1492 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1493 Asm->getFunctionNumber());
1494 // Assumes in correct section after the entry point.
1495 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1497 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1499 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1500 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1501 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1503 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1505 bool AtBlockEntry = true;
1506 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1508 const MachineInstr *MI = II;
1510 if (MI->isDebugValue()) {
1511 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1513 // Keep track of user variables.
1515 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1517 // Variable is in a register, we need to check for clobbers.
1518 if (isDbgValueInDefinedReg(MI))
1519 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1521 // Check the history of this variable.
1522 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1523 if (History.empty()) {
1524 UserVariables.push_back(Var);
1525 // The first mention of a function argument gets the FunctionBeginSym
1526 // label, so arguments are visible when breaking at function entry.
1528 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1529 DISubprogram(getDISubprogram(DV.getContext()))
1530 .describes(MF->getFunction()))
1531 LabelsBeforeInsn[MI] = FunctionBeginSym;
1533 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1534 const MachineInstr *Prev = History.back();
1535 if (Prev->isDebugValue()) {
1536 // Coalesce identical entries at the end of History.
1537 if (History.size() >= 2 &&
1538 Prev->isIdenticalTo(History[History.size() - 2])) {
1539 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1541 << "\t" << *History[History.size() - 2] << "\n");
1545 // Terminate old register assignments that don't reach MI;
1546 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1547 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1548 isDbgValueInDefinedReg(Prev)) {
1549 // Previous register assignment needs to terminate at the end of
1551 MachineBasicBlock::const_iterator LastMI =
1552 PrevMBB->getLastNonDebugInstr();
1553 if (LastMI == PrevMBB->end()) {
1554 // Drop DBG_VALUE for empty range.
1555 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1556 << "\t" << *Prev << "\n");
1558 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1559 // Terminate after LastMI.
1560 History.push_back(LastMI);
1564 History.push_back(MI);
1566 // Not a DBG_VALUE instruction.
1568 AtBlockEntry = false;
1570 // First known non-DBG_VALUE and non-frame setup location marks
1571 // the beginning of the function body.
1572 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1573 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1574 PrologEndLoc = MI->getDebugLoc();
1576 // Check if the instruction clobbers any registers with debug vars.
1577 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1578 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1579 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1581 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1582 AI.isValid(); ++AI) {
1584 const MDNode *Var = LiveUserVar[Reg];
1587 // Reg is now clobbered.
1588 LiveUserVar[Reg] = 0;
1590 // Was MD last defined by a DBG_VALUE referring to Reg?
1591 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1592 if (HistI == DbgValues.end())
1594 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1595 if (History.empty())
1597 const MachineInstr *Prev = History.back();
1598 // Sanity-check: Register assignments are terminated at the end of
1600 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1602 // Is the variable still in Reg?
1603 if (!isDbgValueInDefinedReg(Prev) ||
1604 Prev->getOperand(0).getReg() != Reg)
1606 // Var is clobbered. Make sure the next instruction gets a label.
1607 History.push_back(MI);
1614 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1616 SmallVectorImpl<const MachineInstr*> &History = I->second;
1617 if (History.empty())
1620 // Make sure the final register assignments are terminated.
1621 const MachineInstr *Prev = History.back();
1622 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1623 const MachineBasicBlock *PrevMBB = Prev->getParent();
1624 MachineBasicBlock::const_iterator LastMI =
1625 PrevMBB->getLastNonDebugInstr();
1626 if (LastMI == PrevMBB->end())
1627 // Drop DBG_VALUE for empty range.
1629 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1630 // Terminate after LastMI.
1631 History.push_back(LastMI);
1634 // Request labels for the full history.
1635 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1636 const MachineInstr *MI = History[i];
1637 if (MI->isDebugValue())
1638 requestLabelBeforeInsn(MI);
1640 requestLabelAfterInsn(MI);
1644 PrevInstLoc = DebugLoc();
1645 PrevLabel = FunctionBeginSym;
1647 // Record beginning of function.
1648 if (!PrologEndLoc.isUnknown()) {
1649 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1650 MF->getFunction()->getContext());
1651 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1652 FnStartDL.getScope(MF->getFunction()->getContext()),
1653 // We'd like to list the prologue as "not statements" but GDB behaves
1654 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1655 DWARF2_FLAG_IS_STMT);
1659 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1660 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1661 DIVariable DV = Var->getVariable();
1662 // Variables with positive arg numbers are parameters.
1663 if (unsigned ArgNum = DV.getArgNumber()) {
1664 // Keep all parameters in order at the start of the variable list to ensure
1665 // function types are correct (no out-of-order parameters)
1667 // This could be improved by only doing it for optimized builds (unoptimized
1668 // builds have the right order to begin with), searching from the back (this
1669 // would catch the unoptimized case quickly), or doing a binary search
1670 // rather than linear search.
1671 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1672 while (I != Vars.end()) {
1673 unsigned CurNum = (*I)->getVariable().getArgNumber();
1674 // A local (non-parameter) variable has been found, insert immediately
1678 // A later indexed parameter has been found, insert immediately before it.
1679 if (CurNum > ArgNum)
1683 Vars.insert(I, Var);
1687 Vars.push_back(Var);
1690 // Gather and emit post-function debug information.
1691 void DwarfDebug::endFunction(const MachineFunction *MF) {
1692 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1694 // Define end label for subprogram.
1695 FunctionEndSym = Asm->GetTempSymbol("func_end",
1696 Asm->getFunctionNumber());
1697 // Assumes in correct section after the entry point.
1698 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1699 // Set DwarfCompileUnitID in MCContext to default value.
1700 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1702 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1703 collectVariableInfo(MF, ProcessedVars);
1705 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1706 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1707 assert(TheCU && "Unable to find compile unit!");
1709 // Construct abstract scopes.
1710 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1711 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1712 LexicalScope *AScope = AList[i];
1713 DISubprogram SP(AScope->getScopeNode());
1714 if (SP.isSubprogram()) {
1715 // Collect info for variables that were optimized out.
1716 DIArray Variables = SP.getVariables();
1717 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1718 DIVariable DV(Variables.getElement(i));
1719 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1721 // Check that DbgVariable for DV wasn't created earlier, when
1722 // findAbstractVariable() was called for inlined instance of DV.
1723 LLVMContext &Ctx = DV->getContext();
1724 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1725 if (AbstractVariables.lookup(CleanDV))
1727 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1728 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1731 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1732 constructScopeDIE(TheCU, AScope);
1735 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1737 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1738 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1741 for (ScopeVariablesMap::iterator
1742 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1743 DeleteContainerPointers(I->second);
1744 ScopeVariables.clear();
1745 DeleteContainerPointers(CurrentFnArguments);
1746 UserVariables.clear();
1748 AbstractVariables.clear();
1749 LabelsBeforeInsn.clear();
1750 LabelsAfterInsn.clear();
1754 // Register a source line with debug info. Returns the unique label that was
1755 // emitted and which provides correspondence to the source line list.
1756 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1762 DIDescriptor Scope(S);
1764 if (Scope.isCompileUnit()) {
1765 DICompileUnit CU(S);
1766 Fn = CU.getFilename();
1767 Dir = CU.getDirectory();
1768 } else if (Scope.isFile()) {
1770 Fn = F.getFilename();
1771 Dir = F.getDirectory();
1772 } else if (Scope.isSubprogram()) {
1774 Fn = SP.getFilename();
1775 Dir = SP.getDirectory();
1776 } else if (Scope.isLexicalBlockFile()) {
1777 DILexicalBlockFile DBF(S);
1778 Fn = DBF.getFilename();
1779 Dir = DBF.getDirectory();
1780 } else if (Scope.isLexicalBlock()) {
1781 DILexicalBlock DB(S);
1782 Fn = DB.getFilename();
1783 Dir = DB.getDirectory();
1785 llvm_unreachable("Unexpected scope info");
1787 Src = getOrCreateSourceID(Fn, Dir,
1788 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1790 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1793 //===----------------------------------------------------------------------===//
1795 //===----------------------------------------------------------------------===//
1797 // Compute the size and offset of a DIE.
1799 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1800 // Get the children.
1801 const std::vector<DIE *> &Children = Die->getChildren();
1803 // Record the abbreviation.
1804 assignAbbrevNumber(Die->getAbbrev());
1806 // Get the abbreviation for this DIE.
1807 unsigned AbbrevNumber = Die->getAbbrevNumber();
1808 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1811 Die->setOffset(Offset);
1813 // Start the size with the size of abbreviation code.
1814 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1816 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1817 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1819 // Size the DIE attribute values.
1820 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1821 // Size attribute value.
1822 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1824 // Size the DIE children if any.
1825 if (!Children.empty()) {
1826 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1827 "Children flag not set");
1829 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1830 Offset = computeSizeAndOffset(Children[j], Offset);
1832 // End of children marker.
1833 Offset += sizeof(int8_t);
1836 Die->setSize(Offset - Die->getOffset());
1840 // Compute the size and offset of all the DIEs.
1841 void DwarfUnits::computeSizeAndOffsets() {
1842 // Offset from the beginning of debug info section.
1843 unsigned SecOffset = 0;
1844 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1845 E = CUs.end(); I != E; ++I) {
1846 (*I)->setDebugInfoOffset(SecOffset);
1848 sizeof(int32_t) + // Length of Compilation Unit Info
1849 sizeof(int16_t) + // DWARF version number
1850 sizeof(int32_t) + // Offset Into Abbrev. Section
1851 sizeof(int8_t); // Pointer Size (in bytes)
1853 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1854 SecOffset += EndOffset;
1858 // Emit initial Dwarf sections with a label at the start of each one.
1859 void DwarfDebug::emitSectionLabels() {
1860 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1862 // Dwarf sections base addresses.
1863 DwarfInfoSectionSym =
1864 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1865 DwarfAbbrevSectionSym =
1866 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1867 if (useSplitDwarf())
1868 DwarfAbbrevDWOSectionSym =
1869 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1870 "section_abbrev_dwo");
1871 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1873 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1874 emitSectionSym(Asm, MacroInfo);
1876 DwarfLineSectionSym =
1877 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1878 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1879 if (HasDwarfPubSections) {
1880 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1881 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1883 DwarfStrSectionSym =
1884 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1885 if (useSplitDwarf()) {
1886 DwarfStrDWOSectionSym =
1887 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1888 DwarfAddrSectionSym =
1889 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1891 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1894 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1895 "section_debug_loc");
1897 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1898 emitSectionSym(Asm, TLOF.getDataSection());
1901 // Recursively emits a debug information entry.
1902 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1903 // Get the abbreviation for this DIE.
1904 unsigned AbbrevNumber = Die->getAbbrevNumber();
1905 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1907 // Emit the code (index) for the abbreviation.
1908 if (Asm->isVerbose())
1909 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1910 Twine::utohexstr(Die->getOffset()) + ":0x" +
1911 Twine::utohexstr(Die->getSize()) + " " +
1912 dwarf::TagString(Abbrev->getTag()));
1913 Asm->EmitULEB128(AbbrevNumber);
1915 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1916 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1918 // Emit the DIE attribute values.
1919 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1920 unsigned Attr = AbbrevData[i].getAttribute();
1921 unsigned Form = AbbrevData[i].getForm();
1922 assert(Form && "Too many attributes for DIE (check abbreviation)");
1924 if (Asm->isVerbose())
1925 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1928 case dwarf::DW_AT_abstract_origin: {
1929 DIEEntry *E = cast<DIEEntry>(Values[i]);
1930 DIE *Origin = E->getEntry();
1931 unsigned Addr = Origin->getOffset();
1932 if (Form == dwarf::DW_FORM_ref_addr) {
1933 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1934 // section. Origin->getOffset() returns the offset from start of the
1936 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1937 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1939 Asm->OutStreamer.EmitIntValue(Addr,
1940 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1943 case dwarf::DW_AT_ranges: {
1944 // DW_AT_range Value encodes offset in debug_range section.
1945 DIEInteger *V = cast<DIEInteger>(Values[i]);
1947 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1948 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1952 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1954 DwarfDebugRangeSectionSym,
1959 case dwarf::DW_AT_location: {
1960 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1961 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1962 Asm->EmitLabelReference(L->getValue(), 4);
1964 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1966 Values[i]->EmitValue(Asm, Form);
1970 case dwarf::DW_AT_accessibility: {
1971 if (Asm->isVerbose()) {
1972 DIEInteger *V = cast<DIEInteger>(Values[i]);
1973 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1975 Values[i]->EmitValue(Asm, Form);
1979 // Emit an attribute using the defined form.
1980 Values[i]->EmitValue(Asm, Form);
1985 // Emit the DIE children if any.
1986 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1987 const std::vector<DIE *> &Children = Die->getChildren();
1989 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1990 emitDIE(Children[j], Abbrevs);
1992 if (Asm->isVerbose())
1993 Asm->OutStreamer.AddComment("End Of Children Mark");
1998 // Emit the various dwarf units to the unit section USection with
1999 // the abbreviations going into ASection.
2000 void DwarfUnits::emitUnits(DwarfDebug *DD,
2001 const MCSection *USection,
2002 const MCSection *ASection,
2003 const MCSymbol *ASectionSym) {
2004 Asm->OutStreamer.SwitchSection(USection);
2005 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2006 E = CUs.end(); I != E; ++I) {
2007 CompileUnit *TheCU = *I;
2008 DIE *Die = TheCU->getCUDie();
2010 // Emit the compile units header.
2012 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2013 TheCU->getUniqueID()));
2015 // Emit size of content not including length itself
2016 unsigned ContentSize = Die->getSize() +
2017 sizeof(int16_t) + // DWARF version number
2018 sizeof(int32_t) + // Offset Into Abbrev. Section
2019 sizeof(int8_t); // Pointer Size (in bytes)
2021 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2022 Asm->EmitInt32(ContentSize);
2023 Asm->OutStreamer.AddComment("DWARF version number");
2024 Asm->EmitInt16(DD->getDwarfVersion());
2025 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2026 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2028 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2029 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2031 DD->emitDIE(Die, Abbreviations);
2032 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2033 TheCU->getUniqueID()));
2037 /// For a given compile unit DIE, returns offset from beginning of debug info.
2038 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2039 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2040 "Input DIE should be compile unit in getCUOffset.");
2041 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2043 CompileUnit *TheCU = *I;
2044 if (TheCU->getCUDie() == Die)
2045 return TheCU->getDebugInfoOffset();
2047 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2050 // Emit the debug info section.
2051 void DwarfDebug::emitDebugInfo() {
2052 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2054 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2055 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2056 DwarfAbbrevSectionSym);
2059 // Emit the abbreviation section.
2060 void DwarfDebug::emitAbbreviations() {
2061 if (!useSplitDwarf())
2062 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2065 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2068 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2069 std::vector<DIEAbbrev *> *Abbrevs) {
2070 // Check to see if it is worth the effort.
2071 if (!Abbrevs->empty()) {
2072 // Start the debug abbrev section.
2073 Asm->OutStreamer.SwitchSection(Section);
2075 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2076 Asm->OutStreamer.EmitLabel(Begin);
2078 // For each abbrevation.
2079 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2080 // Get abbreviation data
2081 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2083 // Emit the abbrevations code (base 1 index.)
2084 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2086 // Emit the abbreviations data.
2090 // Mark end of abbreviations.
2091 Asm->EmitULEB128(0, "EOM(3)");
2093 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2094 Asm->OutStreamer.EmitLabel(End);
2098 // Emit the last address of the section and the end of the line matrix.
2099 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2100 // Define last address of section.
2101 Asm->OutStreamer.AddComment("Extended Op");
2104 Asm->OutStreamer.AddComment("Op size");
2105 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2106 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2107 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2109 Asm->OutStreamer.AddComment("Section end label");
2111 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2112 Asm->getDataLayout().getPointerSize());
2114 // Mark end of matrix.
2115 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2121 // Emit visible names into a hashed accelerator table section.
2122 void DwarfDebug::emitAccelNames() {
2123 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2124 dwarf::DW_FORM_data4));
2125 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2126 E = CUMap.end(); I != E; ++I) {
2127 CompileUnit *TheCU = I->second;
2128 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2129 for (StringMap<std::vector<DIE*> >::const_iterator
2130 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2131 StringRef Name = GI->getKey();
2132 const std::vector<DIE *> &Entities = GI->second;
2133 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2134 DE = Entities.end(); DI != DE; ++DI)
2135 AT.AddName(Name, (*DI));
2139 AT.FinalizeTable(Asm, "Names");
2140 Asm->OutStreamer.SwitchSection(
2141 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2142 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2143 Asm->OutStreamer.EmitLabel(SectionBegin);
2145 // Emit the full data.
2146 AT.Emit(Asm, SectionBegin, &InfoHolder);
2149 // Emit objective C classes and categories into a hashed accelerator table
2151 void DwarfDebug::emitAccelObjC() {
2152 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2153 dwarf::DW_FORM_data4));
2154 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2155 E = CUMap.end(); I != E; ++I) {
2156 CompileUnit *TheCU = I->second;
2157 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2158 for (StringMap<std::vector<DIE*> >::const_iterator
2159 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2160 StringRef Name = GI->getKey();
2161 const std::vector<DIE *> &Entities = GI->second;
2162 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2163 DE = Entities.end(); DI != DE; ++DI)
2164 AT.AddName(Name, (*DI));
2168 AT.FinalizeTable(Asm, "ObjC");
2169 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2170 .getDwarfAccelObjCSection());
2171 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2172 Asm->OutStreamer.EmitLabel(SectionBegin);
2174 // Emit the full data.
2175 AT.Emit(Asm, SectionBegin, &InfoHolder);
2178 // Emit namespace dies into a hashed accelerator table.
2179 void DwarfDebug::emitAccelNamespaces() {
2180 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2181 dwarf::DW_FORM_data4));
2182 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2183 E = CUMap.end(); I != E; ++I) {
2184 CompileUnit *TheCU = I->second;
2185 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2186 for (StringMap<std::vector<DIE*> >::const_iterator
2187 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2188 StringRef Name = GI->getKey();
2189 const std::vector<DIE *> &Entities = GI->second;
2190 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2191 DE = Entities.end(); DI != DE; ++DI)
2192 AT.AddName(Name, (*DI));
2196 AT.FinalizeTable(Asm, "namespac");
2197 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2198 .getDwarfAccelNamespaceSection());
2199 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2200 Asm->OutStreamer.EmitLabel(SectionBegin);
2202 // Emit the full data.
2203 AT.Emit(Asm, SectionBegin, &InfoHolder);
2206 // Emit type dies into a hashed accelerator table.
2207 void DwarfDebug::emitAccelTypes() {
2208 std::vector<DwarfAccelTable::Atom> Atoms;
2209 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2210 dwarf::DW_FORM_data4));
2211 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2212 dwarf::DW_FORM_data2));
2213 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2214 dwarf::DW_FORM_data1));
2215 DwarfAccelTable AT(Atoms);
2216 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2217 E = CUMap.end(); I != E; ++I) {
2218 CompileUnit *TheCU = I->second;
2219 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2220 = TheCU->getAccelTypes();
2221 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2222 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2223 StringRef Name = GI->getKey();
2224 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2225 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2226 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2227 AT.AddName(Name, (*DI).first, (*DI).second);
2231 AT.FinalizeTable(Asm, "types");
2232 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2233 .getDwarfAccelTypesSection());
2234 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2235 Asm->OutStreamer.EmitLabel(SectionBegin);
2237 // Emit the full data.
2238 AT.Emit(Asm, SectionBegin, &InfoHolder);
2241 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2243 void DwarfDebug::emitDebugPubnames() {
2244 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2246 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2247 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2248 CompileUnit *TheCU = I->second;
2249 unsigned ID = TheCU->getUniqueID();
2251 if (TheCU->getGlobalNames().empty())
2254 // Start the dwarf pubnames section.
2256 .SwitchSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
2258 Asm->OutStreamer.AddComment("Length of Public Names Info");
2259 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2260 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2262 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2264 Asm->OutStreamer.AddComment("DWARF Version");
2265 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2267 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2268 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2269 DwarfInfoSectionSym);
2271 Asm->OutStreamer.AddComment("Compilation Unit Length");
2272 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2273 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2276 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2277 for (StringMap<DIE*>::const_iterator
2278 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2279 const char *Name = GI->getKeyData();
2280 const DIE *Entity = GI->second;
2282 Asm->OutStreamer.AddComment("DIE offset");
2283 Asm->EmitInt32(Entity->getOffset());
2285 if (Asm->isVerbose())
2286 Asm->OutStreamer.AddComment("External Name");
2287 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2290 Asm->OutStreamer.AddComment("End Mark");
2292 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2296 void DwarfDebug::emitDebugPubTypes() {
2297 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2298 E = CUMap.end(); I != E; ++I) {
2299 CompileUnit *TheCU = I->second;
2300 // Start the dwarf pubtypes section.
2301 Asm->OutStreamer.SwitchSection(
2302 Asm->getObjFileLowering().getDwarfPubTypesSection());
2303 Asm->OutStreamer.AddComment("Length of Public Types Info");
2304 Asm->EmitLabelDifference(
2305 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2306 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2308 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2309 TheCU->getUniqueID()));
2311 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2312 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2314 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2315 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2316 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2317 TheCU->getUniqueID()),
2318 DwarfInfoSectionSym);
2320 Asm->OutStreamer.AddComment("Compilation Unit Length");
2321 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2322 TheCU->getUniqueID()),
2323 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2324 TheCU->getUniqueID()),
2327 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2328 for (StringMap<DIE*>::const_iterator
2329 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2330 const char *Name = GI->getKeyData();
2331 DIE *Entity = GI->second;
2333 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2334 Asm->EmitInt32(Entity->getOffset());
2336 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2337 // Emit the name with a terminating null byte.
2338 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2341 Asm->OutStreamer.AddComment("End Mark");
2343 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2344 TheCU->getUniqueID()));
2348 // Emit strings into a string section.
2349 void DwarfUnits::emitStrings(const MCSection *StrSection,
2350 const MCSection *OffsetSection = NULL,
2351 const MCSymbol *StrSecSym = NULL) {
2353 if (StringPool.empty()) return;
2355 // Start the dwarf str section.
2356 Asm->OutStreamer.SwitchSection(StrSection);
2358 // Get all of the string pool entries and put them in an array by their ID so
2359 // we can sort them.
2360 SmallVector<std::pair<unsigned,
2361 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2363 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2364 I = StringPool.begin(), E = StringPool.end();
2366 Entries.push_back(std::make_pair(I->second.second, &*I));
2368 array_pod_sort(Entries.begin(), Entries.end());
2370 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2371 // Emit a label for reference from debug information entries.
2372 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2374 // Emit the string itself with a terminating null byte.
2375 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2376 Entries[i].second->getKeyLength()+1));
2379 // If we've got an offset section go ahead and emit that now as well.
2380 if (OffsetSection) {
2381 Asm->OutStreamer.SwitchSection(OffsetSection);
2382 unsigned offset = 0;
2383 unsigned size = 4; // FIXME: DWARF64 is 8.
2384 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2385 Asm->OutStreamer.EmitIntValue(offset, size);
2386 offset += Entries[i].second->getKeyLength() + 1;
2391 // Emit strings into a string section.
2392 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2394 if (AddressPool.empty()) return;
2396 // Start the dwarf addr section.
2397 Asm->OutStreamer.SwitchSection(AddrSection);
2399 // Order the address pool entries by ID
2400 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2402 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2403 E = AddressPool.end();
2405 Entries[I->second] = I->first;
2407 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2408 // Emit an expression for reference from debug information entries.
2409 if (const MCExpr *Expr = Entries[i])
2410 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2412 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2417 // Emit visible names into a debug str section.
2418 void DwarfDebug::emitDebugStr() {
2419 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2420 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2423 // Emit locations into the debug loc section.
2424 void DwarfDebug::emitDebugLoc() {
2425 if (DotDebugLocEntries.empty())
2428 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2429 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2431 DotDebugLocEntry &Entry = *I;
2432 if (I + 1 != DotDebugLocEntries.end())
2436 // Start the dwarf loc section.
2437 Asm->OutStreamer.SwitchSection(
2438 Asm->getObjFileLowering().getDwarfLocSection());
2439 unsigned char Size = Asm->getDataLayout().getPointerSize();
2440 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2442 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2443 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2444 I != E; ++I, ++index) {
2445 DotDebugLocEntry &Entry = *I;
2446 if (Entry.isMerged()) continue;
2447 if (Entry.isEmpty()) {
2448 Asm->OutStreamer.EmitIntValue(0, Size);
2449 Asm->OutStreamer.EmitIntValue(0, Size);
2450 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2452 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2453 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2454 DIVariable DV(Entry.getVariable());
2455 Asm->OutStreamer.AddComment("Loc expr size");
2456 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2457 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2458 Asm->EmitLabelDifference(end, begin, 2);
2459 Asm->OutStreamer.EmitLabel(begin);
2460 if (Entry.isInt()) {
2461 DIBasicType BTy(DV.getType());
2463 (BTy.getEncoding() == dwarf::DW_ATE_signed
2464 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2465 Asm->OutStreamer.AddComment("DW_OP_consts");
2466 Asm->EmitInt8(dwarf::DW_OP_consts);
2467 Asm->EmitSLEB128(Entry.getInt());
2469 Asm->OutStreamer.AddComment("DW_OP_constu");
2470 Asm->EmitInt8(dwarf::DW_OP_constu);
2471 Asm->EmitULEB128(Entry.getInt());
2473 } else if (Entry.isLocation()) {
2474 MachineLocation Loc = Entry.getLoc();
2475 if (!DV.hasComplexAddress())
2477 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2479 // Complex address entry.
2480 unsigned N = DV.getNumAddrElements();
2482 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2483 if (Loc.getOffset()) {
2485 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2486 Asm->OutStreamer.AddComment("DW_OP_deref");
2487 Asm->EmitInt8(dwarf::DW_OP_deref);
2488 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2489 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2490 Asm->EmitSLEB128(DV.getAddrElement(1));
2492 // If first address element is OpPlus then emit
2493 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2494 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2495 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2499 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2502 // Emit remaining complex address elements.
2503 for (; i < N; ++i) {
2504 uint64_t Element = DV.getAddrElement(i);
2505 if (Element == DIBuilder::OpPlus) {
2506 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2507 Asm->EmitULEB128(DV.getAddrElement(++i));
2508 } else if (Element == DIBuilder::OpDeref) {
2510 Asm->EmitInt8(dwarf::DW_OP_deref);
2512 llvm_unreachable("unknown Opcode found in complex address");
2516 // else ... ignore constant fp. There is not any good way to
2517 // to represent them here in dwarf.
2518 Asm->OutStreamer.EmitLabel(end);
2523 // Emit visible names into a debug aranges section.
2524 void DwarfDebug::emitDebugARanges() {
2525 // Start the dwarf aranges section.
2527 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2530 // Emit visible names into a debug ranges section.
2531 void DwarfDebug::emitDebugRanges() {
2532 // Start the dwarf ranges section.
2534 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2535 unsigned char Size = Asm->getDataLayout().getPointerSize();
2536 for (SmallVectorImpl<const MCSymbol *>::iterator
2537 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2540 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2542 Asm->OutStreamer.EmitIntValue(0, Size);
2546 // Emit visible names into a debug macinfo section.
2547 void DwarfDebug::emitDebugMacInfo() {
2548 if (const MCSection *LineInfo =
2549 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2550 // Start the dwarf macinfo section.
2551 Asm->OutStreamer.SwitchSection(LineInfo);
2555 // DWARF5 Experimental Separate Dwarf emitters.
2557 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2558 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2559 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2560 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2561 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2563 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2564 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2565 Asm, this, &SkeletonHolder);
2567 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2568 DICompileUnit(CU->getNode()).getSplitDebugFilename());
2570 // Relocate to the beginning of the addr_base section, else 0 for the
2571 // beginning of the one for this compile unit.
2572 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2573 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2574 DwarfAddrSectionSym);
2576 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2577 dwarf::DW_FORM_sec_offset, 0);
2579 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2580 // into an entity. We're using 0, or a NULL label for this.
2581 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2583 // DW_AT_stmt_list is a offset of line number information for this
2584 // compile unit in debug_line section.
2585 // FIXME: Should handle multiple compile units.
2586 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2587 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2588 DwarfLineSectionSym);
2590 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2592 if (!CompilationDir.empty())
2593 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2595 SkeletonHolder.addUnit(NewCU);
2596 SkeletonCUs.push_back(NewCU);
2601 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2602 assert(useSplitDwarf() && "No split dwarf debug info?");
2603 emitAbbrevs(Section, &SkeletonAbbrevs);
2606 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2607 // compile units that would normally be in debug_info.
2608 void DwarfDebug::emitDebugInfoDWO() {
2609 assert(useSplitDwarf() && "No split dwarf debug info?");
2610 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2611 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2612 DwarfAbbrevDWOSectionSym);
2615 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2616 // abbreviations for the .debug_info.dwo section.
2617 void DwarfDebug::emitDebugAbbrevDWO() {
2618 assert(useSplitDwarf() && "No split dwarf?");
2619 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2623 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2624 // string section and is identical in format to traditional .debug_str
2626 void DwarfDebug::emitDebugStrDWO() {
2627 assert(useSplitDwarf() && "No split dwarf?");
2628 const MCSection *OffSec = Asm->getObjFileLowering()
2629 .getDwarfStrOffDWOSection();
2630 const MCSymbol *StrSym = DwarfStrSectionSym;
2631 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),