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 "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Analysis/DIBuilder.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Path.h"
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
49 cl::desc("Disable debug info printing"));
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absence of debug location information explicit."),
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
68 DIType DbgVariable::getType() const {
69 DIType Ty = Var.getType();
70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
72 if (Var.isBlockByrefVariable()) {
73 /* Byref variables, in Blocks, are declared by the programmer as
74 "SomeType VarName;", but the compiler creates a
75 __Block_byref_x_VarName struct, and gives the variable VarName
76 either the struct, or a pointer to the struct, as its type. This
77 is necessary for various behind-the-scenes things the compiler
78 needs to do with by-reference variables in blocks.
80 However, as far as the original *programmer* is concerned, the
81 variable should still have type 'SomeType', as originally declared.
83 The following function dives into the __Block_byref_x_VarName
84 struct to find the original type of the variable. This will be
85 passed back to the code generating the type for the Debug
86 Information Entry for the variable 'VarName'. 'VarName' will then
87 have the original type 'SomeType' in its debug information.
89 The original type 'SomeType' will be the type of the field named
90 'VarName' inside the __Block_byref_x_VarName struct.
92 NOTE: In order for this to not completely fail on the debugger
93 side, the Debug Information Entry for the variable VarName needs to
94 have a DW_AT_location that tells the debugger how to unwind through
95 the pointers and __Block_byref_x_VarName struct to find the actual
96 value of the variable. The function addBlockByrefType does this. */
98 unsigned tag = Ty.getTag();
100 if (tag == dwarf::DW_TAG_pointer_type) {
101 DIDerivedType DTy = DIDerivedType(Ty);
102 subType = DTy.getTypeDerivedFrom();
105 DICompositeType blockStruct = DICompositeType(subType);
106 DIArray Elements = blockStruct.getTypeArray();
108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
109 DIDescriptor Element = Elements.getElement(i);
110 DIDerivedType DT = DIDerivedType(Element);
111 if (getName() == DT.getName())
112 return (DT.getTypeDerivedFrom());
119 } // end llvm namespace
121 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
122 : Asm(A), MMI(Asm->MMI), FirstCU(0),
123 AbbreviationsSet(InitAbbreviationsSetSize),
125 NextStringPoolNumber = 0;
127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
128 DwarfStrSectionSym = TextSectionSym = 0;
129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
130 FunctionBeginSym = FunctionEndSym = 0;
132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
136 DwarfDebug::~DwarfDebug() {
139 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
140 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
141 if (Entry.first) return Entry.first;
143 Entry.second = NextStringPoolNumber++;
144 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
148 /// assignAbbrevNumber - Define a unique number for the abbreviation.
150 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
151 // Profile the node so that we can make it unique.
155 // Check the set for priors.
156 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
158 // If it's newly added.
159 if (InSet == &Abbrev) {
160 // Add to abbreviation list.
161 Abbreviations.push_back(&Abbrev);
163 // Assign the vector position + 1 as its number.
164 Abbrev.setNumber(Abbreviations.size());
166 // Assign existing abbreviation number.
167 Abbrev.setNumber(InSet->getNumber());
171 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
172 /// printer to not emit usual symbol prefix before the symbol name is used then
173 /// return linkage name after skipping this special LLVM prefix.
174 static StringRef getRealLinkageName(StringRef LinkageName) {
176 if (LinkageName.startswith(StringRef(&One, 1)))
177 return LinkageName.substr(1);
181 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
182 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
183 /// If there are global variables in this scope then create and insert
184 /// DIEs for these variables.
185 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
186 CompileUnit *SPCU = getCompileUnit(SPNode);
187 DIE *SPDie = SPCU->getDIE(SPNode);
189 assert(SPDie && "Unable to find subprogram DIE!");
190 DISubprogram SP(SPNode);
192 DISubprogram SPDecl = SP.getFunctionDeclaration();
193 if (SPDecl.isSubprogram())
194 // Refer function declaration directly.
195 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
196 SPCU->getOrCreateSubprogramDIE(SPDecl));
198 // There is not any need to generate specification DIE for a function
199 // defined at compile unit level. If a function is defined inside another
200 // function then gdb prefers the definition at top level and but does not
201 // expect specification DIE in parent function. So avoid creating
202 // specification DIE for a function defined inside a function.
203 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
204 !SP.getContext().isFile() &&
205 !isSubprogramContext(SP.getContext())) {
206 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
209 DICompositeType SPTy = SP.getType();
210 DIArray Args = SPTy.getTypeArray();
211 unsigned SPTag = SPTy.getTag();
212 if (SPTag == dwarf::DW_TAG_subroutine_type)
213 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
214 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
215 DIType ATy = DIType(DIType(Args.getElement(i)));
216 SPCU->addType(Arg, ATy);
217 if (ATy.isArtificial())
218 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
219 SPDie->addChild(Arg);
221 DIE *SPDeclDie = SPDie;
222 SPDie = new DIE(dwarf::DW_TAG_subprogram);
223 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
228 // Pick up abstract subprogram DIE.
229 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
230 SPDie = new DIE(dwarf::DW_TAG_subprogram);
231 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
232 dwarf::DW_FORM_ref4, AbsSPDIE);
236 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
237 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
238 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
239 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
240 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
241 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
242 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
247 /// constructLexicalScope - Construct new DW_TAG_lexical_block
248 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
249 DIE *DwarfDebug::constructLexicalScopeDIE(LexicalScope *Scope) {
251 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
252 if (Scope->isAbstractScope())
255 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
259 CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
260 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
261 if (Ranges.size() > 1) {
262 // .debug_range section has not been laid out yet. Emit offset in
263 // .debug_range as a uint, size 4, for now. emitDIE will handle
264 // DW_AT_ranges appropriately.
265 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
266 DebugRangeSymbols.size()
267 * Asm->getTargetData().getPointerSize());
268 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
269 RE = Ranges.end(); RI != RE; ++RI) {
270 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
271 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
273 DebugRangeSymbols.push_back(NULL);
274 DebugRangeSymbols.push_back(NULL);
278 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
279 const MCSymbol *End = getLabelAfterInsn(RI->second);
281 if (End == 0) return 0;
283 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
284 assert(End->isDefined() && "Invalid end label for an inlined scope!");
286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
287 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
292 /// constructInlinedScopeDIE - This scope represents inlined body of
293 /// a function. Construct DIE to represent this concrete inlined copy
295 DIE *DwarfDebug::constructInlinedScopeDIE(LexicalScope *Scope) {
297 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
298 assert (Ranges.empty() == false
299 && "LexicalScope does not have instruction markers!");
301 if (!Scope->getScopeNode())
303 DIScope DS(Scope->getScopeNode());
304 DISubprogram InlinedSP = getDISubprogram(DS);
305 CompileUnit *TheCU = getCompileUnit(InlinedSP);
306 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
308 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
312 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
313 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
314 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
316 if (StartLabel == 0 || EndLabel == 0) {
317 assert (0 && "Unexpected Start and End labels for a inlined scope!");
320 assert(StartLabel->isDefined() &&
321 "Invalid starting label for an inlined scope!");
322 assert(EndLabel->isDefined() &&
323 "Invalid end label for an inlined scope!");
325 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
326 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
327 dwarf::DW_FORM_ref4, OriginDIE);
329 if (Ranges.size() > 1) {
330 // .debug_range section has not been laid out yet. Emit offset in
331 // .debug_range as a uint, size 4, for now. emitDIE will handle
332 // DW_AT_ranges appropriately.
333 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
334 DebugRangeSymbols.size()
335 * Asm->getTargetData().getPointerSize());
336 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
337 RE = Ranges.end(); RI != RE; ++RI) {
338 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
339 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
341 DebugRangeSymbols.push_back(NULL);
342 DebugRangeSymbols.push_back(NULL);
344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
346 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
350 InlinedSubprogramDIEs.insert(OriginDIE);
352 // Track the start label for this inlined function.
353 //.debug_inlined section specification does not clearly state how
354 // to emit inlined scope that is split into multiple instruction ranges.
355 // For now, use first instruction range and emit low_pc/high_pc pair and
356 // corresponding .debug_inlined section entry for this pair.
357 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
358 I = InlineInfo.find(InlinedSP);
360 if (I == InlineInfo.end()) {
361 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
363 InlinedSPNodes.push_back(InlinedSP);
365 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
367 DILocation DL(Scope->getInlinedAt());
368 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
369 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
374 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
375 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, LexicalScope *Scope) {
376 StringRef Name = DV->getName();
380 // Translate tag to proper Dwarf tag.
381 unsigned Tag = DV->getTag();
383 // Define variable debug information entry.
384 DIE *VariableDie = new DIE(Tag);
385 CompileUnit *VariableCU = getCompileUnit(DV->getVariable());
387 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
388 V2AVI = VarToAbstractVarMap.find(DV);
389 if (V2AVI != VarToAbstractVarMap.end())
390 AbsDIE = V2AVI->second->getDIE();
393 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
394 dwarf::DW_FORM_ref4, AbsDIE);
396 VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
398 VariableCU->addSourceLine(VariableDie, DV->getVariable());
400 // Add variable type.
401 VariableCU->addType(VariableDie, DV->getType());
404 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
405 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
406 dwarf::DW_FORM_flag, 1);
407 else if (DIVariable(DV->getVariable()).isArtificial())
408 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
409 dwarf::DW_FORM_flag, 1);
411 if (Scope->isAbstractScope()) {
412 DV->setDIE(VariableDie);
416 // Add variable address.
418 unsigned Offset = DV->getDotDebugLocOffset();
420 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location,
421 dwarf::DW_FORM_data4,
422 Asm->GetTempSymbol("debug_loc", Offset));
423 DV->setDIE(VariableDie);
424 UseDotDebugLocEntry.insert(VariableDie);
428 // Check if variable is described by a DBG_VALUE instruction.
429 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
430 DbgVariableToDbgInstMap.find(DV);
431 if (DVI != DbgVariableToDbgInstMap.end()) {
432 const MachineInstr *DVInsn = DVI->second;
433 bool updated = false;
434 if (DVInsn->getNumOperands() == 3) {
435 if (DVInsn->getOperand(0).isReg()) {
436 const MachineOperand RegOp = DVInsn->getOperand(0);
437 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
438 if (DVInsn->getOperand(1).isImm() &&
439 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
440 unsigned FrameReg = 0;
441 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
443 TFI->getFrameIndexReference(*Asm->MF,
444 DVInsn->getOperand(1).getImm(),
446 MachineLocation Location(FrameReg, Offset);
447 VariableCU->addVariableAddress(DV, VariableDie, Location);
449 } else if (RegOp.getReg())
450 VariableCU->addVariableAddress(DV, VariableDie,
451 MachineLocation(RegOp.getReg()));
454 else if (DVInsn->getOperand(0).isImm())
456 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
458 else if (DVInsn->getOperand(0).isFPImm())
460 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
461 else if (DVInsn->getOperand(0).isCImm())
463 VariableCU->addConstantValue(VariableDie,
464 DVInsn->getOperand(0).getCImm(),
465 DV->getType().isUnsignedDIType());
467 VariableCU->addVariableAddress(DV, VariableDie,
468 Asm->getDebugValueLocation(DVInsn));
472 // If variableDie is not updated then DBG_VALUE instruction does not
473 // have valid variable info.
477 DV->setDIE(VariableDie);
481 // .. else use frame index, if available.
483 if (findVariableFrameIndex(DV, &FI)) {
484 unsigned FrameReg = 0;
485 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
487 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
488 MachineLocation Location(FrameReg, Offset);
489 VariableCU->addVariableAddress(DV, VariableDie, Location);
492 DV->setDIE(VariableDie);
497 /// constructScopeDIE - Construct a DIE for this scope.
498 DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) {
499 if (!Scope || !Scope->getScopeNode())
502 SmallVector <DIE *, 8> Children;
504 // Collect arguments for current function.
505 if (LScopes.isCurrentFunctionScope(Scope))
506 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
507 if (DbgVariable *ArgDV = CurrentFnArguments[i])
508 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
509 Children.push_back(Arg);
511 // Collect lexical scope childrens first.
512 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
513 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
514 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
515 Children.push_back(Variable);
516 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
517 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
518 if (DIE *Nested = constructScopeDIE(Scopes[j]))
519 Children.push_back(Nested);
520 DIScope DS(Scope->getScopeNode());
521 DIE *ScopeDIE = NULL;
522 if (Scope->getInlinedAt())
523 ScopeDIE = constructInlinedScopeDIE(Scope);
524 else if (DS.isSubprogram()) {
525 ProcessedSPNodes.insert(DS);
526 if (Scope->isAbstractScope()) {
527 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
528 // Note down abstract DIE.
530 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
533 ScopeDIE = updateSubprogramScopeDIE(DS);
536 // There is no need to emit empty lexical block DIE.
537 if (Children.empty())
539 ScopeDIE = constructLexicalScopeDIE(Scope);
542 if (!ScopeDIE) return NULL;
545 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
546 E = Children.end(); I != E; ++I)
547 ScopeDIE->addChild(*I);
549 if (DS.isSubprogram())
550 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
555 /// GetOrCreateSourceID - Look up the source id with the given directory and
556 /// source file names. If none currently exists, create a new id and insert it
557 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
560 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
562 // If FE did not provide a file name, then assume stdin.
563 if (FileName.empty())
564 return GetOrCreateSourceID("<stdin>", StringRef());
566 // MCStream expects full path name as filename.
567 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
568 SmallString<128> FullPathName = DirName;
569 sys::path::append(FullPathName, FileName);
570 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
571 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
574 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
575 if (Entry.getValue())
576 return Entry.getValue();
578 unsigned SrcId = SourceIdMap.size();
579 Entry.setValue(SrcId);
581 // Print out a .file directive to specify files for .loc directives.
582 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
587 /// constructCompileUnit - Create new CompileUnit for the given
588 /// metadata node with tag DW_TAG_compile_unit.
589 void DwarfDebug::constructCompileUnit(const MDNode *N) {
590 DICompileUnit DIUnit(N);
591 StringRef FN = DIUnit.getFilename();
592 StringRef Dir = DIUnit.getDirectory();
593 unsigned ID = GetOrCreateSourceID(FN, Dir);
595 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
596 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
597 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
598 DIUnit.getProducer());
599 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
600 DIUnit.getLanguage());
601 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
602 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
603 // simplifies debug range entries.
604 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
605 // DW_AT_stmt_list is a offset of line number information for this
606 // compile unit in debug_line section.
607 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
608 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
609 Asm->GetTempSymbol("section_line"));
611 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
614 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
615 if (DIUnit.isOptimized())
616 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
618 StringRef Flags = DIUnit.getFlags();
620 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
623 unsigned RVer = DIUnit.getRunTimeVersion();
625 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
626 dwarf::DW_FORM_data1, RVer);
630 CUMap.insert(std::make_pair(N, NewCU));
633 /// getCompileUnit - Get CompileUnit DIE.
634 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
635 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
637 const MDNode *CUNode = NULL;
638 if (D.isCompileUnit())
640 else if (D.isSubprogram())
641 CUNode = DISubprogram(N).getCompileUnit();
643 CUNode = DIType(N).getCompileUnit();
644 else if (D.isGlobalVariable())
645 CUNode = DIGlobalVariable(N).getCompileUnit();
646 else if (D.isVariable())
647 CUNode = DIVariable(N).getCompileUnit();
648 else if (D.isNameSpace())
649 CUNode = DINameSpace(N).getCompileUnit();
651 CUNode = DIFile(N).getCompileUnit();
655 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
656 = CUMap.find(CUNode);
657 if (I == CUMap.end())
662 /// constructGlobalVariableDIE - Construct global variable DIE.
663 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
664 DIGlobalVariable GV(N);
666 // If debug information is malformed then ignore it.
667 if (GV.Verify() == false)
670 // Check for pre-existence.
671 CompileUnit *TheCU = getCompileUnit(N);
672 TheCU->createGlobalVariableDIE(N);
676 /// construct SubprogramDIE - Construct subprogram DIE.
677 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
680 // Check for pre-existence.
681 CompileUnit *TheCU = getCompileUnit(N);
682 if (TheCU->getDIE(N))
685 if (!SP.isDefinition())
686 // This is a method declaration which will be handled while constructing
690 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
693 TheCU->insertDIE(N, SubprogramDie);
695 // Add to context owner.
696 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
699 TheCU->addGlobal(SP.getName(), SubprogramDie);
704 /// beginModule - Emit all Dwarf sections that should come prior to the
705 /// content. Create global DIEs and emit initial debug info sections.
706 /// This is invoked by the target AsmPrinter.
707 void DwarfDebug::beginModule(Module *M) {
708 if (DisableDebugInfoPrinting)
711 // If module has named metadata anchors then use them, otherwise scan the
712 // module using debug info finder to collect debug info.
713 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
716 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
717 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
718 if (!GV_Nodes && !SP_Nodes)
719 // If there are not any global variables or any functions then
720 // there is not any debug info in this module.
723 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
724 constructCompileUnit(CU_Nodes->getOperand(i));
727 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
728 constructGlobalVariableDIE(GV_Nodes->getOperand(i));
731 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
732 constructSubprogramDIE(SP_Nodes->getOperand(i));
736 DebugInfoFinder DbgFinder;
737 DbgFinder.processModule(*M);
739 bool HasDebugInfo = false;
740 // Scan all the compile-units to see if there are any marked as the main
741 // unit. If not, we do not generate debug info.
742 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
743 E = DbgFinder.compile_unit_end(); I != E; ++I) {
744 if (DICompileUnit(*I).isMain()) {
749 if (!HasDebugInfo) return;
751 // Create all the compile unit DIEs.
752 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
753 E = DbgFinder.compile_unit_end(); I != E; ++I)
754 constructCompileUnit(*I);
756 // Create DIEs for each global variable.
757 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
758 E = DbgFinder.global_variable_end(); I != E; ++I)
759 constructGlobalVariableDIE(*I);
761 // Create DIEs for each subprogram.
762 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
763 E = DbgFinder.subprogram_end(); I != E; ++I)
764 constructSubprogramDIE(*I);
767 // Tell MMI that we have debug info.
768 MMI->setDebugInfoAvailability(true);
770 // Emit initial sections.
774 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
775 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
776 DIType Ty(NMD->getOperand(i));
777 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
780 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
781 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
782 DIType Ty(NMD->getOperand(i));
783 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
786 // Prime section data.
787 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
790 /// endModule - Emit all Dwarf sections that should come after the content.
792 void DwarfDebug::endModule() {
793 if (!FirstCU) return;
794 const Module *M = MMI->getModule();
795 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
796 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
797 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
798 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
799 DISubprogram SP(AllSPs->getOperand(SI));
800 if (!SP.Verify()) continue;
802 // Collect info for variables that were optimized out.
803 if (!SP.isDefinition()) continue;
804 StringRef FName = SP.getLinkageName();
806 FName = SP.getName();
807 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
809 unsigned E = NMD->getNumOperands();
811 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
813 DeadFnScopeMap[SP] = Scope;
814 SmallVector<DbgVariable, 8> Variables;
815 for (unsigned I = 0; I != E; ++I) {
816 DIVariable DV(NMD->getOperand(I));
817 if (!DV.Verify()) continue;
818 Variables.push_back(DbgVariable(DV));
821 // Construct subprogram DIE and add variables DIEs.
822 constructSubprogramDIE(SP);
823 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
824 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
825 if (DIE *VariableDIE = constructVariableDIE(&Variables[i], Scope))
826 ScopeDIE->addChild(VariableDIE);
831 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
832 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
833 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
835 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
838 // Emit DW_AT_containing_type attribute to connect types with their
839 // vtable holding type.
840 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
841 CUE = CUMap.end(); CUI != CUE; ++CUI) {
842 CompileUnit *TheCU = CUI->second;
843 TheCU->constructContainingTypeDIEs();
846 // Standard sections final addresses.
847 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
848 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
849 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
850 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
852 // End text sections.
853 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
854 Asm->OutStreamer.SwitchSection(SectionMap[i]);
855 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
858 // Compute DIE offsets and sizes.
859 computeSizeAndOffsets();
861 // Emit all the DIEs into a debug info section
864 // Corresponding abbreviations into a abbrev section.
867 // Emit info into a debug pubnames section.
870 // Emit info into a debug pubtypes section.
873 // Emit info into a debug loc section.
876 // Emit info into a debug aranges section.
879 // Emit info into a debug ranges section.
882 // Emit info into a debug macinfo section.
886 emitDebugInlineInfo();
888 // Emit info into a debug str section.
892 DeleteContainerSeconds(DeadFnScopeMap);
893 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
894 E = CUMap.end(); I != E; ++I)
896 FirstCU = NULL; // Reset for the next Module, if any.
899 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
900 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
902 LLVMContext &Ctx = DV->getContext();
903 // More then one inlined variable corresponds to one abstract variable.
904 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
905 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
907 return AbsDbgVariable;
909 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
913 AbsDbgVariable = new DbgVariable(Var);
914 addScopeVariable(Scope, AbsDbgVariable);
915 AbstractVariables[Var] = AbsDbgVariable;
916 return AbsDbgVariable;
919 /// addCurrentFnArgument - If Var is a current function argument then add
920 /// it to CurrentFnArguments list.
921 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
922 DbgVariable *Var, LexicalScope *Scope) {
923 if (!LScopes.isCurrentFunctionScope(Scope))
925 DIVariable DV = Var->getVariable();
926 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
928 unsigned ArgNo = DV.getArgNumber();
932 size_t Size = CurrentFnArguments.size();
934 CurrentFnArguments.resize(MF->getFunction()->arg_size());
935 // llvm::Function argument size is not good indicator of how many
936 // arguments does the function have at source level.
938 CurrentFnArguments.resize(ArgNo * 2);
939 CurrentFnArguments[ArgNo - 1] = Var;
943 /// collectVariableInfoFromMMITable - Collect variable information from
944 /// side table maintained by MMI.
946 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
947 SmallPtrSet<const MDNode *, 16> &Processed) {
948 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
949 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
950 VE = VMap.end(); VI != VE; ++VI) {
951 const MDNode *Var = VI->first;
953 Processed.insert(Var);
955 const std::pair<unsigned, DebugLoc> &VP = VI->second;
957 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
959 // If variable scope is not found then skip this variable.
963 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
964 DbgVariable *RegVar = new DbgVariable(DV);
965 recordVariableFrameIndex(RegVar, VP.first);
966 if (!addCurrentFnArgument(MF, RegVar, Scope))
967 addScopeVariable(Scope, RegVar);
968 if (AbsDbgVariable) {
969 recordVariableFrameIndex(AbsDbgVariable, VP.first);
970 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
975 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
976 /// DBG_VALUE instruction, is in a defined reg.
977 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
978 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
979 return MI->getNumOperands() == 3 &&
980 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
981 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
984 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
986 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
987 const MCSymbol *FLabel,
988 const MCSymbol *SLabel,
989 const MachineInstr *MI) {
990 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
992 if (MI->getNumOperands() != 3) {
993 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
994 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
996 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
997 MachineLocation MLoc;
998 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
999 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1001 if (MI->getOperand(0).isImm())
1002 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1003 if (MI->getOperand(0).isFPImm())
1004 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1005 if (MI->getOperand(0).isCImm())
1006 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1008 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
1009 return DotDebugLocEntry();
1012 /// collectVariableInfo - Find variables for each lexical scope.
1014 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1015 SmallPtrSet<const MDNode *, 16> &Processed) {
1017 /// collection info from MMI table.
1018 collectVariableInfoFromMMITable(MF, Processed);
1020 for (SmallVectorImpl<const MDNode*>::const_iterator
1021 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1023 const MDNode *Var = *UVI;
1024 if (Processed.count(Var))
1027 // History contains relevant DBG_VALUE instructions for Var and instructions
1029 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1030 if (History.empty())
1032 const MachineInstr *MInsn = History.front();
1035 LexicalScope *Scope = NULL;
1036 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1037 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1038 Scope = LScopes.getCurrentFunctionScope();
1040 if (DV.getVersion() <= LLVMDebugVersion9)
1041 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1043 if (MDNode *IA = DV.getInlinedAt())
1044 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1046 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1049 // If variable scope is not found then skip this variable.
1053 Processed.insert(DV);
1054 assert(MInsn->isDebugValue() && "History must begin with debug value");
1055 DbgVariable *RegVar = new DbgVariable(DV);
1056 if (!addCurrentFnArgument(MF, RegVar, Scope))
1057 addScopeVariable(Scope, RegVar);
1058 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1059 DbgVariableToDbgInstMap[AbsVar] = MInsn;
1060 VarToAbstractVarMap[RegVar] = AbsVar;
1063 // Simple ranges that are fully coalesced.
1064 if (History.size() <= 1 || (History.size() == 2 &&
1065 MInsn->isIdenticalTo(History.back()))) {
1066 DbgVariableToDbgInstMap[RegVar] = MInsn;
1070 // handle multiple DBG_VALUE instructions describing one variable.
1071 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1073 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1074 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1075 const MachineInstr *Begin = *HI;
1076 assert(Begin->isDebugValue() && "Invalid History entry");
1078 // Check if DBG_VALUE is truncating a range.
1079 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1080 && !Begin->getOperand(0).getReg())
1083 // Compute the range for a register location.
1084 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1085 const MCSymbol *SLabel = 0;
1088 // If Begin is the last instruction in History then its value is valid
1089 // until the end of the function.
1090 SLabel = FunctionEndSym;
1092 const MachineInstr *End = HI[1];
1093 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1094 << "\t" << *Begin << "\t" << *End << "\n");
1095 if (End->isDebugValue())
1096 SLabel = getLabelBeforeInsn(End);
1098 // End is a normal instruction clobbering the range.
1099 SLabel = getLabelAfterInsn(End);
1100 assert(SLabel && "Forgot label after clobber instruction");
1105 // The value is valid until the next DBG_VALUE or clobber.
1106 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1108 DotDebugLocEntries.push_back(DotDebugLocEntry());
1111 // Collect info for variables that were optimized out.
1112 const Function *F = MF->getFunction();
1113 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1114 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1115 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1116 if (!DV || !Processed.insert(DV))
1118 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1119 addScopeVariable(Scope, new DbgVariable(DV));
1124 /// getLabelBeforeInsn - Return Label preceding the instruction.
1125 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1126 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1127 assert(Label && "Didn't insert label before instruction");
1131 /// getLabelAfterInsn - Return Label immediately following the instruction.
1132 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1133 return LabelsAfterInsn.lookup(MI);
1136 /// beginInstruction - Process beginning of an instruction.
1137 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1138 // Check if source location changes, but ignore DBG_VALUE locations.
1139 if (!MI->isDebugValue()) {
1140 DebugLoc DL = MI->getDebugLoc();
1141 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1142 unsigned Flags = DWARF2_FLAG_IS_STMT;
1144 if (DL == PrologEndLoc) {
1145 Flags |= DWARF2_FLAG_PROLOGUE_END;
1146 PrologEndLoc = DebugLoc();
1148 if (!DL.isUnknown()) {
1149 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1150 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1152 recordSourceLine(0, 0, 0, 0);
1156 // Insert labels where requested.
1157 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1158 LabelsBeforeInsn.find(MI);
1161 if (I == LabelsBeforeInsn.end())
1164 // Label already assigned.
1169 PrevLabel = MMI->getContext().CreateTempSymbol();
1170 Asm->OutStreamer.EmitLabel(PrevLabel);
1172 I->second = PrevLabel;
1175 /// endInstruction - Process end of an instruction.
1176 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1177 // Don't create a new label after DBG_VALUE instructions.
1178 // They don't generate code.
1179 if (!MI->isDebugValue())
1182 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1183 LabelsAfterInsn.find(MI);
1186 if (I == LabelsAfterInsn.end())
1189 // Label already assigned.
1193 // We need a label after this instruction.
1195 PrevLabel = MMI->getContext().CreateTempSymbol();
1196 Asm->OutStreamer.EmitLabel(PrevLabel);
1198 I->second = PrevLabel;
1201 /// identifyScopeMarkers() -
1202 /// Each LexicalScope has first instruction and last instruction to mark
1203 /// beginning and end of a scope respectively. Create an inverse map that list
1204 /// scopes starts (and ends) with an instruction. One instruction may start (or
1205 /// end) multiple scopes. Ignore scopes that are not reachable.
1206 void DwarfDebug::identifyScopeMarkers() {
1207 SmallVector<LexicalScope *, 4> WorkList;
1208 WorkList.push_back(LScopes.getCurrentFunctionScope());
1209 while (!WorkList.empty()) {
1210 LexicalScope *S = WorkList.pop_back_val();
1212 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1213 if (!Children.empty())
1214 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1215 SE = Children.end(); SI != SE; ++SI)
1216 WorkList.push_back(*SI);
1218 if (S->isAbstractScope())
1221 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1224 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1225 RE = Ranges.end(); RI != RE; ++RI) {
1226 assert(RI->first && "InsnRange does not have first instruction!");
1227 assert(RI->second && "InsnRange does not have second instruction!");
1228 requestLabelBeforeInsn(RI->first);
1229 requestLabelAfterInsn(RI->second);
1234 /// getScopeNode - Get MDNode for DebugLoc's scope.
1235 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1236 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1237 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1238 return DL.getScope(Ctx);
1241 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1242 /// line number info for the function.
1243 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1244 const MDNode *Scope = getScopeNode(DL, Ctx);
1245 DISubprogram SP = getDISubprogram(Scope);
1247 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1251 /// beginFunction - Gather pre-function debug information. Assumes being
1252 /// emitted immediately after the function entry point.
1253 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1254 if (!MMI->hasDebugInfo()) return;
1255 LScopes.initialize(*MF);
1256 if (LScopes.empty()) return;
1257 identifyScopeMarkers();
1259 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1260 Asm->getFunctionNumber());
1261 // Assumes in correct section after the entry point.
1262 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1264 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1266 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1267 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1268 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1270 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1272 bool AtBlockEntry = true;
1273 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1275 const MachineInstr *MI = II;
1277 if (MI->isDebugValue()) {
1278 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1280 // Keep track of user variables.
1282 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1284 // Variable is in a register, we need to check for clobbers.
1285 if (isDbgValueInDefinedReg(MI))
1286 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1288 // Check the history of this variable.
1289 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1290 if (History.empty()) {
1291 UserVariables.push_back(Var);
1292 // The first mention of a function argument gets the FunctionBeginSym
1293 // label, so arguments are visible when breaking at function entry.
1295 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1296 DISubprogram(getDISubprogram(DV.getContext()))
1297 .describes(MF->getFunction()))
1298 LabelsBeforeInsn[MI] = FunctionBeginSym;
1300 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1301 const MachineInstr *Prev = History.back();
1302 if (Prev->isDebugValue()) {
1303 // Coalesce identical entries at the end of History.
1304 if (History.size() >= 2 &&
1305 Prev->isIdenticalTo(History[History.size() - 2])) {
1306 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1308 << "\t" << *History[History.size() - 2] << "\n");
1312 // Terminate old register assignments that don't reach MI;
1313 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1314 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1315 isDbgValueInDefinedReg(Prev)) {
1316 // Previous register assignment needs to terminate at the end of
1318 MachineBasicBlock::const_iterator LastMI =
1319 PrevMBB->getLastNonDebugInstr();
1320 if (LastMI == PrevMBB->end()) {
1321 // Drop DBG_VALUE for empty range.
1322 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1323 << "\t" << *Prev << "\n");
1327 // Terminate after LastMI.
1328 History.push_back(LastMI);
1333 History.push_back(MI);
1335 // Not a DBG_VALUE instruction.
1337 AtBlockEntry = false;
1339 // First known non DBG_VALUE location marks beginning of function
1341 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1342 PrologEndLoc = MI->getDebugLoc();
1344 // Check if the instruction clobbers any registers with debug vars.
1345 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1346 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1347 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1349 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1350 unsigned Reg = *AI; ++AI) {
1351 const MDNode *Var = LiveUserVar[Reg];
1354 // Reg is now clobbered.
1355 LiveUserVar[Reg] = 0;
1357 // Was MD last defined by a DBG_VALUE referring to Reg?
1358 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1359 if (HistI == DbgValues.end())
1361 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1362 if (History.empty())
1364 const MachineInstr *Prev = History.back();
1365 // Sanity-check: Register assignments are terminated at the end of
1367 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1369 // Is the variable still in Reg?
1370 if (!isDbgValueInDefinedReg(Prev) ||
1371 Prev->getOperand(0).getReg() != Reg)
1373 // Var is clobbered. Make sure the next instruction gets a label.
1374 History.push_back(MI);
1381 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1383 SmallVectorImpl<const MachineInstr*> &History = I->second;
1384 if (History.empty())
1387 // Make sure the final register assignments are terminated.
1388 const MachineInstr *Prev = History.back();
1389 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1390 const MachineBasicBlock *PrevMBB = Prev->getParent();
1391 MachineBasicBlock::const_iterator LastMI =
1392 PrevMBB->getLastNonDebugInstr();
1393 if (LastMI == PrevMBB->end())
1394 // Drop DBG_VALUE for empty range.
1397 // Terminate after LastMI.
1398 History.push_back(LastMI);
1401 // Request labels for the full history.
1402 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1403 const MachineInstr *MI = History[i];
1404 if (MI->isDebugValue())
1405 requestLabelBeforeInsn(MI);
1407 requestLabelAfterInsn(MI);
1411 PrevInstLoc = DebugLoc();
1412 PrevLabel = FunctionBeginSym;
1414 // Record beginning of function.
1415 if (!PrologEndLoc.isUnknown()) {
1416 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1417 MF->getFunction()->getContext());
1418 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1419 FnStartDL.getScope(MF->getFunction()->getContext()),
1420 DWARF2_FLAG_IS_STMT);
1424 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1425 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1426 ScopeVariables[LS].push_back(Var);
1427 // Vars.push_back(Var);
1430 /// endFunction - Gather and emit post-function debug information.
1432 void DwarfDebug::endFunction(const MachineFunction *MF) {
1433 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1435 // Define end label for subprogram.
1436 FunctionEndSym = Asm->GetTempSymbol("func_end",
1437 Asm->getFunctionNumber());
1438 // Assumes in correct section after the entry point.
1439 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1441 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1442 collectVariableInfo(MF, ProcessedVars);
1444 // Construct abstract scopes.
1445 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1446 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1447 LexicalScope *AScope = AList[i];
1448 DISubprogram SP(AScope->getScopeNode());
1450 // Collect info for variables that were optimized out.
1451 StringRef FName = SP.getLinkageName();
1453 FName = SP.getName();
1454 if (NamedMDNode *NMD =
1455 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1456 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1457 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1458 if (!DV || !ProcessedVars.insert(DV))
1460 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1461 addScopeVariable(Scope, new DbgVariable(DV));
1465 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1466 constructScopeDIE(AScope);
1469 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope());
1471 if (!DisableFramePointerElim(*MF)) {
1472 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1473 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1474 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1475 dwarf::DW_FORM_flag, 1);
1477 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1478 MMI->getFrameMoves()));
1481 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1482 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1483 DeleteContainerPointers(I->second);
1484 ScopeVariables.clear();
1485 DeleteContainerPointers(CurrentFnArguments);
1486 DbgVariableToFrameIndexMap.clear();
1487 VarToAbstractVarMap.clear();
1488 DbgVariableToDbgInstMap.clear();
1489 UserVariables.clear();
1491 AbstractVariables.clear();
1492 LabelsBeforeInsn.clear();
1493 LabelsAfterInsn.clear();
1497 /// recordVariableFrameIndex - Record a variable's index.
1498 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
1499 assert (V && "Invalid DbgVariable!");
1500 DbgVariableToFrameIndexMap[V] = Index;
1503 /// findVariableFrameIndex - Return true if frame index for the variable
1504 /// is found. Update FI to hold value of the index.
1505 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
1506 assert (V && "Invalid DbgVariable!");
1507 DenseMap<const DbgVariable *, int>::iterator I =
1508 DbgVariableToFrameIndexMap.find(V);
1509 if (I == DbgVariableToFrameIndexMap.end())
1515 /// recordSourceLine - Register a source line with debug info. Returns the
1516 /// unique label that was emitted and which provides correspondence to
1517 /// the source line list.
1518 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1524 DIDescriptor Scope(S);
1526 if (Scope.isCompileUnit()) {
1527 DICompileUnit CU(S);
1528 Fn = CU.getFilename();
1529 Dir = CU.getDirectory();
1530 } else if (Scope.isFile()) {
1532 Fn = F.getFilename();
1533 Dir = F.getDirectory();
1534 } else if (Scope.isSubprogram()) {
1536 Fn = SP.getFilename();
1537 Dir = SP.getDirectory();
1538 } else if (Scope.isLexicalBlock()) {
1539 DILexicalBlock DB(S);
1540 Fn = DB.getFilename();
1541 Dir = DB.getDirectory();
1543 assert(0 && "Unexpected scope info");
1545 Src = GetOrCreateSourceID(Fn, Dir);
1547 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1550 //===----------------------------------------------------------------------===//
1552 //===----------------------------------------------------------------------===//
1554 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1557 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1558 // Get the children.
1559 const std::vector<DIE *> &Children = Die->getChildren();
1561 // If not last sibling and has children then add sibling offset attribute.
1562 if (!Last && !Children.empty())
1563 Die->addSiblingOffset(DIEValueAllocator);
1565 // Record the abbreviation.
1566 assignAbbrevNumber(Die->getAbbrev());
1568 // Get the abbreviation for this DIE.
1569 unsigned AbbrevNumber = Die->getAbbrevNumber();
1570 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1573 Die->setOffset(Offset);
1575 // Start the size with the size of abbreviation code.
1576 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1578 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1579 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1581 // Size the DIE attribute values.
1582 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1583 // Size attribute value.
1584 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1586 // Size the DIE children if any.
1587 if (!Children.empty()) {
1588 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1589 "Children flag not set");
1591 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1592 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1594 // End of children marker.
1595 Offset += sizeof(int8_t);
1598 Die->setSize(Offset - Die->getOffset());
1602 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1604 void DwarfDebug::computeSizeAndOffsets() {
1605 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1606 E = CUMap.end(); I != E; ++I) {
1607 // Compute size of compile unit header.
1609 sizeof(int32_t) + // Length of Compilation Unit Info
1610 sizeof(int16_t) + // DWARF version number
1611 sizeof(int32_t) + // Offset Into Abbrev. Section
1612 sizeof(int8_t); // Pointer Size (in bytes)
1613 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1617 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1618 /// temporary label to it if SymbolStem is specified.
1619 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1620 const char *SymbolStem = 0) {
1621 Asm->OutStreamer.SwitchSection(Section);
1622 if (!SymbolStem) return 0;
1624 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1625 Asm->OutStreamer.EmitLabel(TmpSym);
1629 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1630 /// the start of each one.
1631 void DwarfDebug::EmitSectionLabels() {
1632 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1634 // Dwarf sections base addresses.
1635 DwarfInfoSectionSym =
1636 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1637 DwarfAbbrevSectionSym =
1638 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1639 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1641 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1642 EmitSectionSym(Asm, MacroInfo);
1644 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1645 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1646 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1647 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1648 DwarfStrSectionSym =
1649 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1650 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1653 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1654 "section_debug_loc");
1656 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1657 EmitSectionSym(Asm, TLOF.getDataSection());
1660 /// emitDIE - Recursively emits a debug information entry.
1662 void DwarfDebug::emitDIE(DIE *Die) {
1663 // Get the abbreviation for this DIE.
1664 unsigned AbbrevNumber = Die->getAbbrevNumber();
1665 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1667 // Emit the code (index) for the abbreviation.
1668 if (Asm->isVerbose())
1669 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1670 Twine::utohexstr(Die->getOffset()) + ":0x" +
1671 Twine::utohexstr(Die->getSize()) + " " +
1672 dwarf::TagString(Abbrev->getTag()));
1673 Asm->EmitULEB128(AbbrevNumber);
1675 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1676 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1678 // Emit the DIE attribute values.
1679 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1680 unsigned Attr = AbbrevData[i].getAttribute();
1681 unsigned Form = AbbrevData[i].getForm();
1682 assert(Form && "Too many attributes for DIE (check abbreviation)");
1684 if (Asm->isVerbose())
1685 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1688 case dwarf::DW_AT_sibling:
1689 Asm->EmitInt32(Die->getSiblingOffset());
1691 case dwarf::DW_AT_abstract_origin: {
1692 DIEEntry *E = cast<DIEEntry>(Values[i]);
1693 DIE *Origin = E->getEntry();
1694 unsigned Addr = Origin->getOffset();
1695 Asm->EmitInt32(Addr);
1698 case dwarf::DW_AT_ranges: {
1699 // DW_AT_range Value encodes offset in debug_range section.
1700 DIEInteger *V = cast<DIEInteger>(Values[i]);
1702 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1703 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1707 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1709 DwarfDebugRangeSectionSym,
1714 case dwarf::DW_AT_location: {
1715 if (UseDotDebugLocEntry.count(Die) != 0) {
1716 DIELabel *L = cast<DIELabel>(Values[i]);
1717 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1719 Values[i]->EmitValue(Asm, Form);
1722 case dwarf::DW_AT_accessibility: {
1723 if (Asm->isVerbose()) {
1724 DIEInteger *V = cast<DIEInteger>(Values[i]);
1725 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1727 Values[i]->EmitValue(Asm, Form);
1731 // Emit an attribute using the defined form.
1732 Values[i]->EmitValue(Asm, Form);
1737 // Emit the DIE children if any.
1738 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1739 const std::vector<DIE *> &Children = Die->getChildren();
1741 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1742 emitDIE(Children[j]);
1744 if (Asm->isVerbose())
1745 Asm->OutStreamer.AddComment("End Of Children Mark");
1750 /// emitDebugInfo - Emit the debug info section.
1752 void DwarfDebug::emitDebugInfo() {
1753 // Start debug info section.
1754 Asm->OutStreamer.SwitchSection(
1755 Asm->getObjFileLowering().getDwarfInfoSection());
1756 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1757 E = CUMap.end(); I != E; ++I) {
1758 CompileUnit *TheCU = I->second;
1759 DIE *Die = TheCU->getCUDie();
1761 // Emit the compile units header.
1762 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1765 // Emit size of content not including length itself
1766 unsigned ContentSize = Die->getSize() +
1767 sizeof(int16_t) + // DWARF version number
1768 sizeof(int32_t) + // Offset Into Abbrev. Section
1769 sizeof(int8_t); // Pointer Size (in bytes)
1771 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1772 Asm->EmitInt32(ContentSize);
1773 Asm->OutStreamer.AddComment("DWARF version number");
1774 Asm->EmitInt16(dwarf::DWARF_VERSION);
1775 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1776 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1777 DwarfAbbrevSectionSym);
1778 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1779 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1782 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1786 /// emitAbbreviations - Emit the abbreviation section.
1788 void DwarfDebug::emitAbbreviations() const {
1789 // Check to see if it is worth the effort.
1790 if (!Abbreviations.empty()) {
1791 // Start the debug abbrev section.
1792 Asm->OutStreamer.SwitchSection(
1793 Asm->getObjFileLowering().getDwarfAbbrevSection());
1795 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1797 // For each abbrevation.
1798 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1799 // Get abbreviation data
1800 const DIEAbbrev *Abbrev = Abbreviations[i];
1802 // Emit the abbrevations code (base 1 index.)
1803 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1805 // Emit the abbreviations data.
1809 // Mark end of abbreviations.
1810 Asm->EmitULEB128(0, "EOM(3)");
1812 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1816 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1817 /// the line matrix.
1819 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1820 // Define last address of section.
1821 Asm->OutStreamer.AddComment("Extended Op");
1824 Asm->OutStreamer.AddComment("Op size");
1825 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1826 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1827 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1829 Asm->OutStreamer.AddComment("Section end label");
1831 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1832 Asm->getTargetData().getPointerSize(),
1835 // Mark end of matrix.
1836 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1842 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1844 void DwarfDebug::emitDebugPubNames() {
1845 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1846 E = CUMap.end(); I != E; ++I) {
1847 CompileUnit *TheCU = I->second;
1848 // Start the dwarf pubnames section.
1849 Asm->OutStreamer.SwitchSection(
1850 Asm->getObjFileLowering().getDwarfPubNamesSection());
1852 Asm->OutStreamer.AddComment("Length of Public Names Info");
1853 Asm->EmitLabelDifference(
1854 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1855 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1857 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1860 Asm->OutStreamer.AddComment("DWARF Version");
1861 Asm->EmitInt16(dwarf::DWARF_VERSION);
1863 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1864 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1865 DwarfInfoSectionSym);
1867 Asm->OutStreamer.AddComment("Compilation Unit Length");
1868 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1869 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1872 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1873 for (StringMap<DIE*>::const_iterator
1874 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1875 const char *Name = GI->getKeyData();
1876 DIE *Entity = GI->second;
1878 Asm->OutStreamer.AddComment("DIE offset");
1879 Asm->EmitInt32(Entity->getOffset());
1881 if (Asm->isVerbose())
1882 Asm->OutStreamer.AddComment("External Name");
1883 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1886 Asm->OutStreamer.AddComment("End Mark");
1888 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1893 void DwarfDebug::emitDebugPubTypes() {
1894 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1895 E = CUMap.end(); I != E; ++I) {
1896 CompileUnit *TheCU = I->second;
1897 // Start the dwarf pubnames section.
1898 Asm->OutStreamer.SwitchSection(
1899 Asm->getObjFileLowering().getDwarfPubTypesSection());
1900 Asm->OutStreamer.AddComment("Length of Public Types Info");
1901 Asm->EmitLabelDifference(
1902 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1903 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1905 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1908 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1909 Asm->EmitInt16(dwarf::DWARF_VERSION);
1911 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1912 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1913 DwarfInfoSectionSym);
1915 Asm->OutStreamer.AddComment("Compilation Unit Length");
1916 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1917 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1920 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1921 for (StringMap<DIE*>::const_iterator
1922 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1923 const char *Name = GI->getKeyData();
1924 DIE *Entity = GI->second;
1926 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1927 Asm->EmitInt32(Entity->getOffset());
1929 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1930 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1933 Asm->OutStreamer.AddComment("End Mark");
1935 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1940 /// emitDebugStr - Emit visible names into a debug str section.
1942 void DwarfDebug::emitDebugStr() {
1943 // Check to see if it is worth the effort.
1944 if (StringPool.empty()) return;
1946 // Start the dwarf str section.
1947 Asm->OutStreamer.SwitchSection(
1948 Asm->getObjFileLowering().getDwarfStrSection());
1950 // Get all of the string pool entries and put them in an array by their ID so
1951 // we can sort them.
1952 SmallVector<std::pair<unsigned,
1953 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1955 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1956 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1957 Entries.push_back(std::make_pair(I->second.second, &*I));
1959 array_pod_sort(Entries.begin(), Entries.end());
1961 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1962 // Emit a label for reference from debug information entries.
1963 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1965 // Emit the string itself.
1966 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1970 /// emitDebugLoc - Emit visible names into a debug loc section.
1972 void DwarfDebug::emitDebugLoc() {
1973 if (DotDebugLocEntries.empty())
1976 for (SmallVector<DotDebugLocEntry, 4>::iterator
1977 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1979 DotDebugLocEntry &Entry = *I;
1980 if (I + 1 != DotDebugLocEntries.end())
1984 // Start the dwarf loc section.
1985 Asm->OutStreamer.SwitchSection(
1986 Asm->getObjFileLowering().getDwarfLocSection());
1987 unsigned char Size = Asm->getTargetData().getPointerSize();
1988 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1990 for (SmallVector<DotDebugLocEntry, 4>::iterator
1991 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1992 I != E; ++I, ++index) {
1993 DotDebugLocEntry &Entry = *I;
1994 if (Entry.isMerged()) continue;
1995 if (Entry.isEmpty()) {
1996 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1997 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1998 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2000 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2001 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2002 DIVariable DV(Entry.Variable);
2003 Asm->OutStreamer.AddComment("Loc expr size");
2004 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2005 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2006 Asm->EmitLabelDifference(end, begin, 2);
2007 Asm->OutStreamer.EmitLabel(begin);
2008 if (Entry.isInt()) {
2009 DIBasicType BTy(DV.getType());
2011 (BTy.getEncoding() == dwarf::DW_ATE_signed
2012 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2013 Asm->OutStreamer.AddComment("DW_OP_consts");
2014 Asm->EmitInt8(dwarf::DW_OP_consts);
2015 Asm->EmitSLEB128(Entry.getInt());
2017 Asm->OutStreamer.AddComment("DW_OP_constu");
2018 Asm->EmitInt8(dwarf::DW_OP_constu);
2019 Asm->EmitULEB128(Entry.getInt());
2021 } else if (Entry.isLocation()) {
2022 if (!DV.hasComplexAddress())
2024 Asm->EmitDwarfRegOp(Entry.Loc);
2026 // Complex address entry.
2027 unsigned N = DV.getNumAddrElements();
2029 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2030 if (Entry.Loc.getOffset()) {
2032 Asm->EmitDwarfRegOp(Entry.Loc);
2033 Asm->OutStreamer.AddComment("DW_OP_deref");
2034 Asm->EmitInt8(dwarf::DW_OP_deref);
2035 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2036 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2037 Asm->EmitSLEB128(DV.getAddrElement(1));
2039 // If first address element is OpPlus then emit
2040 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2041 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2042 Asm->EmitDwarfRegOp(Loc);
2046 Asm->EmitDwarfRegOp(Entry.Loc);
2049 // Emit remaining complex address elements.
2050 for (; i < N; ++i) {
2051 uint64_t Element = DV.getAddrElement(i);
2052 if (Element == DIBuilder::OpPlus) {
2053 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2054 Asm->EmitULEB128(DV.getAddrElement(++i));
2055 } else if (Element == DIBuilder::OpDeref)
2056 Asm->EmitInt8(dwarf::DW_OP_deref);
2057 else llvm_unreachable("unknown Opcode found in complex address");
2061 // else ... ignore constant fp. There is not any good way to
2062 // to represent them here in dwarf.
2063 Asm->OutStreamer.EmitLabel(end);
2068 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2070 void DwarfDebug::EmitDebugARanges() {
2071 // Start the dwarf aranges section.
2072 Asm->OutStreamer.SwitchSection(
2073 Asm->getObjFileLowering().getDwarfARangesSection());
2076 /// emitDebugRanges - Emit visible names into a debug ranges section.
2078 void DwarfDebug::emitDebugRanges() {
2079 // Start the dwarf ranges section.
2080 Asm->OutStreamer.SwitchSection(
2081 Asm->getObjFileLowering().getDwarfRangesSection());
2082 unsigned char Size = Asm->getTargetData().getPointerSize();
2083 for (SmallVector<const MCSymbol *, 8>::iterator
2084 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2087 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2089 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2093 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2095 void DwarfDebug::emitDebugMacInfo() {
2096 if (const MCSection *LineInfo =
2097 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2098 // Start the dwarf macinfo section.
2099 Asm->OutStreamer.SwitchSection(LineInfo);
2103 /// emitDebugInlineInfo - Emit inline info using following format.
2105 /// 1. length of section
2106 /// 2. Dwarf version number
2107 /// 3. address size.
2109 /// Entries (one "entry" for each function that was inlined):
2111 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2112 /// otherwise offset into __debug_str for regular function name.
2113 /// 2. offset into __debug_str section for regular function name.
2114 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2115 /// instances for the function.
2117 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2118 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2119 /// __debug_info section, and the low_pc is the starting address for the
2120 /// inlining instance.
2121 void DwarfDebug::emitDebugInlineInfo() {
2122 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2128 Asm->OutStreamer.SwitchSection(
2129 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2131 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2132 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2133 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2135 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2137 Asm->OutStreamer.AddComment("Dwarf Version");
2138 Asm->EmitInt16(dwarf::DWARF_VERSION);
2139 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2140 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2142 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2143 E = InlinedSPNodes.end(); I != E; ++I) {
2145 const MDNode *Node = *I;
2146 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2147 = InlineInfo.find(Node);
2148 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2149 DISubprogram SP(Node);
2150 StringRef LName = SP.getLinkageName();
2151 StringRef Name = SP.getName();
2153 Asm->OutStreamer.AddComment("MIPS linkage name");
2154 if (LName.empty()) {
2155 Asm->OutStreamer.EmitBytes(Name, 0);
2156 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2158 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2159 DwarfStrSectionSym);
2161 Asm->OutStreamer.AddComment("Function name");
2162 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2163 Asm->EmitULEB128(Labels.size(), "Inline count");
2165 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2166 LE = Labels.end(); LI != LE; ++LI) {
2167 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2168 Asm->EmitInt32(LI->second->getOffset());
2170 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2171 Asm->OutStreamer.EmitSymbolValue(LI->first,
2172 Asm->getTargetData().getPointerSize(),0);
2176 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));