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 "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Analysis/DebugInfo.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/System/Path.h"
44 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
45 cl::desc("Print DbgScope information for each machine instruction"));
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 absense 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 //===----------------------------------------------------------------------===//
69 /// CompileUnit - This dwarf writer support class manages information associate
70 /// with a source file.
72 /// ID - File identifier for source.
76 /// Die - Compile unit debug information entry.
78 const OwningPtr<DIE> CUDie;
80 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
83 /// MDNodeToDieMap - Tracks the mapping of unit level debug informaton
84 /// variables to debug information entries.
85 DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
87 /// MDNodeToDIEEntryMap - Tracks the mapping of unit level debug informaton
88 /// descriptors to debug information entries using a DIEEntry proxy.
89 DenseMap<const MDNode *, DIEEntry *> MDNodeToDIEEntryMap;
91 /// Globals - A map of globally visible named entities for this unit.
93 StringMap<DIE*> Globals;
95 /// GlobalTypes - A map of globally visible types for this unit.
97 StringMap<DIE*> GlobalTypes;
100 CompileUnit(unsigned I, DIE *D)
101 : ID(I), CUDie(D), IndexTyDie(0) {}
104 unsigned getID() const { return ID; }
105 DIE* getCUDie() const { return CUDie.get(); }
106 const StringMap<DIE*> &getGlobals() const { return Globals; }
107 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
109 /// hasContent - Return true if this compile unit has something to write out.
111 bool hasContent() const { return !CUDie->getChildren().empty(); }
113 /// addGlobal - Add a new global entity to the compile unit.
115 void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
117 /// addGlobalType - Add a new global type to the compile unit.
119 void addGlobalType(StringRef Name, DIE *Die) {
120 GlobalTypes[Name] = Die;
123 /// getDIE - Returns the debug information entry map slot for the
124 /// specified debug variable.
125 DIE *getDIE(const MDNode *N) { return MDNodeToDieMap.lookup(N); }
127 /// insertDIE - Insert DIE into the map.
128 void insertDIE(const MDNode *N, DIE *D) {
129 MDNodeToDieMap.insert(std::make_pair(N, D));
132 /// getDIEEntry - Returns the debug information entry for the speciefied
134 DIEEntry *getDIEEntry(const MDNode *N) {
135 DenseMap<const MDNode *, DIEEntry *>::iterator I =
136 MDNodeToDIEEntryMap.find(N);
137 if (I == MDNodeToDIEEntryMap.end())
142 /// insertDIEEntry - Insert debug information entry into the map.
143 void insertDIEEntry(const MDNode *N, DIEEntry *E) {
144 MDNodeToDIEEntryMap.insert(std::make_pair(N, E));
147 /// addDie - Adds or interns the DIE to the compile unit.
149 void addDie(DIE *Buffer) {
150 this->CUDie->addChild(Buffer);
153 // getIndexTyDie - Get an anonymous type for index type.
154 DIE *getIndexTyDie() {
158 // setIndexTyDie - Set D as anonymous type for index which can be reused
160 void setIndexTyDie(DIE *D) {
166 //===----------------------------------------------------------------------===//
167 /// DbgVariable - This class is used to track local variable information.
170 DIVariable Var; // Variable Descriptor.
171 DIE *TheDIE; // Variable DIE.
172 unsigned DotDebugLocOffset; // Offset in DotDebugLocEntries.
174 // AbsVar may be NULL.
175 DbgVariable(DIVariable V) : Var(V), TheDIE(0), DotDebugLocOffset(~0U) {}
178 DIVariable getVariable() const { return Var; }
179 void setDIE(DIE *D) { TheDIE = D; }
180 DIE *getDIE() const { return TheDIE; }
181 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
182 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
183 StringRef getName() const { return Var.getName(); }
184 unsigned getTag() const { return Var.getTag(); }
185 bool variableHasComplexAddress() const {
186 assert(Var.Verify() && "Invalid complex DbgVariable!");
187 return Var.hasComplexAddress();
189 bool isBlockByrefVariable() const {
190 assert(Var.Verify() && "Invalid complex DbgVariable!");
191 return Var.isBlockByrefVariable();
193 unsigned getNumAddrElements() const {
194 assert(Var.Verify() && "Invalid complex DbgVariable!");
195 return Var.getNumAddrElements();
197 uint64_t getAddrElement(unsigned i) const {
198 return Var.getAddrElement(i);
200 DIType getType() const {
201 DIType Ty = Var.getType();
202 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
203 // addresses instead.
204 if (Var.isBlockByrefVariable()) {
205 /* Byref variables, in Blocks, are declared by the programmer as
206 "SomeType VarName;", but the compiler creates a
207 __Block_byref_x_VarName struct, and gives the variable VarName
208 either the struct, or a pointer to the struct, as its type. This
209 is necessary for various behind-the-scenes things the compiler
210 needs to do with by-reference variables in blocks.
212 However, as far as the original *programmer* is concerned, the
213 variable should still have type 'SomeType', as originally declared.
215 The following function dives into the __Block_byref_x_VarName
216 struct to find the original type of the variable. This will be
217 passed back to the code generating the type for the Debug
218 Information Entry for the variable 'VarName'. 'VarName' will then
219 have the original type 'SomeType' in its debug information.
221 The original type 'SomeType' will be the type of the field named
222 'VarName' inside the __Block_byref_x_VarName struct.
224 NOTE: In order for this to not completely fail on the debugger
225 side, the Debug Information Entry for the variable VarName needs to
226 have a DW_AT_location that tells the debugger how to unwind through
227 the pointers and __Block_byref_x_VarName struct to find the actual
228 value of the variable. The function addBlockByrefType does this. */
230 unsigned tag = Ty.getTag();
232 if (tag == dwarf::DW_TAG_pointer_type) {
233 DIDerivedType DTy = DIDerivedType(Ty);
234 subType = DTy.getTypeDerivedFrom();
237 DICompositeType blockStruct = DICompositeType(subType);
238 DIArray Elements = blockStruct.getTypeArray();
240 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
241 DIDescriptor Element = Elements.getElement(i);
242 DIDerivedType DT = DIDerivedType(Element);
243 if (getName() == DT.getName())
244 return (DT.getTypeDerivedFrom());
252 //===----------------------------------------------------------------------===//
253 /// DbgRange - This is used to track range of instructions with identical
254 /// debug info scope.
256 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
258 //===----------------------------------------------------------------------===//
259 /// DbgScope - This class is used to track scope information.
262 DbgScope *Parent; // Parent to this scope.
263 DIDescriptor Desc; // Debug info descriptor for scope.
264 // Location at which this scope is inlined.
265 AssertingVH<const MDNode> InlinedAtLocation;
266 bool AbstractScope; // Abstract Scope
267 const MachineInstr *LastInsn; // Last instruction of this scope.
268 const MachineInstr *FirstInsn; // First instruction of this scope.
269 unsigned DFSIn, DFSOut;
270 // Scopes defined in scope. Contents not owned.
271 SmallVector<DbgScope *, 4> Scopes;
272 // Variables declared in scope. Contents owned.
273 SmallVector<DbgVariable *, 8> Variables;
274 SmallVector<DbgRange, 4> Ranges;
275 // Private state for dump()
276 mutable unsigned IndentLevel;
278 DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
279 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
280 LastInsn(0), FirstInsn(0),
281 DFSIn(0), DFSOut(0), IndentLevel(0) {}
285 DbgScope *getParent() const { return Parent; }
286 void setParent(DbgScope *P) { Parent = P; }
287 DIDescriptor getDesc() const { return Desc; }
288 const MDNode *getInlinedAt() const { return InlinedAtLocation; }
289 const MDNode *getScopeNode() const { return Desc; }
290 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
291 const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
292 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
294 /// openInsnRange - This scope covers instruction range starting from MI.
295 void openInsnRange(const MachineInstr *MI) {
300 Parent->openInsnRange(MI);
303 /// extendInsnRange - Extend the current instruction range covered by
305 void extendInsnRange(const MachineInstr *MI) {
306 assert (FirstInsn && "MI Range is not open!");
309 Parent->extendInsnRange(MI);
312 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
313 /// until now. This is used when a new scope is encountered while walking
314 /// machine instructions.
315 void closeInsnRange(DbgScope *NewScope = NULL) {
316 assert (LastInsn && "Last insn missing!");
317 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
320 // If Parent dominates NewScope then do not close Parent's instruction
322 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
323 Parent->closeInsnRange(NewScope);
326 void setAbstractScope() { AbstractScope = true; }
327 bool isAbstractScope() const { return AbstractScope; }
329 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
330 unsigned getDFSOut() const { return DFSOut; }
331 void setDFSOut(unsigned O) { DFSOut = O; }
332 unsigned getDFSIn() const { return DFSIn; }
333 void setDFSIn(unsigned I) { DFSIn = I; }
334 bool dominates(const DbgScope *S) {
337 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
342 /// addScope - Add a scope to the scope.
344 void addScope(DbgScope *S) { Scopes.push_back(S); }
346 /// addVariable - Add a variable to the scope.
348 void addVariable(DbgVariable *V) { Variables.push_back(V); }
355 } // end llvm namespace
358 void DbgScope::dump() const {
359 raw_ostream &err = dbgs();
360 err.indent(IndentLevel);
361 const MDNode *N = Desc;
364 err << "Abstract Scope\n";
368 err << "Children ...\n";
369 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
370 if (Scopes[i] != this)
377 DbgScope::~DbgScope() {
378 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
382 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
383 : Asm(A), MMI(Asm->MMI), FirstCU(0),
384 AbbreviationsSet(InitAbbreviationsSetSize),
385 CurrentFnDbgScope(0), PrevLabel(NULL) {
386 NextStringPoolNumber = 0;
388 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
389 DwarfStrSectionSym = TextSectionSym = 0;
390 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
391 FunctionBeginSym = FunctionEndSym = 0;
392 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
394 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
398 DwarfDebug::~DwarfDebug() {
399 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
400 DIEBlocks[j]->~DIEBlock();
403 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
404 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
405 if (Entry.first) return Entry.first;
407 Entry.second = NextStringPoolNumber++;
408 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
412 /// assignAbbrevNumber - Define a unique number for the abbreviation.
414 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
415 // Profile the node so that we can make it unique.
419 // Check the set for priors.
420 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
422 // If it's newly added.
423 if (InSet == &Abbrev) {
424 // Add to abbreviation list.
425 Abbreviations.push_back(&Abbrev);
427 // Assign the vector position + 1 as its number.
428 Abbrev.setNumber(Abbreviations.size());
430 // Assign existing abbreviation number.
431 Abbrev.setNumber(InSet->getNumber());
435 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
436 /// information entry.
437 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
438 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
442 /// addUInt - Add an unsigned integer attribute data and value.
444 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
445 unsigned Form, uint64_t Integer) {
446 if (!Form) Form = DIEInteger::BestForm(false, Integer);
447 DIEValue *Value = Integer == 1 ?
448 DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
449 Die->addValue(Attribute, Form, Value);
452 /// addSInt - Add an signed integer attribute data and value.
454 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
455 unsigned Form, int64_t Integer) {
456 if (!Form) Form = DIEInteger::BestForm(true, Integer);
457 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
458 Die->addValue(Attribute, Form, Value);
461 /// addString - Add a string attribute data and value. DIEString only
462 /// keeps string reference.
463 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
465 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
466 Die->addValue(Attribute, Form, Value);
469 /// addLabel - Add a Dwarf label attribute data and value.
471 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
472 const MCSymbol *Label) {
473 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
474 Die->addValue(Attribute, Form, Value);
477 /// addDelta - Add a label delta attribute data and value.
479 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
480 const MCSymbol *Hi, const MCSymbol *Lo) {
481 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
482 Die->addValue(Attribute, Form, Value);
485 /// addDIEEntry - Add a DIE attribute data and value.
487 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
489 Die->addValue(Attribute, Form, createDIEEntry(Entry));
493 /// addBlock - Add block data.
495 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
497 Block->ComputeSize(Asm);
498 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
499 Die->addValue(Attribute, Block->BestForm(), Block);
502 /// addSourceLine - Add location information to specified debug information
504 void DwarfDebug::addSourceLine(DIE *Die, DIVariable V) {
509 unsigned Line = V.getLineNumber();
510 unsigned FileID = GetOrCreateSourceID(V.getContext().getDirectory(),
511 V.getContext().getFilename());
512 assert(FileID && "Invalid file id");
513 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
514 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
517 /// addSourceLine - Add location information to specified debug information
519 void DwarfDebug::addSourceLine(DIE *Die, DIGlobalVariable G) {
520 // Verify global variable.
524 unsigned Line = G.getLineNumber();
525 unsigned FileID = GetOrCreateSourceID(G.getContext().getDirectory(),
526 G.getContext().getFilename());
527 assert(FileID && "Invalid file id");
528 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
529 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
532 /// addSourceLine - Add location information to specified debug information
534 void DwarfDebug::addSourceLine(DIE *Die, DISubprogram SP) {
535 // Verify subprogram.
538 // If the line number is 0, don't add it.
539 if (SP.getLineNumber() == 0)
542 unsigned Line = SP.getLineNumber();
543 if (!SP.getContext().Verify())
545 unsigned FileID = GetOrCreateSourceID(SP.getDirectory(),
547 assert(FileID && "Invalid file id");
548 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
549 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
552 /// addSourceLine - Add location information to specified debug information
554 void DwarfDebug::addSourceLine(DIE *Die, DIType Ty) {
559 unsigned Line = Ty.getLineNumber();
560 if (!Ty.getContext().Verify())
562 unsigned FileID = GetOrCreateSourceID(Ty.getContext().getDirectory(),
563 Ty.getContext().getFilename());
564 assert(FileID && "Invalid file id");
565 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
566 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
569 /// addSourceLine - Add location information to specified debug information
571 void DwarfDebug::addSourceLine(DIE *Die, DINameSpace NS) {
576 unsigned Line = NS.getLineNumber();
577 StringRef FN = NS.getFilename();
578 StringRef Dir = NS.getDirectory();
580 unsigned FileID = GetOrCreateSourceID(Dir, FN);
581 assert(FileID && "Invalid file id");
582 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
583 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
586 /// addVariableAddress - Add DW_AT_location attribute for a DbgVariable.
587 void DwarfDebug::addVariableAddress(DbgVariable *&DV, DIE *Die,
589 const MachineLocation &Location) {
590 if (DV->variableHasComplexAddress())
591 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
592 else if (DV->isBlockByrefVariable())
593 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
595 addAddress(Die, dwarf::DW_AT_location, Location);
598 /// addComplexAddress - Start with the address based on the location provided,
599 /// and generate the DWARF information necessary to find the actual variable
600 /// given the extra address information encoded in the DIVariable, starting from
601 /// the starting location. Add the DWARF information to the die.
603 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
605 const MachineLocation &Location) {
606 DIType Ty = DV->getType();
608 // Decode the original location, and use that as the start of the byref
609 // variable's location.
610 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
611 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
612 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
614 if (Location.isReg()) {
616 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
618 Reg = Reg - dwarf::DW_OP_reg0;
619 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
620 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
624 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
626 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
627 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
630 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
633 for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
634 uint64_t Element = DV->getAddrElement(i);
636 if (Element == DIFactory::OpPlus) {
637 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
638 addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
639 } else if (Element == DIFactory::OpDeref) {
640 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
641 } else llvm_unreachable("unknown DIFactory Opcode");
644 // Now attach the location information to the DIE.
645 addBlock(Die, Attribute, 0, Block);
648 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
649 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
650 gives the variable VarName either the struct, or a pointer to the struct, as
651 its type. This is necessary for various behind-the-scenes things the
652 compiler needs to do with by-reference variables in Blocks.
654 However, as far as the original *programmer* is concerned, the variable
655 should still have type 'SomeType', as originally declared.
657 The function getBlockByrefType dives into the __Block_byref_x_VarName
658 struct to find the original type of the variable, which is then assigned to
659 the variable's Debug Information Entry as its real type. So far, so good.
660 However now the debugger will expect the variable VarName to have the type
661 SomeType. So we need the location attribute for the variable to be an
662 expression that explains to the debugger how to navigate through the
663 pointers and struct to find the actual variable of type SomeType.
665 The following function does just that. We start by getting
666 the "normal" location for the variable. This will be the location
667 of either the struct __Block_byref_x_VarName or the pointer to the
668 struct __Block_byref_x_VarName.
670 The struct will look something like:
672 struct __Block_byref_x_VarName {
674 struct __Block_byref_x_VarName *forwarding;
675 ... <various other fields>
677 ... <maybe more fields>
680 If we are given the struct directly (as our starting point) we
681 need to tell the debugger to:
683 1). Add the offset of the forwarding field.
685 2). Follow that pointer to get the real __Block_byref_x_VarName
686 struct to use (the real one may have been copied onto the heap).
688 3). Add the offset for the field VarName, to find the actual variable.
690 If we started with a pointer to the struct, then we need to
691 dereference that pointer first, before the other steps.
692 Translating this into DWARF ops, we will need to append the following
693 to the current location description for the variable:
695 DW_OP_deref -- optional, if we start with a pointer
696 DW_OP_plus_uconst <forward_fld_offset>
698 DW_OP_plus_uconst <varName_fld_offset>
700 That is what this function does. */
702 /// addBlockByrefAddress - Start with the address based on the location
703 /// provided, and generate the DWARF information necessary to find the
704 /// actual Block variable (navigating the Block struct) based on the
705 /// starting location. Add the DWARF information to the die. For
706 /// more information, read large comment just above here.
708 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
710 const MachineLocation &Location) {
711 DIType Ty = DV->getType();
713 unsigned Tag = Ty.getTag();
714 bool isPointer = false;
716 StringRef varName = DV->getName();
718 if (Tag == dwarf::DW_TAG_pointer_type) {
719 DIDerivedType DTy = DIDerivedType(Ty);
720 TmpTy = DTy.getTypeDerivedFrom();
724 DICompositeType blockStruct = DICompositeType(TmpTy);
726 // Find the __forwarding field and the variable field in the __Block_byref
728 DIArray Fields = blockStruct.getTypeArray();
729 DIDescriptor varField = DIDescriptor();
730 DIDescriptor forwardingField = DIDescriptor();
732 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
733 DIDescriptor Element = Fields.getElement(i);
734 DIDerivedType DT = DIDerivedType(Element);
735 StringRef fieldName = DT.getName();
736 if (fieldName == "__forwarding")
737 forwardingField = Element;
738 else if (fieldName == varName)
742 // Get the offsets for the forwarding field and the variable field.
743 unsigned forwardingFieldOffset =
744 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
745 unsigned varFieldOffset =
746 DIDerivedType(varField).getOffsetInBits() >> 3;
748 // Decode the original location, and use that as the start of the byref
749 // variable's location.
750 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
751 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
752 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
754 if (Location.isReg()) {
756 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
758 Reg = Reg - dwarf::DW_OP_reg0;
759 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
760 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
764 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
766 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
767 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
770 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
773 // If we started with a pointer to the __Block_byref... struct, then
774 // the first thing we need to do is dereference the pointer (DW_OP_deref).
776 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
778 // Next add the offset for the '__forwarding' field:
779 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
780 // adding the offset if it's 0.
781 if (forwardingFieldOffset > 0) {
782 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
783 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
786 // Now dereference the __forwarding field to get to the real __Block_byref
787 // struct: DW_OP_deref.
788 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
790 // Now that we've got the real __Block_byref... struct, add the offset
791 // for the variable's field to get to the location of the actual variable:
792 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
793 if (varFieldOffset > 0) {
794 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
795 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
798 // Now attach the location information to the DIE.
799 addBlock(Die, Attribute, 0, Block);
802 /// addAddress - Add an address attribute to a die based on the location
804 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
805 const MachineLocation &Location) {
806 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
807 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
808 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
810 if (Location.isReg()) {
812 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
814 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
815 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
819 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
821 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
822 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
825 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
828 addBlock(Die, Attribute, 0, Block);
831 /// addRegisterAddress - Add register location entry in variable DIE.
832 bool DwarfDebug::addRegisterAddress(DIE *Die, const MCSymbol *VS,
833 const MachineOperand &MO) {
834 assert (MO.isReg() && "Invalid machine operand!");
837 MachineLocation Location;
838 Location.set(MO.getReg());
839 addAddress(Die, dwarf::DW_AT_location, Location);
841 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
845 /// addConstantValue - Add constant value entry in variable DIE.
846 bool DwarfDebug::addConstantValue(DIE *Die, const MCSymbol *VS,
847 const MachineOperand &MO) {
848 assert (MO.isImm() && "Invalid machine operand!");
849 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
850 unsigned Imm = MO.getImm();
851 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
852 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
854 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
858 /// addConstantFPValue - Add constant value entry in variable DIE.
859 bool DwarfDebug::addConstantFPValue(DIE *Die, const MCSymbol *VS,
860 const MachineOperand &MO) {
861 assert (MO.isFPImm() && "Invalid machine operand!");
862 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
863 APFloat FPImm = MO.getFPImm()->getValueAPF();
865 // Get the raw data form of the floating point.
866 const APInt FltVal = FPImm.bitcastToAPInt();
867 const char *FltPtr = (const char*)FltVal.getRawData();
869 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
870 bool LittleEndian = Asm->getTargetData().isLittleEndian();
871 int Incr = (LittleEndian ? 1 : -1);
872 int Start = (LittleEndian ? 0 : NumBytes - 1);
873 int Stop = (LittleEndian ? NumBytes : -1);
875 // Output the constant to DWARF one byte at a time.
876 for (; Start != Stop; Start += Incr)
877 addUInt(Block, 0, dwarf::DW_FORM_data1,
878 (unsigned char)0xFF & FltPtr[Start]);
880 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
882 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
887 /// addToContextOwner - Add Die into the list of its context owner's children.
888 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
889 if (Context.isType()) {
890 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
891 ContextDIE->addChild(Die);
892 } else if (Context.isNameSpace()) {
893 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
894 ContextDIE->addChild(Die);
895 } else if (Context.isSubprogram()) {
896 DIE *ContextDIE = createSubprogramDIE(DISubprogram(Context),
898 ContextDIE->addChild(Die);
899 } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
900 ContextDIE->addChild(Die);
902 getCompileUnit(Context)->addDie(Die);
905 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
907 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
908 CompileUnit *TypeCU = getCompileUnit(Ty);
909 DIE *TyDIE = TypeCU->getDIE(Ty);
914 TyDIE = new DIE(dwarf::DW_TAG_base_type);
915 TypeCU->insertDIE(Ty, TyDIE);
916 if (Ty.isBasicType())
917 constructTypeDIE(*TyDIE, DIBasicType(Ty));
918 else if (Ty.isCompositeType())
919 constructTypeDIE(*TyDIE, DICompositeType(Ty));
921 assert(Ty.isDerivedType() && "Unknown kind of DIType");
922 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
925 addToContextOwner(TyDIE, Ty.getContext());
929 /// addType - Add a new type attribute to the specified entity.
930 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
934 // Check for pre-existence.
935 CompileUnit *TypeCU = getCompileUnit(Ty);
936 DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
937 // If it exists then use the existing value.
939 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
944 DIE *Buffer = getOrCreateTypeDIE(Ty);
947 Entry = createDIEEntry(Buffer);
948 TypeCU->insertDIEEntry(Ty, Entry);
950 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
953 /// constructTypeDIE - Construct basic type die from DIBasicType.
954 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
955 // Get core information.
956 StringRef Name = BTy.getName();
957 Buffer.setTag(dwarf::DW_TAG_base_type);
958 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
961 // Add name if not anonymous or intermediate type.
963 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
964 uint64_t Size = BTy.getSizeInBits() >> 3;
965 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
968 /// constructTypeDIE - Construct derived type die from DIDerivedType.
969 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
970 // Get core information.
971 StringRef Name = DTy.getName();
972 uint64_t Size = DTy.getSizeInBits() >> 3;
973 unsigned Tag = DTy.getTag();
975 // FIXME - Workaround for templates.
976 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
980 // Map to main type, void will not have a type.
981 DIType FromTy = DTy.getTypeDerivedFrom();
982 addType(&Buffer, FromTy);
984 // Add name if not anonymous or intermediate type.
986 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
988 // Add size if non-zero (derived types might be zero-sized.)
990 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
992 // Add source line info if available and TyDesc is not a forward declaration.
993 if (!DTy.isForwardDecl())
994 addSourceLine(&Buffer, DTy);
997 /// constructTypeDIE - Construct type DIE from DICompositeType.
998 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
999 // Get core information.
1000 StringRef Name = CTy.getName();
1002 uint64_t Size = CTy.getSizeInBits() >> 3;
1003 unsigned Tag = CTy.getTag();
1007 case dwarf::DW_TAG_vector_type:
1008 case dwarf::DW_TAG_array_type:
1009 constructArrayTypeDIE(Buffer, &CTy);
1011 case dwarf::DW_TAG_enumeration_type: {
1012 DIArray Elements = CTy.getTypeArray();
1014 // Add enumerators to enumeration type.
1015 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1016 DIE *ElemDie = NULL;
1017 DIDescriptor Enum(Elements.getElement(i));
1018 if (Enum.isEnumerator()) {
1019 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1020 Buffer.addChild(ElemDie);
1025 case dwarf::DW_TAG_subroutine_type: {
1027 DIArray Elements = CTy.getTypeArray();
1028 DIDescriptor RTy = Elements.getElement(0);
1029 addType(&Buffer, DIType(RTy));
1031 // Add prototype flag.
1032 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1035 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1036 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1037 DIDescriptor Ty = Elements.getElement(i);
1038 addType(Arg, DIType(Ty));
1039 Buffer.addChild(Arg);
1043 case dwarf::DW_TAG_structure_type:
1044 case dwarf::DW_TAG_union_type:
1045 case dwarf::DW_TAG_class_type: {
1046 // Add elements to structure type.
1047 DIArray Elements = CTy.getTypeArray();
1049 // A forward struct declared type may not have elements available.
1050 unsigned N = Elements.getNumElements();
1054 // Add elements to structure type.
1055 for (unsigned i = 0; i < N; ++i) {
1056 DIDescriptor Element = Elements.getElement(i);
1057 DIE *ElemDie = NULL;
1058 if (Element.isSubprogram())
1059 ElemDie = createSubprogramDIE(DISubprogram(Element));
1060 else if (Element.isVariable()) {
1061 DIVariable DV(Element);
1062 ElemDie = new DIE(dwarf::DW_TAG_variable);
1063 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1065 addType(ElemDie, DV.getType());
1066 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1067 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1068 addSourceLine(ElemDie, DV);
1069 } else if (Element.isDerivedType())
1070 ElemDie = createMemberDIE(DIDerivedType(Element));
1073 Buffer.addChild(ElemDie);
1076 if (CTy.isAppleBlockExtension())
1077 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1079 unsigned RLang = CTy.getRunTimeLang();
1081 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1082 dwarf::DW_FORM_data1, RLang);
1084 DICompositeType ContainingType = CTy.getContainingType();
1085 if (DIDescriptor(ContainingType).isCompositeType())
1086 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1087 getOrCreateTypeDIE(DIType(ContainingType)));
1089 DIDescriptor Context = CTy.getContext();
1090 addToContextOwner(&Buffer, Context);
1098 // Add name if not anonymous or intermediate type.
1100 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1102 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1103 || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1105 // Add size if non-zero (derived types might be zero-sized.)
1107 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1109 // Add zero size if it is not a forward declaration.
1110 if (CTy.isForwardDecl())
1111 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1113 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1116 // Add source line info if available.
1117 if (!CTy.isForwardDecl())
1118 addSourceLine(&Buffer, CTy);
1122 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1123 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1124 int64_t L = SR.getLo();
1125 int64_t H = SR.getHi();
1126 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1128 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1130 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1131 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1133 Buffer.addChild(DW_Subrange);
1136 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1137 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1138 DICompositeType *CTy) {
1139 Buffer.setTag(dwarf::DW_TAG_array_type);
1140 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1141 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1143 // Emit derived type.
1144 addType(&Buffer, CTy->getTypeDerivedFrom());
1145 DIArray Elements = CTy->getTypeArray();
1147 // Get an anonymous type for index type.
1148 CompileUnit *TheCU = getCompileUnit(*CTy);
1149 DIE *IdxTy = TheCU->getIndexTyDie();
1151 // Construct an anonymous type for index type.
1152 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1153 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1154 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1155 dwarf::DW_ATE_signed);
1156 TheCU->addDie(IdxTy);
1157 TheCU->setIndexTyDie(IdxTy);
1160 // Add subranges to array type.
1161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1162 DIDescriptor Element = Elements.getElement(i);
1163 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1164 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1168 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1169 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1170 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1171 StringRef Name = ETy.getName();
1172 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1173 int64_t Value = ETy.getEnumValue();
1174 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1178 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1179 /// printer to not emit usual symbol prefix before the symbol name is used then
1180 /// return linkage name after skipping this special LLVM prefix.
1181 static StringRef getRealLinkageName(StringRef LinkageName) {
1183 if (LinkageName.startswith(StringRef(&One, 1)))
1184 return LinkageName.substr(1);
1188 /// createMemberDIE - Create new member DIE.
1189 DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1190 DIE *MemberDie = new DIE(DT.getTag());
1191 StringRef Name = DT.getName();
1193 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1195 addType(MemberDie, DT.getTypeDerivedFrom());
1197 addSourceLine(MemberDie, DT);
1199 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1200 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1202 uint64_t Size = DT.getSizeInBits();
1203 uint64_t FieldSize = DT.getOriginalTypeSize();
1205 if (Size != FieldSize) {
1207 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1208 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1210 uint64_t Offset = DT.getOffsetInBits();
1211 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1212 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1213 uint64_t FieldOffset = (HiMark - FieldSize);
1214 Offset -= FieldOffset;
1216 // Maybe we need to work from the other end.
1217 if (Asm->getTargetData().isLittleEndian())
1218 Offset = FieldSize - (Offset + Size);
1219 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1221 // Here WD_AT_data_member_location points to the anonymous
1222 // field that includes this bit field.
1223 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1226 // This is not a bitfield.
1227 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1229 if (DT.getTag() == dwarf::DW_TAG_inheritance
1230 && DT.isVirtual()) {
1232 // For C++, virtual base classes are not at fixed offset. Use following
1233 // expression to extract appropriate offset from vtable.
1234 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1236 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1237 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1238 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1239 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1240 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1241 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1242 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1243 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1245 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1248 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1250 if (DT.isProtected())
1251 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1252 dwarf::DW_ACCESS_protected);
1253 else if (DT.isPrivate())
1254 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1255 dwarf::DW_ACCESS_private);
1256 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1257 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1258 dwarf::DW_ACCESS_public);
1260 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1261 dwarf::DW_VIRTUALITY_virtual);
1265 /// createSubprogramDIE - Create new DIE using SP.
1266 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP, bool MakeDecl) {
1267 CompileUnit *SPCU = getCompileUnit(SP);
1268 DIE *SPDie = SPCU->getDIE(SP);
1272 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1273 // Constructors and operators for anonymous aggregates do not have names.
1274 if (!SP.getName().empty())
1275 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1277 StringRef LinkageName = SP.getLinkageName();
1278 if (!LinkageName.empty())
1279 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1280 getRealLinkageName(LinkageName));
1282 addSourceLine(SPDie, SP);
1284 // Add prototyped tag, if C or ObjC.
1285 unsigned Lang = SP.getCompileUnit().getLanguage();
1286 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1287 Lang == dwarf::DW_LANG_ObjC)
1288 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1291 DICompositeType SPTy = SP.getType();
1292 DIArray Args = SPTy.getTypeArray();
1293 unsigned SPTag = SPTy.getTag();
1295 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1296 addType(SPDie, SPTy);
1298 addType(SPDie, DIType(Args.getElement(0)));
1300 unsigned VK = SP.getVirtuality();
1302 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1303 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1304 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1305 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1306 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1307 ContainingTypeMap.insert(std::make_pair(SPDie,
1308 SP.getContainingType()));
1311 if (MakeDecl || !SP.isDefinition()) {
1312 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1314 // Add arguments. Do not add arguments for subprogram definition. They will
1315 // be handled while processing variables.
1316 DICompositeType SPTy = SP.getType();
1317 DIArray Args = SPTy.getTypeArray();
1318 unsigned SPTag = SPTy.getTag();
1320 if (SPTag == dwarf::DW_TAG_subroutine_type)
1321 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1322 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1323 DIType ATy = DIType(DIType(Args.getElement(i)));
1325 if (ATy.isArtificial())
1326 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1327 SPDie->addChild(Arg);
1331 if (SP.isArtificial())
1332 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1334 if (!SP.isLocalToUnit())
1335 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1337 if (SP.isOptimized())
1338 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1340 if (unsigned isa = Asm->getISAEncoding()) {
1341 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1344 // DW_TAG_inlined_subroutine may refer to this DIE.
1345 SPCU->insertDIE(SP, SPDie);
1347 // Add to context owner.
1348 addToContextOwner(SPDie, SP.getContext());
1353 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1354 assert(N && "Invalid Scope encoding!");
1356 DbgScope *AScope = AbstractScopes.lookup(N);
1360 DbgScope *Parent = NULL;
1362 DIDescriptor Scope(N);
1363 if (Scope.isLexicalBlock()) {
1364 DILexicalBlock DB(N);
1365 DIDescriptor ParentDesc = DB.getContext();
1366 Parent = getOrCreateAbstractScope(ParentDesc);
1369 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1372 Parent->addScope(AScope);
1373 AScope->setAbstractScope();
1374 AbstractScopes[N] = AScope;
1375 if (DIDescriptor(N).isSubprogram())
1376 AbstractScopesList.push_back(AScope);
1380 /// isSubprogramContext - Return true if Context is either a subprogram
1381 /// or another context nested inside a subprogram.
1382 static bool isSubprogramContext(const MDNode *Context) {
1385 DIDescriptor D(Context);
1386 if (D.isSubprogram())
1389 return isSubprogramContext(DIType(Context).getContext());
1393 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1394 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1395 /// If there are global variables in this scope then create and insert
1396 /// DIEs for these variables.
1397 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1398 CompileUnit *SPCU = getCompileUnit(SPNode);
1399 DIE *SPDie = SPCU->getDIE(SPNode);
1401 assert(SPDie && "Unable to find subprogram DIE!");
1402 DISubprogram SP(SPNode);
1404 // There is not any need to generate specification DIE for a function
1405 // defined at compile unit level. If a function is defined inside another
1406 // function then gdb prefers the definition at top level and but does not
1407 // expect specification DIE in parent function. So avoid creating
1408 // specification DIE for a function defined inside a function.
1409 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1410 !SP.getContext().isFile() &&
1411 !isSubprogramContext(SP.getContext())) {
1412 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1415 DICompositeType SPTy = SP.getType();
1416 DIArray Args = SPTy.getTypeArray();
1417 unsigned SPTag = SPTy.getTag();
1418 if (SPTag == dwarf::DW_TAG_subroutine_type)
1419 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1420 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1421 DIType ATy = DIType(DIType(Args.getElement(i)));
1423 if (ATy.isArtificial())
1424 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1425 SPDie->addChild(Arg);
1427 DIE *SPDeclDie = SPDie;
1428 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1429 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1431 SPCU->addDie(SPDie);
1434 // Pick up abstract subprogram DIE.
1435 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1436 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1437 addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1438 dwarf::DW_FORM_ref4, AbsSPDIE);
1439 SPCU->addDie(SPDie);
1442 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1443 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1444 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1445 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1446 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1447 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1448 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1453 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1454 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1455 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1457 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1458 if (Scope->isAbstractScope())
1461 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1465 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1466 if (Ranges.size() > 1) {
1467 // .debug_range section has not been laid out yet. Emit offset in
1468 // .debug_range as a uint, size 4, for now. emitDIE will handle
1469 // DW_AT_ranges appropriately.
1470 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1471 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1472 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1473 RE = Ranges.end(); RI != RE; ++RI) {
1474 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1475 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1477 DebugRangeSymbols.push_back(NULL);
1478 DebugRangeSymbols.push_back(NULL);
1482 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1483 const MCSymbol *End = getLabelAfterInsn(RI->second);
1485 if (End == 0) return 0;
1487 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1488 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1490 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1491 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1496 /// constructInlinedScopeDIE - This scope represents inlined body of
1497 /// a function. Construct DIE to represent this concrete inlined copy
1498 /// of the function.
1499 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1501 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1502 assert (Ranges.empty() == false
1503 && "DbgScope does not have instruction markers!");
1505 // FIXME : .debug_inlined section specification does not clearly state how
1506 // to emit inlined scope that is split into multiple instruction ranges.
1507 // For now, use first instruction range and emit low_pc/high_pc pair and
1508 // corresponding .debug_inlined section entry for this pair.
1509 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1510 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1511 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1513 if (StartLabel == 0 || EndLabel == 0) {
1514 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1517 assert(StartLabel->isDefined() &&
1518 "Invalid starting label for an inlined scope!");
1519 assert(EndLabel->isDefined() &&
1520 "Invalid end label for an inlined scope!");
1522 if (!Scope->getScopeNode())
1524 DIScope DS(Scope->getScopeNode());
1525 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1527 DISubprogram InlinedSP = getDISubprogram(DS);
1528 CompileUnit *TheCU = getCompileUnit(InlinedSP);
1529 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1530 assert(OriginDIE && "Unable to find Origin DIE!");
1531 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1532 dwarf::DW_FORM_ref4, OriginDIE);
1534 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1535 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1537 InlinedSubprogramDIEs.insert(OriginDIE);
1539 // Track the start label for this inlined function.
1540 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1541 I = InlineInfo.find(InlinedSP);
1543 if (I == InlineInfo.end()) {
1544 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1546 InlinedSPNodes.push_back(InlinedSP);
1548 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1550 DILocation DL(Scope->getInlinedAt());
1551 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1552 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1558 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1559 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1560 StringRef Name = DV->getName();
1564 // Translate tag to proper Dwarf tag. The result variable is dropped for
1567 switch (DV->getTag()) {
1568 case dwarf::DW_TAG_return_variable:
1570 case dwarf::DW_TAG_arg_variable:
1571 Tag = dwarf::DW_TAG_formal_parameter;
1573 case dwarf::DW_TAG_auto_variable: // fall thru
1575 Tag = dwarf::DW_TAG_variable;
1579 // Define variable debug information entry.
1580 DIE *VariableDie = new DIE(Tag);
1583 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1584 V2AVI = VarToAbstractVarMap.find(DV);
1585 if (V2AVI != VarToAbstractVarMap.end())
1586 AbsDIE = V2AVI->second->getDIE();
1589 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1590 dwarf::DW_FORM_ref4, AbsDIE);
1592 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1593 addSourceLine(VariableDie, DV->getVariable());
1595 // Add variable type.
1596 addType(VariableDie, DV->getType());
1599 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1600 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1602 if (Scope->isAbstractScope()) {
1603 DV->setDIE(VariableDie);
1607 // Add variable address.
1609 unsigned Offset = DV->getDotDebugLocOffset();
1610 if (Offset != ~0U) {
1611 addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1612 Asm->GetTempSymbol("debug_loc", Offset));
1613 DV->setDIE(VariableDie);
1614 UseDotDebugLocEntry.insert(VariableDie);
1618 // Check if variable is described by a DBG_VALUE instruction.
1619 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1620 DbgVariableToDbgInstMap.find(DV);
1621 if (DVI != DbgVariableToDbgInstMap.end()) {
1622 const MachineInstr *DVInsn = DVI->second;
1623 const MCSymbol *DVLabel = findVariableLabel(DV);
1624 bool updated = false;
1625 // FIXME : Handle getNumOperands != 3
1626 if (DVInsn->getNumOperands() == 3) {
1627 if (DVInsn->getOperand(0).isReg())
1629 addRegisterAddress(VariableDie, DVLabel, DVInsn->getOperand(0));
1630 else if (DVInsn->getOperand(0).isImm())
1631 updated = addConstantValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1632 else if (DVInsn->getOperand(0).isFPImm())
1634 addConstantFPValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1636 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1637 if (Location.getReg()) {
1638 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1640 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1646 // If variableDie is not updated then DBG_VALUE instruction does not
1647 // have valid variable info.
1651 DV->setDIE(VariableDie);
1655 // .. else use frame index, if available.
1656 MachineLocation Location;
1658 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1660 if (findVariableFrameIndex(DV, &FI)) {
1661 int Offset = RI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1662 Location.set(FrameReg, Offset);
1663 addVariableAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1665 DV->setDIE(VariableDie);
1670 void DwarfDebug::addPubTypes(DISubprogram SP) {
1671 DICompositeType SPTy = SP.getType();
1672 unsigned SPTag = SPTy.getTag();
1673 if (SPTag != dwarf::DW_TAG_subroutine_type)
1676 DIArray Args = SPTy.getTypeArray();
1677 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1678 DIType ATy(Args.getElement(i));
1681 DICompositeType CATy = getDICompositeType(ATy);
1682 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1683 && !CATy.isForwardDecl()) {
1684 CompileUnit *TheCU = getCompileUnit(CATy);
1685 if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1686 TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1691 /// constructScopeDIE - Construct a DIE for this scope.
1692 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1693 if (!Scope || !Scope->getScopeNode())
1696 DIScope DS(Scope->getScopeNode());
1697 DIE *ScopeDIE = NULL;
1698 if (Scope->getInlinedAt())
1699 ScopeDIE = constructInlinedScopeDIE(Scope);
1700 else if (DS.isSubprogram()) {
1701 ProcessedSPNodes.insert(DS);
1702 if (Scope->isAbstractScope()) {
1703 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1704 // Note down abstract DIE.
1706 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1709 ScopeDIE = updateSubprogramScopeDIE(DS);
1712 ScopeDIE = constructLexicalScopeDIE(Scope);
1713 if (!ScopeDIE) return NULL;
1715 // Add variables to scope.
1716 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1717 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1718 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1720 ScopeDIE->addChild(VariableDIE);
1723 // Add nested scopes.
1724 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1725 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1726 // Define the Scope debug information entry.
1727 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1729 ScopeDIE->addChild(NestedDIE);
1732 if (DS.isSubprogram())
1733 addPubTypes(DISubprogram(DS));
1738 /// GetOrCreateSourceID - Look up the source id with the given directory and
1739 /// source file names. If none currently exists, create a new id and insert it
1740 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1742 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1744 assert (DirName.empty() == false && "Invalid directory name!");
1746 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1747 if (DI != DirectoryIdMap.end()) {
1748 DId = DI->getValue();
1750 DId = DirectoryNames.size() + 1;
1751 DirectoryIdMap[DirName] = DId;
1752 DirectoryNames.push_back(DirName);
1756 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1757 if (FI != SourceFileIdMap.end()) {
1758 FId = FI->getValue();
1760 FId = SourceFileNames.size() + 1;
1761 SourceFileIdMap[FileName] = FId;
1762 SourceFileNames.push_back(FileName);
1765 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1766 SourceIdMap.find(std::make_pair(DId, FId));
1767 if (SI != SourceIdMap.end())
1770 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1771 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1772 SourceIds.push_back(std::make_pair(DId, FId));
1777 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1778 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1779 CompileUnit *TheCU = getCompileUnit(NS);
1780 DIE *NDie = TheCU->getDIE(NS);
1783 NDie = new DIE(dwarf::DW_TAG_namespace);
1784 TheCU->insertDIE(NS, NDie);
1785 if (!NS.getName().empty())
1786 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1787 addSourceLine(NDie, NS);
1788 addToContextOwner(NDie, NS.getContext());
1792 /// constructCompileUnit - Create new CompileUnit for the given
1793 /// metadata node with tag DW_TAG_compile_unit.
1794 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1795 DICompileUnit DIUnit(N);
1796 StringRef FN = DIUnit.getFilename();
1797 StringRef Dir = DIUnit.getDirectory();
1798 unsigned ID = GetOrCreateSourceID(Dir, FN);
1800 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1801 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1802 DIUnit.getProducer());
1803 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1804 DIUnit.getLanguage());
1805 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1806 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1807 // simplifies debug range entries.
1808 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1809 // DW_AT_stmt_list is a offset of line number information for this
1810 // compile unit in debug_line section.
1811 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1814 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1815 if (DIUnit.isOptimized())
1816 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1818 StringRef Flags = DIUnit.getFlags();
1820 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1822 unsigned RVer = DIUnit.getRunTimeVersion();
1824 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1825 dwarf::DW_FORM_data1, RVer);
1827 CompileUnit *NewCU = new CompileUnit(ID, Die);
1830 CUMap.insert(std::make_pair(N, NewCU));
1833 /// getCompielUnit - Get CompileUnit DIE.
1834 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1835 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1837 const MDNode *CUNode = NULL;
1838 if (D.isCompileUnit())
1840 else if (D.isSubprogram())
1841 CUNode = DISubprogram(N).getCompileUnit();
1842 else if (D.isType())
1843 CUNode = DIType(N).getCompileUnit();
1844 else if (D.isGlobalVariable())
1845 CUNode = DIGlobalVariable(N).getCompileUnit();
1846 else if (D.isVariable())
1847 CUNode = DIVariable(N).getCompileUnit();
1848 else if (D.isNameSpace())
1849 CUNode = DINameSpace(N).getCompileUnit();
1850 else if (D.isFile())
1851 CUNode = DIFile(N).getCompileUnit();
1855 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1856 = CUMap.find(CUNode);
1857 if (I == CUMap.end())
1862 /// isUnsignedDIType - Return true if type encoding is unsigned.
1863 static bool isUnsignedDIType(DIType Ty) {
1864 DIDerivedType DTy(Ty);
1866 return isUnsignedDIType(DTy.getTypeDerivedFrom());
1868 DIBasicType BTy(Ty);
1870 unsigned Encoding = BTy.getEncoding();
1871 if (Encoding == dwarf::DW_ATE_unsigned ||
1872 Encoding == dwarf::DW_ATE_unsigned_char)
1878 /// constructGlobalVariableDIE - Construct global variable DIE.
1879 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1880 DIGlobalVariable GV(N);
1882 // If debug information is malformed then ignore it.
1883 if (GV.Verify() == false)
1886 // Check for pre-existence.
1887 CompileUnit *TheCU = getCompileUnit(N);
1888 if (TheCU->getDIE(GV))
1891 DIType GTy = GV.getType();
1892 DIE *VariableDIE = new DIE(GV.getTag());
1894 bool isGlobalVariable = GV.getGlobal() != NULL;
1897 addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1898 GV.getDisplayName());
1899 StringRef LinkageName = GV.getLinkageName();
1900 if (!LinkageName.empty() && isGlobalVariable)
1901 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1902 getRealLinkageName(LinkageName));
1904 addType(VariableDIE, GTy);
1905 if (GTy.isCompositeType() && !GTy.getName().empty()
1906 && !GTy.isForwardDecl()) {
1907 DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1908 assert(Entry && "Missing global type!");
1909 TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1911 // Add scoping info.
1912 if (!GV.isLocalToUnit()) {
1913 addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1914 // Expose as global.
1915 TheCU->addGlobal(GV.getName(), VariableDIE);
1917 // Add line number info.
1918 addSourceLine(VariableDIE, GV);
1920 TheCU->insertDIE(N, VariableDIE);
1921 // Add to context owner.
1922 DIDescriptor GVContext = GV.getContext();
1923 addToContextOwner(VariableDIE, GVContext);
1925 if (isGlobalVariable) {
1926 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1927 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1928 addLabel(Block, 0, dwarf::DW_FORM_udata,
1929 Asm->Mang->getSymbol(GV.getGlobal()));
1930 // Do not create specification DIE if context is either compile unit
1932 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1933 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1934 // Create specification DIE.
1935 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1936 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1937 dwarf::DW_FORM_ref4, VariableDIE);
1938 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1939 addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1940 TheCU->addDie(VariableSpecDIE);
1942 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1944 } else if (Constant *C = GV.getConstant()) {
1945 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1946 if (isUnsignedDIType(GTy))
1947 addUInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1948 CI->getZExtValue());
1950 addSInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1951 CI->getSExtValue());
1957 /// construct SubprogramDIE - Construct subprogram DIE.
1958 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1961 // Check for pre-existence.
1962 CompileUnit *TheCU = getCompileUnit(N);
1963 if (TheCU->getDIE(N))
1966 if (!SP.isDefinition())
1967 // This is a method declaration which will be handled while constructing
1971 DIE *SubprogramDie = createSubprogramDIE(SP);
1974 TheCU->insertDIE(N, SubprogramDie);
1976 // Add to context owner.
1977 addToContextOwner(SubprogramDie, SP.getContext());
1979 // Expose as global.
1980 TheCU->addGlobal(SP.getName(), SubprogramDie);
1985 /// beginModule - Emit all Dwarf sections that should come prior to the
1986 /// content. Create global DIEs and emit initial debug info sections.
1987 /// This is inovked by the target AsmPrinter.
1988 void DwarfDebug::beginModule(Module *M) {
1989 if (DisableDebugInfoPrinting)
1992 DebugInfoFinder DbgFinder;
1993 DbgFinder.processModule(*M);
1995 bool HasDebugInfo = false;
1997 // Scan all the compile-units to see if there are any marked as the main unit.
1998 // if not, we do not generate debug info.
1999 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2000 E = DbgFinder.compile_unit_end(); I != E; ++I) {
2001 if (DICompileUnit(*I).isMain()) {
2002 HasDebugInfo = true;
2007 if (!HasDebugInfo) return;
2009 // Tell MMI that we have debug info.
2010 MMI->setDebugInfoAvailability(true);
2012 // Emit initial sections.
2013 EmitSectionLabels();
2015 // Create all the compile unit DIEs.
2016 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2017 E = DbgFinder.compile_unit_end(); I != E; ++I)
2018 constructCompileUnit(*I);
2020 // Create DIEs for each subprogram.
2021 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2022 E = DbgFinder.subprogram_end(); I != E; ++I)
2023 constructSubprogramDIE(*I);
2025 // Create DIEs for each global variable.
2026 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2027 E = DbgFinder.global_variable_end(); I != E; ++I)
2028 constructGlobalVariableDIE(*I);
2030 //getOrCreateTypeDIE
2031 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2032 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2033 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2035 // Prime section data.
2036 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2038 // Print out .file directives to specify files for .loc directives. These are
2039 // printed out early so that they precede any .loc directives.
2040 if (Asm->MAI->hasDotLocAndDotFile()) {
2041 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2042 // Remember source id starts at 1.
2043 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2044 // FIXME: don't use sys::path for this! This should not depend on the
2046 sys::Path FullPath(getSourceDirectoryName(Id.first));
2048 FullPath.appendComponent(getSourceFileName(Id.second));
2049 assert(AppendOk && "Could not append filename to directory!");
2051 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
2056 /// endModule - Emit all Dwarf sections that should come after the content.
2058 void DwarfDebug::endModule() {
2059 if (!FirstCU) return;
2060 const Module *M = MMI->getModule();
2061 DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2062 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2063 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2064 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2065 DISubprogram SP(AllSPs->getOperand(SI));
2066 if (!SP.Verify()) continue;
2068 // Collect info for variables that were optimized out.
2069 if (!SP.isDefinition()) continue;
2070 StringRef FName = SP.getLinkageName();
2072 FName = SP.getName();
2074 M->getNamedMetadata(Twine("llvm.dbg.lv.", getRealLinkageName(FName)));
2076 unsigned E = NMD->getNumOperands();
2078 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2079 DeadFnScopeMap[SP] = Scope;
2080 for (unsigned I = 0; I != E; ++I) {
2081 DIVariable DV(NMD->getOperand(I));
2082 if (!DV.Verify()) continue;
2083 Scope->addVariable(new DbgVariable(DV));
2086 // Construct subprogram DIE and add variables DIEs.
2087 constructSubprogramDIE(SP);
2088 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2089 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2090 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2091 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2093 ScopeDIE->addChild(VariableDIE);
2098 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2099 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2100 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2102 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2105 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2106 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2107 DIE *SPDie = CI->first;
2108 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2110 DIE *NDie = getCompileUnit(N)->getDIE(N);
2111 if (!NDie) continue;
2112 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2115 // Standard sections final addresses.
2116 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2117 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2118 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2119 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2121 // End text sections.
2122 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2123 Asm->OutStreamer.SwitchSection(SectionMap[i]);
2124 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2127 // Emit common frame information.
2128 emitCommonDebugFrame();
2130 // Emit function debug frame information
2131 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2132 E = DebugFrames.end(); I != E; ++I)
2133 emitFunctionDebugFrame(*I);
2135 // Compute DIE offsets and sizes.
2136 computeSizeAndOffsets();
2138 // Emit all the DIEs into a debug info section
2141 // Corresponding abbreviations into a abbrev section.
2142 emitAbbreviations();
2144 // Emit source line correspondence into a debug line section.
2147 // Emit info into a debug pubnames section.
2148 emitDebugPubNames();
2150 // Emit info into a debug pubtypes section.
2151 emitDebugPubTypes();
2153 // Emit info into a debug loc section.
2156 // Emit info into a debug aranges section.
2159 // Emit info into a debug ranges section.
2162 // Emit info into a debug macinfo section.
2165 // Emit inline info.
2166 emitDebugInlineInfo();
2168 // Emit info into a debug str section.
2172 DeleteContainerSeconds(DeadFnScopeMap);
2173 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2174 E = CUMap.end(); I != E; ++I)
2176 FirstCU = NULL; // Reset for the next Module, if any.
2179 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2180 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2181 DebugLoc ScopeLoc) {
2183 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2185 return AbsDbgVariable;
2187 LLVMContext &Ctx = Var->getContext();
2188 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2192 AbsDbgVariable = new DbgVariable(Var);
2193 Scope->addVariable(AbsDbgVariable);
2194 AbstractVariables[Var] = AbsDbgVariable;
2195 return AbsDbgVariable;
2198 /// collectVariableInfoFromMMITable - Collect variable information from
2199 /// side table maintained by MMI.
2201 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2202 SmallPtrSet<const MDNode *, 16> &Processed) {
2203 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2204 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2205 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2206 VE = VMap.end(); VI != VE; ++VI) {
2207 const MDNode *Var = VI->first;
2209 Processed.insert(Var);
2211 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2213 DbgScope *Scope = 0;
2214 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2215 Scope = ConcreteScopes.lookup(IA);
2217 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2219 // If variable scope is not found then skip this variable.
2223 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2224 DbgVariable *RegVar = new DbgVariable(DV);
2225 recordVariableFrameIndex(RegVar, VP.first);
2226 Scope->addVariable(RegVar);
2227 if (AbsDbgVariable) {
2228 recordVariableFrameIndex(AbsDbgVariable, VP.first);
2229 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2234 /// isDbgValueInUndefinedReg - Return true if debug value, encoded by
2235 /// DBG_VALUE instruction, is in undefined reg.
2236 static bool isDbgValueInUndefinedReg(const MachineInstr *MI) {
2237 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2238 if (MI->getOperand(0).isReg() && !MI->getOperand(0).getReg())
2243 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
2244 /// DBG_VALUE instruction, is in a defined reg.
2245 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2246 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2247 if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
2252 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2254 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2255 SmallPtrSet<const MDNode *, 16> &Processed) {
2257 /// collection info from MMI table.
2258 collectVariableInfoFromMMITable(MF, Processed);
2260 SmallVector<const MachineInstr *, 8> DbgValues;
2261 // Collect variable information from DBG_VALUE machine instructions;
2262 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2264 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2266 const MachineInstr *MInsn = II;
2267 if (!MInsn->isDebugValue() || isDbgValueInUndefinedReg(MInsn))
2269 DbgValues.push_back(MInsn);
2272 // This is a collection of DBV_VALUE instructions describing same variable.
2273 SmallVector<const MachineInstr *, 4> MultipleValues;
2274 for(SmallVector<const MachineInstr *, 8>::iterator I = DbgValues.begin(),
2275 E = DbgValues.end(); I != E; ++I) {
2276 const MachineInstr *MInsn = *I;
2277 MultipleValues.clear();
2278 if (isDbgValueInDefinedReg(MInsn))
2279 MultipleValues.push_back(MInsn);
2280 DIVariable DV(MInsn->getOperand(MInsn->getNumOperands() - 1).getMetadata());
2281 if (Processed.count(DV) != 0)
2284 const MachineInstr *PrevMI = MInsn;
2285 for (SmallVector<const MachineInstr *, 8>::iterator MI = I+1,
2286 ME = DbgValues.end(); MI != ME; ++MI) {
2288 (*MI)->getOperand((*MI)->getNumOperands()-1).getMetadata();
2289 if (Var == DV && isDbgValueInDefinedReg(*MI) &&
2290 !PrevMI->isIdenticalTo(*MI))
2291 MultipleValues.push_back(*MI);
2295 DbgScope *Scope = findDbgScope(MInsn);
2296 bool CurFnArg = false;
2297 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2298 DISubprogram(DV.getContext()).describes(MF->getFunction()))
2300 if (!Scope && CurFnArg)
2301 Scope = CurrentFnDbgScope;
2302 // If variable scope is not found then skip this variable.
2306 Processed.insert(DV);
2307 DbgVariable *RegVar = new DbgVariable(DV);
2308 Scope->addVariable(RegVar);
2310 DbgVariableLabelsMap[RegVar] = getLabelBeforeInsn(MInsn);
2311 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2312 DbgVariableToDbgInstMap[AbsVar] = MInsn;
2313 VarToAbstractVarMap[RegVar] = AbsVar;
2315 if (MultipleValues.size() <= 1) {
2316 DbgVariableToDbgInstMap[RegVar] = MInsn;
2320 // handle multiple DBG_VALUE instructions describing one variable.
2321 if (DotDebugLocEntries.empty())
2322 RegVar->setDotDebugLocOffset(0);
2324 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2325 const MachineInstr *Begin = NULL;
2326 const MachineInstr *End = NULL;
2327 for (SmallVector<const MachineInstr *, 4>::iterator
2328 MVI = MultipleValues.begin(), MVE = MultipleValues.end();
2329 MVI != MVE; ++MVI) {
2335 MachineLocation MLoc;
2336 if (Begin->getNumOperands() == 3) {
2337 if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2338 MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2340 MLoc = Asm->getDebugValueLocation(Begin);
2342 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2343 const MCSymbol *SLabel = getLabelBeforeInsn(End);
2345 DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2348 if (MVI + 1 == MVE) {
2349 // If End is the last instruction then its value is valid
2350 // until the end of the funtion.
2351 MachineLocation EMLoc;
2352 if (End->getNumOperands() == 3) {
2353 if (End->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2354 EMLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2356 EMLoc = Asm->getDebugValueLocation(End);
2359 push_back(DotDebugLocEntry(SLabel, FunctionEndSym, EMLoc));
2362 DotDebugLocEntries.push_back(DotDebugLocEntry());
2365 // Collect info for variables that were optimized out.
2366 const Function *F = MF->getFunction();
2367 const Module *M = F->getParent();
2368 if (NamedMDNode *NMD =
2369 M->getNamedMetadata(Twine("llvm.dbg.lv.",
2370 getRealLinkageName(F->getName())))) {
2371 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2372 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2373 if (!DV || !Processed.insert(DV))
2375 DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2377 Scope->addVariable(new DbgVariable(DV));
2382 /// getLabelBeforeInsn - Return Label preceding the instruction.
2383 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2384 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2385 LabelsBeforeInsn.find(MI);
2386 if (I == LabelsBeforeInsn.end())
2387 // FunctionBeginSym always preceeds all the instruction in current function.
2388 return FunctionBeginSym;
2392 /// getLabelAfterInsn - Return Label immediately following the instruction.
2393 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2394 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2395 LabelsAfterInsn.find(MI);
2396 if (I == LabelsAfterInsn.end())
2401 /// beginScope - Process beginning of a scope.
2402 void DwarfDebug::beginScope(const MachineInstr *MI) {
2403 if (InsnNeedsLabel.count(MI) == 0) {
2404 LabelsBeforeInsn[MI] = PrevLabel;
2409 DebugLoc DL = MI->getDebugLoc();
2410 if (!DL.isUnknown()) {
2411 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2412 PrevLabel = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2414 LabelsBeforeInsn[MI] = PrevLabel;
2418 // If location is unknown then use temp label for this DBG_VALUE
2420 if (MI->isDebugValue()) {
2421 PrevLabel = MMI->getContext().CreateTempSymbol();
2422 Asm->OutStreamer.EmitLabel(PrevLabel);
2423 LabelsBeforeInsn[MI] = PrevLabel;
2427 if (UnknownLocations) {
2428 PrevLabel = recordSourceLine(0, 0, 0);
2429 LabelsBeforeInsn[MI] = PrevLabel;
2433 assert (0 && "Instruction is not processed!");
2436 /// endScope - Process end of a scope.
2437 void DwarfDebug::endScope(const MachineInstr *MI) {
2438 if (InsnsEndScopeSet.count(MI) != 0) {
2439 // Emit a label if this instruction ends a scope.
2440 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2441 Asm->OutStreamer.EmitLabel(Label);
2442 LabelsAfterInsn[MI] = Label;
2446 /// getOrCreateDbgScope - Create DbgScope for the scope.
2447 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2448 const MDNode *InlinedAt) {
2450 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2453 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2454 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2455 if (DIDescriptor(Scope).isLexicalBlock()) {
2457 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2458 WScope->setParent(Parent);
2459 Parent->addScope(WScope);
2462 if (!WScope->getParent()) {
2463 StringRef SPName = DISubprogram(Scope).getLinkageName();
2464 // We used to check only for a linkage name, but that fails
2465 // since we began omitting the linkage name for private
2466 // functions. The new way is to check for the name in metadata,
2467 // but that's not supported in old .ll test cases. Ergo, we
2469 if (SPName == Asm->MF->getFunction()->getName() ||
2470 DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2471 CurrentFnDbgScope = WScope;
2477 getOrCreateAbstractScope(Scope);
2478 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2482 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2483 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2484 DILocation DL(InlinedAt);
2486 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2487 WScope->setParent(Parent);
2488 Parent->addScope(WScope);
2490 ConcreteScopes[InlinedAt] = WScope;
2495 /// hasValidLocation - Return true if debug location entry attached with
2496 /// machine instruction encodes valid location info.
2497 static bool hasValidLocation(LLVMContext &Ctx,
2498 const MachineInstr *MInsn,
2499 const MDNode *&Scope, const MDNode *&InlinedAt) {
2500 DebugLoc DL = MInsn->getDebugLoc();
2501 if (DL.isUnknown()) return false;
2503 const MDNode *S = DL.getScope(Ctx);
2505 // There is no need to create another DIE for compile unit. For all
2506 // other scopes, create one DbgScope now. This will be translated
2507 // into a scope DIE at the end.
2508 if (DIScope(S).isCompileUnit()) return false;
2511 InlinedAt = DL.getInlinedAt(Ctx);
2515 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2517 static void calculateDominanceGraph(DbgScope *Scope) {
2518 assert (Scope && "Unable to calculate scop edominance graph!");
2519 SmallVector<DbgScope *, 4> WorkStack;
2520 WorkStack.push_back(Scope);
2521 unsigned Counter = 0;
2522 while (!WorkStack.empty()) {
2523 DbgScope *WS = WorkStack.back();
2524 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2525 bool visitedChildren = false;
2526 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2527 SE = Children.end(); SI != SE; ++SI) {
2528 DbgScope *ChildScope = *SI;
2529 if (!ChildScope->getDFSOut()) {
2530 WorkStack.push_back(ChildScope);
2531 visitedChildren = true;
2532 ChildScope->setDFSIn(++Counter);
2536 if (!visitedChildren) {
2537 WorkStack.pop_back();
2538 WS->setDFSOut(++Counter);
2543 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2545 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2546 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2549 unsigned PrevDFSIn = 0;
2550 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2552 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2554 const MachineInstr *MInsn = II;
2555 const MDNode *Scope = NULL;
2556 const MDNode *InlinedAt = NULL;
2558 // Check if instruction has valid location information.
2559 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2563 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2564 MI2ScopeMap.find(MInsn);
2565 if (DI != MI2ScopeMap.end()) {
2566 DbgScope *S = DI->second;
2567 dbgs() << S->getDFSIn();
2568 PrevDFSIn = S->getDFSIn();
2570 dbgs() << PrevDFSIn;
2572 dbgs() << " [ x" << PrevDFSIn;
2580 /// extractScopeInformation - Scan machine instructions in this function
2581 /// and collect DbgScopes. Return true, if at least one scope was found.
2582 bool DwarfDebug::extractScopeInformation() {
2583 // If scope information was extracted using .dbg intrinsics then there is not
2584 // any need to extract these information by scanning each instruction.
2585 if (!DbgScopeMap.empty())
2588 // Scan each instruction and create scopes. First build working set of scopes.
2589 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2590 SmallVector<DbgRange, 4> MIRanges;
2591 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2592 const MDNode *PrevScope = NULL;
2593 const MDNode *PrevInlinedAt = NULL;
2594 const MachineInstr *RangeBeginMI = NULL;
2595 const MachineInstr *PrevMI = NULL;
2596 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2598 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2600 const MachineInstr *MInsn = II;
2601 const MDNode *Scope = NULL;
2602 const MDNode *InlinedAt = NULL;
2604 // Check if instruction has valid location information.
2605 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2610 // If scope has not changed then skip this instruction.
2611 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2617 // If we have alread seen a beginning of a instruction range and
2618 // current instruction scope does not match scope of first instruction
2619 // in this range then create a new instruction range.
2620 DbgRange R(RangeBeginMI, PrevMI);
2621 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2623 MIRanges.push_back(R);
2626 // This is a beginning of a new instruction range.
2627 RangeBeginMI = MInsn;
2629 // Reset previous markers.
2632 PrevInlinedAt = InlinedAt;
2636 // Create last instruction range.
2637 if (RangeBeginMI && PrevMI && PrevScope) {
2638 DbgRange R(RangeBeginMI, PrevMI);
2639 MIRanges.push_back(R);
2640 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2643 if (!CurrentFnDbgScope)
2646 calculateDominanceGraph(CurrentFnDbgScope);
2648 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2650 // Find ranges of instructions covered by each DbgScope;
2651 DbgScope *PrevDbgScope = NULL;
2652 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2653 RE = MIRanges.end(); RI != RE; ++RI) {
2654 const DbgRange &R = *RI;
2655 DbgScope *S = MI2ScopeMap.lookup(R.first);
2656 assert (S && "Lost DbgScope for a machine instruction!");
2657 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2658 PrevDbgScope->closeInsnRange(S);
2659 S->openInsnRange(R.first);
2660 S->extendInsnRange(R.second);
2665 PrevDbgScope->closeInsnRange();
2667 identifyScopeMarkers();
2669 return !DbgScopeMap.empty();
2672 /// identifyScopeMarkers() -
2673 /// Each DbgScope has first instruction and last instruction to mark beginning
2674 /// and end of a scope respectively. Create an inverse map that list scopes
2675 /// starts (and ends) with an instruction. One instruction may start (or end)
2676 /// multiple scopes. Ignore scopes that are not reachable.
2677 void DwarfDebug::identifyScopeMarkers() {
2678 SmallVector<DbgScope *, 4> WorkList;
2679 WorkList.push_back(CurrentFnDbgScope);
2680 while (!WorkList.empty()) {
2681 DbgScope *S = WorkList.pop_back_val();
2683 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2684 if (!Children.empty())
2685 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2686 SE = Children.end(); SI != SE; ++SI)
2687 WorkList.push_back(*SI);
2689 if (S->isAbstractScope())
2692 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2695 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2696 RE = Ranges.end(); RI != RE; ++RI) {
2697 assert(RI->first && "DbgRange does not have first instruction!");
2698 assert(RI->second && "DbgRange does not have second instruction!");
2699 InsnsEndScopeSet.insert(RI->second);
2704 /// FindFirstDebugLoc - Find the first debug location in the function. This
2705 /// is intended to be an approximation for the source position of the
2706 /// beginning of the function.
2707 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2708 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2710 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2711 MBBI != MBBE; ++MBBI) {
2712 DebugLoc DL = MBBI->getDebugLoc();
2713 if (!DL.isUnknown())
2719 /// beginFunction - Gather pre-function debug information. Assumes being
2720 /// emitted immediately after the function entry point.
2721 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2722 if (!MMI->hasDebugInfo()) return;
2723 if (!extractScopeInformation()) return;
2725 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2726 Asm->getFunctionNumber());
2727 // Assumes in correct section after the entry point.
2728 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2730 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2732 DebugLoc FDL = FindFirstDebugLoc(MF);
2733 if (FDL.isUnknown()) return;
2735 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2736 const MDNode *TheScope = 0;
2738 DISubprogram SP = getDISubprogram(Scope);
2741 Line = SP.getLineNumber();
2745 Line = FDL.getLine();
2750 recordSourceLine(Line, Col, TheScope);
2752 /// ProcessedArgs - Collection of arguments already processed.
2753 SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2756 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2758 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2760 const MachineInstr *MI = II;
2761 DebugLoc DL = MI->getDebugLoc();
2762 if (MI->isDebugValue()) {
2763 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2764 DIVariable DV(MI->getOperand(MI->getNumOperands() - 1).getMetadata());
2765 if (!DV.Verify()) continue;
2766 // If DBG_VALUE is for a local variable then it needs a label.
2767 if (DV.getTag() != dwarf::DW_TAG_arg_variable
2768 && isDbgValueInUndefinedReg(MI) == false)
2769 InsnNeedsLabel.insert(MI);
2770 // DBG_VALUE for inlined functions argument needs a label.
2771 else if (!DISubprogram(getDISubprogram(DV.getContext())).
2772 describes(MF->getFunction()))
2773 InsnNeedsLabel.insert(MI);
2774 // DBG_VALUE indicating argument location change needs a label.
2775 else if (isDbgValueInUndefinedReg(MI) == false
2776 && !ProcessedArgs.insert(DV))
2777 InsnNeedsLabel.insert(MI);
2779 // If location is unknown then instruction needs a location only if
2780 // UnknownLocations flag is set.
2781 if (DL.isUnknown()) {
2782 if (UnknownLocations && !PrevLoc.isUnknown())
2783 InsnNeedsLabel.insert(MI);
2784 } else if (DL != PrevLoc)
2785 // Otherwise, instruction needs a location only if it is new location.
2786 InsnNeedsLabel.insert(MI);
2789 if (!DL.isUnknown() || UnknownLocations)
2793 PrevLabel = FunctionBeginSym;
2796 /// endFunction - Gather and emit post-function debug information.
2798 void DwarfDebug::endFunction(const MachineFunction *MF) {
2799 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2801 if (CurrentFnDbgScope) {
2803 // Define end label for subprogram.
2804 FunctionEndSym = Asm->GetTempSymbol("func_end",
2805 Asm->getFunctionNumber());
2806 // Assumes in correct section after the entry point.
2807 Asm->OutStreamer.EmitLabel(FunctionEndSym);
2809 SmallPtrSet<const MDNode *, 16> ProcessedVars;
2810 collectVariableInfo(MF, ProcessedVars);
2812 // Get function line info.
2813 if (!Lines.empty()) {
2814 // Get section line info.
2815 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2816 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2817 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2818 // Append the function info to section info.
2819 SectionLineInfos.insert(SectionLineInfos.end(),
2820 Lines.begin(), Lines.end());
2823 // Construct abstract scopes.
2824 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2825 AE = AbstractScopesList.end(); AI != AE; ++AI) {
2826 DISubprogram SP((*AI)->getScopeNode());
2828 // Collect info for variables that were optimized out.
2829 StringRef FName = SP.getLinkageName();
2831 FName = SP.getName();
2832 const Module *M = MF->getFunction()->getParent();
2833 if (NamedMDNode *NMD =
2834 M->getNamedMetadata(Twine("llvm.dbg.lv.",
2835 getRealLinkageName(FName)))) {
2836 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2837 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2838 if (!DV || !ProcessedVars.insert(DV))
2840 DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2842 Scope->addVariable(new DbgVariable(DV));
2846 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2847 constructScopeDIE(*AI);
2850 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2852 if (!DisableFramePointerElim(*MF))
2853 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2854 dwarf::DW_FORM_flag, 1);
2857 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2858 MMI->getFrameMoves()));
2862 CurrentFnDbgScope = NULL;
2863 InsnNeedsLabel.clear();
2864 DbgVariableToFrameIndexMap.clear();
2865 VarToAbstractVarMap.clear();
2866 DbgVariableToDbgInstMap.clear();
2867 DbgVariableLabelsMap.clear();
2868 DeleteContainerSeconds(DbgScopeMap);
2869 InsnsEndScopeSet.clear();
2870 ConcreteScopes.clear();
2871 DeleteContainerSeconds(AbstractScopes);
2872 AbstractScopesList.clear();
2873 AbstractVariables.clear();
2874 LabelsBeforeInsn.clear();
2875 LabelsAfterInsn.clear();
2880 /// recordVariableFrameIndex - Record a variable's index.
2881 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2882 assert (V && "Invalid DbgVariable!");
2883 DbgVariableToFrameIndexMap[V] = Index;
2886 /// findVariableFrameIndex - Return true if frame index for the variable
2887 /// is found. Update FI to hold value of the index.
2888 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2889 assert (V && "Invalid DbgVariable!");
2890 DenseMap<const DbgVariable *, int>::iterator I =
2891 DbgVariableToFrameIndexMap.find(V);
2892 if (I == DbgVariableToFrameIndexMap.end())
2898 /// findVariableLabel - Find MCSymbol for the variable.
2899 const MCSymbol *DwarfDebug::findVariableLabel(const DbgVariable *V) {
2900 DenseMap<const DbgVariable *, const MCSymbol *>::iterator I
2901 = DbgVariableLabelsMap.find(V);
2902 if (I == DbgVariableLabelsMap.end())
2904 else return I->second;
2907 /// findDbgScope - Find DbgScope for the debug loc attached with an
2909 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2910 DbgScope *Scope = NULL;
2912 MInsn->getParent()->getParent()->getFunction()->getContext();
2913 DebugLoc DL = MInsn->getDebugLoc();
2918 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2919 Scope = ConcreteScopes.lookup(IA);
2921 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2927 /// recordSourceLine - Register a source line with debug info. Returns the
2928 /// unique label that was emitted and which provides correspondence to
2929 /// the source line list.
2930 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2937 DIDescriptor Scope(S);
2939 if (Scope.isCompileUnit()) {
2940 DICompileUnit CU(S);
2941 Dir = CU.getDirectory();
2942 Fn = CU.getFilename();
2943 } else if (Scope.isSubprogram()) {
2945 Dir = SP.getDirectory();
2946 Fn = SP.getFilename();
2947 } else if (Scope.isLexicalBlock()) {
2948 DILexicalBlock DB(S);
2949 Dir = DB.getDirectory();
2950 Fn = DB.getFilename();
2952 assert(0 && "Unexpected scope info");
2954 Src = GetOrCreateSourceID(Dir, Fn);
2957 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2958 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2960 Asm->OutStreamer.EmitLabel(Label);
2964 //===----------------------------------------------------------------------===//
2966 //===----------------------------------------------------------------------===//
2968 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2971 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2972 // Get the children.
2973 const std::vector<DIE *> &Children = Die->getChildren();
2975 // If not last sibling and has children then add sibling offset attribute.
2976 if (!Last && !Children.empty())
2977 Die->addSiblingOffset(DIEValueAllocator);
2979 // Record the abbreviation.
2980 assignAbbrevNumber(Die->getAbbrev());
2982 // Get the abbreviation for this DIE.
2983 unsigned AbbrevNumber = Die->getAbbrevNumber();
2984 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2987 Die->setOffset(Offset);
2989 // Start the size with the size of abbreviation code.
2990 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2992 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2993 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2995 // Size the DIE attribute values.
2996 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2997 // Size attribute value.
2998 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
3000 // Size the DIE children if any.
3001 if (!Children.empty()) {
3002 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
3003 "Children flag not set");
3005 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3006 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3008 // End of children marker.
3009 Offset += sizeof(int8_t);
3012 Die->setSize(Offset - Die->getOffset());
3016 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3018 void DwarfDebug::computeSizeAndOffsets() {
3019 unsigned PrevOffset = 0;
3020 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3021 E = CUMap.end(); I != E; ++I) {
3022 // Compute size of compile unit header.
3023 static unsigned Offset = PrevOffset +
3024 sizeof(int32_t) + // Length of Compilation Unit Info
3025 sizeof(int16_t) + // DWARF version number
3026 sizeof(int32_t) + // Offset Into Abbrev. Section
3027 sizeof(int8_t); // Pointer Size (in bytes)
3028 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3029 PrevOffset = Offset;
3033 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3034 /// temporary label to it if SymbolStem is specified.
3035 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3036 const char *SymbolStem = 0) {
3037 Asm->OutStreamer.SwitchSection(Section);
3038 if (!SymbolStem) return 0;
3040 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3041 Asm->OutStreamer.EmitLabel(TmpSym);
3045 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
3046 /// the start of each one.
3047 void DwarfDebug::EmitSectionLabels() {
3048 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3050 // Dwarf sections base addresses.
3051 if (Asm->MAI->doesDwarfRequireFrameSection()) {
3052 DwarfFrameSectionSym =
3053 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3056 DwarfInfoSectionSym =
3057 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3058 DwarfAbbrevSectionSym =
3059 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3060 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3062 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3063 EmitSectionSym(Asm, MacroInfo);
3065 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3066 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3067 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3068 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3069 DwarfStrSectionSym =
3070 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3071 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3074 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3075 "section_debug_loc");
3077 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3078 EmitSectionSym(Asm, TLOF.getDataSection());
3081 /// emitDIE - Recusively Emits a debug information entry.
3083 void DwarfDebug::emitDIE(DIE *Die) {
3084 // Get the abbreviation for this DIE.
3085 unsigned AbbrevNumber = Die->getAbbrevNumber();
3086 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3088 // Emit the code (index) for the abbreviation.
3089 if (Asm->isVerbose())
3090 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3091 Twine::utohexstr(Die->getOffset()) + ":0x" +
3092 Twine::utohexstr(Die->getSize()) + " " +
3093 dwarf::TagString(Abbrev->getTag()));
3094 Asm->EmitULEB128(AbbrevNumber);
3096 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3097 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3099 // Emit the DIE attribute values.
3100 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3101 unsigned Attr = AbbrevData[i].getAttribute();
3102 unsigned Form = AbbrevData[i].getForm();
3103 assert(Form && "Too many attributes for DIE (check abbreviation)");
3105 if (Asm->isVerbose())
3106 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3109 case dwarf::DW_AT_sibling:
3110 Asm->EmitInt32(Die->getSiblingOffset());
3112 case dwarf::DW_AT_abstract_origin: {
3113 DIEEntry *E = cast<DIEEntry>(Values[i]);
3114 DIE *Origin = E->getEntry();
3115 unsigned Addr = Origin->getOffset();
3116 Asm->EmitInt32(Addr);
3119 case dwarf::DW_AT_ranges: {
3120 // DW_AT_range Value encodes offset in debug_range section.
3121 DIEInteger *V = cast<DIEInteger>(Values[i]);
3122 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3124 DwarfDebugRangeSectionSym,
3128 case dwarf::DW_AT_location: {
3129 if (UseDotDebugLocEntry.count(Die) != 0) {
3130 DIELabel *L = cast<DIELabel>(Values[i]);
3131 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3133 Values[i]->EmitValue(Asm, Form);
3137 // Emit an attribute using the defined form.
3138 Values[i]->EmitValue(Asm, Form);
3143 // Emit the DIE children if any.
3144 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3145 const std::vector<DIE *> &Children = Die->getChildren();
3147 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3148 emitDIE(Children[j]);
3150 if (Asm->isVerbose())
3151 Asm->OutStreamer.AddComment("End Of Children Mark");
3156 /// emitDebugInfo - Emit the debug info section.
3158 void DwarfDebug::emitDebugInfo() {
3159 // Start debug info section.
3160 Asm->OutStreamer.SwitchSection(
3161 Asm->getObjFileLowering().getDwarfInfoSection());
3162 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3163 E = CUMap.end(); I != E; ++I) {
3164 CompileUnit *TheCU = I->second;
3165 DIE *Die = TheCU->getCUDie();
3167 // Emit the compile units header.
3168 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3171 // Emit size of content not including length itself
3172 unsigned ContentSize = Die->getSize() +
3173 sizeof(int16_t) + // DWARF version number
3174 sizeof(int32_t) + // Offset Into Abbrev. Section
3175 sizeof(int8_t) + // Pointer Size (in bytes)
3176 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3178 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3179 Asm->EmitInt32(ContentSize);
3180 Asm->OutStreamer.AddComment("DWARF version number");
3181 Asm->EmitInt16(dwarf::DWARF_VERSION);
3182 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3183 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3184 DwarfAbbrevSectionSym);
3185 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3186 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3189 // FIXME - extra padding for gdb bug.
3190 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3195 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3199 /// emitAbbreviations - Emit the abbreviation section.
3201 void DwarfDebug::emitAbbreviations() const {
3202 // Check to see if it is worth the effort.
3203 if (!Abbreviations.empty()) {
3204 // Start the debug abbrev section.
3205 Asm->OutStreamer.SwitchSection(
3206 Asm->getObjFileLowering().getDwarfAbbrevSection());
3208 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3210 // For each abbrevation.
3211 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3212 // Get abbreviation data
3213 const DIEAbbrev *Abbrev = Abbreviations[i];
3215 // Emit the abbrevations code (base 1 index.)
3216 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3218 // Emit the abbreviations data.
3222 // Mark end of abbreviations.
3223 Asm->EmitULEB128(0, "EOM(3)");
3225 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3229 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
3230 /// the line matrix.
3232 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3233 // Define last address of section.
3234 Asm->OutStreamer.AddComment("Extended Op");
3237 Asm->OutStreamer.AddComment("Op size");
3238 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3239 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3240 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3242 Asm->OutStreamer.AddComment("Section end label");
3244 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3245 Asm->getTargetData().getPointerSize(),
3248 // Mark end of matrix.
3249 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3255 /// emitDebugLines - Emit source line information.
3257 void DwarfDebug::emitDebugLines() {
3258 // If the target is using .loc/.file, the assembler will be emitting the
3259 // .debug_line table automatically.
3260 if (Asm->MAI->hasDotLocAndDotFile())
3263 // Minimum line delta, thus ranging from -10..(255-10).
3264 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
3265 // Maximum line delta, thus ranging from -10..(255-10).
3266 const int MaxLineDelta = 255 + MinLineDelta;
3268 // Start the dwarf line section.
3269 Asm->OutStreamer.SwitchSection(
3270 Asm->getObjFileLowering().getDwarfLineSection());
3272 // Construct the section header.
3273 Asm->OutStreamer.AddComment("Length of Source Line Info");
3274 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
3275 Asm->GetTempSymbol("line_begin"), 4);
3276 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
3278 Asm->OutStreamer.AddComment("DWARF version number");
3279 Asm->EmitInt16(dwarf::DWARF_VERSION);
3281 Asm->OutStreamer.AddComment("Prolog Length");
3282 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
3283 Asm->GetTempSymbol("line_prolog_begin"), 4);
3284 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
3286 Asm->OutStreamer.AddComment("Minimum Instruction Length");
3288 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
3290 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
3291 Asm->EmitInt8(MinLineDelta);
3292 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
3293 Asm->EmitInt8(MaxLineDelta);
3294 Asm->OutStreamer.AddComment("Special Opcode Base");
3295 Asm->EmitInt8(-MinLineDelta);
3297 // Line number standard opcode encodings argument count
3298 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
3300 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
3302 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
3304 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
3306 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
3308 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
3310 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
3312 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
3314 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
3317 // Emit directories.
3318 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
3319 const std::string &Dir = getSourceDirectoryName(DI);
3320 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
3321 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
3324 Asm->OutStreamer.AddComment("End of directories");
3328 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
3329 // Remember source id starts at 1.
3330 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
3331 const std::string &FN = getSourceFileName(Id.second);
3332 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
3333 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
3335 Asm->EmitULEB128(Id.first, "Directory #");
3336 Asm->EmitULEB128(0, "Mod date");
3337 Asm->EmitULEB128(0, "File size");
3340 Asm->OutStreamer.AddComment("End of files");
3343 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
3345 // A sequence for each text section.
3346 unsigned SecSrcLinesSize = SectionSourceLines.size();
3348 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3349 // Isolate current sections line info.
3350 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3352 // Dwarf assumes we start with first line of first source file.
3353 unsigned Source = 1;
3356 // Construct rows of the address, source, line, column matrix.
3357 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3358 const SrcLineInfo &LineInfo = LineInfos[i];
3359 MCSymbol *Label = LineInfo.getLabel();
3360 if (!Label->isDefined()) continue; // Not emitted, in dead code.
3362 if (Asm->isVerbose()) {
3363 std::pair<unsigned, unsigned> SrcID =
3364 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3365 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3367 Twine(getSourceFileName(SrcID.second)) +
3368 ":" + Twine(LineInfo.getLine()));
3371 // Define the line address.
3372 Asm->OutStreamer.AddComment("Extended Op");
3374 Asm->OutStreamer.AddComment("Op size");
3375 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3377 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3378 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3380 Asm->OutStreamer.AddComment("Location label");
3381 Asm->OutStreamer.EmitSymbolValue(Label,
3382 Asm->getTargetData().getPointerSize(),
3385 // If change of source, then switch to the new source.
3386 if (Source != LineInfo.getSourceID()) {
3387 Source = LineInfo.getSourceID();
3388 Asm->OutStreamer.AddComment("DW_LNS_set_file");
3389 Asm->EmitInt8(dwarf::DW_LNS_set_file);
3390 Asm->EmitULEB128(Source, "New Source");
3393 // If change of line.
3394 if (Line != LineInfo.getLine()) {
3395 // Determine offset.
3396 int Offset = LineInfo.getLine() - Line;
3397 int Delta = Offset - MinLineDelta;
3400 Line = LineInfo.getLine();
3402 // If delta is small enough and in range...
3403 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3404 // ... then use fast opcode.
3405 Asm->OutStreamer.AddComment("Line Delta");
3406 Asm->EmitInt8(Delta - MinLineDelta);
3408 // ... otherwise use long hand.
3409 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3410 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3411 Asm->EmitSLEB128(Offset, "Line Offset");
3412 Asm->OutStreamer.AddComment("DW_LNS_copy");
3413 Asm->EmitInt8(dwarf::DW_LNS_copy);
3416 // Copy the previous row (different address or source)
3417 Asm->OutStreamer.AddComment("DW_LNS_copy");
3418 Asm->EmitInt8(dwarf::DW_LNS_copy);
3422 emitEndOfLineMatrix(j + 1);
3425 if (SecSrcLinesSize == 0)
3426 // Because we're emitting a debug_line section, we still need a line
3427 // table. The linker and friends expect it to exist. If there's nothing to
3428 // put into it, emit an empty table.
3429 emitEndOfLineMatrix(1);
3431 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3434 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3436 void DwarfDebug::emitCommonDebugFrame() {
3437 if (!Asm->MAI->doesDwarfRequireFrameSection())
3440 int stackGrowth = Asm->getTargetData().getPointerSize();
3441 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3442 TargetFrameInfo::StackGrowsDown)
3445 // Start the dwarf frame section.
3446 Asm->OutStreamer.SwitchSection(
3447 Asm->getObjFileLowering().getDwarfFrameSection());
3449 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3450 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3451 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3452 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3454 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3455 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3456 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3457 Asm->OutStreamer.AddComment("CIE Version");
3458 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3459 Asm->OutStreamer.AddComment("CIE Augmentation");
3460 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3461 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3462 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3463 Asm->OutStreamer.AddComment("CIE RA Column");
3464 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3465 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3467 std::vector<MachineMove> Moves;
3468 RI->getInitialFrameState(Moves);
3470 Asm->EmitFrameMoves(Moves, 0, false);
3472 Asm->EmitAlignment(2);
3473 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3476 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3479 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3480 if (!Asm->MAI->doesDwarfRequireFrameSection())
3483 // Start the dwarf frame section.
3484 Asm->OutStreamer.SwitchSection(
3485 Asm->getObjFileLowering().getDwarfFrameSection());
3487 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3488 MCSymbol *DebugFrameBegin =
3489 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3490 MCSymbol *DebugFrameEnd =
3491 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3492 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3494 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3496 Asm->OutStreamer.AddComment("FDE CIE offset");
3497 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3498 DwarfFrameSectionSym);
3500 Asm->OutStreamer.AddComment("FDE initial location");
3501 MCSymbol *FuncBeginSym =
3502 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3503 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3504 Asm->getTargetData().getPointerSize(),
3508 Asm->OutStreamer.AddComment("FDE address range");
3509 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3510 FuncBeginSym, Asm->getTargetData().getPointerSize());
3512 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3514 Asm->EmitAlignment(2);
3515 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3518 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3520 void DwarfDebug::emitDebugPubNames() {
3521 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3522 E = CUMap.end(); I != E; ++I) {
3523 CompileUnit *TheCU = I->second;
3524 // Start the dwarf pubnames section.
3525 Asm->OutStreamer.SwitchSection(
3526 Asm->getObjFileLowering().getDwarfPubNamesSection());
3528 Asm->OutStreamer.AddComment("Length of Public Names Info");
3529 Asm->EmitLabelDifference(
3530 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3531 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3533 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3536 Asm->OutStreamer.AddComment("DWARF Version");
3537 Asm->EmitInt16(dwarf::DWARF_VERSION);
3539 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3540 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3541 DwarfInfoSectionSym);
3543 Asm->OutStreamer.AddComment("Compilation Unit Length");
3544 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3545 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3548 const StringMap<DIE*> &Globals = TheCU->getGlobals();
3549 for (StringMap<DIE*>::const_iterator
3550 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3551 const char *Name = GI->getKeyData();
3552 DIE *Entity = GI->second;
3554 Asm->OutStreamer.AddComment("DIE offset");
3555 Asm->EmitInt32(Entity->getOffset());
3557 if (Asm->isVerbose())
3558 Asm->OutStreamer.AddComment("External Name");
3559 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3562 Asm->OutStreamer.AddComment("End Mark");
3564 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3569 void DwarfDebug::emitDebugPubTypes() {
3570 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3571 E = CUMap.end(); I != E; ++I) {
3572 CompileUnit *TheCU = I->second;
3573 // Start the dwarf pubnames section.
3574 Asm->OutStreamer.SwitchSection(
3575 Asm->getObjFileLowering().getDwarfPubTypesSection());
3576 Asm->OutStreamer.AddComment("Length of Public Types Info");
3577 Asm->EmitLabelDifference(
3578 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3579 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3581 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3584 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3585 Asm->EmitInt16(dwarf::DWARF_VERSION);
3587 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3588 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3589 DwarfInfoSectionSym);
3591 Asm->OutStreamer.AddComment("Compilation Unit Length");
3592 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3593 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3596 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3597 for (StringMap<DIE*>::const_iterator
3598 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3599 const char *Name = GI->getKeyData();
3600 DIE * Entity = GI->second;
3602 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3603 Asm->EmitInt32(Entity->getOffset());
3605 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3606 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3609 Asm->OutStreamer.AddComment("End Mark");
3611 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3616 /// emitDebugStr - Emit visible names into a debug str section.
3618 void DwarfDebug::emitDebugStr() {
3619 // Check to see if it is worth the effort.
3620 if (StringPool.empty()) return;
3622 // Start the dwarf str section.
3623 Asm->OutStreamer.SwitchSection(
3624 Asm->getObjFileLowering().getDwarfStrSection());
3626 // Get all of the string pool entries and put them in an array by their ID so
3627 // we can sort them.
3628 SmallVector<std::pair<unsigned,
3629 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3631 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3632 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3633 Entries.push_back(std::make_pair(I->second.second, &*I));
3635 array_pod_sort(Entries.begin(), Entries.end());
3637 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3638 // Emit a label for reference from debug information entries.
3639 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3641 // Emit the string itself.
3642 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3646 /// emitDebugLoc - Emit visible names into a debug loc section.
3648 void DwarfDebug::emitDebugLoc() {
3649 if (DotDebugLocEntries.empty())
3652 // Start the dwarf loc section.
3653 Asm->OutStreamer.SwitchSection(
3654 Asm->getObjFileLowering().getDwarfLocSection());
3655 unsigned char Size = Asm->getTargetData().getPointerSize();
3656 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3658 for (SmallVector<DotDebugLocEntry, 4>::iterator
3659 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3660 I != E; ++I, ++index) {
3661 DotDebugLocEntry Entry = *I;
3662 if (Entry.isEmpty()) {
3663 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3664 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3665 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3667 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3668 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3669 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3670 unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3671 if (int Offset = Entry.Loc.getOffset()) {
3672 // If the value is at a certain offset from frame register then
3674 unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3675 Asm->OutStreamer.AddComment("Loc expr size");
3676 Asm->EmitInt16(1 + OffsetSize);
3677 Asm->OutStreamer.AddComment(
3678 dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3679 Asm->EmitInt8(dwarf::DW_OP_fbreg);
3680 Asm->OutStreamer.AddComment("Offset");
3681 Asm->EmitSLEB128(Offset);
3684 Asm->OutStreamer.AddComment("Loc expr size");
3686 Asm->OutStreamer.AddComment(
3687 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3688 Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3690 Asm->OutStreamer.AddComment("Loc expr size");
3691 Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3692 Asm->EmitInt8(dwarf::DW_OP_regx);
3693 Asm->EmitULEB128(Reg);
3700 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3702 void DwarfDebug::EmitDebugARanges() {
3703 // Start the dwarf aranges section.
3704 Asm->OutStreamer.SwitchSection(
3705 Asm->getObjFileLowering().getDwarfARangesSection());
3708 /// emitDebugRanges - Emit visible names into a debug ranges section.
3710 void DwarfDebug::emitDebugRanges() {
3711 // Start the dwarf ranges section.
3712 Asm->OutStreamer.SwitchSection(
3713 Asm->getObjFileLowering().getDwarfRangesSection());
3714 unsigned char Size = Asm->getTargetData().getPointerSize();
3715 for (SmallVector<const MCSymbol *, 8>::iterator
3716 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3719 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3721 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3725 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3727 void DwarfDebug::emitDebugMacInfo() {
3728 if (const MCSection *LineInfo =
3729 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3730 // Start the dwarf macinfo section.
3731 Asm->OutStreamer.SwitchSection(LineInfo);
3735 /// emitDebugInlineInfo - Emit inline info using following format.
3737 /// 1. length of section
3738 /// 2. Dwarf version number
3739 /// 3. address size.
3741 /// Entries (one "entry" for each function that was inlined):
3743 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3744 /// otherwise offset into __debug_str for regular function name.
3745 /// 2. offset into __debug_str section for regular function name.
3746 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3747 /// instances for the function.
3749 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3750 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3751 /// __debug_info section, and the low_pc is the starting address for the
3752 /// inlining instance.
3753 void DwarfDebug::emitDebugInlineInfo() {
3754 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3760 Asm->OutStreamer.SwitchSection(
3761 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3763 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3764 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3765 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3767 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3769 Asm->OutStreamer.AddComment("Dwarf Version");
3770 Asm->EmitInt16(dwarf::DWARF_VERSION);
3771 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3772 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3774 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3775 E = InlinedSPNodes.end(); I != E; ++I) {
3777 const MDNode *Node = *I;
3778 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3779 = InlineInfo.find(Node);
3780 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3781 DISubprogram SP(Node);
3782 StringRef LName = SP.getLinkageName();
3783 StringRef Name = SP.getName();
3785 Asm->OutStreamer.AddComment("MIPS linkage name");
3786 if (LName.empty()) {
3787 Asm->OutStreamer.EmitBytes(Name, 0);
3788 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3790 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3791 DwarfStrSectionSym);
3793 Asm->OutStreamer.AddComment("Function name");
3794 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3795 Asm->EmitULEB128(Labels.size(), "Inline count");
3797 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3798 LE = Labels.end(); LI != LE; ++LI) {
3799 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3800 Asm->EmitInt32(LI->second->getOffset());
3802 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3803 Asm->OutStreamer.EmitSymbolValue(LI->first,
3804 Asm->getTargetData().getPointerSize(),0);
3808 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));