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());
386 DbgVariable *AbsVar = DV->getAbstractVariable();
387 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
389 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
390 dwarf::DW_FORM_ref4, AbsDIE);
392 VariableCU->addString(VariableDie, dwarf::DW_AT_name,
393 dwarf::DW_FORM_string, Name);
394 VariableCU->addSourceLine(VariableDie, DV->getVariable());
395 VariableCU->addType(VariableDie, DV->getType());
398 if (DV->isArtificial())
399 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
400 dwarf::DW_FORM_flag, 1);
402 if (Scope->isAbstractScope()) {
403 DV->setDIE(VariableDie);
407 // Add variable address.
409 unsigned Offset = DV->getDotDebugLocOffset();
411 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location,
412 dwarf::DW_FORM_data4,
413 Asm->GetTempSymbol("debug_loc", Offset));
414 DV->setDIE(VariableDie);
418 // Check if variable is described by a DBG_VALUE instruction.
419 if (const MachineInstr *DVInsn = DV->getMInsn()) {
420 bool updated = false;
421 if (DVInsn->getNumOperands() == 3) {
422 if (DVInsn->getOperand(0).isReg()) {
423 const MachineOperand RegOp = DVInsn->getOperand(0);
424 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
425 if (DVInsn->getOperand(1).isImm() &&
426 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
427 unsigned FrameReg = 0;
428 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
430 TFI->getFrameIndexReference(*Asm->MF,
431 DVInsn->getOperand(1).getImm(),
433 MachineLocation Location(FrameReg, Offset);
434 VariableCU->addVariableAddress(DV, VariableDie, Location);
436 } else if (RegOp.getReg())
437 VariableCU->addVariableAddress(DV, VariableDie,
438 MachineLocation(RegOp.getReg()));
441 else if (DVInsn->getOperand(0).isImm())
443 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
445 else if (DVInsn->getOperand(0).isFPImm())
447 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
448 else if (DVInsn->getOperand(0).isCImm())
450 VariableCU->addConstantValue(VariableDie,
451 DVInsn->getOperand(0).getCImm(),
452 DV->getType().isUnsignedDIType());
454 VariableCU->addVariableAddress(DV, VariableDie,
455 Asm->getDebugValueLocation(DVInsn));
459 // If variableDie is not updated then DBG_VALUE instruction does not
460 // have valid variable info.
464 DV->setDIE(VariableDie);
467 // .. else use frame index.
468 int FI = DV->getFrameIndex();
470 unsigned FrameReg = 0;
471 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
473 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
474 MachineLocation Location(FrameReg, Offset);
475 VariableCU->addVariableAddress(DV, VariableDie, Location);
479 DV->setDIE(VariableDie);
484 /// constructScopeDIE - Construct a DIE for this scope.
485 DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) {
486 if (!Scope || !Scope->getScopeNode())
489 SmallVector <DIE *, 8> Children;
491 // Collect arguments for current function.
492 if (LScopes.isCurrentFunctionScope(Scope))
493 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
494 if (DbgVariable *ArgDV = CurrentFnArguments[i])
495 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
496 Children.push_back(Arg);
498 // Collect lexical scope childrens first.
499 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
500 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
501 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
502 Children.push_back(Variable);
503 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
504 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
505 if (DIE *Nested = constructScopeDIE(Scopes[j]))
506 Children.push_back(Nested);
507 DIScope DS(Scope->getScopeNode());
508 DIE *ScopeDIE = NULL;
509 if (Scope->getInlinedAt())
510 ScopeDIE = constructInlinedScopeDIE(Scope);
511 else if (DS.isSubprogram()) {
512 ProcessedSPNodes.insert(DS);
513 if (Scope->isAbstractScope()) {
514 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
515 // Note down abstract DIE.
517 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
520 ScopeDIE = updateSubprogramScopeDIE(DS);
523 // There is no need to emit empty lexical block DIE.
524 if (Children.empty())
526 ScopeDIE = constructLexicalScopeDIE(Scope);
529 if (!ScopeDIE) return NULL;
532 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
533 E = Children.end(); I != E; ++I)
534 ScopeDIE->addChild(*I);
536 if (DS.isSubprogram())
537 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
542 /// GetOrCreateSourceID - Look up the source id with the given directory and
543 /// source file names. If none currently exists, create a new id and insert it
544 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
547 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
549 // If FE did not provide a file name, then assume stdin.
550 if (FileName.empty())
551 return GetOrCreateSourceID("<stdin>", StringRef());
553 // MCStream expects full path name as filename.
554 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
555 SmallString<128> FullPathName = DirName;
556 sys::path::append(FullPathName, FileName);
557 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
558 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
561 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
562 if (Entry.getValue())
563 return Entry.getValue();
565 unsigned SrcId = SourceIdMap.size();
566 Entry.setValue(SrcId);
568 // Print out a .file directive to specify files for .loc directives.
569 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
574 /// constructCompileUnit - Create new CompileUnit for the given
575 /// metadata node with tag DW_TAG_compile_unit.
576 void DwarfDebug::constructCompileUnit(const MDNode *N) {
577 DICompileUnit DIUnit(N);
578 StringRef FN = DIUnit.getFilename();
579 StringRef Dir = DIUnit.getDirectory();
580 unsigned ID = GetOrCreateSourceID(FN, Dir);
582 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
583 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
584 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
585 DIUnit.getProducer());
586 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
587 DIUnit.getLanguage());
588 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
589 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
590 // simplifies debug range entries.
591 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
592 // DW_AT_stmt_list is a offset of line number information for this
593 // compile unit in debug_line section.
594 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
595 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
596 Asm->GetTempSymbol("section_line"));
598 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
601 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
602 if (DIUnit.isOptimized())
603 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
605 StringRef Flags = DIUnit.getFlags();
607 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
610 unsigned RVer = DIUnit.getRunTimeVersion();
612 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
613 dwarf::DW_FORM_data1, RVer);
617 CUMap.insert(std::make_pair(N, NewCU));
620 /// getCompileUnit - Get CompileUnit DIE.
621 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
622 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
624 const MDNode *CUNode = NULL;
625 if (D.isCompileUnit())
627 else if (D.isSubprogram())
628 CUNode = DISubprogram(N).getCompileUnit();
630 CUNode = DIType(N).getCompileUnit();
631 else if (D.isGlobalVariable())
632 CUNode = DIGlobalVariable(N).getCompileUnit();
633 else if (D.isVariable())
634 CUNode = DIVariable(N).getCompileUnit();
635 else if (D.isNameSpace())
636 CUNode = DINameSpace(N).getCompileUnit();
638 CUNode = DIFile(N).getCompileUnit();
642 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
643 = CUMap.find(CUNode);
644 if (I == CUMap.end())
649 /// constructGlobalVariableDIE - Construct global variable DIE.
650 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
651 DIGlobalVariable GV(N);
653 // If debug information is malformed then ignore it.
654 if (GV.Verify() == false)
657 // Check for pre-existence.
658 CompileUnit *TheCU = getCompileUnit(N);
659 TheCU->createGlobalVariableDIE(N);
663 /// construct SubprogramDIE - Construct subprogram DIE.
664 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
667 // Check for pre-existence.
668 CompileUnit *TheCU = getCompileUnit(N);
669 if (TheCU->getDIE(N))
672 if (!SP.isDefinition())
673 // This is a method declaration which will be handled while constructing
677 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
680 TheCU->insertDIE(N, SubprogramDie);
682 // Add to context owner.
683 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
686 TheCU->addGlobal(SP.getName(), SubprogramDie);
691 /// beginModule - Emit all Dwarf sections that should come prior to the
692 /// content. Create global DIEs and emit initial debug info sections.
693 /// This is invoked by the target AsmPrinter.
694 void DwarfDebug::beginModule(Module *M) {
695 if (DisableDebugInfoPrinting)
698 // If module has named metadata anchors then use them, otherwise scan the
699 // module using debug info finder to collect debug info.
700 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
703 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
704 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
705 if (!GV_Nodes && !SP_Nodes)
706 // If there are not any global variables or any functions then
707 // there is not any debug info in this module.
710 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
711 constructCompileUnit(CU_Nodes->getOperand(i));
714 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
715 constructGlobalVariableDIE(GV_Nodes->getOperand(i));
718 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
719 constructSubprogramDIE(SP_Nodes->getOperand(i));
723 DebugInfoFinder DbgFinder;
724 DbgFinder.processModule(*M);
726 bool HasDebugInfo = false;
727 // Scan all the compile-units to see if there are any marked as the main
728 // unit. If not, we do not generate debug info.
729 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
730 E = DbgFinder.compile_unit_end(); I != E; ++I) {
731 if (DICompileUnit(*I).isMain()) {
736 if (!HasDebugInfo) return;
738 // Create all the compile unit DIEs.
739 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
740 E = DbgFinder.compile_unit_end(); I != E; ++I)
741 constructCompileUnit(*I);
743 // Create DIEs for each global variable.
744 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
745 E = DbgFinder.global_variable_end(); I != E; ++I)
746 constructGlobalVariableDIE(*I);
748 // Create DIEs for each subprogram.
749 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
750 E = DbgFinder.subprogram_end(); I != E; ++I)
751 constructSubprogramDIE(*I);
754 // Tell MMI that we have debug info.
755 MMI->setDebugInfoAvailability(true);
757 // Emit initial sections.
761 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
762 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
763 DIType Ty(NMD->getOperand(i));
764 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
767 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
768 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
769 DIType Ty(NMD->getOperand(i));
770 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
773 // Prime section data.
774 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
777 /// endModule - Emit all Dwarf sections that should come after the content.
779 void DwarfDebug::endModule() {
780 if (!FirstCU) return;
781 const Module *M = MMI->getModule();
782 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
783 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
784 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
785 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
786 DISubprogram SP(AllSPs->getOperand(SI));
787 if (!SP.Verify()) continue;
789 // Collect info for variables that were optimized out.
790 if (!SP.isDefinition()) continue;
791 StringRef FName = SP.getLinkageName();
793 FName = SP.getName();
794 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
796 unsigned E = NMD->getNumOperands();
798 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
800 DeadFnScopeMap[SP] = Scope;
801 SmallVector<DbgVariable, 8> Variables;
802 for (unsigned I = 0; I != E; ++I) {
803 DIVariable DV(NMD->getOperand(I));
804 if (!DV.Verify()) continue;
805 Variables.push_back(DbgVariable(DV, NULL));
808 // Construct subprogram DIE and add variables DIEs.
809 constructSubprogramDIE(SP);
810 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
811 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
812 if (DIE *VariableDIE = constructVariableDIE(&Variables[i], Scope))
813 ScopeDIE->addChild(VariableDIE);
818 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
819 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
820 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
822 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
825 // Emit DW_AT_containing_type attribute to connect types with their
826 // vtable holding type.
827 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
828 CUE = CUMap.end(); CUI != CUE; ++CUI) {
829 CompileUnit *TheCU = CUI->second;
830 TheCU->constructContainingTypeDIEs();
833 // Standard sections final addresses.
834 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
835 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
836 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
837 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
839 // End text sections.
840 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
841 Asm->OutStreamer.SwitchSection(SectionMap[i]);
842 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
845 // Compute DIE offsets and sizes.
846 computeSizeAndOffsets();
848 // Emit all the DIEs into a debug info section
851 // Corresponding abbreviations into a abbrev section.
854 // Emit info into a debug pubnames section.
857 // Emit info into a debug pubtypes section.
860 // Emit info into a debug loc section.
863 // Emit info into a debug aranges section.
866 // Emit info into a debug ranges section.
869 // Emit info into a debug macinfo section.
873 emitDebugInlineInfo();
875 // Emit info into a debug str section.
879 DeleteContainerSeconds(DeadFnScopeMap);
880 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
881 E = CUMap.end(); I != E; ++I)
883 FirstCU = NULL; // Reset for the next Module, if any.
886 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
887 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
889 LLVMContext &Ctx = DV->getContext();
890 // More then one inlined variable corresponds to one abstract variable.
891 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
892 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
894 return AbsDbgVariable;
896 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
900 AbsDbgVariable = new DbgVariable(Var, NULL);
901 addScopeVariable(Scope, AbsDbgVariable);
902 AbstractVariables[Var] = AbsDbgVariable;
903 return AbsDbgVariable;
906 /// addCurrentFnArgument - If Var is a current function argument then add
907 /// it to CurrentFnArguments list.
908 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
909 DbgVariable *Var, LexicalScope *Scope) {
910 if (!LScopes.isCurrentFunctionScope(Scope))
912 DIVariable DV = Var->getVariable();
913 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
915 unsigned ArgNo = DV.getArgNumber();
919 size_t Size = CurrentFnArguments.size();
921 CurrentFnArguments.resize(MF->getFunction()->arg_size());
922 // llvm::Function argument size is not good indicator of how many
923 // arguments does the function have at source level.
925 CurrentFnArguments.resize(ArgNo * 2);
926 CurrentFnArguments[ArgNo - 1] = Var;
930 /// collectVariableInfoFromMMITable - Collect variable information from
931 /// side table maintained by MMI.
933 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
934 SmallPtrSet<const MDNode *, 16> &Processed) {
935 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
936 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
937 VE = VMap.end(); VI != VE; ++VI) {
938 const MDNode *Var = VI->first;
940 Processed.insert(Var);
942 const std::pair<unsigned, DebugLoc> &VP = VI->second;
944 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
946 // If variable scope is not found then skip this variable.
950 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
951 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
952 RegVar->setFrameIndex(VP.first);
953 if (!addCurrentFnArgument(MF, RegVar, Scope))
954 addScopeVariable(Scope, RegVar);
956 AbsDbgVariable->setFrameIndex(VP.first);
960 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
961 /// DBG_VALUE instruction, is in a defined reg.
962 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
963 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
964 return MI->getNumOperands() == 3 &&
965 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
966 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
969 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
971 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
972 const MCSymbol *FLabel,
973 const MCSymbol *SLabel,
974 const MachineInstr *MI) {
975 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
977 if (MI->getNumOperands() != 3) {
978 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
979 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
981 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
982 MachineLocation MLoc;
983 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
984 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
986 if (MI->getOperand(0).isImm())
987 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
988 if (MI->getOperand(0).isFPImm())
989 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
990 if (MI->getOperand(0).isCImm())
991 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
993 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
994 return DotDebugLocEntry();
997 /// collectVariableInfo - Find variables for each lexical scope.
999 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1000 SmallPtrSet<const MDNode *, 16> &Processed) {
1002 /// collection info from MMI table.
1003 collectVariableInfoFromMMITable(MF, Processed);
1005 for (SmallVectorImpl<const MDNode*>::const_iterator
1006 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1008 const MDNode *Var = *UVI;
1009 if (Processed.count(Var))
1012 // History contains relevant DBG_VALUE instructions for Var and instructions
1014 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1015 if (History.empty())
1017 const MachineInstr *MInsn = History.front();
1020 LexicalScope *Scope = NULL;
1021 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1022 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1023 Scope = LScopes.getCurrentFunctionScope();
1025 if (DV.getVersion() <= LLVMDebugVersion9)
1026 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1028 if (MDNode *IA = DV.getInlinedAt())
1029 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1031 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1034 // If variable scope is not found then skip this variable.
1038 Processed.insert(DV);
1039 assert(MInsn->isDebugValue() && "History must begin with debug value");
1040 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1041 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1042 if (!addCurrentFnArgument(MF, RegVar, Scope))
1043 addScopeVariable(Scope, RegVar);
1045 AbsVar->setMInsn(MInsn);
1047 // Simple ranges that are fully coalesced.
1048 if (History.size() <= 1 || (History.size() == 2 &&
1049 MInsn->isIdenticalTo(History.back()))) {
1050 RegVar->setMInsn(MInsn);
1054 // handle multiple DBG_VALUE instructions describing one variable.
1055 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1057 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1058 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1059 const MachineInstr *Begin = *HI;
1060 assert(Begin->isDebugValue() && "Invalid History entry");
1062 // Check if DBG_VALUE is truncating a range.
1063 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1064 && !Begin->getOperand(0).getReg())
1067 // Compute the range for a register location.
1068 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1069 const MCSymbol *SLabel = 0;
1072 // If Begin is the last instruction in History then its value is valid
1073 // until the end of the function.
1074 SLabel = FunctionEndSym;
1076 const MachineInstr *End = HI[1];
1077 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1078 << "\t" << *Begin << "\t" << *End << "\n");
1079 if (End->isDebugValue())
1080 SLabel = getLabelBeforeInsn(End);
1082 // End is a normal instruction clobbering the range.
1083 SLabel = getLabelAfterInsn(End);
1084 assert(SLabel && "Forgot label after clobber instruction");
1089 // The value is valid until the next DBG_VALUE or clobber.
1090 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1092 DotDebugLocEntries.push_back(DotDebugLocEntry());
1095 // Collect info for variables that were optimized out.
1096 const Function *F = MF->getFunction();
1097 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1098 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1099 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1100 if (!DV || !Processed.insert(DV))
1102 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1103 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1108 /// getLabelBeforeInsn - Return Label preceding the instruction.
1109 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1110 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1111 assert(Label && "Didn't insert label before instruction");
1115 /// getLabelAfterInsn - Return Label immediately following the instruction.
1116 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1117 return LabelsAfterInsn.lookup(MI);
1120 /// beginInstruction - Process beginning of an instruction.
1121 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1122 // Check if source location changes, but ignore DBG_VALUE locations.
1123 if (!MI->isDebugValue()) {
1124 DebugLoc DL = MI->getDebugLoc();
1125 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1126 unsigned Flags = DWARF2_FLAG_IS_STMT;
1128 if (DL == PrologEndLoc) {
1129 Flags |= DWARF2_FLAG_PROLOGUE_END;
1130 PrologEndLoc = DebugLoc();
1132 if (!DL.isUnknown()) {
1133 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1134 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1136 recordSourceLine(0, 0, 0, 0);
1140 // Insert labels where requested.
1141 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1142 LabelsBeforeInsn.find(MI);
1145 if (I == LabelsBeforeInsn.end())
1148 // Label already assigned.
1153 PrevLabel = MMI->getContext().CreateTempSymbol();
1154 Asm->OutStreamer.EmitLabel(PrevLabel);
1156 I->second = PrevLabel;
1159 /// endInstruction - Process end of an instruction.
1160 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1161 // Don't create a new label after DBG_VALUE instructions.
1162 // They don't generate code.
1163 if (!MI->isDebugValue())
1166 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1167 LabelsAfterInsn.find(MI);
1170 if (I == LabelsAfterInsn.end())
1173 // Label already assigned.
1177 // We need a label after this instruction.
1179 PrevLabel = MMI->getContext().CreateTempSymbol();
1180 Asm->OutStreamer.EmitLabel(PrevLabel);
1182 I->second = PrevLabel;
1185 /// identifyScopeMarkers() -
1186 /// Each LexicalScope has first instruction and last instruction to mark
1187 /// beginning and end of a scope respectively. Create an inverse map that list
1188 /// scopes starts (and ends) with an instruction. One instruction may start (or
1189 /// end) multiple scopes. Ignore scopes that are not reachable.
1190 void DwarfDebug::identifyScopeMarkers() {
1191 SmallVector<LexicalScope *, 4> WorkList;
1192 WorkList.push_back(LScopes.getCurrentFunctionScope());
1193 while (!WorkList.empty()) {
1194 LexicalScope *S = WorkList.pop_back_val();
1196 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1197 if (!Children.empty())
1198 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1199 SE = Children.end(); SI != SE; ++SI)
1200 WorkList.push_back(*SI);
1202 if (S->isAbstractScope())
1205 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1208 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1209 RE = Ranges.end(); RI != RE; ++RI) {
1210 assert(RI->first && "InsnRange does not have first instruction!");
1211 assert(RI->second && "InsnRange does not have second instruction!");
1212 requestLabelBeforeInsn(RI->first);
1213 requestLabelAfterInsn(RI->second);
1218 /// getScopeNode - Get MDNode for DebugLoc's scope.
1219 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1220 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1221 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1222 return DL.getScope(Ctx);
1225 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1226 /// line number info for the function.
1227 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1228 const MDNode *Scope = getScopeNode(DL, Ctx);
1229 DISubprogram SP = getDISubprogram(Scope);
1231 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1235 /// beginFunction - Gather pre-function debug information. Assumes being
1236 /// emitted immediately after the function entry point.
1237 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1238 if (!MMI->hasDebugInfo()) return;
1239 LScopes.initialize(*MF);
1240 if (LScopes.empty()) return;
1241 identifyScopeMarkers();
1243 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1244 Asm->getFunctionNumber());
1245 // Assumes in correct section after the entry point.
1246 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1248 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1250 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1251 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1252 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1254 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1256 bool AtBlockEntry = true;
1257 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1259 const MachineInstr *MI = II;
1261 if (MI->isDebugValue()) {
1262 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1264 // Keep track of user variables.
1266 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1268 // Variable is in a register, we need to check for clobbers.
1269 if (isDbgValueInDefinedReg(MI))
1270 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1272 // Check the history of this variable.
1273 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1274 if (History.empty()) {
1275 UserVariables.push_back(Var);
1276 // The first mention of a function argument gets the FunctionBeginSym
1277 // label, so arguments are visible when breaking at function entry.
1279 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1280 DISubprogram(getDISubprogram(DV.getContext()))
1281 .describes(MF->getFunction()))
1282 LabelsBeforeInsn[MI] = FunctionBeginSym;
1284 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1285 const MachineInstr *Prev = History.back();
1286 if (Prev->isDebugValue()) {
1287 // Coalesce identical entries at the end of History.
1288 if (History.size() >= 2 &&
1289 Prev->isIdenticalTo(History[History.size() - 2])) {
1290 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1292 << "\t" << *History[History.size() - 2] << "\n");
1296 // Terminate old register assignments that don't reach MI;
1297 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1298 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1299 isDbgValueInDefinedReg(Prev)) {
1300 // Previous register assignment needs to terminate at the end of
1302 MachineBasicBlock::const_iterator LastMI =
1303 PrevMBB->getLastNonDebugInstr();
1304 if (LastMI == PrevMBB->end()) {
1305 // Drop DBG_VALUE for empty range.
1306 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1307 << "\t" << *Prev << "\n");
1311 // Terminate after LastMI.
1312 History.push_back(LastMI);
1317 History.push_back(MI);
1319 // Not a DBG_VALUE instruction.
1321 AtBlockEntry = false;
1323 // First known non DBG_VALUE location marks beginning of function
1325 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1326 PrologEndLoc = MI->getDebugLoc();
1328 // Check if the instruction clobbers any registers with debug vars.
1329 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1330 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1331 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1333 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1334 unsigned Reg = *AI; ++AI) {
1335 const MDNode *Var = LiveUserVar[Reg];
1338 // Reg is now clobbered.
1339 LiveUserVar[Reg] = 0;
1341 // Was MD last defined by a DBG_VALUE referring to Reg?
1342 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1343 if (HistI == DbgValues.end())
1345 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1346 if (History.empty())
1348 const MachineInstr *Prev = History.back();
1349 // Sanity-check: Register assignments are terminated at the end of
1351 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1353 // Is the variable still in Reg?
1354 if (!isDbgValueInDefinedReg(Prev) ||
1355 Prev->getOperand(0).getReg() != Reg)
1357 // Var is clobbered. Make sure the next instruction gets a label.
1358 History.push_back(MI);
1365 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1367 SmallVectorImpl<const MachineInstr*> &History = I->second;
1368 if (History.empty())
1371 // Make sure the final register assignments are terminated.
1372 const MachineInstr *Prev = History.back();
1373 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1374 const MachineBasicBlock *PrevMBB = Prev->getParent();
1375 MachineBasicBlock::const_iterator LastMI =
1376 PrevMBB->getLastNonDebugInstr();
1377 if (LastMI == PrevMBB->end())
1378 // Drop DBG_VALUE for empty range.
1381 // Terminate after LastMI.
1382 History.push_back(LastMI);
1385 // Request labels for the full history.
1386 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1387 const MachineInstr *MI = History[i];
1388 if (MI->isDebugValue())
1389 requestLabelBeforeInsn(MI);
1391 requestLabelAfterInsn(MI);
1395 PrevInstLoc = DebugLoc();
1396 PrevLabel = FunctionBeginSym;
1398 // Record beginning of function.
1399 if (!PrologEndLoc.isUnknown()) {
1400 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1401 MF->getFunction()->getContext());
1402 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1403 FnStartDL.getScope(MF->getFunction()->getContext()),
1404 DWARF2_FLAG_IS_STMT);
1408 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1409 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1410 ScopeVariables[LS].push_back(Var);
1411 // Vars.push_back(Var);
1414 /// endFunction - Gather and emit post-function debug information.
1416 void DwarfDebug::endFunction(const MachineFunction *MF) {
1417 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1419 // Define end label for subprogram.
1420 FunctionEndSym = Asm->GetTempSymbol("func_end",
1421 Asm->getFunctionNumber());
1422 // Assumes in correct section after the entry point.
1423 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1425 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1426 collectVariableInfo(MF, ProcessedVars);
1428 // Construct abstract scopes.
1429 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1430 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1431 LexicalScope *AScope = AList[i];
1432 DISubprogram SP(AScope->getScopeNode());
1434 // Collect info for variables that were optimized out.
1435 StringRef FName = SP.getLinkageName();
1437 FName = SP.getName();
1438 if (NamedMDNode *NMD =
1439 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1440 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1441 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1442 if (!DV || !ProcessedVars.insert(DV))
1444 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1445 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1449 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1450 constructScopeDIE(AScope);
1453 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope());
1455 if (!DisableFramePointerElim(*MF)) {
1456 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1457 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
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.isLexicalBlock()) {
1502 DILexicalBlock DB(S);
1503 Fn = DB.getFilename();
1504 Dir = DB.getDirectory();
1506 assert(0 && "Unexpected scope info");
1508 Src = GetOrCreateSourceID(Fn, Dir);
1510 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1513 //===----------------------------------------------------------------------===//
1515 //===----------------------------------------------------------------------===//
1517 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1520 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1521 // Get the children.
1522 const std::vector<DIE *> &Children = Die->getChildren();
1524 // If not last sibling and has children then add sibling offset attribute.
1525 if (!Last && !Children.empty())
1526 Die->addSiblingOffset(DIEValueAllocator);
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 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1581 /// temporary label to it if SymbolStem is specified.
1582 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1583 const char *SymbolStem = 0) {
1584 Asm->OutStreamer.SwitchSection(Section);
1585 if (!SymbolStem) return 0;
1587 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1588 Asm->OutStreamer.EmitLabel(TmpSym);
1592 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1593 /// the start of each one.
1594 void DwarfDebug::EmitSectionLabels() {
1595 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1597 // Dwarf sections base addresses.
1598 DwarfInfoSectionSym =
1599 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1600 DwarfAbbrevSectionSym =
1601 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1602 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1604 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1605 EmitSectionSym(Asm, MacroInfo);
1607 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1608 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1609 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1610 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1611 DwarfStrSectionSym =
1612 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1613 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1616 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1617 "section_debug_loc");
1619 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1620 EmitSectionSym(Asm, TLOF.getDataSection());
1623 /// emitDIE - Recursively emits a debug information entry.
1625 void DwarfDebug::emitDIE(DIE *Die) {
1626 // Get the abbreviation for this DIE.
1627 unsigned AbbrevNumber = Die->getAbbrevNumber();
1628 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1630 // Emit the code (index) for the abbreviation.
1631 if (Asm->isVerbose())
1632 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1633 Twine::utohexstr(Die->getOffset()) + ":0x" +
1634 Twine::utohexstr(Die->getSize()) + " " +
1635 dwarf::TagString(Abbrev->getTag()));
1636 Asm->EmitULEB128(AbbrevNumber);
1638 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1639 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1641 // Emit the DIE attribute values.
1642 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1643 unsigned Attr = AbbrevData[i].getAttribute();
1644 unsigned Form = AbbrevData[i].getForm();
1645 assert(Form && "Too many attributes for DIE (check abbreviation)");
1647 if (Asm->isVerbose())
1648 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1651 case dwarf::DW_AT_sibling:
1652 Asm->EmitInt32(Die->getSiblingOffset());
1654 case dwarf::DW_AT_abstract_origin: {
1655 DIEEntry *E = cast<DIEEntry>(Values[i]);
1656 DIE *Origin = E->getEntry();
1657 unsigned Addr = Origin->getOffset();
1658 Asm->EmitInt32(Addr);
1661 case dwarf::DW_AT_ranges: {
1662 // DW_AT_range Value encodes offset in debug_range section.
1663 DIEInteger *V = cast<DIEInteger>(Values[i]);
1665 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1666 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1670 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1672 DwarfDebugRangeSectionSym,
1677 case dwarf::DW_AT_location: {
1678 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1679 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1681 Values[i]->EmitValue(Asm, Form);
1684 case dwarf::DW_AT_accessibility: {
1685 if (Asm->isVerbose()) {
1686 DIEInteger *V = cast<DIEInteger>(Values[i]);
1687 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1689 Values[i]->EmitValue(Asm, Form);
1693 // Emit an attribute using the defined form.
1694 Values[i]->EmitValue(Asm, Form);
1699 // Emit the DIE children if any.
1700 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1701 const std::vector<DIE *> &Children = Die->getChildren();
1703 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1704 emitDIE(Children[j]);
1706 if (Asm->isVerbose())
1707 Asm->OutStreamer.AddComment("End Of Children Mark");
1712 /// emitDebugInfo - Emit the debug info section.
1714 void DwarfDebug::emitDebugInfo() {
1715 // Start debug info section.
1716 Asm->OutStreamer.SwitchSection(
1717 Asm->getObjFileLowering().getDwarfInfoSection());
1718 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1719 E = CUMap.end(); I != E; ++I) {
1720 CompileUnit *TheCU = I->second;
1721 DIE *Die = TheCU->getCUDie();
1723 // Emit the compile units header.
1724 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1727 // Emit size of content not including length itself
1728 unsigned ContentSize = Die->getSize() +
1729 sizeof(int16_t) + // DWARF version number
1730 sizeof(int32_t) + // Offset Into Abbrev. Section
1731 sizeof(int8_t); // Pointer Size (in bytes)
1733 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1734 Asm->EmitInt32(ContentSize);
1735 Asm->OutStreamer.AddComment("DWARF version number");
1736 Asm->EmitInt16(dwarf::DWARF_VERSION);
1737 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1738 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1739 DwarfAbbrevSectionSym);
1740 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1741 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1744 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1748 /// emitAbbreviations - Emit the abbreviation section.
1750 void DwarfDebug::emitAbbreviations() const {
1751 // Check to see if it is worth the effort.
1752 if (!Abbreviations.empty()) {
1753 // Start the debug abbrev section.
1754 Asm->OutStreamer.SwitchSection(
1755 Asm->getObjFileLowering().getDwarfAbbrevSection());
1757 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1759 // For each abbrevation.
1760 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1761 // Get abbreviation data
1762 const DIEAbbrev *Abbrev = Abbreviations[i];
1764 // Emit the abbrevations code (base 1 index.)
1765 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1767 // Emit the abbreviations data.
1771 // Mark end of abbreviations.
1772 Asm->EmitULEB128(0, "EOM(3)");
1774 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1778 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1779 /// the line matrix.
1781 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1782 // Define last address of section.
1783 Asm->OutStreamer.AddComment("Extended Op");
1786 Asm->OutStreamer.AddComment("Op size");
1787 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1788 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1789 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1791 Asm->OutStreamer.AddComment("Section end label");
1793 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1794 Asm->getTargetData().getPointerSize(),
1797 // Mark end of matrix.
1798 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1804 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1806 void DwarfDebug::emitDebugPubNames() {
1807 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1808 E = CUMap.end(); I != E; ++I) {
1809 CompileUnit *TheCU = I->second;
1810 // Start the dwarf pubnames section.
1811 Asm->OutStreamer.SwitchSection(
1812 Asm->getObjFileLowering().getDwarfPubNamesSection());
1814 Asm->OutStreamer.AddComment("Length of Public Names Info");
1815 Asm->EmitLabelDifference(
1816 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1817 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1819 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1822 Asm->OutStreamer.AddComment("DWARF Version");
1823 Asm->EmitInt16(dwarf::DWARF_VERSION);
1825 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1826 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1827 DwarfInfoSectionSym);
1829 Asm->OutStreamer.AddComment("Compilation Unit Length");
1830 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1831 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1834 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1835 for (StringMap<DIE*>::const_iterator
1836 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1837 const char *Name = GI->getKeyData();
1838 DIE *Entity = GI->second;
1840 Asm->OutStreamer.AddComment("DIE offset");
1841 Asm->EmitInt32(Entity->getOffset());
1843 if (Asm->isVerbose())
1844 Asm->OutStreamer.AddComment("External Name");
1845 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1848 Asm->OutStreamer.AddComment("End Mark");
1850 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1855 void DwarfDebug::emitDebugPubTypes() {
1856 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1857 E = CUMap.end(); I != E; ++I) {
1858 CompileUnit *TheCU = I->second;
1859 // Start the dwarf pubnames section.
1860 Asm->OutStreamer.SwitchSection(
1861 Asm->getObjFileLowering().getDwarfPubTypesSection());
1862 Asm->OutStreamer.AddComment("Length of Public Types Info");
1863 Asm->EmitLabelDifference(
1864 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1865 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1867 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1870 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1871 Asm->EmitInt16(dwarf::DWARF_VERSION);
1873 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1874 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1875 DwarfInfoSectionSym);
1877 Asm->OutStreamer.AddComment("Compilation Unit Length");
1878 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1879 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1882 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1883 for (StringMap<DIE*>::const_iterator
1884 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1885 const char *Name = GI->getKeyData();
1886 DIE *Entity = GI->second;
1888 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1889 Asm->EmitInt32(Entity->getOffset());
1891 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1892 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1895 Asm->OutStreamer.AddComment("End Mark");
1897 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1902 /// emitDebugStr - Emit visible names into a debug str section.
1904 void DwarfDebug::emitDebugStr() {
1905 // Check to see if it is worth the effort.
1906 if (StringPool.empty()) return;
1908 // Start the dwarf str section.
1909 Asm->OutStreamer.SwitchSection(
1910 Asm->getObjFileLowering().getDwarfStrSection());
1912 // Get all of the string pool entries and put them in an array by their ID so
1913 // we can sort them.
1914 SmallVector<std::pair<unsigned,
1915 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1917 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1918 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1919 Entries.push_back(std::make_pair(I->second.second, &*I));
1921 array_pod_sort(Entries.begin(), Entries.end());
1923 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1924 // Emit a label for reference from debug information entries.
1925 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1927 // Emit the string itself.
1928 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1932 /// emitDebugLoc - Emit visible names into a debug loc section.
1934 void DwarfDebug::emitDebugLoc() {
1935 if (DotDebugLocEntries.empty())
1938 for (SmallVector<DotDebugLocEntry, 4>::iterator
1939 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1941 DotDebugLocEntry &Entry = *I;
1942 if (I + 1 != DotDebugLocEntries.end())
1946 // Start the dwarf loc section.
1947 Asm->OutStreamer.SwitchSection(
1948 Asm->getObjFileLowering().getDwarfLocSection());
1949 unsigned char Size = Asm->getTargetData().getPointerSize();
1950 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1952 for (SmallVector<DotDebugLocEntry, 4>::iterator
1953 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1954 I != E; ++I, ++index) {
1955 DotDebugLocEntry &Entry = *I;
1956 if (Entry.isMerged()) continue;
1957 if (Entry.isEmpty()) {
1958 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1959 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1960 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1962 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1963 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1964 DIVariable DV(Entry.Variable);
1965 Asm->OutStreamer.AddComment("Loc expr size");
1966 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1967 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1968 Asm->EmitLabelDifference(end, begin, 2);
1969 Asm->OutStreamer.EmitLabel(begin);
1970 if (Entry.isInt()) {
1971 DIBasicType BTy(DV.getType());
1973 (BTy.getEncoding() == dwarf::DW_ATE_signed
1974 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1975 Asm->OutStreamer.AddComment("DW_OP_consts");
1976 Asm->EmitInt8(dwarf::DW_OP_consts);
1977 Asm->EmitSLEB128(Entry.getInt());
1979 Asm->OutStreamer.AddComment("DW_OP_constu");
1980 Asm->EmitInt8(dwarf::DW_OP_constu);
1981 Asm->EmitULEB128(Entry.getInt());
1983 } else if (Entry.isLocation()) {
1984 if (!DV.hasComplexAddress())
1986 Asm->EmitDwarfRegOp(Entry.Loc);
1988 // Complex address entry.
1989 unsigned N = DV.getNumAddrElements();
1991 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1992 if (Entry.Loc.getOffset()) {
1994 Asm->EmitDwarfRegOp(Entry.Loc);
1995 Asm->OutStreamer.AddComment("DW_OP_deref");
1996 Asm->EmitInt8(dwarf::DW_OP_deref);
1997 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1998 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1999 Asm->EmitSLEB128(DV.getAddrElement(1));
2001 // If first address element is OpPlus then emit
2002 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2003 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2004 Asm->EmitDwarfRegOp(Loc);
2008 Asm->EmitDwarfRegOp(Entry.Loc);
2011 // Emit remaining complex address elements.
2012 for (; i < N; ++i) {
2013 uint64_t Element = DV.getAddrElement(i);
2014 if (Element == DIBuilder::OpPlus) {
2015 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2016 Asm->EmitULEB128(DV.getAddrElement(++i));
2017 } else if (Element == DIBuilder::OpDeref)
2018 Asm->EmitInt8(dwarf::DW_OP_deref);
2019 else llvm_unreachable("unknown Opcode found in complex address");
2023 // else ... ignore constant fp. There is not any good way to
2024 // to represent them here in dwarf.
2025 Asm->OutStreamer.EmitLabel(end);
2030 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2032 void DwarfDebug::EmitDebugARanges() {
2033 // Start the dwarf aranges section.
2034 Asm->OutStreamer.SwitchSection(
2035 Asm->getObjFileLowering().getDwarfARangesSection());
2038 /// emitDebugRanges - Emit visible names into a debug ranges section.
2040 void DwarfDebug::emitDebugRanges() {
2041 // Start the dwarf ranges section.
2042 Asm->OutStreamer.SwitchSection(
2043 Asm->getObjFileLowering().getDwarfRangesSection());
2044 unsigned char Size = Asm->getTargetData().getPointerSize();
2045 for (SmallVector<const MCSymbol *, 8>::iterator
2046 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2049 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2051 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2055 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2057 void DwarfDebug::emitDebugMacInfo() {
2058 if (const MCSection *LineInfo =
2059 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2060 // Start the dwarf macinfo section.
2061 Asm->OutStreamer.SwitchSection(LineInfo);
2065 /// emitDebugInlineInfo - Emit inline info using following format.
2067 /// 1. length of section
2068 /// 2. Dwarf version number
2069 /// 3. address size.
2071 /// Entries (one "entry" for each function that was inlined):
2073 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2074 /// otherwise offset into __debug_str for regular function name.
2075 /// 2. offset into __debug_str section for regular function name.
2076 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2077 /// instances for the function.
2079 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2080 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2081 /// __debug_info section, and the low_pc is the starting address for the
2082 /// inlining instance.
2083 void DwarfDebug::emitDebugInlineInfo() {
2084 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2090 Asm->OutStreamer.SwitchSection(
2091 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2093 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2094 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2095 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2097 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2099 Asm->OutStreamer.AddComment("Dwarf Version");
2100 Asm->EmitInt16(dwarf::DWARF_VERSION);
2101 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2102 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2104 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2105 E = InlinedSPNodes.end(); I != E; ++I) {
2107 const MDNode *Node = *I;
2108 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2109 = InlineInfo.find(Node);
2110 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2111 DISubprogram SP(Node);
2112 StringRef LName = SP.getLinkageName();
2113 StringRef Name = SP.getName();
2115 Asm->OutStreamer.AddComment("MIPS linkage name");
2116 if (LName.empty()) {
2117 Asm->OutStreamer.EmitBytes(Name, 0);
2118 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2120 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2121 DwarfStrSectionSym);
2123 Asm->OutStreamer.AddComment("Function name");
2124 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2125 Asm->EmitULEB128(Labels.size(), "Inline count");
2127 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2128 LE = Labels.end(); LI != LE; ++LI) {
2129 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2130 Asm->EmitInt32(LI->second->getOffset());
2132 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2133 Asm->OutStreamer.EmitSymbolValue(LI->first,
2134 Asm->getTargetData().getPointerSize(),0);
2138 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));