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);
415 UseDotDebugLocEntry.insert(VariableDie);
419 // Check if variable is described by a DBG_VALUE instruction.
420 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
421 DbgVariableToDbgInstMap.find(DV);
422 if (DVI != DbgVariableToDbgInstMap.end()) {
423 const MachineInstr *DVInsn = DVI->second;
424 bool updated = false;
425 if (DVInsn->getNumOperands() == 3) {
426 if (DVInsn->getOperand(0).isReg()) {
427 const MachineOperand RegOp = DVInsn->getOperand(0);
428 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
429 if (DVInsn->getOperand(1).isImm() &&
430 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
431 unsigned FrameReg = 0;
432 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
434 TFI->getFrameIndexReference(*Asm->MF,
435 DVInsn->getOperand(1).getImm(),
437 MachineLocation Location(FrameReg, Offset);
438 VariableCU->addVariableAddress(DV, VariableDie, Location);
440 } else if (RegOp.getReg())
441 VariableCU->addVariableAddress(DV, VariableDie,
442 MachineLocation(RegOp.getReg()));
445 else if (DVInsn->getOperand(0).isImm())
447 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
449 else if (DVInsn->getOperand(0).isFPImm())
451 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
452 else if (DVInsn->getOperand(0).isCImm())
454 VariableCU->addConstantValue(VariableDie,
455 DVInsn->getOperand(0).getCImm(),
456 DV->getType().isUnsignedDIType());
458 VariableCU->addVariableAddress(DV, VariableDie,
459 Asm->getDebugValueLocation(DVInsn));
463 // If variableDie is not updated then DBG_VALUE instruction does not
464 // have valid variable info.
468 DV->setDIE(VariableDie);
472 // .. else use frame index, if available.
474 if (findVariableFrameIndex(DV, &FI)) {
475 unsigned FrameReg = 0;
476 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
478 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
479 MachineLocation Location(FrameReg, Offset);
480 VariableCU->addVariableAddress(DV, VariableDie, Location);
483 DV->setDIE(VariableDie);
488 /// constructScopeDIE - Construct a DIE for this scope.
489 DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) {
490 if (!Scope || !Scope->getScopeNode())
493 SmallVector <DIE *, 8> Children;
495 // Collect arguments for current function.
496 if (LScopes.isCurrentFunctionScope(Scope))
497 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
498 if (DbgVariable *ArgDV = CurrentFnArguments[i])
499 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
500 Children.push_back(Arg);
502 // Collect lexical scope childrens first.
503 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
504 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
505 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
506 Children.push_back(Variable);
507 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
508 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
509 if (DIE *Nested = constructScopeDIE(Scopes[j]))
510 Children.push_back(Nested);
511 DIScope DS(Scope->getScopeNode());
512 DIE *ScopeDIE = NULL;
513 if (Scope->getInlinedAt())
514 ScopeDIE = constructInlinedScopeDIE(Scope);
515 else if (DS.isSubprogram()) {
516 ProcessedSPNodes.insert(DS);
517 if (Scope->isAbstractScope()) {
518 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
519 // Note down abstract DIE.
521 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
524 ScopeDIE = updateSubprogramScopeDIE(DS);
527 // There is no need to emit empty lexical block DIE.
528 if (Children.empty())
530 ScopeDIE = constructLexicalScopeDIE(Scope);
533 if (!ScopeDIE) return NULL;
536 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
537 E = Children.end(); I != E; ++I)
538 ScopeDIE->addChild(*I);
540 if (DS.isSubprogram())
541 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
546 /// GetOrCreateSourceID - Look up the source id with the given directory and
547 /// source file names. If none currently exists, create a new id and insert it
548 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
551 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
553 // If FE did not provide a file name, then assume stdin.
554 if (FileName.empty())
555 return GetOrCreateSourceID("<stdin>", StringRef());
557 // MCStream expects full path name as filename.
558 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
559 SmallString<128> FullPathName = DirName;
560 sys::path::append(FullPathName, FileName);
561 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
562 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
565 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
566 if (Entry.getValue())
567 return Entry.getValue();
569 unsigned SrcId = SourceIdMap.size();
570 Entry.setValue(SrcId);
572 // Print out a .file directive to specify files for .loc directives.
573 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
578 /// constructCompileUnit - Create new CompileUnit for the given
579 /// metadata node with tag DW_TAG_compile_unit.
580 void DwarfDebug::constructCompileUnit(const MDNode *N) {
581 DICompileUnit DIUnit(N);
582 StringRef FN = DIUnit.getFilename();
583 StringRef Dir = DIUnit.getDirectory();
584 unsigned ID = GetOrCreateSourceID(FN, Dir);
586 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
587 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
588 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
589 DIUnit.getProducer());
590 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
591 DIUnit.getLanguage());
592 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
593 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
594 // simplifies debug range entries.
595 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
596 // DW_AT_stmt_list is a offset of line number information for this
597 // compile unit in debug_line section.
598 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
599 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
600 Asm->GetTempSymbol("section_line"));
602 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
605 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
606 if (DIUnit.isOptimized())
607 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
609 StringRef Flags = DIUnit.getFlags();
611 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
614 unsigned RVer = DIUnit.getRunTimeVersion();
616 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
617 dwarf::DW_FORM_data1, RVer);
621 CUMap.insert(std::make_pair(N, NewCU));
624 /// getCompileUnit - Get CompileUnit DIE.
625 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
626 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
628 const MDNode *CUNode = NULL;
629 if (D.isCompileUnit())
631 else if (D.isSubprogram())
632 CUNode = DISubprogram(N).getCompileUnit();
634 CUNode = DIType(N).getCompileUnit();
635 else if (D.isGlobalVariable())
636 CUNode = DIGlobalVariable(N).getCompileUnit();
637 else if (D.isVariable())
638 CUNode = DIVariable(N).getCompileUnit();
639 else if (D.isNameSpace())
640 CUNode = DINameSpace(N).getCompileUnit();
642 CUNode = DIFile(N).getCompileUnit();
646 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
647 = CUMap.find(CUNode);
648 if (I == CUMap.end())
653 /// constructGlobalVariableDIE - Construct global variable DIE.
654 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
655 DIGlobalVariable GV(N);
657 // If debug information is malformed then ignore it.
658 if (GV.Verify() == false)
661 // Check for pre-existence.
662 CompileUnit *TheCU = getCompileUnit(N);
663 TheCU->createGlobalVariableDIE(N);
667 /// construct SubprogramDIE - Construct subprogram DIE.
668 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
671 // Check for pre-existence.
672 CompileUnit *TheCU = getCompileUnit(N);
673 if (TheCU->getDIE(N))
676 if (!SP.isDefinition())
677 // This is a method declaration which will be handled while constructing
681 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
684 TheCU->insertDIE(N, SubprogramDie);
686 // Add to context owner.
687 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
690 TheCU->addGlobal(SP.getName(), SubprogramDie);
695 /// beginModule - Emit all Dwarf sections that should come prior to the
696 /// content. Create global DIEs and emit initial debug info sections.
697 /// This is invoked by the target AsmPrinter.
698 void DwarfDebug::beginModule(Module *M) {
699 if (DisableDebugInfoPrinting)
702 // If module has named metadata anchors then use them, otherwise scan the
703 // module using debug info finder to collect debug info.
704 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
707 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
708 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
709 if (!GV_Nodes && !SP_Nodes)
710 // If there are not any global variables or any functions then
711 // there is not any debug info in this module.
714 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
715 constructCompileUnit(CU_Nodes->getOperand(i));
718 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
719 constructGlobalVariableDIE(GV_Nodes->getOperand(i));
722 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
723 constructSubprogramDIE(SP_Nodes->getOperand(i));
727 DebugInfoFinder DbgFinder;
728 DbgFinder.processModule(*M);
730 bool HasDebugInfo = false;
731 // Scan all the compile-units to see if there are any marked as the main
732 // unit. If not, we do not generate debug info.
733 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
734 E = DbgFinder.compile_unit_end(); I != E; ++I) {
735 if (DICompileUnit(*I).isMain()) {
740 if (!HasDebugInfo) return;
742 // Create all the compile unit DIEs.
743 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
744 E = DbgFinder.compile_unit_end(); I != E; ++I)
745 constructCompileUnit(*I);
747 // Create DIEs for each global variable.
748 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
749 E = DbgFinder.global_variable_end(); I != E; ++I)
750 constructGlobalVariableDIE(*I);
752 // Create DIEs for each subprogram.
753 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
754 E = DbgFinder.subprogram_end(); I != E; ++I)
755 constructSubprogramDIE(*I);
758 // Tell MMI that we have debug info.
759 MMI->setDebugInfoAvailability(true);
761 // Emit initial sections.
765 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
766 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
767 DIType Ty(NMD->getOperand(i));
768 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
771 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
772 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
773 DIType Ty(NMD->getOperand(i));
774 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
777 // Prime section data.
778 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
781 /// endModule - Emit all Dwarf sections that should come after the content.
783 void DwarfDebug::endModule() {
784 if (!FirstCU) return;
785 const Module *M = MMI->getModule();
786 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
787 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
788 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
789 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
790 DISubprogram SP(AllSPs->getOperand(SI));
791 if (!SP.Verify()) continue;
793 // Collect info for variables that were optimized out.
794 if (!SP.isDefinition()) continue;
795 StringRef FName = SP.getLinkageName();
797 FName = SP.getName();
798 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
800 unsigned E = NMD->getNumOperands();
802 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
804 DeadFnScopeMap[SP] = Scope;
805 SmallVector<DbgVariable, 8> Variables;
806 for (unsigned I = 0; I != E; ++I) {
807 DIVariable DV(NMD->getOperand(I));
808 if (!DV.Verify()) continue;
809 Variables.push_back(DbgVariable(DV, NULL));
812 // Construct subprogram DIE and add variables DIEs.
813 constructSubprogramDIE(SP);
814 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
815 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
816 if (DIE *VariableDIE = constructVariableDIE(&Variables[i], Scope))
817 ScopeDIE->addChild(VariableDIE);
822 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
823 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
824 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
826 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
829 // Emit DW_AT_containing_type attribute to connect types with their
830 // vtable holding type.
831 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
832 CUE = CUMap.end(); CUI != CUE; ++CUI) {
833 CompileUnit *TheCU = CUI->second;
834 TheCU->constructContainingTypeDIEs();
837 // Standard sections final addresses.
838 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
839 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
840 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
841 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
843 // End text sections.
844 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
845 Asm->OutStreamer.SwitchSection(SectionMap[i]);
846 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
849 // Compute DIE offsets and sizes.
850 computeSizeAndOffsets();
852 // Emit all the DIEs into a debug info section
855 // Corresponding abbreviations into a abbrev section.
858 // Emit info into a debug pubnames section.
861 // Emit info into a debug pubtypes section.
864 // Emit info into a debug loc section.
867 // Emit info into a debug aranges section.
870 // Emit info into a debug ranges section.
873 // Emit info into a debug macinfo section.
877 emitDebugInlineInfo();
879 // Emit info into a debug str section.
883 DeleteContainerSeconds(DeadFnScopeMap);
884 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
885 E = CUMap.end(); I != E; ++I)
887 FirstCU = NULL; // Reset for the next Module, if any.
890 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
891 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
893 LLVMContext &Ctx = DV->getContext();
894 // More then one inlined variable corresponds to one abstract variable.
895 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
896 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
898 return AbsDbgVariable;
900 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
904 AbsDbgVariable = new DbgVariable(Var, NULL);
905 addScopeVariable(Scope, AbsDbgVariable);
906 AbstractVariables[Var] = AbsDbgVariable;
907 return AbsDbgVariable;
910 /// addCurrentFnArgument - If Var is a current function argument then add
911 /// it to CurrentFnArguments list.
912 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
913 DbgVariable *Var, LexicalScope *Scope) {
914 if (!LScopes.isCurrentFunctionScope(Scope))
916 DIVariable DV = Var->getVariable();
917 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
919 unsigned ArgNo = DV.getArgNumber();
923 size_t Size = CurrentFnArguments.size();
925 CurrentFnArguments.resize(MF->getFunction()->arg_size());
926 // llvm::Function argument size is not good indicator of how many
927 // arguments does the function have at source level.
929 CurrentFnArguments.resize(ArgNo * 2);
930 CurrentFnArguments[ArgNo - 1] = Var;
934 /// collectVariableInfoFromMMITable - Collect variable information from
935 /// side table maintained by MMI.
937 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
938 SmallPtrSet<const MDNode *, 16> &Processed) {
939 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
940 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
941 VE = VMap.end(); VI != VE; ++VI) {
942 const MDNode *Var = VI->first;
944 Processed.insert(Var);
946 const std::pair<unsigned, DebugLoc> &VP = VI->second;
948 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
950 // If variable scope is not found then skip this variable.
954 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
955 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
956 recordVariableFrameIndex(RegVar, VP.first);
957 if (!addCurrentFnArgument(MF, RegVar, Scope))
958 addScopeVariable(Scope, RegVar);
960 recordVariableFrameIndex(AbsDbgVariable, VP.first);
964 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
965 /// DBG_VALUE instruction, is in a defined reg.
966 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
967 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
968 return MI->getNumOperands() == 3 &&
969 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
970 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
973 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
975 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
976 const MCSymbol *FLabel,
977 const MCSymbol *SLabel,
978 const MachineInstr *MI) {
979 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
981 if (MI->getNumOperands() != 3) {
982 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
983 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
985 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
986 MachineLocation MLoc;
987 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
988 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
990 if (MI->getOperand(0).isImm())
991 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
992 if (MI->getOperand(0).isFPImm())
993 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
994 if (MI->getOperand(0).isCImm())
995 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
997 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
998 return DotDebugLocEntry();
1001 /// collectVariableInfo - Find variables for each lexical scope.
1003 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1004 SmallPtrSet<const MDNode *, 16> &Processed) {
1006 /// collection info from MMI table.
1007 collectVariableInfoFromMMITable(MF, Processed);
1009 for (SmallVectorImpl<const MDNode*>::const_iterator
1010 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1012 const MDNode *Var = *UVI;
1013 if (Processed.count(Var))
1016 // History contains relevant DBG_VALUE instructions for Var and instructions
1018 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1019 if (History.empty())
1021 const MachineInstr *MInsn = History.front();
1024 LexicalScope *Scope = NULL;
1025 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1026 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1027 Scope = LScopes.getCurrentFunctionScope();
1029 if (DV.getVersion() <= LLVMDebugVersion9)
1030 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1032 if (MDNode *IA = DV.getInlinedAt())
1033 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1035 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1038 // If variable scope is not found then skip this variable.
1042 Processed.insert(DV);
1043 assert(MInsn->isDebugValue() && "History must begin with debug value");
1044 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1045 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1046 if (!addCurrentFnArgument(MF, RegVar, Scope))
1047 addScopeVariable(Scope, RegVar);
1049 DbgVariableToDbgInstMap[AbsVar] = MInsn;
1051 // Simple ranges that are fully coalesced.
1052 if (History.size() <= 1 || (History.size() == 2 &&
1053 MInsn->isIdenticalTo(History.back()))) {
1054 DbgVariableToDbgInstMap[RegVar] = MInsn;
1058 // handle multiple DBG_VALUE instructions describing one variable.
1059 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1061 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1062 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1063 const MachineInstr *Begin = *HI;
1064 assert(Begin->isDebugValue() && "Invalid History entry");
1066 // Check if DBG_VALUE is truncating a range.
1067 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1068 && !Begin->getOperand(0).getReg())
1071 // Compute the range for a register location.
1072 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1073 const MCSymbol *SLabel = 0;
1076 // If Begin is the last instruction in History then its value is valid
1077 // until the end of the function.
1078 SLabel = FunctionEndSym;
1080 const MachineInstr *End = HI[1];
1081 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1082 << "\t" << *Begin << "\t" << *End << "\n");
1083 if (End->isDebugValue())
1084 SLabel = getLabelBeforeInsn(End);
1086 // End is a normal instruction clobbering the range.
1087 SLabel = getLabelAfterInsn(End);
1088 assert(SLabel && "Forgot label after clobber instruction");
1093 // The value is valid until the next DBG_VALUE or clobber.
1094 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1096 DotDebugLocEntries.push_back(DotDebugLocEntry());
1099 // Collect info for variables that were optimized out.
1100 const Function *F = MF->getFunction();
1101 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1102 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1103 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1104 if (!DV || !Processed.insert(DV))
1106 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1107 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1112 /// getLabelBeforeInsn - Return Label preceding the instruction.
1113 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1114 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1115 assert(Label && "Didn't insert label before instruction");
1119 /// getLabelAfterInsn - Return Label immediately following the instruction.
1120 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1121 return LabelsAfterInsn.lookup(MI);
1124 /// beginInstruction - Process beginning of an instruction.
1125 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1126 // Check if source location changes, but ignore DBG_VALUE locations.
1127 if (!MI->isDebugValue()) {
1128 DebugLoc DL = MI->getDebugLoc();
1129 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1130 unsigned Flags = DWARF2_FLAG_IS_STMT;
1132 if (DL == PrologEndLoc) {
1133 Flags |= DWARF2_FLAG_PROLOGUE_END;
1134 PrologEndLoc = DebugLoc();
1136 if (!DL.isUnknown()) {
1137 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1138 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1140 recordSourceLine(0, 0, 0, 0);
1144 // Insert labels where requested.
1145 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1146 LabelsBeforeInsn.find(MI);
1149 if (I == LabelsBeforeInsn.end())
1152 // Label already assigned.
1157 PrevLabel = MMI->getContext().CreateTempSymbol();
1158 Asm->OutStreamer.EmitLabel(PrevLabel);
1160 I->second = PrevLabel;
1163 /// endInstruction - Process end of an instruction.
1164 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1165 // Don't create a new label after DBG_VALUE instructions.
1166 // They don't generate code.
1167 if (!MI->isDebugValue())
1170 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1171 LabelsAfterInsn.find(MI);
1174 if (I == LabelsAfterInsn.end())
1177 // Label already assigned.
1181 // We need a label after this instruction.
1183 PrevLabel = MMI->getContext().CreateTempSymbol();
1184 Asm->OutStreamer.EmitLabel(PrevLabel);
1186 I->second = PrevLabel;
1189 /// identifyScopeMarkers() -
1190 /// Each LexicalScope has first instruction and last instruction to mark
1191 /// beginning and end of a scope respectively. Create an inverse map that list
1192 /// scopes starts (and ends) with an instruction. One instruction may start (or
1193 /// end) multiple scopes. Ignore scopes that are not reachable.
1194 void DwarfDebug::identifyScopeMarkers() {
1195 SmallVector<LexicalScope *, 4> WorkList;
1196 WorkList.push_back(LScopes.getCurrentFunctionScope());
1197 while (!WorkList.empty()) {
1198 LexicalScope *S = WorkList.pop_back_val();
1200 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1201 if (!Children.empty())
1202 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1203 SE = Children.end(); SI != SE; ++SI)
1204 WorkList.push_back(*SI);
1206 if (S->isAbstractScope())
1209 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1212 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1213 RE = Ranges.end(); RI != RE; ++RI) {
1214 assert(RI->first && "InsnRange does not have first instruction!");
1215 assert(RI->second && "InsnRange does not have second instruction!");
1216 requestLabelBeforeInsn(RI->first);
1217 requestLabelAfterInsn(RI->second);
1222 /// getScopeNode - Get MDNode for DebugLoc's scope.
1223 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1224 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1225 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1226 return DL.getScope(Ctx);
1229 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1230 /// line number info for the function.
1231 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1232 const MDNode *Scope = getScopeNode(DL, Ctx);
1233 DISubprogram SP = getDISubprogram(Scope);
1235 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1239 /// beginFunction - Gather pre-function debug information. Assumes being
1240 /// emitted immediately after the function entry point.
1241 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1242 if (!MMI->hasDebugInfo()) return;
1243 LScopes.initialize(*MF);
1244 if (LScopes.empty()) return;
1245 identifyScopeMarkers();
1247 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1248 Asm->getFunctionNumber());
1249 // Assumes in correct section after the entry point.
1250 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1252 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1254 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1255 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1256 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1258 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1260 bool AtBlockEntry = true;
1261 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1263 const MachineInstr *MI = II;
1265 if (MI->isDebugValue()) {
1266 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1268 // Keep track of user variables.
1270 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1272 // Variable is in a register, we need to check for clobbers.
1273 if (isDbgValueInDefinedReg(MI))
1274 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1276 // Check the history of this variable.
1277 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1278 if (History.empty()) {
1279 UserVariables.push_back(Var);
1280 // The first mention of a function argument gets the FunctionBeginSym
1281 // label, so arguments are visible when breaking at function entry.
1283 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1284 DISubprogram(getDISubprogram(DV.getContext()))
1285 .describes(MF->getFunction()))
1286 LabelsBeforeInsn[MI] = FunctionBeginSym;
1288 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1289 const MachineInstr *Prev = History.back();
1290 if (Prev->isDebugValue()) {
1291 // Coalesce identical entries at the end of History.
1292 if (History.size() >= 2 &&
1293 Prev->isIdenticalTo(History[History.size() - 2])) {
1294 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1296 << "\t" << *History[History.size() - 2] << "\n");
1300 // Terminate old register assignments that don't reach MI;
1301 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1302 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1303 isDbgValueInDefinedReg(Prev)) {
1304 // Previous register assignment needs to terminate at the end of
1306 MachineBasicBlock::const_iterator LastMI =
1307 PrevMBB->getLastNonDebugInstr();
1308 if (LastMI == PrevMBB->end()) {
1309 // Drop DBG_VALUE for empty range.
1310 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1311 << "\t" << *Prev << "\n");
1315 // Terminate after LastMI.
1316 History.push_back(LastMI);
1321 History.push_back(MI);
1323 // Not a DBG_VALUE instruction.
1325 AtBlockEntry = false;
1327 // First known non DBG_VALUE location marks beginning of function
1329 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1330 PrologEndLoc = MI->getDebugLoc();
1332 // Check if the instruction clobbers any registers with debug vars.
1333 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1334 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1335 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1337 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1338 unsigned Reg = *AI; ++AI) {
1339 const MDNode *Var = LiveUserVar[Reg];
1342 // Reg is now clobbered.
1343 LiveUserVar[Reg] = 0;
1345 // Was MD last defined by a DBG_VALUE referring to Reg?
1346 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1347 if (HistI == DbgValues.end())
1349 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1350 if (History.empty())
1352 const MachineInstr *Prev = History.back();
1353 // Sanity-check: Register assignments are terminated at the end of
1355 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1357 // Is the variable still in Reg?
1358 if (!isDbgValueInDefinedReg(Prev) ||
1359 Prev->getOperand(0).getReg() != Reg)
1361 // Var is clobbered. Make sure the next instruction gets a label.
1362 History.push_back(MI);
1369 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1371 SmallVectorImpl<const MachineInstr*> &History = I->second;
1372 if (History.empty())
1375 // Make sure the final register assignments are terminated.
1376 const MachineInstr *Prev = History.back();
1377 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1378 const MachineBasicBlock *PrevMBB = Prev->getParent();
1379 MachineBasicBlock::const_iterator LastMI =
1380 PrevMBB->getLastNonDebugInstr();
1381 if (LastMI == PrevMBB->end())
1382 // Drop DBG_VALUE for empty range.
1385 // Terminate after LastMI.
1386 History.push_back(LastMI);
1389 // Request labels for the full history.
1390 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1391 const MachineInstr *MI = History[i];
1392 if (MI->isDebugValue())
1393 requestLabelBeforeInsn(MI);
1395 requestLabelAfterInsn(MI);
1399 PrevInstLoc = DebugLoc();
1400 PrevLabel = FunctionBeginSym;
1402 // Record beginning of function.
1403 if (!PrologEndLoc.isUnknown()) {
1404 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1405 MF->getFunction()->getContext());
1406 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1407 FnStartDL.getScope(MF->getFunction()->getContext()),
1408 DWARF2_FLAG_IS_STMT);
1412 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1413 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1414 ScopeVariables[LS].push_back(Var);
1415 // Vars.push_back(Var);
1418 /// endFunction - Gather and emit post-function debug information.
1420 void DwarfDebug::endFunction(const MachineFunction *MF) {
1421 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1423 // Define end label for subprogram.
1424 FunctionEndSym = Asm->GetTempSymbol("func_end",
1425 Asm->getFunctionNumber());
1426 // Assumes in correct section after the entry point.
1427 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1429 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1430 collectVariableInfo(MF, ProcessedVars);
1432 // Construct abstract scopes.
1433 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1434 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1435 LexicalScope *AScope = AList[i];
1436 DISubprogram SP(AScope->getScopeNode());
1438 // Collect info for variables that were optimized out.
1439 StringRef FName = SP.getLinkageName();
1441 FName = SP.getName();
1442 if (NamedMDNode *NMD =
1443 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1444 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1445 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1446 if (!DV || !ProcessedVars.insert(DV))
1448 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1449 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1453 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1454 constructScopeDIE(AScope);
1457 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope());
1459 if (!DisableFramePointerElim(*MF)) {
1460 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1461 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1462 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1463 dwarf::DW_FORM_flag, 1);
1465 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1466 MMI->getFrameMoves()));
1469 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1470 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1471 DeleteContainerPointers(I->second);
1472 ScopeVariables.clear();
1473 DeleteContainerPointers(CurrentFnArguments);
1474 DbgVariableToFrameIndexMap.clear();
1475 DbgVariableToDbgInstMap.clear();
1476 UserVariables.clear();
1478 AbstractVariables.clear();
1479 LabelsBeforeInsn.clear();
1480 LabelsAfterInsn.clear();
1484 /// recordVariableFrameIndex - Record a variable's index.
1485 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
1486 assert (V && "Invalid DbgVariable!");
1487 DbgVariableToFrameIndexMap[V] = Index;
1490 /// findVariableFrameIndex - Return true if frame index for the variable
1491 /// is found. Update FI to hold value of the index.
1492 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
1493 assert (V && "Invalid DbgVariable!");
1494 DenseMap<const DbgVariable *, int>::iterator I =
1495 DbgVariableToFrameIndexMap.find(V);
1496 if (I == DbgVariableToFrameIndexMap.end())
1502 /// recordSourceLine - Register a source line with debug info. Returns the
1503 /// unique label that was emitted and which provides correspondence to
1504 /// the source line list.
1505 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1511 DIDescriptor Scope(S);
1513 if (Scope.isCompileUnit()) {
1514 DICompileUnit CU(S);
1515 Fn = CU.getFilename();
1516 Dir = CU.getDirectory();
1517 } else if (Scope.isFile()) {
1519 Fn = F.getFilename();
1520 Dir = F.getDirectory();
1521 } else if (Scope.isSubprogram()) {
1523 Fn = SP.getFilename();
1524 Dir = SP.getDirectory();
1525 } else if (Scope.isLexicalBlock()) {
1526 DILexicalBlock DB(S);
1527 Fn = DB.getFilename();
1528 Dir = DB.getDirectory();
1530 assert(0 && "Unexpected scope info");
1532 Src = GetOrCreateSourceID(Fn, Dir);
1534 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1537 //===----------------------------------------------------------------------===//
1539 //===----------------------------------------------------------------------===//
1541 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1544 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1545 // Get the children.
1546 const std::vector<DIE *> &Children = Die->getChildren();
1548 // If not last sibling and has children then add sibling offset attribute.
1549 if (!Last && !Children.empty())
1550 Die->addSiblingOffset(DIEValueAllocator);
1552 // Record the abbreviation.
1553 assignAbbrevNumber(Die->getAbbrev());
1555 // Get the abbreviation for this DIE.
1556 unsigned AbbrevNumber = Die->getAbbrevNumber();
1557 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1560 Die->setOffset(Offset);
1562 // Start the size with the size of abbreviation code.
1563 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1565 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1566 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1568 // Size the DIE attribute values.
1569 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1570 // Size attribute value.
1571 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1573 // Size the DIE children if any.
1574 if (!Children.empty()) {
1575 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1576 "Children flag not set");
1578 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1579 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1581 // End of children marker.
1582 Offset += sizeof(int8_t);
1585 Die->setSize(Offset - Die->getOffset());
1589 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1591 void DwarfDebug::computeSizeAndOffsets() {
1592 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1593 E = CUMap.end(); I != E; ++I) {
1594 // Compute size of compile unit header.
1596 sizeof(int32_t) + // Length of Compilation Unit Info
1597 sizeof(int16_t) + // DWARF version number
1598 sizeof(int32_t) + // Offset Into Abbrev. Section
1599 sizeof(int8_t); // Pointer Size (in bytes)
1600 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1604 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1605 /// temporary label to it if SymbolStem is specified.
1606 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1607 const char *SymbolStem = 0) {
1608 Asm->OutStreamer.SwitchSection(Section);
1609 if (!SymbolStem) return 0;
1611 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1612 Asm->OutStreamer.EmitLabel(TmpSym);
1616 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1617 /// the start of each one.
1618 void DwarfDebug::EmitSectionLabels() {
1619 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1621 // Dwarf sections base addresses.
1622 DwarfInfoSectionSym =
1623 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1624 DwarfAbbrevSectionSym =
1625 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1626 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1628 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1629 EmitSectionSym(Asm, MacroInfo);
1631 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1632 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1633 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1634 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1635 DwarfStrSectionSym =
1636 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1637 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1640 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1641 "section_debug_loc");
1643 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1644 EmitSectionSym(Asm, TLOF.getDataSection());
1647 /// emitDIE - Recursively emits a debug information entry.
1649 void DwarfDebug::emitDIE(DIE *Die) {
1650 // Get the abbreviation for this DIE.
1651 unsigned AbbrevNumber = Die->getAbbrevNumber();
1652 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1654 // Emit the code (index) for the abbreviation.
1655 if (Asm->isVerbose())
1656 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1657 Twine::utohexstr(Die->getOffset()) + ":0x" +
1658 Twine::utohexstr(Die->getSize()) + " " +
1659 dwarf::TagString(Abbrev->getTag()));
1660 Asm->EmitULEB128(AbbrevNumber);
1662 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1663 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1665 // Emit the DIE attribute values.
1666 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1667 unsigned Attr = AbbrevData[i].getAttribute();
1668 unsigned Form = AbbrevData[i].getForm();
1669 assert(Form && "Too many attributes for DIE (check abbreviation)");
1671 if (Asm->isVerbose())
1672 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1675 case dwarf::DW_AT_sibling:
1676 Asm->EmitInt32(Die->getSiblingOffset());
1678 case dwarf::DW_AT_abstract_origin: {
1679 DIEEntry *E = cast<DIEEntry>(Values[i]);
1680 DIE *Origin = E->getEntry();
1681 unsigned Addr = Origin->getOffset();
1682 Asm->EmitInt32(Addr);
1685 case dwarf::DW_AT_ranges: {
1686 // DW_AT_range Value encodes offset in debug_range section.
1687 DIEInteger *V = cast<DIEInteger>(Values[i]);
1689 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1690 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1694 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1696 DwarfDebugRangeSectionSym,
1701 case dwarf::DW_AT_location: {
1702 if (UseDotDebugLocEntry.count(Die) != 0) {
1703 DIELabel *L = cast<DIELabel>(Values[i]);
1704 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1706 Values[i]->EmitValue(Asm, Form);
1709 case dwarf::DW_AT_accessibility: {
1710 if (Asm->isVerbose()) {
1711 DIEInteger *V = cast<DIEInteger>(Values[i]);
1712 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1714 Values[i]->EmitValue(Asm, Form);
1718 // Emit an attribute using the defined form.
1719 Values[i]->EmitValue(Asm, Form);
1724 // Emit the DIE children if any.
1725 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1726 const std::vector<DIE *> &Children = Die->getChildren();
1728 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1729 emitDIE(Children[j]);
1731 if (Asm->isVerbose())
1732 Asm->OutStreamer.AddComment("End Of Children Mark");
1737 /// emitDebugInfo - Emit the debug info section.
1739 void DwarfDebug::emitDebugInfo() {
1740 // Start debug info section.
1741 Asm->OutStreamer.SwitchSection(
1742 Asm->getObjFileLowering().getDwarfInfoSection());
1743 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1744 E = CUMap.end(); I != E; ++I) {
1745 CompileUnit *TheCU = I->second;
1746 DIE *Die = TheCU->getCUDie();
1748 // Emit the compile units header.
1749 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1752 // Emit size of content not including length itself
1753 unsigned ContentSize = Die->getSize() +
1754 sizeof(int16_t) + // DWARF version number
1755 sizeof(int32_t) + // Offset Into Abbrev. Section
1756 sizeof(int8_t); // Pointer Size (in bytes)
1758 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1759 Asm->EmitInt32(ContentSize);
1760 Asm->OutStreamer.AddComment("DWARF version number");
1761 Asm->EmitInt16(dwarf::DWARF_VERSION);
1762 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1763 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1764 DwarfAbbrevSectionSym);
1765 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1766 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1769 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1773 /// emitAbbreviations - Emit the abbreviation section.
1775 void DwarfDebug::emitAbbreviations() const {
1776 // Check to see if it is worth the effort.
1777 if (!Abbreviations.empty()) {
1778 // Start the debug abbrev section.
1779 Asm->OutStreamer.SwitchSection(
1780 Asm->getObjFileLowering().getDwarfAbbrevSection());
1782 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1784 // For each abbrevation.
1785 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1786 // Get abbreviation data
1787 const DIEAbbrev *Abbrev = Abbreviations[i];
1789 // Emit the abbrevations code (base 1 index.)
1790 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1792 // Emit the abbreviations data.
1796 // Mark end of abbreviations.
1797 Asm->EmitULEB128(0, "EOM(3)");
1799 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1803 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1804 /// the line matrix.
1806 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1807 // Define last address of section.
1808 Asm->OutStreamer.AddComment("Extended Op");
1811 Asm->OutStreamer.AddComment("Op size");
1812 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1813 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1814 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1816 Asm->OutStreamer.AddComment("Section end label");
1818 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1819 Asm->getTargetData().getPointerSize(),
1822 // Mark end of matrix.
1823 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1829 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1831 void DwarfDebug::emitDebugPubNames() {
1832 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1833 E = CUMap.end(); I != E; ++I) {
1834 CompileUnit *TheCU = I->second;
1835 // Start the dwarf pubnames section.
1836 Asm->OutStreamer.SwitchSection(
1837 Asm->getObjFileLowering().getDwarfPubNamesSection());
1839 Asm->OutStreamer.AddComment("Length of Public Names Info");
1840 Asm->EmitLabelDifference(
1841 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1842 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1844 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1847 Asm->OutStreamer.AddComment("DWARF Version");
1848 Asm->EmitInt16(dwarf::DWARF_VERSION);
1850 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1851 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1852 DwarfInfoSectionSym);
1854 Asm->OutStreamer.AddComment("Compilation Unit Length");
1855 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1856 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1859 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1860 for (StringMap<DIE*>::const_iterator
1861 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1862 const char *Name = GI->getKeyData();
1863 DIE *Entity = GI->second;
1865 Asm->OutStreamer.AddComment("DIE offset");
1866 Asm->EmitInt32(Entity->getOffset());
1868 if (Asm->isVerbose())
1869 Asm->OutStreamer.AddComment("External Name");
1870 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1873 Asm->OutStreamer.AddComment("End Mark");
1875 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1880 void DwarfDebug::emitDebugPubTypes() {
1881 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1882 E = CUMap.end(); I != E; ++I) {
1883 CompileUnit *TheCU = I->second;
1884 // Start the dwarf pubnames section.
1885 Asm->OutStreamer.SwitchSection(
1886 Asm->getObjFileLowering().getDwarfPubTypesSection());
1887 Asm->OutStreamer.AddComment("Length of Public Types Info");
1888 Asm->EmitLabelDifference(
1889 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1890 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1892 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1895 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1896 Asm->EmitInt16(dwarf::DWARF_VERSION);
1898 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1899 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1900 DwarfInfoSectionSym);
1902 Asm->OutStreamer.AddComment("Compilation Unit Length");
1903 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1904 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1907 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1908 for (StringMap<DIE*>::const_iterator
1909 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1910 const char *Name = GI->getKeyData();
1911 DIE *Entity = GI->second;
1913 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1914 Asm->EmitInt32(Entity->getOffset());
1916 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1917 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1920 Asm->OutStreamer.AddComment("End Mark");
1922 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1927 /// emitDebugStr - Emit visible names into a debug str section.
1929 void DwarfDebug::emitDebugStr() {
1930 // Check to see if it is worth the effort.
1931 if (StringPool.empty()) return;
1933 // Start the dwarf str section.
1934 Asm->OutStreamer.SwitchSection(
1935 Asm->getObjFileLowering().getDwarfStrSection());
1937 // Get all of the string pool entries and put them in an array by their ID so
1938 // we can sort them.
1939 SmallVector<std::pair<unsigned,
1940 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1942 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1943 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1944 Entries.push_back(std::make_pair(I->second.second, &*I));
1946 array_pod_sort(Entries.begin(), Entries.end());
1948 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1949 // Emit a label for reference from debug information entries.
1950 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1952 // Emit the string itself.
1953 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1957 /// emitDebugLoc - Emit visible names into a debug loc section.
1959 void DwarfDebug::emitDebugLoc() {
1960 if (DotDebugLocEntries.empty())
1963 for (SmallVector<DotDebugLocEntry, 4>::iterator
1964 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1966 DotDebugLocEntry &Entry = *I;
1967 if (I + 1 != DotDebugLocEntries.end())
1971 // Start the dwarf loc section.
1972 Asm->OutStreamer.SwitchSection(
1973 Asm->getObjFileLowering().getDwarfLocSection());
1974 unsigned char Size = Asm->getTargetData().getPointerSize();
1975 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1977 for (SmallVector<DotDebugLocEntry, 4>::iterator
1978 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1979 I != E; ++I, ++index) {
1980 DotDebugLocEntry &Entry = *I;
1981 if (Entry.isMerged()) continue;
1982 if (Entry.isEmpty()) {
1983 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1984 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1985 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1987 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1988 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1989 DIVariable DV(Entry.Variable);
1990 Asm->OutStreamer.AddComment("Loc expr size");
1991 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1992 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1993 Asm->EmitLabelDifference(end, begin, 2);
1994 Asm->OutStreamer.EmitLabel(begin);
1995 if (Entry.isInt()) {
1996 DIBasicType BTy(DV.getType());
1998 (BTy.getEncoding() == dwarf::DW_ATE_signed
1999 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2000 Asm->OutStreamer.AddComment("DW_OP_consts");
2001 Asm->EmitInt8(dwarf::DW_OP_consts);
2002 Asm->EmitSLEB128(Entry.getInt());
2004 Asm->OutStreamer.AddComment("DW_OP_constu");
2005 Asm->EmitInt8(dwarf::DW_OP_constu);
2006 Asm->EmitULEB128(Entry.getInt());
2008 } else if (Entry.isLocation()) {
2009 if (!DV.hasComplexAddress())
2011 Asm->EmitDwarfRegOp(Entry.Loc);
2013 // Complex address entry.
2014 unsigned N = DV.getNumAddrElements();
2016 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2017 if (Entry.Loc.getOffset()) {
2019 Asm->EmitDwarfRegOp(Entry.Loc);
2020 Asm->OutStreamer.AddComment("DW_OP_deref");
2021 Asm->EmitInt8(dwarf::DW_OP_deref);
2022 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2023 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2024 Asm->EmitSLEB128(DV.getAddrElement(1));
2026 // If first address element is OpPlus then emit
2027 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2028 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2029 Asm->EmitDwarfRegOp(Loc);
2033 Asm->EmitDwarfRegOp(Entry.Loc);
2036 // Emit remaining complex address elements.
2037 for (; i < N; ++i) {
2038 uint64_t Element = DV.getAddrElement(i);
2039 if (Element == DIBuilder::OpPlus) {
2040 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2041 Asm->EmitULEB128(DV.getAddrElement(++i));
2042 } else if (Element == DIBuilder::OpDeref)
2043 Asm->EmitInt8(dwarf::DW_OP_deref);
2044 else llvm_unreachable("unknown Opcode found in complex address");
2048 // else ... ignore constant fp. There is not any good way to
2049 // to represent them here in dwarf.
2050 Asm->OutStreamer.EmitLabel(end);
2055 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2057 void DwarfDebug::EmitDebugARanges() {
2058 // Start the dwarf aranges section.
2059 Asm->OutStreamer.SwitchSection(
2060 Asm->getObjFileLowering().getDwarfARangesSection());
2063 /// emitDebugRanges - Emit visible names into a debug ranges section.
2065 void DwarfDebug::emitDebugRanges() {
2066 // Start the dwarf ranges section.
2067 Asm->OutStreamer.SwitchSection(
2068 Asm->getObjFileLowering().getDwarfRangesSection());
2069 unsigned char Size = Asm->getTargetData().getPointerSize();
2070 for (SmallVector<const MCSymbol *, 8>::iterator
2071 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2074 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2076 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2080 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2082 void DwarfDebug::emitDebugMacInfo() {
2083 if (const MCSection *LineInfo =
2084 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2085 // Start the dwarf macinfo section.
2086 Asm->OutStreamer.SwitchSection(LineInfo);
2090 /// emitDebugInlineInfo - Emit inline info using following format.
2092 /// 1. length of section
2093 /// 2. Dwarf version number
2094 /// 3. address size.
2096 /// Entries (one "entry" for each function that was inlined):
2098 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2099 /// otherwise offset into __debug_str for regular function name.
2100 /// 2. offset into __debug_str section for regular function name.
2101 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2102 /// instances for the function.
2104 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2105 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2106 /// __debug_info section, and the low_pc is the starting address for the
2107 /// inlining instance.
2108 void DwarfDebug::emitDebugInlineInfo() {
2109 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2115 Asm->OutStreamer.SwitchSection(
2116 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2118 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2119 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2120 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2122 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2124 Asm->OutStreamer.AddComment("Dwarf Version");
2125 Asm->EmitInt16(dwarf::DWARF_VERSION);
2126 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2127 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2129 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2130 E = InlinedSPNodes.end(); I != E; ++I) {
2132 const MDNode *Node = *I;
2133 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2134 = InlineInfo.find(Node);
2135 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2136 DISubprogram SP(Node);
2137 StringRef LName = SP.getLinkageName();
2138 StringRef Name = SP.getName();
2140 Asm->OutStreamer.AddComment("MIPS linkage name");
2141 if (LName.empty()) {
2142 Asm->OutStreamer.EmitBytes(Name, 0);
2143 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2145 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2146 DwarfStrSectionSym);
2148 Asm->OutStreamer.AddComment("Function name");
2149 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2150 Asm->EmitULEB128(Labels.size(), "Inline count");
2152 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2153 LE = Labels.end(); LI != LE; ++LI) {
2154 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2155 Asm->EmitInt32(LI->second->getOffset());
2157 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2158 Asm->OutStreamer.EmitSymbolValue(LI->first,
2159 Asm->getTargetData().getPointerSize(),0);
2163 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));