1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DebugInfo.h"
21 #include "llvm/DIBuilder.h"
22 #include "llvm/Module.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/Path.h"
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
51 cl::desc("Disable debug info printing"));
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54 cl::desc("Make an absence of debug location information explicit."),
57 static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
58 cl::desc("Output prototype dwarf accelerator tables."),
61 static cl::opt<bool> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
62 cl::desc("Compatibility with Darwin gdb."),
66 const char *DWARFGroupName = "DWARF Emission";
67 const char *DbgTimerName = "DWARF Debug Writer";
68 } // end anonymous namespace
70 //===----------------------------------------------------------------------===//
72 /// Configuration values for initial hash set sizes (log2).
74 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
78 DIType DbgVariable::getType() const {
79 DIType Ty = Var.getType();
80 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
82 if (Var.isBlockByrefVariable()) {
83 /* Byref variables, in Blocks, are declared by the programmer as
84 "SomeType VarName;", but the compiler creates a
85 __Block_byref_x_VarName struct, and gives the variable VarName
86 either the struct, or a pointer to the struct, as its type. This
87 is necessary for various behind-the-scenes things the compiler
88 needs to do with by-reference variables in blocks.
90 However, as far as the original *programmer* is concerned, the
91 variable should still have type 'SomeType', as originally declared.
93 The following function dives into the __Block_byref_x_VarName
94 struct to find the original type of the variable. This will be
95 passed back to the code generating the type for the Debug
96 Information Entry for the variable 'VarName'. 'VarName' will then
97 have the original type 'SomeType' in its debug information.
99 The original type 'SomeType' will be the type of the field named
100 'VarName' inside the __Block_byref_x_VarName struct.
102 NOTE: In order for this to not completely fail on the debugger
103 side, the Debug Information Entry for the variable VarName needs to
104 have a DW_AT_location that tells the debugger how to unwind through
105 the pointers and __Block_byref_x_VarName struct to find the actual
106 value of the variable. The function addBlockByrefType does this. */
108 unsigned tag = Ty.getTag();
110 if (tag == dwarf::DW_TAG_pointer_type) {
111 DIDerivedType DTy = DIDerivedType(Ty);
112 subType = DTy.getTypeDerivedFrom();
115 DICompositeType blockStruct = DICompositeType(subType);
116 DIArray Elements = blockStruct.getTypeArray();
118 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
119 DIDescriptor Element = Elements.getElement(i);
120 DIDerivedType DT = DIDerivedType(Element);
121 if (getName() == DT.getName())
122 return (DT.getTypeDerivedFrom());
128 } // end llvm namespace
130 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
131 : Asm(A), MMI(Asm->MMI), FirstCU(0),
132 AbbreviationsSet(InitAbbreviationsSetSize),
133 SourceIdMap(DIEValueAllocator), StringPool(DIEValueAllocator),
135 NextStringPoolNumber = 0;
137 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
138 DwarfStrSectionSym = TextSectionSym = 0;
139 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
140 FunctionBeginSym = FunctionEndSym = 0;
142 // Turn on accelerator tables and older gdb compatibility
144 if (Triple(M->getTargetTriple()).isOSDarwin()) {
145 DwarfAccelTables = true;
146 DarwinGDBCompat = true;
149 isDarwinGDBCompat = DarwinGDBCompat;
152 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
156 DwarfDebug::~DwarfDebug() {
159 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
160 /// temporary label to it if SymbolStem is specified.
161 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
162 const char *SymbolStem = 0) {
163 Asm->OutStreamer.SwitchSection(Section);
164 if (!SymbolStem) return 0;
166 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
167 Asm->OutStreamer.EmitLabel(TmpSym);
171 MCSymbol *DwarfDebug::getStringPool() {
172 return Asm->GetTempSymbol("section_str");
175 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
176 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
177 if (Entry.first) return Entry.first;
179 Entry.second = NextStringPoolNumber++;
180 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
183 /// assignAbbrevNumber - Define a unique number for the abbreviation.
185 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
186 // Profile the node so that we can make it unique.
190 // Check the set for priors.
191 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
193 // If it's newly added.
194 if (InSet == &Abbrev) {
195 // Add to abbreviation list.
196 Abbreviations.push_back(&Abbrev);
198 // Assign the vector position + 1 as its number.
199 Abbrev.setNumber(Abbreviations.size());
201 // Assign existing abbreviation number.
202 Abbrev.setNumber(InSet->getNumber());
206 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
207 /// printer to not emit usual symbol prefix before the symbol name is used then
208 /// return linkage name after skipping this special LLVM prefix.
209 static StringRef getRealLinkageName(StringRef LinkageName) {
211 if (LinkageName.startswith(StringRef(&One, 1)))
212 return LinkageName.substr(1);
216 static bool isObjCClass(StringRef Name) {
217 return Name.startswith("+") || Name.startswith("-");
220 static bool hasObjCCategory(StringRef Name) {
221 if (!isObjCClass(Name)) return false;
223 size_t pos = Name.find(')');
224 if (pos != std::string::npos) {
225 if (Name[pos+1] != ' ') return false;
231 static void getObjCClassCategory(StringRef In, StringRef &Class,
232 StringRef &Category) {
233 if (!hasObjCCategory(In)) {
234 Class = In.slice(In.find('[') + 1, In.find(' '));
239 Class = In.slice(In.find('[') + 1, In.find('('));
240 Category = In.slice(In.find('[') + 1, In.find(' '));
244 static StringRef getObjCMethodName(StringRef In) {
245 return In.slice(In.find(' ') + 1, In.find(']'));
248 // Add the various names to the Dwarf accelerator table names.
249 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
251 if (!SP.isDefinition()) return;
253 TheCU->addAccelName(SP.getName(), Die);
255 // If the linkage name is different than the name, go ahead and output
256 // that as well into the name table.
257 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
258 TheCU->addAccelName(SP.getLinkageName(), Die);
260 // If this is an Objective-C selector name add it to the ObjC accelerator
262 if (isObjCClass(SP.getName())) {
263 StringRef Class, Category;
264 getObjCClassCategory(SP.getName(), Class, Category);
265 TheCU->addAccelObjC(Class, Die);
267 TheCU->addAccelObjC(Category, Die);
268 // Also add the base method name to the name table.
269 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
273 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
274 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
275 /// If there are global variables in this scope then create and insert
276 /// DIEs for these variables.
277 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
278 const MDNode *SPNode) {
279 DIE *SPDie = SPCU->getDIE(SPNode);
281 assert(SPDie && "Unable to find subprogram DIE!");
282 DISubprogram SP(SPNode);
284 DISubprogram SPDecl = SP.getFunctionDeclaration();
285 if (!SPDecl.isSubprogram()) {
286 // There is not any need to generate specification DIE for a function
287 // defined at compile unit level. If a function is defined inside another
288 // function then gdb prefers the definition at top level and but does not
289 // expect specification DIE in parent function. So avoid creating
290 // specification DIE for a function defined inside a function.
291 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
292 !SP.getContext().isFile() &&
293 !isSubprogramContext(SP.getContext())) {
294 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
297 DICompositeType SPTy = SP.getType();
298 DIArray Args = SPTy.getTypeArray();
299 unsigned SPTag = SPTy.getTag();
300 if (SPTag == dwarf::DW_TAG_subroutine_type)
301 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
302 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
303 DIType ATy = DIType(DIType(Args.getElement(i)));
304 SPCU->addType(Arg, ATy);
305 if (ATy.isArtificial())
306 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
307 SPDie->addChild(Arg);
309 DIE *SPDeclDie = SPDie;
310 SPDie = new DIE(dwarf::DW_TAG_subprogram);
311 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
316 // Pick up abstract subprogram DIE.
317 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
318 SPDie = new DIE(dwarf::DW_TAG_subprogram);
319 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
320 dwarf::DW_FORM_ref4, AbsSPDIE);
324 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
325 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
326 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
327 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
328 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
329 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
330 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
332 // Add name to the name table, we do this here because we're guaranteed
333 // to have concrete versions of our DW_TAG_subprogram nodes.
334 addSubprogramNames(SPCU, SP, SPDie);
339 /// constructLexicalScope - Construct new DW_TAG_lexical_block
340 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
341 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
342 LexicalScope *Scope) {
343 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
344 if (Scope->isAbstractScope())
347 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
351 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
352 if (Ranges.size() > 1) {
353 // .debug_range section has not been laid out yet. Emit offset in
354 // .debug_range as a uint, size 4, for now. emitDIE will handle
355 // DW_AT_ranges appropriately.
356 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
357 DebugRangeSymbols.size()
358 * Asm->getTargetData().getPointerSize());
359 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
360 RE = Ranges.end(); RI != RE; ++RI) {
361 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
362 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
364 DebugRangeSymbols.push_back(NULL);
365 DebugRangeSymbols.push_back(NULL);
369 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
370 const MCSymbol *End = getLabelAfterInsn(RI->second);
372 if (End == 0) return 0;
374 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
375 assert(End->isDefined() && "Invalid end label for an inlined scope!");
377 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
378 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
383 /// constructInlinedScopeDIE - This scope represents inlined body of
384 /// a function. Construct DIE to represent this concrete inlined copy
386 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
387 LexicalScope *Scope) {
388 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
389 assert(Ranges.empty() == false &&
390 "LexicalScope does not have instruction markers!");
392 if (!Scope->getScopeNode())
394 DIScope DS(Scope->getScopeNode());
395 DISubprogram InlinedSP = getDISubprogram(DS);
396 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
398 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
402 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
403 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
404 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
406 if (StartLabel == 0 || EndLabel == 0) {
407 llvm_unreachable("Unexpected Start and End labels for a inlined scope!");
409 assert(StartLabel->isDefined() &&
410 "Invalid starting label for an inlined scope!");
411 assert(EndLabel->isDefined() &&
412 "Invalid end label for an inlined scope!");
414 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
415 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
416 dwarf::DW_FORM_ref4, OriginDIE);
418 if (Ranges.size() > 1) {
419 // .debug_range section has not been laid out yet. Emit offset in
420 // .debug_range as a uint, size 4, for now. emitDIE will handle
421 // DW_AT_ranges appropriately.
422 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
423 DebugRangeSymbols.size()
424 * Asm->getTargetData().getPointerSize());
425 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
426 RE = Ranges.end(); RI != RE; ++RI) {
427 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
428 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
430 DebugRangeSymbols.push_back(NULL);
431 DebugRangeSymbols.push_back(NULL);
433 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
435 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
439 InlinedSubprogramDIEs.insert(OriginDIE);
441 // Track the start label for this inlined function.
442 //.debug_inlined section specification does not clearly state how
443 // to emit inlined scope that is split into multiple instruction ranges.
444 // For now, use first instruction range and emit low_pc/high_pc pair and
445 // corresponding .debug_inlined section entry for this pair.
446 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
447 I = InlineInfo.find(InlinedSP);
449 if (I == InlineInfo.end()) {
450 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
451 InlinedSPNodes.push_back(InlinedSP);
453 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
455 DILocation DL(Scope->getInlinedAt());
456 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
457 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
458 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
460 // Add name to the name table, we do this here because we're guaranteed
461 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
462 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
467 /// constructScopeDIE - Construct a DIE for this scope.
468 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
469 if (!Scope || !Scope->getScopeNode())
472 SmallVector<DIE *, 8> Children;
474 // Collect arguments for current function.
475 if (LScopes.isCurrentFunctionScope(Scope))
476 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
477 if (DbgVariable *ArgDV = CurrentFnArguments[i])
479 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
480 Children.push_back(Arg);
482 // Collect lexical scope children first.
483 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
484 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
486 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
487 Children.push_back(Variable);
488 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
489 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
490 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
491 Children.push_back(Nested);
492 DIScope DS(Scope->getScopeNode());
493 DIE *ScopeDIE = NULL;
494 if (Scope->getInlinedAt())
495 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
496 else if (DS.isSubprogram()) {
497 ProcessedSPNodes.insert(DS);
498 if (Scope->isAbstractScope()) {
499 ScopeDIE = TheCU->getDIE(DS);
500 // Note down abstract DIE.
502 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
505 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
508 // There is no need to emit empty lexical block DIE.
509 if (Children.empty())
511 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
514 if (!ScopeDIE) return NULL;
517 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
518 E = Children.end(); I != E; ++I)
519 ScopeDIE->addChild(*I);
521 if (DS.isSubprogram())
522 TheCU->addPubTypes(DISubprogram(DS));
527 /// GetOrCreateSourceID - Look up the source id with the given directory and
528 /// source file names. If none currently exists, create a new id and insert it
529 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
531 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
533 // If FE did not provide a file name, then assume stdin.
534 if (FileName.empty())
535 return GetOrCreateSourceID("<stdin>", StringRef());
537 // TODO: this might not belong here. See if we can factor this better.
538 if (DirName == CompilationDir)
541 unsigned SrcId = SourceIdMap.size()+1;
543 // We look up the file/dir pair by concatenating them with a zero byte.
544 SmallString<128> NamePair;
546 NamePair += '\0'; // Zero bytes are not allowed in paths.
547 NamePair += FileName;
549 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
550 if (Ent.getValue() != SrcId)
551 return Ent.getValue();
553 // Print out a .file directive to specify files for .loc directives.
554 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
559 /// constructCompileUnit - Create new CompileUnit for the given
560 /// metadata node with tag DW_TAG_compile_unit.
561 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
562 DICompileUnit DIUnit(N);
563 StringRef FN = DIUnit.getFilename();
564 CompilationDir = DIUnit.getDirectory();
565 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
567 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
568 CompileUnit *NewCU = new CompileUnit(ID, DIUnit.getLanguage(), Die, Asm, this);
569 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
570 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
571 DIUnit.getLanguage());
572 NewCU->addString(Die, dwarf::DW_AT_name, FN);
573 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
575 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
576 // DW_AT_stmt_list is a offset of line number information for this
577 // compile unit in debug_line section.
578 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
579 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
580 Asm->GetTempSymbol("section_line"));
582 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
584 if (!CompilationDir.empty())
585 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
586 if (DIUnit.isOptimized())
587 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
589 StringRef Flags = DIUnit.getFlags();
591 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
593 if (unsigned RVer = DIUnit.getRunTimeVersion())
594 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
595 dwarf::DW_FORM_data1, RVer);
599 CUMap.insert(std::make_pair(N, NewCU));
603 /// construct SubprogramDIE - Construct subprogram DIE.
604 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
606 CompileUnit *&CURef = SPMap[N];
612 if (!SP.isDefinition())
613 // This is a method declaration which will be handled while constructing
617 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
620 TheCU->insertDIE(N, SubprogramDie);
622 // Add to context owner.
623 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
628 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
629 /// as llvm.dbg.enum and llvm.dbg.ty
630 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
631 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
632 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
633 const MDNode *N = NMD->getOperand(i);
634 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
635 constructSubprogramDIE(CU, N);
638 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
639 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
640 const MDNode *N = NMD->getOperand(i);
641 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
642 CU->createGlobalVariableDIE(N);
645 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
646 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
647 DIType Ty(NMD->getOperand(i));
648 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
649 CU->getOrCreateTypeDIE(Ty);
652 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
653 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
654 DIType Ty(NMD->getOperand(i));
655 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
656 CU->getOrCreateTypeDIE(Ty);
660 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
661 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
662 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
663 DebugInfoFinder DbgFinder;
664 DbgFinder.processModule(*M);
666 bool HasDebugInfo = false;
667 // Scan all the compile-units to see if there are any marked as the main
668 // unit. If not, we do not generate debug info.
669 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
670 E = DbgFinder.compile_unit_end(); I != E; ++I) {
671 if (DICompileUnit(*I).isMain()) {
676 if (!HasDebugInfo) return false;
678 // Create all the compile unit DIEs.
679 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
680 E = DbgFinder.compile_unit_end(); I != E; ++I)
681 constructCompileUnit(*I);
683 // Create DIEs for each global variable.
684 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
685 E = DbgFinder.global_variable_end(); I != E; ++I) {
686 const MDNode *N = *I;
687 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
688 CU->createGlobalVariableDIE(N);
691 // Create DIEs for each subprogram.
692 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
693 E = DbgFinder.subprogram_end(); I != E; ++I) {
694 const MDNode *N = *I;
695 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
696 constructSubprogramDIE(CU, N);
702 /// beginModule - Emit all Dwarf sections that should come prior to the
703 /// content. Create global DIEs and emit initial debug info sections.
704 /// This is invoked by the target AsmPrinter.
705 void DwarfDebug::beginModule(Module *M) {
706 if (DisableDebugInfoPrinting)
709 // If module has named metadata anchors then use them, otherwise scan the
710 // module using debug info finder to collect debug info.
711 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
713 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
714 DICompileUnit CUNode(CU_Nodes->getOperand(i));
715 CompileUnit *CU = constructCompileUnit(CUNode);
716 DIArray GVs = CUNode.getGlobalVariables();
717 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
718 CU->createGlobalVariableDIE(GVs.getElement(i));
719 DIArray SPs = CUNode.getSubprograms();
720 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
721 constructSubprogramDIE(CU, SPs.getElement(i));
722 DIArray EnumTypes = CUNode.getEnumTypes();
723 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
724 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
725 DIArray RetainedTypes = CUNode.getRetainedTypes();
726 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
727 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
729 } else if (!collectLegacyDebugInfo(M))
732 collectInfoFromNamedMDNodes(M);
734 // Tell MMI that we have debug info.
735 MMI->setDebugInfoAvailability(true);
737 // Emit initial sections.
740 // Prime section data.
741 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
744 /// endModule - Emit all Dwarf sections that should come after the content.
746 void DwarfDebug::endModule() {
747 if (!FirstCU) return;
748 const Module *M = MMI->getModule();
749 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
751 // Collect info for variables that were optimized out.
752 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
753 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
754 DICompileUnit TheCU(CU_Nodes->getOperand(i));
755 DIArray Subprograms = TheCU.getSubprograms();
756 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
757 DISubprogram SP(Subprograms.getElement(i));
758 if (ProcessedSPNodes.count(SP) != 0) continue;
759 if (!SP.Verify()) continue;
760 if (!SP.isDefinition()) continue;
761 DIArray Variables = SP.getVariables();
762 if (Variables.getNumElements() == 0) continue;
764 LexicalScope *Scope =
765 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
766 DeadFnScopeMap[SP] = Scope;
768 // Construct subprogram DIE and add variables DIEs.
769 CompileUnit *SPCU = CUMap.lookup(TheCU);
770 assert(SPCU && "Unable to find Compile Unit!");
771 constructSubprogramDIE(SPCU, SP);
772 DIE *ScopeDIE = SPCU->getDIE(SP);
773 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
774 DIVariable DV(Variables.getElement(vi));
775 if (!DV.Verify()) continue;
776 DbgVariable *NewVar = new DbgVariable(DV, NULL);
777 if (DIE *VariableDIE =
778 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
779 ScopeDIE->addChild(VariableDIE);
785 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
786 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
787 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
789 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
791 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
792 AE = AbstractSPDies.end(); AI != AE; ++AI) {
793 DIE *ISP = AI->second;
794 if (InlinedSubprogramDIEs.count(ISP))
796 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
799 // Emit DW_AT_containing_type attribute to connect types with their
800 // vtable holding type.
801 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
802 CUE = CUMap.end(); CUI != CUE; ++CUI) {
803 CompileUnit *TheCU = CUI->second;
804 TheCU->constructContainingTypeDIEs();
807 // Standard sections final addresses.
808 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
809 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
810 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
811 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
813 // End text sections.
814 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
815 Asm->OutStreamer.SwitchSection(SectionMap[i]);
816 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
819 // Compute DIE offsets and sizes.
820 computeSizeAndOffsets();
822 // Emit all the DIEs into a debug info section
825 // Corresponding abbreviations into a abbrev section.
828 // Emit info into the dwarf accelerator table sections.
829 if (DwarfAccelTables) {
832 emitAccelNamespaces();
836 // Emit info into a debug pubtypes section.
837 // TODO: When we don't need the option anymore we can
838 // remove all of the code that adds to the table.
842 // Emit info into a debug loc section.
845 // Emit info into a debug aranges section.
848 // Emit info into a debug ranges section.
851 // Emit info into a debug macinfo section.
855 // TODO: When we don't need the option anymore we
856 // can remove all of the code that this section
859 emitDebugInlineInfo();
861 // Emit info into a debug str section.
865 DeleteContainerSeconds(DeadFnScopeMap);
867 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
868 E = CUMap.end(); I != E; ++I)
870 FirstCU = NULL; // Reset for the next Module, if any.
873 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
874 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
876 LLVMContext &Ctx = DV->getContext();
877 // More then one inlined variable corresponds to one abstract variable.
878 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
879 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
881 return AbsDbgVariable;
883 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
887 AbsDbgVariable = new DbgVariable(Var, NULL);
888 addScopeVariable(Scope, AbsDbgVariable);
889 AbstractVariables[Var] = AbsDbgVariable;
890 return AbsDbgVariable;
893 /// addCurrentFnArgument - If Var is a current function argument then add
894 /// it to CurrentFnArguments list.
895 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
896 DbgVariable *Var, LexicalScope *Scope) {
897 if (!LScopes.isCurrentFunctionScope(Scope))
899 DIVariable DV = Var->getVariable();
900 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
902 unsigned ArgNo = DV.getArgNumber();
906 size_t Size = CurrentFnArguments.size();
908 CurrentFnArguments.resize(MF->getFunction()->arg_size());
909 // llvm::Function argument size is not good indicator of how many
910 // arguments does the function have at source level.
912 CurrentFnArguments.resize(ArgNo * 2);
913 CurrentFnArguments[ArgNo - 1] = Var;
917 /// collectVariableInfoFromMMITable - Collect variable information from
918 /// side table maintained by MMI.
920 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
921 SmallPtrSet<const MDNode *, 16> &Processed) {
922 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
923 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
924 VE = VMap.end(); VI != VE; ++VI) {
925 const MDNode *Var = VI->first;
927 Processed.insert(Var);
929 const std::pair<unsigned, DebugLoc> &VP = VI->second;
931 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
933 // If variable scope is not found then skip this variable.
937 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
938 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
939 RegVar->setFrameIndex(VP.first);
940 if (!addCurrentFnArgument(MF, RegVar, Scope))
941 addScopeVariable(Scope, RegVar);
943 AbsDbgVariable->setFrameIndex(VP.first);
947 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
948 /// DBG_VALUE instruction, is in a defined reg.
949 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
950 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
951 return MI->getNumOperands() == 3 &&
952 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
953 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
956 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
958 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
959 const MCSymbol *FLabel,
960 const MCSymbol *SLabel,
961 const MachineInstr *MI) {
962 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
964 if (MI->getNumOperands() != 3) {
965 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
966 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
968 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
969 MachineLocation MLoc;
970 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
971 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
973 if (MI->getOperand(0).isImm())
974 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
975 if (MI->getOperand(0).isFPImm())
976 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
977 if (MI->getOperand(0).isCImm())
978 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
980 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
983 /// collectVariableInfo - Find variables for each lexical scope.
985 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
986 SmallPtrSet<const MDNode *, 16> &Processed) {
988 /// collection info from MMI table.
989 collectVariableInfoFromMMITable(MF, Processed);
991 for (SmallVectorImpl<const MDNode*>::const_iterator
992 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
994 const MDNode *Var = *UVI;
995 if (Processed.count(Var))
998 // History contains relevant DBG_VALUE instructions for Var and instructions
1000 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1001 if (History.empty())
1003 const MachineInstr *MInsn = History.front();
1006 LexicalScope *Scope = NULL;
1007 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1008 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1009 Scope = LScopes.getCurrentFunctionScope();
1011 if (DV.getVersion() <= LLVMDebugVersion9)
1012 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1014 if (MDNode *IA = DV.getInlinedAt())
1015 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1017 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1020 // If variable scope is not found then skip this variable.
1024 Processed.insert(DV);
1025 assert(MInsn->isDebugValue() && "History must begin with debug value");
1026 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1027 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1028 if (!addCurrentFnArgument(MF, RegVar, Scope))
1029 addScopeVariable(Scope, RegVar);
1031 AbsVar->setMInsn(MInsn);
1033 // Simple ranges that are fully coalesced.
1034 if (History.size() <= 1 || (History.size() == 2 &&
1035 MInsn->isIdenticalTo(History.back()))) {
1036 RegVar->setMInsn(MInsn);
1040 // handle multiple DBG_VALUE instructions describing one variable.
1041 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1043 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1044 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1045 const MachineInstr *Begin = *HI;
1046 assert(Begin->isDebugValue() && "Invalid History entry");
1048 // Check if DBG_VALUE is truncating a range.
1049 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1050 && !Begin->getOperand(0).getReg())
1053 // Compute the range for a register location.
1054 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1055 const MCSymbol *SLabel = 0;
1058 // If Begin is the last instruction in History then its value is valid
1059 // until the end of the function.
1060 SLabel = FunctionEndSym;
1062 const MachineInstr *End = HI[1];
1063 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1064 << "\t" << *Begin << "\t" << *End << "\n");
1065 if (End->isDebugValue())
1066 SLabel = getLabelBeforeInsn(End);
1068 // End is a normal instruction clobbering the range.
1069 SLabel = getLabelAfterInsn(End);
1070 assert(SLabel && "Forgot label after clobber instruction");
1075 // The value is valid until the next DBG_VALUE or clobber.
1076 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1079 DotDebugLocEntries.push_back(DotDebugLocEntry());
1082 // Collect info for variables that were optimized out.
1083 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1084 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1085 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1086 DIVariable DV(Variables.getElement(i));
1087 if (!DV || !DV.Verify() || !Processed.insert(DV))
1089 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1090 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1094 /// getLabelBeforeInsn - Return Label preceding the instruction.
1095 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1096 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1097 assert(Label && "Didn't insert label before instruction");
1101 /// getLabelAfterInsn - Return Label immediately following the instruction.
1102 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1103 return LabelsAfterInsn.lookup(MI);
1106 /// beginInstruction - Process beginning of an instruction.
1107 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1108 // Check if source location changes, but ignore DBG_VALUE locations.
1109 if (!MI->isDebugValue()) {
1110 DebugLoc DL = MI->getDebugLoc();
1111 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1114 if (DL == PrologEndLoc) {
1115 Flags |= DWARF2_FLAG_PROLOGUE_END;
1116 PrologEndLoc = DebugLoc();
1118 if (PrologEndLoc.isUnknown())
1119 Flags |= DWARF2_FLAG_IS_STMT;
1121 if (!DL.isUnknown()) {
1122 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1123 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1125 recordSourceLine(0, 0, 0, 0);
1129 // Insert labels where requested.
1130 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1131 LabelsBeforeInsn.find(MI);
1134 if (I == LabelsBeforeInsn.end())
1137 // Label already assigned.
1142 PrevLabel = MMI->getContext().CreateTempSymbol();
1143 Asm->OutStreamer.EmitLabel(PrevLabel);
1145 I->second = PrevLabel;
1148 /// endInstruction - Process end of an instruction.
1149 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1150 // Don't create a new label after DBG_VALUE instructions.
1151 // They don't generate code.
1152 if (!MI->isDebugValue())
1155 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1156 LabelsAfterInsn.find(MI);
1159 if (I == LabelsAfterInsn.end())
1162 // Label already assigned.
1166 // We need a label after this instruction.
1168 PrevLabel = MMI->getContext().CreateTempSymbol();
1169 Asm->OutStreamer.EmitLabel(PrevLabel);
1171 I->second = PrevLabel;
1174 /// identifyScopeMarkers() -
1175 /// Each LexicalScope has first instruction and last instruction to mark
1176 /// beginning and end of a scope respectively. Create an inverse map that list
1177 /// scopes starts (and ends) with an instruction. One instruction may start (or
1178 /// end) multiple scopes. Ignore scopes that are not reachable.
1179 void DwarfDebug::identifyScopeMarkers() {
1180 SmallVector<LexicalScope *, 4> WorkList;
1181 WorkList.push_back(LScopes.getCurrentFunctionScope());
1182 while (!WorkList.empty()) {
1183 LexicalScope *S = WorkList.pop_back_val();
1185 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1186 if (!Children.empty())
1187 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1188 SE = Children.end(); SI != SE; ++SI)
1189 WorkList.push_back(*SI);
1191 if (S->isAbstractScope())
1194 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1197 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1198 RE = Ranges.end(); RI != RE; ++RI) {
1199 assert(RI->first && "InsnRange does not have first instruction!");
1200 assert(RI->second && "InsnRange does not have second instruction!");
1201 requestLabelBeforeInsn(RI->first);
1202 requestLabelAfterInsn(RI->second);
1207 /// getScopeNode - Get MDNode for DebugLoc's scope.
1208 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1209 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1210 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1211 return DL.getScope(Ctx);
1214 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1215 /// line number info for the function.
1216 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1217 const MDNode *Scope = getScopeNode(DL, Ctx);
1218 DISubprogram SP = getDISubprogram(Scope);
1220 // Check for number of operands since the compatibility is
1222 if (SP->getNumOperands() > 19)
1223 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1225 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1231 /// beginFunction - Gather pre-function debug information. Assumes being
1232 /// emitted immediately after the function entry point.
1233 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1234 if (!MMI->hasDebugInfo()) return;
1235 LScopes.initialize(*MF);
1236 if (LScopes.empty()) return;
1237 identifyScopeMarkers();
1239 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1240 Asm->getFunctionNumber());
1241 // Assumes in correct section after the entry point.
1242 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1244 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1246 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1247 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1248 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1250 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1252 bool AtBlockEntry = true;
1253 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1255 const MachineInstr *MI = II;
1257 if (MI->isDebugValue()) {
1258 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1260 // Keep track of user variables.
1262 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1264 // Variable is in a register, we need to check for clobbers.
1265 if (isDbgValueInDefinedReg(MI))
1266 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1268 // Check the history of this variable.
1269 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1270 if (History.empty()) {
1271 UserVariables.push_back(Var);
1272 // The first mention of a function argument gets the FunctionBeginSym
1273 // label, so arguments are visible when breaking at function entry.
1275 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1276 DISubprogram(getDISubprogram(DV.getContext()))
1277 .describes(MF->getFunction()))
1278 LabelsBeforeInsn[MI] = FunctionBeginSym;
1280 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1281 const MachineInstr *Prev = History.back();
1282 if (Prev->isDebugValue()) {
1283 // Coalesce identical entries at the end of History.
1284 if (History.size() >= 2 &&
1285 Prev->isIdenticalTo(History[History.size() - 2])) {
1286 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1288 << "\t" << *History[History.size() - 2] << "\n");
1292 // Terminate old register assignments that don't reach MI;
1293 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1294 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1295 isDbgValueInDefinedReg(Prev)) {
1296 // Previous register assignment needs to terminate at the end of
1298 MachineBasicBlock::const_iterator LastMI =
1299 PrevMBB->getLastNonDebugInstr();
1300 if (LastMI == PrevMBB->end()) {
1301 // Drop DBG_VALUE for empty range.
1302 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1303 << "\t" << *Prev << "\n");
1307 // Terminate after LastMI.
1308 History.push_back(LastMI);
1313 History.push_back(MI);
1315 // Not a DBG_VALUE instruction.
1317 AtBlockEntry = false;
1319 // First known non DBG_VALUE location marks beginning of function
1321 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1322 PrologEndLoc = MI->getDebugLoc();
1324 // Check if the instruction clobbers any registers with debug vars.
1325 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1326 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1327 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1329 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1330 AI.isValid(); ++AI) {
1332 const MDNode *Var = LiveUserVar[Reg];
1335 // Reg is now clobbered.
1336 LiveUserVar[Reg] = 0;
1338 // Was MD last defined by a DBG_VALUE referring to Reg?
1339 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1340 if (HistI == DbgValues.end())
1342 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1343 if (History.empty())
1345 const MachineInstr *Prev = History.back();
1346 // Sanity-check: Register assignments are terminated at the end of
1348 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1350 // Is the variable still in Reg?
1351 if (!isDbgValueInDefinedReg(Prev) ||
1352 Prev->getOperand(0).getReg() != Reg)
1354 // Var is clobbered. Make sure the next instruction gets a label.
1355 History.push_back(MI);
1362 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1364 SmallVectorImpl<const MachineInstr*> &History = I->second;
1365 if (History.empty())
1368 // Make sure the final register assignments are terminated.
1369 const MachineInstr *Prev = History.back();
1370 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1371 const MachineBasicBlock *PrevMBB = Prev->getParent();
1372 MachineBasicBlock::const_iterator LastMI =
1373 PrevMBB->getLastNonDebugInstr();
1374 if (LastMI == PrevMBB->end())
1375 // Drop DBG_VALUE for empty range.
1378 // Terminate after LastMI.
1379 History.push_back(LastMI);
1382 // Request labels for the full history.
1383 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1384 const MachineInstr *MI = History[i];
1385 if (MI->isDebugValue())
1386 requestLabelBeforeInsn(MI);
1388 requestLabelAfterInsn(MI);
1392 PrevInstLoc = DebugLoc();
1393 PrevLabel = FunctionBeginSym;
1395 // Record beginning of function.
1396 if (!PrologEndLoc.isUnknown()) {
1397 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1398 MF->getFunction()->getContext());
1399 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1400 FnStartDL.getScope(MF->getFunction()->getContext()),
1401 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0);
1405 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1406 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1407 ScopeVariables[LS].push_back(Var);
1408 // Vars.push_back(Var);
1411 /// endFunction - Gather and emit post-function debug information.
1413 void DwarfDebug::endFunction(const MachineFunction *MF) {
1414 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1416 // Define end label for subprogram.
1417 FunctionEndSym = Asm->GetTempSymbol("func_end",
1418 Asm->getFunctionNumber());
1419 // Assumes in correct section after the entry point.
1420 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1422 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1423 collectVariableInfo(MF, ProcessedVars);
1425 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1426 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1427 assert(TheCU && "Unable to find compile unit!");
1429 // Construct abstract scopes.
1430 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1431 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1432 LexicalScope *AScope = AList[i];
1433 DISubprogram SP(AScope->getScopeNode());
1435 // Collect info for variables that were optimized out.
1436 DIArray Variables = SP.getVariables();
1437 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1438 DIVariable DV(Variables.getElement(i));
1439 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1441 // Check that DbgVariable for DV wasn't created earlier, when
1442 // findAbstractVariable() was called for inlined instance of DV.
1443 LLVMContext &Ctx = DV->getContext();
1444 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1445 if (AbstractVariables.lookup(CleanDV))
1447 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1448 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1451 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1452 constructScopeDIE(TheCU, AScope);
1455 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1457 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1458 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1459 dwarf::DW_FORM_flag, 1);
1461 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1462 MMI->getFrameMoves()));
1465 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1466 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1467 DeleteContainerPointers(I->second);
1468 ScopeVariables.clear();
1469 DeleteContainerPointers(CurrentFnArguments);
1470 UserVariables.clear();
1472 AbstractVariables.clear();
1473 LabelsBeforeInsn.clear();
1474 LabelsAfterInsn.clear();
1478 /// recordSourceLine - Register a source line with debug info. Returns the
1479 /// unique label that was emitted and which provides correspondence to
1480 /// the source line list.
1481 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1487 DIDescriptor Scope(S);
1489 if (Scope.isCompileUnit()) {
1490 DICompileUnit CU(S);
1491 Fn = CU.getFilename();
1492 Dir = CU.getDirectory();
1493 } else if (Scope.isFile()) {
1495 Fn = F.getFilename();
1496 Dir = F.getDirectory();
1497 } else if (Scope.isSubprogram()) {
1499 Fn = SP.getFilename();
1500 Dir = SP.getDirectory();
1501 } else if (Scope.isLexicalBlockFile()) {
1502 DILexicalBlockFile DBF(S);
1503 Fn = DBF.getFilename();
1504 Dir = DBF.getDirectory();
1505 } else if (Scope.isLexicalBlock()) {
1506 DILexicalBlock DB(S);
1507 Fn = DB.getFilename();
1508 Dir = DB.getDirectory();
1510 llvm_unreachable("Unexpected scope info");
1512 Src = GetOrCreateSourceID(Fn, Dir);
1514 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1517 //===----------------------------------------------------------------------===//
1519 //===----------------------------------------------------------------------===//
1521 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1524 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1525 // Get the children.
1526 const std::vector<DIE *> &Children = Die->getChildren();
1528 // Record the abbreviation.
1529 assignAbbrevNumber(Die->getAbbrev());
1531 // Get the abbreviation for this DIE.
1532 unsigned AbbrevNumber = Die->getAbbrevNumber();
1533 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1536 Die->setOffset(Offset);
1538 // Start the size with the size of abbreviation code.
1539 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1541 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1542 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1544 // Size the DIE attribute values.
1545 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1546 // Size attribute value.
1547 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1549 // Size the DIE children if any.
1550 if (!Children.empty()) {
1551 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1552 "Children flag not set");
1554 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1555 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1557 // End of children marker.
1558 Offset += sizeof(int8_t);
1561 Die->setSize(Offset - Die->getOffset());
1565 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1567 void DwarfDebug::computeSizeAndOffsets() {
1568 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1569 E = CUMap.end(); I != E; ++I) {
1570 // Compute size of compile unit header.
1572 sizeof(int32_t) + // Length of Compilation Unit Info
1573 sizeof(int16_t) + // DWARF version number
1574 sizeof(int32_t) + // Offset Into Abbrev. Section
1575 sizeof(int8_t); // Pointer Size (in bytes)
1576 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1580 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1581 /// the start of each one.
1582 void DwarfDebug::EmitSectionLabels() {
1583 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1585 // Dwarf sections base addresses.
1586 DwarfInfoSectionSym =
1587 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1588 DwarfAbbrevSectionSym =
1589 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1590 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1592 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1593 EmitSectionSym(Asm, MacroInfo);
1595 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1596 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1597 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1598 DwarfStrSectionSym =
1599 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1600 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1603 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1604 "section_debug_loc");
1606 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1607 EmitSectionSym(Asm, TLOF.getDataSection());
1610 /// emitDIE - Recursively emits a debug information entry.
1612 void DwarfDebug::emitDIE(DIE *Die) {
1613 // Get the abbreviation for this DIE.
1614 unsigned AbbrevNumber = Die->getAbbrevNumber();
1615 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1617 // Emit the code (index) for the abbreviation.
1618 if (Asm->isVerbose())
1619 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1620 Twine::utohexstr(Die->getOffset()) + ":0x" +
1621 Twine::utohexstr(Die->getSize()) + " " +
1622 dwarf::TagString(Abbrev->getTag()));
1623 Asm->EmitULEB128(AbbrevNumber);
1625 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1626 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1628 // Emit the DIE attribute values.
1629 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1630 unsigned Attr = AbbrevData[i].getAttribute();
1631 unsigned Form = AbbrevData[i].getForm();
1632 assert(Form && "Too many attributes for DIE (check abbreviation)");
1634 if (Asm->isVerbose())
1635 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1638 case dwarf::DW_AT_abstract_origin: {
1639 DIEEntry *E = cast<DIEEntry>(Values[i]);
1640 DIE *Origin = E->getEntry();
1641 unsigned Addr = Origin->getOffset();
1642 Asm->EmitInt32(Addr);
1645 case dwarf::DW_AT_ranges: {
1646 // DW_AT_range Value encodes offset in debug_range section.
1647 DIEInteger *V = cast<DIEInteger>(Values[i]);
1649 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1650 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1654 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1656 DwarfDebugRangeSectionSym,
1661 case dwarf::DW_AT_location: {
1662 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1663 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1664 Asm->EmitLabelReference(L->getValue(), 4);
1666 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1668 Values[i]->EmitValue(Asm, Form);
1672 case dwarf::DW_AT_accessibility: {
1673 if (Asm->isVerbose()) {
1674 DIEInteger *V = cast<DIEInteger>(Values[i]);
1675 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1677 Values[i]->EmitValue(Asm, Form);
1681 // Emit an attribute using the defined form.
1682 Values[i]->EmitValue(Asm, Form);
1687 // Emit the DIE children if any.
1688 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1689 const std::vector<DIE *> &Children = Die->getChildren();
1691 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1692 emitDIE(Children[j]);
1694 if (Asm->isVerbose())
1695 Asm->OutStreamer.AddComment("End Of Children Mark");
1700 /// emitDebugInfo - Emit the debug info section.
1702 void DwarfDebug::emitDebugInfo() {
1703 // Start debug info section.
1704 Asm->OutStreamer.SwitchSection(
1705 Asm->getObjFileLowering().getDwarfInfoSection());
1706 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1707 E = CUMap.end(); I != E; ++I) {
1708 CompileUnit *TheCU = I->second;
1709 DIE *Die = TheCU->getCUDie();
1711 // Emit the compile units header.
1712 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1715 // Emit size of content not including length itself
1716 unsigned ContentSize = Die->getSize() +
1717 sizeof(int16_t) + // DWARF version number
1718 sizeof(int32_t) + // Offset Into Abbrev. Section
1719 sizeof(int8_t); // Pointer Size (in bytes)
1721 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1722 Asm->EmitInt32(ContentSize);
1723 Asm->OutStreamer.AddComment("DWARF version number");
1724 Asm->EmitInt16(dwarf::DWARF_VERSION);
1725 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1726 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1727 DwarfAbbrevSectionSym);
1728 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1729 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1732 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1736 /// emitAbbreviations - Emit the abbreviation section.
1738 void DwarfDebug::emitAbbreviations() const {
1739 // Check to see if it is worth the effort.
1740 if (!Abbreviations.empty()) {
1741 // Start the debug abbrev section.
1742 Asm->OutStreamer.SwitchSection(
1743 Asm->getObjFileLowering().getDwarfAbbrevSection());
1745 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1747 // For each abbrevation.
1748 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1749 // Get abbreviation data
1750 const DIEAbbrev *Abbrev = Abbreviations[i];
1752 // Emit the abbrevations code (base 1 index.)
1753 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1755 // Emit the abbreviations data.
1759 // Mark end of abbreviations.
1760 Asm->EmitULEB128(0, "EOM(3)");
1762 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1766 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1767 /// the line matrix.
1769 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1770 // Define last address of section.
1771 Asm->OutStreamer.AddComment("Extended Op");
1774 Asm->OutStreamer.AddComment("Op size");
1775 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1776 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1777 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1779 Asm->OutStreamer.AddComment("Section end label");
1781 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1782 Asm->getTargetData().getPointerSize(),
1785 // Mark end of matrix.
1786 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1792 /// emitAccelNames - Emit visible names into a hashed accelerator table
1794 void DwarfDebug::emitAccelNames() {
1795 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1796 dwarf::DW_FORM_data4));
1797 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1798 E = CUMap.end(); I != E; ++I) {
1799 CompileUnit *TheCU = I->second;
1800 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1801 for (StringMap<std::vector<DIE*> >::const_iterator
1802 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1803 const char *Name = GI->getKeyData();
1804 const std::vector<DIE *> &Entities = GI->second;
1805 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1806 DE = Entities.end(); DI != DE; ++DI)
1807 AT.AddName(Name, (*DI));
1811 AT.FinalizeTable(Asm, "Names");
1812 Asm->OutStreamer.SwitchSection(
1813 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1814 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1815 Asm->OutStreamer.EmitLabel(SectionBegin);
1817 // Emit the full data.
1818 AT.Emit(Asm, SectionBegin, this);
1821 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1822 /// accelerator table section.
1823 void DwarfDebug::emitAccelObjC() {
1824 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1825 dwarf::DW_FORM_data4));
1826 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1827 E = CUMap.end(); I != E; ++I) {
1828 CompileUnit *TheCU = I->second;
1829 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1830 for (StringMap<std::vector<DIE*> >::const_iterator
1831 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1832 const char *Name = GI->getKeyData();
1833 const std::vector<DIE *> &Entities = GI->second;
1834 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1835 DE = Entities.end(); DI != DE; ++DI)
1836 AT.AddName(Name, (*DI));
1840 AT.FinalizeTable(Asm, "ObjC");
1841 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1842 .getDwarfAccelObjCSection());
1843 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1844 Asm->OutStreamer.EmitLabel(SectionBegin);
1846 // Emit the full data.
1847 AT.Emit(Asm, SectionBegin, this);
1850 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1852 void DwarfDebug::emitAccelNamespaces() {
1853 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1854 dwarf::DW_FORM_data4));
1855 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1856 E = CUMap.end(); I != E; ++I) {
1857 CompileUnit *TheCU = I->second;
1858 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
1859 for (StringMap<std::vector<DIE*> >::const_iterator
1860 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1861 const char *Name = GI->getKeyData();
1862 const std::vector<DIE *> &Entities = GI->second;
1863 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1864 DE = Entities.end(); DI != DE; ++DI)
1865 AT.AddName(Name, (*DI));
1869 AT.FinalizeTable(Asm, "namespac");
1870 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1871 .getDwarfAccelNamespaceSection());
1872 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1873 Asm->OutStreamer.EmitLabel(SectionBegin);
1875 // Emit the full data.
1876 AT.Emit(Asm, SectionBegin, this);
1879 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1880 void DwarfDebug::emitAccelTypes() {
1881 std::vector<DwarfAccelTable::Atom> Atoms;
1882 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1883 dwarf::DW_FORM_data4));
1884 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
1885 dwarf::DW_FORM_data2));
1886 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
1887 dwarf::DW_FORM_data1));
1888 DwarfAccelTable AT(Atoms);
1889 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1890 E = CUMap.end(); I != E; ++I) {
1891 CompileUnit *TheCU = I->second;
1892 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
1893 = TheCU->getAccelTypes();
1894 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
1895 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1896 const char *Name = GI->getKeyData();
1897 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
1898 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
1899 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
1900 AT.AddName(Name, (*DI).first, (*DI).second);
1904 AT.FinalizeTable(Asm, "types");
1905 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1906 .getDwarfAccelTypesSection());
1907 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1908 Asm->OutStreamer.EmitLabel(SectionBegin);
1910 // Emit the full data.
1911 AT.Emit(Asm, SectionBegin, this);
1914 void DwarfDebug::emitDebugPubTypes() {
1915 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1916 E = CUMap.end(); I != E; ++I) {
1917 CompileUnit *TheCU = I->second;
1918 // Start the dwarf pubtypes section.
1919 Asm->OutStreamer.SwitchSection(
1920 Asm->getObjFileLowering().getDwarfPubTypesSection());
1921 Asm->OutStreamer.AddComment("Length of Public Types Info");
1922 Asm->EmitLabelDifference(
1923 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1924 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1926 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1929 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1930 Asm->EmitInt16(dwarf::DWARF_VERSION);
1932 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1933 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1934 DwarfInfoSectionSym);
1936 Asm->OutStreamer.AddComment("Compilation Unit Length");
1937 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1938 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1941 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1942 for (StringMap<DIE*>::const_iterator
1943 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1944 const char *Name = GI->getKeyData();
1945 DIE *Entity = GI->second;
1947 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1948 Asm->EmitInt32(Entity->getOffset());
1950 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1951 // Emit the name with a terminating null byte.
1952 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1955 Asm->OutStreamer.AddComment("End Mark");
1957 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1962 /// emitDebugStr - Emit visible names into a debug str section.
1964 void DwarfDebug::emitDebugStr() {
1965 // Check to see if it is worth the effort.
1966 if (StringPool.empty()) return;
1968 // Start the dwarf str section.
1969 Asm->OutStreamer.SwitchSection(
1970 Asm->getObjFileLowering().getDwarfStrSection());
1972 // Get all of the string pool entries and put them in an array by their ID so
1973 // we can sort them.
1974 SmallVector<std::pair<unsigned,
1975 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1977 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1978 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1979 Entries.push_back(std::make_pair(I->second.second, &*I));
1981 array_pod_sort(Entries.begin(), Entries.end());
1983 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1984 // Emit a label for reference from debug information entries.
1985 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1987 // Emit the string itself with a terminating null byte.
1988 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
1989 Entries[i].second->getKeyLength()+1),
1994 /// emitDebugLoc - Emit visible names into a debug loc section.
1996 void DwarfDebug::emitDebugLoc() {
1997 if (DotDebugLocEntries.empty())
2000 for (SmallVector<DotDebugLocEntry, 4>::iterator
2001 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2003 DotDebugLocEntry &Entry = *I;
2004 if (I + 1 != DotDebugLocEntries.end())
2008 // Start the dwarf loc section.
2009 Asm->OutStreamer.SwitchSection(
2010 Asm->getObjFileLowering().getDwarfLocSection());
2011 unsigned char Size = Asm->getTargetData().getPointerSize();
2012 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2014 for (SmallVector<DotDebugLocEntry, 4>::iterator
2015 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2016 I != E; ++I, ++index) {
2017 DotDebugLocEntry &Entry = *I;
2018 if (Entry.isMerged()) continue;
2019 if (Entry.isEmpty()) {
2020 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2021 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2022 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2024 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2025 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2026 DIVariable DV(Entry.Variable);
2027 Asm->OutStreamer.AddComment("Loc expr size");
2028 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2029 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2030 Asm->EmitLabelDifference(end, begin, 2);
2031 Asm->OutStreamer.EmitLabel(begin);
2032 if (Entry.isInt()) {
2033 DIBasicType BTy(DV.getType());
2035 (BTy.getEncoding() == dwarf::DW_ATE_signed
2036 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2037 Asm->OutStreamer.AddComment("DW_OP_consts");
2038 Asm->EmitInt8(dwarf::DW_OP_consts);
2039 Asm->EmitSLEB128(Entry.getInt());
2041 Asm->OutStreamer.AddComment("DW_OP_constu");
2042 Asm->EmitInt8(dwarf::DW_OP_constu);
2043 Asm->EmitULEB128(Entry.getInt());
2045 } else if (Entry.isLocation()) {
2046 if (!DV.hasComplexAddress())
2048 Asm->EmitDwarfRegOp(Entry.Loc);
2050 // Complex address entry.
2051 unsigned N = DV.getNumAddrElements();
2053 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2054 if (Entry.Loc.getOffset()) {
2056 Asm->EmitDwarfRegOp(Entry.Loc);
2057 Asm->OutStreamer.AddComment("DW_OP_deref");
2058 Asm->EmitInt8(dwarf::DW_OP_deref);
2059 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2060 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2061 Asm->EmitSLEB128(DV.getAddrElement(1));
2063 // If first address element is OpPlus then emit
2064 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2065 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2066 Asm->EmitDwarfRegOp(Loc);
2070 Asm->EmitDwarfRegOp(Entry.Loc);
2073 // Emit remaining complex address elements.
2074 for (; i < N; ++i) {
2075 uint64_t Element = DV.getAddrElement(i);
2076 if (Element == DIBuilder::OpPlus) {
2077 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2078 Asm->EmitULEB128(DV.getAddrElement(++i));
2079 } else if (Element == DIBuilder::OpDeref) {
2080 if (!Entry.Loc.isReg())
2081 Asm->EmitInt8(dwarf::DW_OP_deref);
2083 llvm_unreachable("unknown Opcode found in complex address");
2087 // else ... ignore constant fp. There is not any good way to
2088 // to represent them here in dwarf.
2089 Asm->OutStreamer.EmitLabel(end);
2094 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2096 void DwarfDebug::EmitDebugARanges() {
2097 // Start the dwarf aranges section.
2098 Asm->OutStreamer.SwitchSection(
2099 Asm->getObjFileLowering().getDwarfARangesSection());
2102 /// emitDebugRanges - Emit visible names into a debug ranges section.
2104 void DwarfDebug::emitDebugRanges() {
2105 // Start the dwarf ranges section.
2106 Asm->OutStreamer.SwitchSection(
2107 Asm->getObjFileLowering().getDwarfRangesSection());
2108 unsigned char Size = Asm->getTargetData().getPointerSize();
2109 for (SmallVector<const MCSymbol *, 8>::iterator
2110 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2113 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2115 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2119 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2121 void DwarfDebug::emitDebugMacInfo() {
2122 if (const MCSection *LineInfo =
2123 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2124 // Start the dwarf macinfo section.
2125 Asm->OutStreamer.SwitchSection(LineInfo);
2129 /// emitDebugInlineInfo - Emit inline info using following format.
2131 /// 1. length of section
2132 /// 2. Dwarf version number
2133 /// 3. address size.
2135 /// Entries (one "entry" for each function that was inlined):
2137 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2138 /// otherwise offset into __debug_str for regular function name.
2139 /// 2. offset into __debug_str section for regular function name.
2140 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2141 /// instances for the function.
2143 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2144 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2145 /// __debug_info section, and the low_pc is the starting address for the
2146 /// inlining instance.
2147 void DwarfDebug::emitDebugInlineInfo() {
2148 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2154 Asm->OutStreamer.SwitchSection(
2155 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2157 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2158 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2159 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2161 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2163 Asm->OutStreamer.AddComment("Dwarf Version");
2164 Asm->EmitInt16(dwarf::DWARF_VERSION);
2165 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2166 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2168 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2169 E = InlinedSPNodes.end(); I != E; ++I) {
2171 const MDNode *Node = *I;
2172 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2173 = InlineInfo.find(Node);
2174 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2175 DISubprogram SP(Node);
2176 StringRef LName = SP.getLinkageName();
2177 StringRef Name = SP.getName();
2179 Asm->OutStreamer.AddComment("MIPS linkage name");
2181 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2183 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2184 DwarfStrSectionSym);
2186 Asm->OutStreamer.AddComment("Function name");
2187 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2188 Asm->EmitULEB128(Labels.size(), "Inline count");
2190 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2191 LE = Labels.end(); LI != LE; ++LI) {
2192 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2193 Asm->EmitInt32(LI->second->getOffset());
2195 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2196 Asm->OutStreamer.EmitSymbolValue(LI->first,
2197 Asm->getTargetData().getPointerSize(),0);
2201 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));