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", cl::Hidden,
48 cl::desc("Disable debug info printing"));
51 const char *DWARFGroupName = "DWARF Emission";
52 const char *DbgTimerName = "DWARF Debug Writer";
53 } // end anonymous namespace
55 //===----------------------------------------------------------------------===//
57 /// Configuration values for initial hash set sizes (log2).
59 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
63 //===----------------------------------------------------------------------===//
64 /// CompileUnit - This dwarf writer support class manages information associate
65 /// with a source file.
67 /// ID - File identifier for source.
71 /// Die - Compile unit debug information entry.
73 const OwningPtr<DIE> CUDie;
75 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
78 /// GVToDieMap - Tracks the mapping of unit level debug informaton
79 /// variables to debug information entries.
80 /// FIXME : Rename GVToDieMap -> NodeToDieMap
81 DenseMap<MDNode *, DIE *> GVToDieMap;
83 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
84 /// descriptors to debug information entries using a DIEEntry proxy.
86 DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
88 /// Globals - A map of globally visible named entities for this unit.
90 StringMap<DIE*> Globals;
92 /// GlobalTypes - A map of globally visible types for this unit.
94 StringMap<DIE*> GlobalTypes;
97 CompileUnit(unsigned I, DIE *D)
98 : ID(I), CUDie(D), IndexTyDie(0) {}
101 unsigned getID() const { return ID; }
102 DIE* getCUDie() const { return CUDie.get(); }
103 const StringMap<DIE*> &getGlobals() const { return Globals; }
104 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
106 /// hasContent - Return true if this compile unit has something to write out.
108 bool hasContent() const { return !CUDie->getChildren().empty(); }
110 /// addGlobal - Add a new global entity to the compile unit.
112 void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
114 /// addGlobalType - Add a new global type to the compile unit.
116 void addGlobalType(StringRef Name, DIE *Die) {
117 GlobalTypes[Name] = Die;
120 /// getDIE - Returns the debug information entry map slot for the
121 /// specified debug variable.
122 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
124 /// insertDIE - Insert DIE into the map.
125 void insertDIE(MDNode *N, DIE *D) {
126 GVToDieMap.insert(std::make_pair(N, D));
129 /// getDIEEntry - Returns the debug information entry for the speciefied
131 DIEEntry *getDIEEntry(MDNode *N) {
132 DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
133 if (I == GVToDIEEntryMap.end())
138 /// insertDIEEntry - Insert debug information entry into the map.
139 void insertDIEEntry(MDNode *N, DIEEntry *E) {
140 GVToDIEEntryMap.insert(std::make_pair(N, E));
143 /// addDie - Adds or interns the DIE to the compile unit.
145 void addDie(DIE *Buffer) {
146 this->CUDie->addChild(Buffer);
149 // getIndexTyDie - Get an anonymous type for index type.
150 DIE *getIndexTyDie() {
154 // setIndexTyDie - Set D as anonymous type for index which can be reused
156 void setIndexTyDie(DIE *D) {
162 //===----------------------------------------------------------------------===//
163 /// DbgVariable - This class is used to track local variable information.
166 DIVariable Var; // Variable Descriptor.
167 unsigned FrameIndex; // Variable frame index.
168 const MachineInstr *DbgValueMInsn; // DBG_VALUE
169 // DbgValueLabel - DBG_VALUE is effective from this label.
170 MCSymbol *DbgValueLabel;
171 DbgVariable *const AbstractVar; // Abstract variable for this variable.
174 // AbsVar may be NULL.
175 DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
176 : Var(V), FrameIndex(I), DbgValueMInsn(0),
177 DbgValueLabel(0), AbstractVar(AbsVar), TheDIE(0) {}
178 DbgVariable(DIVariable V, const MachineInstr *MI, DbgVariable *AbsVar)
179 : Var(V), FrameIndex(0), DbgValueMInsn(MI), DbgValueLabel(0),
180 AbstractVar(AbsVar), TheDIE(0)
184 DIVariable getVariable() const { return Var; }
185 unsigned getFrameIndex() const { return FrameIndex; }
186 const MachineInstr *getDbgValue() const { return DbgValueMInsn; }
187 MCSymbol *getDbgValueLabel() const { return DbgValueLabel; }
188 void setDbgValueLabel(MCSymbol *L) { DbgValueLabel = L; }
189 DbgVariable *getAbstractVariable() const { return AbstractVar; }
190 void setDIE(DIE *D) { TheDIE = D; }
191 DIE *getDIE() const { return TheDIE; }
194 //===----------------------------------------------------------------------===//
195 /// DbgRange - This is used to track range of instructions with identical
196 /// debug info scope.
198 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
200 //===----------------------------------------------------------------------===//
201 /// DbgScope - This class is used to track scope information.
204 DbgScope *Parent; // Parent to this scope.
205 DIDescriptor Desc; // Debug info descriptor for scope.
206 // Location at which this scope is inlined.
207 AssertingVH<MDNode> InlinedAtLocation;
208 bool AbstractScope; // Abstract Scope
209 const MachineInstr *LastInsn; // Last instruction of this scope.
210 const MachineInstr *FirstInsn; // First instruction of this scope.
211 unsigned DFSIn, DFSOut;
212 // Scopes defined in scope. Contents not owned.
213 SmallVector<DbgScope *, 4> Scopes;
214 // Variables declared in scope. Contents owned.
215 SmallVector<DbgVariable *, 8> Variables;
216 SmallVector<DbgRange, 4> Ranges;
217 // Private state for dump()
218 mutable unsigned IndentLevel;
220 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
221 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
222 LastInsn(0), FirstInsn(0),
223 DFSIn(0), DFSOut(0), IndentLevel(0) {}
227 DbgScope *getParent() const { return Parent; }
228 void setParent(DbgScope *P) { Parent = P; }
229 DIDescriptor getDesc() const { return Desc; }
230 MDNode *getInlinedAt() const { return InlinedAtLocation; }
231 MDNode *getScopeNode() const { return Desc.getNode(); }
232 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
233 const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
234 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
236 /// openInsnRange - This scope covers instruction range starting from MI.
237 void openInsnRange(const MachineInstr *MI) {
242 Parent->openInsnRange(MI);
245 /// extendInsnRange - Extend the current instruction range covered by
247 void extendInsnRange(const MachineInstr *MI) {
248 assert (FirstInsn && "MI Range is not open!");
251 Parent->extendInsnRange(MI);
254 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
255 /// until now. This is used when a new scope is encountered while walking
256 /// machine instructions.
257 void closeInsnRange(DbgScope *NewScope = NULL) {
258 assert (LastInsn && "Last insn missing!");
259 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
262 // If Parent dominates NewScope then do not close Parent's instruction
264 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
265 Parent->closeInsnRange(NewScope);
268 void setAbstractScope() { AbstractScope = true; }
269 bool isAbstractScope() const { return AbstractScope; }
271 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
272 unsigned getDFSOut() const { return DFSOut; }
273 void setDFSOut(unsigned O) { DFSOut = O; }
274 unsigned getDFSIn() const { return DFSIn; }
275 void setDFSIn(unsigned I) { DFSIn = I; }
276 bool dominates(const DbgScope *S) {
279 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
284 /// addScope - Add a scope to the scope.
286 void addScope(DbgScope *S) { Scopes.push_back(S); }
288 /// addVariable - Add a variable to the scope.
290 void addVariable(DbgVariable *V) { Variables.push_back(V); }
297 } // end llvm namespace
300 void DbgScope::dump() const {
301 raw_ostream &err = dbgs();
302 err.indent(IndentLevel);
303 MDNode *N = Desc.getNode();
306 err << "Abstract Scope\n";
310 err << "Children ...\n";
311 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
312 if (Scopes[i] != this)
319 DbgScope::~DbgScope() {
320 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
324 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
325 : Asm(A), MMI(Asm->MMI), ModuleCU(0),
326 AbbreviationsSet(InitAbbreviationsSetSize),
327 CurrentFnDbgScope(0), PrevLabel(NULL) {
328 NextStringPoolNumber = 0;
330 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
331 DwarfStrSectionSym = TextSectionSym = 0;
332 DwarfDebugRangeSectionSym = 0;
333 FunctionBeginSym = 0;
334 if (TimePassesIsEnabled) {
335 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
341 DwarfDebug::~DwarfDebug() {
342 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
343 DIEBlocks[j]->~DIEBlock();
346 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
347 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
348 if (Entry.first) return Entry.first;
350 Entry.second = NextStringPoolNumber++;
351 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
355 /// assignAbbrevNumber - Define a unique number for the abbreviation.
357 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
358 // Profile the node so that we can make it unique.
362 // Check the set for priors.
363 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
365 // If it's newly added.
366 if (InSet == &Abbrev) {
367 // Add to abbreviation list.
368 Abbreviations.push_back(&Abbrev);
370 // Assign the vector position + 1 as its number.
371 Abbrev.setNumber(Abbreviations.size());
373 // Assign existing abbreviation number.
374 Abbrev.setNumber(InSet->getNumber());
378 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
379 /// information entry.
380 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
381 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
385 /// addUInt - Add an unsigned integer attribute data and value.
387 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
388 unsigned Form, uint64_t Integer) {
389 if (!Form) Form = DIEInteger::BestForm(false, Integer);
390 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
391 Die->addValue(Attribute, Form, Value);
394 /// addSInt - Add an signed integer attribute data and value.
396 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
397 unsigned Form, int64_t Integer) {
398 if (!Form) Form = DIEInteger::BestForm(true, Integer);
399 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
400 Die->addValue(Attribute, Form, Value);
403 /// addString - Add a string attribute data and value. DIEString only
404 /// keeps string reference.
405 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
407 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
408 Die->addValue(Attribute, Form, Value);
411 /// addLabel - Add a Dwarf label attribute data and value.
413 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
414 const MCSymbol *Label) {
415 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
416 Die->addValue(Attribute, Form, Value);
419 /// addDelta - Add a label delta attribute data and value.
421 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
422 const MCSymbol *Hi, const MCSymbol *Lo) {
423 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
424 Die->addValue(Attribute, Form, Value);
427 /// addDIEEntry - Add a DIE attribute data and value.
429 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
431 Die->addValue(Attribute, Form, createDIEEntry(Entry));
435 /// addBlock - Add block data.
437 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
439 Block->ComputeSize(Asm);
440 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
441 Die->addValue(Attribute, Block->BestForm(), Block);
444 /// addSourceLine - Add location information to specified debug information
446 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
447 // If there is no compile unit specified, don't add a line #.
448 if (!V->getCompileUnit().Verify())
451 unsigned Line = V->getLineNumber();
452 unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
453 V->getContext().getFilename());
454 assert(FileID && "Invalid file id");
455 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
456 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
459 /// addSourceLine - Add location information to specified debug information
461 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
462 // If there is no compile unit specified, don't add a line #.
463 if (!G->getCompileUnit().Verify())
466 unsigned Line = G->getLineNumber();
467 unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
468 G->getContext().getFilename());
469 assert(FileID && "Invalid file id");
470 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
471 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
474 /// addSourceLine - Add location information to specified debug information
476 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
477 // If there is no compile unit specified, don't add a line #.
478 if (!SP->getCompileUnit().Verify())
480 // If the line number is 0, don't add it.
481 if (SP->getLineNumber() == 0)
484 unsigned Line = SP->getLineNumber();
485 if (!SP->getContext().Verify())
487 unsigned FileID = GetOrCreateSourceID(SP->getDirectory(),
489 assert(FileID && "Invalid file id");
490 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
491 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
494 /// addSourceLine - Add location information to specified debug information
496 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
497 // If there is no compile unit specified, don't add a line #.
498 DICompileUnit CU = Ty->getCompileUnit();
502 unsigned Line = Ty->getLineNumber();
503 if (!Ty->getContext().Verify())
505 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
506 Ty->getContext().getFilename());
507 assert(FileID && "Invalid file id");
508 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
509 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
512 /// addSourceLine - Add location information to specified debug information
514 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
515 // If there is no compile unit specified, don't add a line #.
516 if (!NS->getCompileUnit().Verify())
519 unsigned Line = NS->getLineNumber();
520 StringRef FN = NS->getFilename();
521 StringRef Dir = NS->getDirectory();
523 unsigned FileID = GetOrCreateSourceID(Dir, FN);
524 assert(FileID && "Invalid file id");
525 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
526 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
529 /* Byref variables, in Blocks, are declared by the programmer as
530 "SomeType VarName;", but the compiler creates a
531 __Block_byref_x_VarName struct, and gives the variable VarName
532 either the struct, or a pointer to the struct, as its type. This
533 is necessary for various behind-the-scenes things the compiler
534 needs to do with by-reference variables in blocks.
536 However, as far as the original *programmer* is concerned, the
537 variable should still have type 'SomeType', as originally declared.
539 The following function dives into the __Block_byref_x_VarName
540 struct to find the original type of the variable. This will be
541 passed back to the code generating the type for the Debug
542 Information Entry for the variable 'VarName'. 'VarName' will then
543 have the original type 'SomeType' in its debug information.
545 The original type 'SomeType' will be the type of the field named
546 'VarName' inside the __Block_byref_x_VarName struct.
548 NOTE: In order for this to not completely fail on the debugger
549 side, the Debug Information Entry for the variable VarName needs to
550 have a DW_AT_location that tells the debugger how to unwind through
551 the pointers and __Block_byref_x_VarName struct to find the actual
552 value of the variable. The function addBlockByrefType does this. */
554 /// Find the type the programmer originally declared the variable to be
555 /// and return that type.
557 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
560 unsigned tag = Ty.getTag();
562 if (tag == dwarf::DW_TAG_pointer_type) {
563 DIDerivedType DTy = DIDerivedType(Ty.getNode());
564 subType = DTy.getTypeDerivedFrom();
567 DICompositeType blockStruct = DICompositeType(subType.getNode());
568 DIArray Elements = blockStruct.getTypeArray();
570 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
571 DIDescriptor Element = Elements.getElement(i);
572 DIDerivedType DT = DIDerivedType(Element.getNode());
573 if (Name == DT.getName())
574 return (DT.getTypeDerivedFrom());
580 /// addComplexAddress - Start with the address based on the location provided,
581 /// and generate the DWARF information necessary to find the actual variable
582 /// given the extra address information encoded in the DIVariable, starting from
583 /// the starting location. Add the DWARF information to the die.
585 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
587 const MachineLocation &Location) {
588 const DIVariable &VD = DV->getVariable();
589 DIType Ty = VD.getType();
591 // Decode the original location, and use that as the start of the byref
592 // variable's location.
593 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
594 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
595 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
597 if (Location.isReg()) {
599 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
601 Reg = Reg - dwarf::DW_OP_reg0;
602 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
603 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
607 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
609 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
610 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
613 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
616 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
617 uint64_t Element = VD.getAddrElement(i);
619 if (Element == DIFactory::OpPlus) {
620 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
621 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
622 } else if (Element == DIFactory::OpDeref) {
623 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
624 } else llvm_unreachable("unknown DIFactory Opcode");
627 // Now attach the location information to the DIE.
628 addBlock(Die, Attribute, 0, Block);
631 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
632 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
633 gives the variable VarName either the struct, or a pointer to the struct, as
634 its type. This is necessary for various behind-the-scenes things the
635 compiler needs to do with by-reference variables in Blocks.
637 However, as far as the original *programmer* is concerned, the variable
638 should still have type 'SomeType', as originally declared.
640 The function getBlockByrefType dives into the __Block_byref_x_VarName
641 struct to find the original type of the variable, which is then assigned to
642 the variable's Debug Information Entry as its real type. So far, so good.
643 However now the debugger will expect the variable VarName to have the type
644 SomeType. So we need the location attribute for the variable to be an
645 expression that explains to the debugger how to navigate through the
646 pointers and struct to find the actual variable of type SomeType.
648 The following function does just that. We start by getting
649 the "normal" location for the variable. This will be the location
650 of either the struct __Block_byref_x_VarName or the pointer to the
651 struct __Block_byref_x_VarName.
653 The struct will look something like:
655 struct __Block_byref_x_VarName {
657 struct __Block_byref_x_VarName *forwarding;
658 ... <various other fields>
660 ... <maybe more fields>
663 If we are given the struct directly (as our starting point) we
664 need to tell the debugger to:
666 1). Add the offset of the forwarding field.
668 2). Follow that pointer to get the real __Block_byref_x_VarName
669 struct to use (the real one may have been copied onto the heap).
671 3). Add the offset for the field VarName, to find the actual variable.
673 If we started with a pointer to the struct, then we need to
674 dereference that pointer first, before the other steps.
675 Translating this into DWARF ops, we will need to append the following
676 to the current location description for the variable:
678 DW_OP_deref -- optional, if we start with a pointer
679 DW_OP_plus_uconst <forward_fld_offset>
681 DW_OP_plus_uconst <varName_fld_offset>
683 That is what this function does. */
685 /// addBlockByrefAddress - Start with the address based on the location
686 /// provided, and generate the DWARF information necessary to find the
687 /// actual Block variable (navigating the Block struct) based on the
688 /// starting location. Add the DWARF information to the die. For
689 /// more information, read large comment just above here.
691 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
693 const MachineLocation &Location) {
694 const DIVariable &VD = DV->getVariable();
695 DIType Ty = VD.getType();
697 unsigned Tag = Ty.getTag();
698 bool isPointer = false;
700 StringRef varName = VD.getName();
702 if (Tag == dwarf::DW_TAG_pointer_type) {
703 DIDerivedType DTy = DIDerivedType(Ty.getNode());
704 TmpTy = DTy.getTypeDerivedFrom();
708 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
710 // Find the __forwarding field and the variable field in the __Block_byref
712 DIArray Fields = blockStruct.getTypeArray();
713 DIDescriptor varField = DIDescriptor();
714 DIDescriptor forwardingField = DIDescriptor();
716 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
717 DIDescriptor Element = Fields.getElement(i);
718 DIDerivedType DT = DIDerivedType(Element.getNode());
719 StringRef fieldName = DT.getName();
720 if (fieldName == "__forwarding")
721 forwardingField = Element;
722 else if (fieldName == varName)
726 // Get the offsets for the forwarding field and the variable field.
727 unsigned forwardingFieldOffset =
728 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
729 unsigned varFieldOffset =
730 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
732 // Decode the original location, and use that as the start of the byref
733 // variable's location.
734 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
735 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
736 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
738 if (Location.isReg()) {
740 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
742 Reg = Reg - dwarf::DW_OP_reg0;
743 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
744 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
748 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
750 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
751 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
754 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
757 // If we started with a pointer to the __Block_byref... struct, then
758 // the first thing we need to do is dereference the pointer (DW_OP_deref).
760 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
762 // Next add the offset for the '__forwarding' field:
763 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
764 // adding the offset if it's 0.
765 if (forwardingFieldOffset > 0) {
766 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
767 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
770 // Now dereference the __forwarding field to get to the real __Block_byref
771 // struct: DW_OP_deref.
772 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
774 // Now that we've got the real __Block_byref... struct, add the offset
775 // for the variable's field to get to the location of the actual variable:
776 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
777 if (varFieldOffset > 0) {
778 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
779 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
782 // Now attach the location information to the DIE.
783 addBlock(Die, Attribute, 0, Block);
786 /// addAddress - Add an address attribute to a die based on the location
788 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
789 const MachineLocation &Location) {
790 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
791 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
792 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
794 if (Location.isReg()) {
796 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
798 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
799 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
803 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
805 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
806 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
809 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
812 addBlock(Die, Attribute, 0, Block);
815 /// addToContextOwner - Add Die into the list of its context owner's children.
816 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
817 if (Context.isType()) {
818 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
819 ContextDIE->addChild(Die);
820 } else if (Context.isNameSpace()) {
821 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
822 ContextDIE->addChild(Die);
823 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
824 ContextDIE->addChild(Die);
826 ModuleCU->addDie(Die);
829 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
831 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
832 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
837 TyDIE = new DIE(dwarf::DW_TAG_base_type);
838 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
839 if (Ty.isBasicType())
840 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
841 else if (Ty.isCompositeType())
842 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
844 assert(Ty.isDerivedType() && "Unknown kind of DIType");
845 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
848 addToContextOwner(TyDIE, Ty.getContext());
852 /// addType - Add a new type attribute to the specified entity.
853 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
857 // Check for pre-existence.
858 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
859 // If it exists then use the existing value.
861 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
866 DIE *Buffer = getOrCreateTypeDIE(Ty);
869 Entry = createDIEEntry(Buffer);
870 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
872 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
875 /// constructTypeDIE - Construct basic type die from DIBasicType.
876 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
877 // Get core information.
878 StringRef Name = BTy.getName();
879 Buffer.setTag(dwarf::DW_TAG_base_type);
880 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
883 // Add name if not anonymous or intermediate type.
885 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
886 uint64_t Size = BTy.getSizeInBits() >> 3;
887 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
890 /// constructTypeDIE - Construct derived type die from DIDerivedType.
891 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
892 // Get core information.
893 StringRef Name = DTy.getName();
894 uint64_t Size = DTy.getSizeInBits() >> 3;
895 unsigned Tag = DTy.getTag();
897 // FIXME - Workaround for templates.
898 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
902 // Map to main type, void will not have a type.
903 DIType FromTy = DTy.getTypeDerivedFrom();
904 addType(&Buffer, FromTy);
906 // Add name if not anonymous or intermediate type.
908 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
910 // Add size if non-zero (derived types might be zero-sized.)
912 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
914 // Add source line info if available and TyDesc is not a forward declaration.
915 if (!DTy.isForwardDecl())
916 addSourceLine(&Buffer, &DTy);
919 /// constructTypeDIE - Construct type DIE from DICompositeType.
920 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
921 // Get core information.
922 StringRef Name = CTy.getName();
924 uint64_t Size = CTy.getSizeInBits() >> 3;
925 unsigned Tag = CTy.getTag();
929 case dwarf::DW_TAG_vector_type:
930 case dwarf::DW_TAG_array_type:
931 constructArrayTypeDIE(Buffer, &CTy);
933 case dwarf::DW_TAG_enumeration_type: {
934 DIArray Elements = CTy.getTypeArray();
936 // Add enumerators to enumeration type.
937 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
939 DIDescriptor Enum(Elements.getElement(i).getNode());
940 if (Enum.isEnumerator()) {
941 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
942 Buffer.addChild(ElemDie);
947 case dwarf::DW_TAG_subroutine_type: {
949 DIArray Elements = CTy.getTypeArray();
950 DIDescriptor RTy = Elements.getElement(0);
951 addType(&Buffer, DIType(RTy.getNode()));
953 // Add prototype flag.
954 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
957 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
958 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
959 DIDescriptor Ty = Elements.getElement(i);
960 addType(Arg, DIType(Ty.getNode()));
961 Buffer.addChild(Arg);
965 case dwarf::DW_TAG_structure_type:
966 case dwarf::DW_TAG_union_type:
967 case dwarf::DW_TAG_class_type: {
968 // Add elements to structure type.
969 DIArray Elements = CTy.getTypeArray();
971 // A forward struct declared type may not have elements available.
972 unsigned N = Elements.getNumElements();
976 // Add elements to structure type.
977 for (unsigned i = 0; i < N; ++i) {
978 DIDescriptor Element = Elements.getElement(i);
980 if (Element.isSubprogram())
981 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
982 else if (Element.isVariable()) {
983 DIVariable DV(Element.getNode());
984 ElemDie = new DIE(dwarf::DW_TAG_variable);
985 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
987 addType(ElemDie, DV.getType());
988 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
989 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
990 addSourceLine(ElemDie, &DV);
991 } else if (Element.isDerivedType())
992 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
995 Buffer.addChild(ElemDie);
998 if (CTy.isAppleBlockExtension())
999 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1001 unsigned RLang = CTy.getRunTimeLang();
1003 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1004 dwarf::DW_FORM_data1, RLang);
1006 DICompositeType ContainingType = CTy.getContainingType();
1007 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
1008 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1009 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
1016 // Add name if not anonymous or intermediate type.
1018 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1020 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1021 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1022 // Add size if non-zero (derived types might be zero-sized.)
1024 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1026 // Add zero size if it is not a forward declaration.
1027 if (CTy.isForwardDecl())
1028 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1030 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1033 // Add source line info if available.
1034 if (!CTy.isForwardDecl())
1035 addSourceLine(&Buffer, &CTy);
1039 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1040 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1041 int64_t L = SR.getLo();
1042 int64_t H = SR.getHi();
1043 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1045 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1047 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1048 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1050 Buffer.addChild(DW_Subrange);
1053 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1054 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1055 DICompositeType *CTy) {
1056 Buffer.setTag(dwarf::DW_TAG_array_type);
1057 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1058 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1060 // Emit derived type.
1061 addType(&Buffer, CTy->getTypeDerivedFrom());
1062 DIArray Elements = CTy->getTypeArray();
1064 // Get an anonymous type for index type.
1065 DIE *IdxTy = ModuleCU->getIndexTyDie();
1067 // Construct an anonymous type for index type.
1068 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1069 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1070 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1071 dwarf::DW_ATE_signed);
1072 ModuleCU->addDie(IdxTy);
1073 ModuleCU->setIndexTyDie(IdxTy);
1076 // Add subranges to array type.
1077 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1078 DIDescriptor Element = Elements.getElement(i);
1079 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1080 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1084 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1085 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1086 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1087 StringRef Name = ETy.getName();
1088 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1089 int64_t Value = ETy.getEnumValue();
1090 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1094 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1095 /// printer to not emit usual symbol prefix before the symbol name is used then
1096 /// return linkage name after skipping this special LLVM prefix.
1097 static StringRef getRealLinkageName(StringRef LinkageName) {
1099 if (LinkageName.startswith(StringRef(&One, 1)))
1100 return LinkageName.substr(1);
1104 /// createGlobalVariableDIE - Create new DIE using GV.
1105 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1106 // If the global variable was optmized out then no need to create debug info
1108 if (!GV.getGlobal()) return NULL;
1109 if (GV.getDisplayName().empty()) return NULL;
1111 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1112 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1113 GV.getDisplayName());
1115 StringRef LinkageName = GV.getLinkageName();
1116 if (!LinkageName.empty())
1117 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1118 getRealLinkageName(LinkageName));
1120 addType(GVDie, GV.getType());
1121 if (!GV.isLocalToUnit())
1122 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1123 addSourceLine(GVDie, &GV);
1128 /// createMemberDIE - Create new member DIE.
1129 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1130 DIE *MemberDie = new DIE(DT.getTag());
1131 StringRef Name = DT.getName();
1133 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1135 addType(MemberDie, DT.getTypeDerivedFrom());
1137 addSourceLine(MemberDie, &DT);
1139 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1140 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1142 uint64_t Size = DT.getSizeInBits();
1143 uint64_t FieldSize = DT.getOriginalTypeSize();
1145 if (Size != FieldSize) {
1147 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1148 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1150 uint64_t Offset = DT.getOffsetInBits();
1151 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1152 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1153 uint64_t FieldOffset = (HiMark - FieldSize);
1154 Offset -= FieldOffset;
1156 // Maybe we need to work from the other end.
1157 if (Asm->getTargetData().isLittleEndian())
1158 Offset = FieldSize - (Offset + Size);
1159 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1161 // Here WD_AT_data_member_location points to the anonymous
1162 // field that includes this bit field.
1163 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1166 // This is not a bitfield.
1167 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1169 if (DT.getTag() == dwarf::DW_TAG_inheritance
1170 && DT.isVirtual()) {
1172 // For C++, virtual base classes are not at fixed offset. Use following
1173 // expression to extract appropriate offset from vtable.
1174 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1176 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1177 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1178 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1179 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1180 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1181 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1182 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1183 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1185 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1188 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1190 if (DT.isProtected())
1191 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1192 dwarf::DW_ACCESS_protected);
1193 else if (DT.isPrivate())
1194 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1195 dwarf::DW_ACCESS_private);
1196 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1197 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1198 dwarf::DW_ACCESS_public);
1200 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1201 dwarf::DW_VIRTUALITY_virtual);
1205 /// createSubprogramDIE - Create new DIE using SP.
1206 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1207 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1211 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1212 // Constructors and operators for anonymous aggregates do not have names.
1213 if (!SP.getName().empty())
1214 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1216 StringRef LinkageName = SP.getLinkageName();
1217 if (!LinkageName.empty())
1218 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1219 getRealLinkageName(LinkageName));
1221 addSourceLine(SPDie, &SP);
1223 // Add prototyped tag, if C or ObjC.
1224 unsigned Lang = SP.getCompileUnit().getLanguage();
1225 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1226 Lang == dwarf::DW_LANG_ObjC)
1227 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1230 DICompositeType SPTy = SP.getType();
1231 DIArray Args = SPTy.getTypeArray();
1232 unsigned SPTag = SPTy.getTag();
1234 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1235 addType(SPDie, SPTy);
1237 addType(SPDie, DIType(Args.getElement(0).getNode()));
1239 unsigned VK = SP.getVirtuality();
1241 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1242 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1243 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1244 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1245 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1246 ContainingTypeMap.insert(std::make_pair(SPDie,
1247 SP.getContainingType().getNode()));
1250 if (MakeDecl || !SP.isDefinition()) {
1251 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1253 // Add arguments. Do not add arguments for subprogram definition. They will
1254 // be handled while processing variables.
1255 DICompositeType SPTy = SP.getType();
1256 DIArray Args = SPTy.getTypeArray();
1257 unsigned SPTag = SPTy.getTag();
1259 if (SPTag == dwarf::DW_TAG_subroutine_type)
1260 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1261 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1262 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1264 if (ATy.isArtificial())
1265 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1266 SPDie->addChild(Arg);
1270 if (SP.isArtificial())
1271 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1273 // DW_TAG_inlined_subroutine may refer to this DIE.
1274 ModuleCU->insertDIE(SP.getNode(), SPDie);
1276 if (!DisableFramePointerElim(*Asm->MF))
1277 addUInt(SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr, dwarf::DW_FORM_flag, 1);
1282 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1283 assert(N && "Invalid Scope encoding!");
1285 DbgScope *AScope = AbstractScopes.lookup(N);
1289 DbgScope *Parent = NULL;
1291 DIDescriptor Scope(N);
1292 if (Scope.isLexicalBlock()) {
1293 DILexicalBlock DB(N);
1294 DIDescriptor ParentDesc = DB.getContext();
1295 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1298 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1301 Parent->addScope(AScope);
1302 AScope->setAbstractScope();
1303 AbstractScopes[N] = AScope;
1304 if (DIDescriptor(N).isSubprogram())
1305 AbstractScopesList.push_back(AScope);
1309 /// isSubprogramContext - Return true if Context is either a subprogram
1310 /// or another context nested inside a subprogram.
1311 static bool isSubprogramContext(MDNode *Context) {
1314 DIDescriptor D(Context);
1315 if (D.isSubprogram())
1318 return isSubprogramContext(DIType(Context).getContext().getNode());
1322 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1323 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1324 /// If there are global variables in this scope then create and insert
1325 /// DIEs for these variables.
1326 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1327 DIE *SPDie = ModuleCU->getDIE(SPNode);
1328 assert(SPDie && "Unable to find subprogram DIE!");
1329 DISubprogram SP(SPNode);
1331 // There is not any need to generate specification DIE for a function
1332 // defined at compile unit level. If a function is defined inside another
1333 // function then gdb prefers the definition at top level and but does not
1334 // expect specification DIE in parent function. So avoid creating
1335 // specification DIE for a function defined inside a function.
1336 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1337 !SP.getContext().isFile() &&
1338 !isSubprogramContext(SP.getContext().getNode())) {
1339 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1342 DICompositeType SPTy = SP.getType();
1343 DIArray Args = SPTy.getTypeArray();
1344 unsigned SPTag = SPTy.getTag();
1345 if (SPTag == dwarf::DW_TAG_subroutine_type)
1346 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1347 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1348 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1350 if (ATy.isArtificial())
1351 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1352 SPDie->addChild(Arg);
1354 DIE *SPDeclDie = SPDie;
1355 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1356 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1358 ModuleCU->addDie(SPDie);
1361 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1362 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1363 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1364 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1365 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1366 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1367 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1369 if (!DISubprogram(SPNode).isLocalToUnit())
1370 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1375 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1376 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1377 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1379 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1380 if (Scope->isAbstractScope())
1383 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1387 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1388 if (Ranges.size() > 1) {
1389 // .debug_range section has not been laid out yet. Emit offset in
1390 // .debug_range as a uint, size 4, for now. emitDIE will handle
1391 // DW_AT_ranges appropriately.
1392 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1393 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1394 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1395 RE = Ranges.end(); RI != RE; ++RI) {
1396 DebugRangeSymbols.push_back(InsnBeforeLabelMap.lookup(RI->first));
1397 DebugRangeSymbols.push_back(InsnAfterLabelMap.lookup(RI->second));
1399 DebugRangeSymbols.push_back(NULL);
1400 DebugRangeSymbols.push_back(NULL);
1404 MCSymbol *Start = InsnBeforeLabelMap.lookup(RI->first);
1405 MCSymbol *End = InsnAfterLabelMap.lookup(RI->second);
1407 if (Start == 0 || End == 0) return 0;
1409 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1410 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1412 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1413 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1418 /// constructInlinedScopeDIE - This scope represents inlined body of
1419 /// a function. Construct DIE to represent this concrete inlined copy
1420 /// of the function.
1421 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1423 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1424 assert (Ranges.empty() == false
1425 && "DbgScope does not have instruction markers!");
1427 // FIXME : .debug_inlined section specification does not clearly state how
1428 // to emit inlined scope that is split into multiple instruction ranges.
1429 // For now, use first instruction range and emit low_pc/high_pc pair and
1430 // corresponding .debug_inlined section entry for this pair.
1431 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1432 MCSymbol *StartLabel = InsnBeforeLabelMap.lookup(RI->first);
1433 MCSymbol *EndLabel = InsnAfterLabelMap.lookup(RI->second);
1435 if (StartLabel == 0 || EndLabel == 0) {
1436 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1439 assert(StartLabel->isDefined() &&
1440 "Invalid starting label for an inlined scope!");
1441 assert(EndLabel->isDefined() &&
1442 "Invalid end label for an inlined scope!");
1444 if (!Scope->getScopeNode())
1446 DIScope DS(Scope->getScopeNode());
1447 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1449 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1450 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1451 assert(OriginDIE && "Unable to find Origin DIE!");
1452 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1453 dwarf::DW_FORM_ref4, OriginDIE);
1455 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1456 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1458 InlinedSubprogramDIEs.insert(OriginDIE);
1460 // Track the start label for this inlined function.
1461 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1462 I = InlineInfo.find(InlinedSP.getNode());
1464 if (I == InlineInfo.end()) {
1465 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1467 InlinedSPNodes.push_back(InlinedSP.getNode());
1469 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1471 DILocation DL(Scope->getInlinedAt());
1472 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1473 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1479 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1480 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1481 // Get the descriptor.
1482 const DIVariable &VD = DV->getVariable();
1483 StringRef Name = VD.getName();
1487 // Translate tag to proper Dwarf tag. The result variable is dropped for
1490 switch (VD.getTag()) {
1491 case dwarf::DW_TAG_return_variable:
1493 case dwarf::DW_TAG_arg_variable:
1494 Tag = dwarf::DW_TAG_formal_parameter;
1496 case dwarf::DW_TAG_auto_variable: // fall thru
1498 Tag = dwarf::DW_TAG_variable;
1502 // Define variable debug information entry.
1503 DIE *VariableDie = new DIE(Tag);
1507 if (DbgVariable *AV = DV->getAbstractVariable())
1508 AbsDIE = AV->getDIE();
1511 DIScope DS(Scope->getScopeNode());
1512 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1513 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1515 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1516 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1517 assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1518 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1519 dwarf::DW_FORM_ref4, AbsDIE);
1522 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1523 addSourceLine(VariableDie, &VD);
1525 // Add variable type.
1526 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1527 // addresses instead.
1528 if (VD.isBlockByrefVariable())
1529 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1531 addType(VariableDie, VD.getType());
1534 // Add variable address.
1535 if (!Scope->isAbstractScope()) {
1536 // Check if variable is described by DBG_VALUE instruction.
1537 if (const MachineInstr *DbgValueInsn = DV->getDbgValue()) {
1538 if (DbgValueInsn->getNumOperands() == 3) {
1539 // FIXME : Handle getNumOperands != 3
1540 if (DbgValueInsn->getOperand(0).getType()
1541 == MachineOperand::MO_Register
1542 && DbgValueInsn->getOperand(0).getReg()) {
1543 MachineLocation Location;
1544 Location.set(DbgValueInsn->getOperand(0).getReg());
1545 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1546 if (MCSymbol *VS = DV->getDbgValueLabel())
1547 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1549 } else if (DbgValueInsn->getOperand(0).getType() ==
1550 MachineOperand::MO_Immediate) {
1551 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1552 unsigned Imm = DbgValueInsn->getOperand(0).getImm();
1553 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
1554 addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1555 if (MCSymbol *VS = DV->getDbgValueLabel())
1556 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1558 } else if (DbgValueInsn->getOperand(0).getType() ==
1559 MachineOperand::MO_FPImmediate) {
1560 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1561 APFloat FPImm = DbgValueInsn->getOperand(0).getFPImm()->getValueAPF();
1563 // Get the raw data form of the floating point.
1564 const APInt FltVal = FPImm.bitcastToAPInt();
1565 const char *FltPtr = (const char*)FltVal.getRawData();
1567 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
1568 bool LittleEndian = Asm->getTargetData().isLittleEndian();
1569 int Incr = (LittleEndian ? 1 : -1);
1570 int Start = (LittleEndian ? 0 : NumBytes - 1);
1571 int Stop = (LittleEndian ? NumBytes : -1);
1573 // Output the constant to DWARF one byte at a time.
1574 for (; Start != Stop; Start += Incr)
1575 addUInt(Block, 0, dwarf::DW_FORM_data1,
1576 (unsigned char)0xFF & FltPtr[Start]);
1578 addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1580 if (MCSymbol *VS = DV->getDbgValueLabel())
1581 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1584 //FIXME : Handle other operand types.
1590 MachineLocation Location;
1592 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1593 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1595 Location.set(FrameReg, Offset);
1597 if (VD.hasComplexAddress())
1598 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1599 else if (VD.isBlockByrefVariable())
1600 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1602 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1606 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1607 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1608 DV->setDIE(VariableDie);
1613 void DwarfDebug::addPubTypes(DISubprogram SP) {
1614 DICompositeType SPTy = SP.getType();
1615 unsigned SPTag = SPTy.getTag();
1616 if (SPTag != dwarf::DW_TAG_subroutine_type)
1619 DIArray Args = SPTy.getTypeArray();
1620 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1621 DIType ATy(Args.getElement(i).getNode());
1624 DICompositeType CATy = getDICompositeType(ATy);
1625 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()
1626 && !CATy.isForwardDecl()) {
1627 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1628 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1633 /// constructScopeDIE - Construct a DIE for this scope.
1634 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1635 if (!Scope || !Scope->getScopeNode())
1638 DIScope DS(Scope->getScopeNode());
1639 DIE *ScopeDIE = NULL;
1640 if (Scope->getInlinedAt())
1641 ScopeDIE = constructInlinedScopeDIE(Scope);
1642 else if (DS.isSubprogram()) {
1643 if (Scope->isAbstractScope())
1644 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1646 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1649 ScopeDIE = constructLexicalScopeDIE(Scope);
1650 if (!ScopeDIE) return NULL;
1652 // Add variables to scope.
1653 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1654 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1655 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1657 ScopeDIE->addChild(VariableDIE);
1660 // Add nested scopes.
1661 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1662 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1663 // Define the Scope debug information entry.
1664 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1666 ScopeDIE->addChild(NestedDIE);
1669 if (DS.isSubprogram())
1670 addPubTypes(DISubprogram(DS.getNode()));
1675 /// GetOrCreateSourceID - Look up the source id with the given directory and
1676 /// source file names. If none currently exists, create a new id and insert it
1677 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1679 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1681 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1682 if (DI != DirectoryIdMap.end()) {
1683 DId = DI->getValue();
1685 DId = DirectoryNames.size() + 1;
1686 DirectoryIdMap[DirName] = DId;
1687 DirectoryNames.push_back(DirName);
1691 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1692 if (FI != SourceFileIdMap.end()) {
1693 FId = FI->getValue();
1695 FId = SourceFileNames.size() + 1;
1696 SourceFileIdMap[FileName] = FId;
1697 SourceFileNames.push_back(FileName);
1700 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1701 SourceIdMap.find(std::make_pair(DId, FId));
1702 if (SI != SourceIdMap.end())
1705 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1706 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1707 SourceIds.push_back(std::make_pair(DId, FId));
1712 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1713 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1714 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1717 NDie = new DIE(dwarf::DW_TAG_namespace);
1718 ModuleCU->insertDIE(NS.getNode(), NDie);
1719 if (!NS.getName().empty())
1720 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1721 addSourceLine(NDie, &NS);
1722 addToContextOwner(NDie, NS.getContext());
1726 void DwarfDebug::constructCompileUnit(MDNode *N) {
1727 DICompileUnit DIUnit(N);
1728 // Use first compile unit marked as isMain as the compile unit for this
1730 if (ModuleCU || !DIUnit.isMain())
1732 StringRef FN = DIUnit.getFilename();
1733 StringRef Dir = DIUnit.getDirectory();
1734 unsigned ID = GetOrCreateSourceID(Dir, FN);
1736 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1737 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1738 DIUnit.getProducer());
1739 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1740 DIUnit.getLanguage());
1741 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1742 addLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, TextSectionSym);
1743 addLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1744 Asm->GetTempSymbol("text_end"));
1745 // DW_AT_stmt_list is a offset of line number information for this
1746 // compile unit in debug_line section. It is always zero when only one
1747 // compile unit is emitted in one object file.
1748 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1751 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1752 if (DIUnit.isOptimized())
1753 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1755 StringRef Flags = DIUnit.getFlags();
1757 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1759 unsigned RVer = DIUnit.getRunTimeVersion();
1761 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1762 dwarf::DW_FORM_data1, RVer);
1765 "ModuleCU assigned since the top of constructCompileUnit");
1766 ModuleCU = new CompileUnit(ID, Die);
1769 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1770 DIGlobalVariable DI_GV(N);
1772 // If debug information is malformed then ignore it.
1773 if (DI_GV.Verify() == false)
1776 // Check for pre-existence.
1777 if (ModuleCU->getDIE(DI_GV.getNode()))
1780 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1785 ModuleCU->insertDIE(N, VariableDie);
1787 // Add to context owner.
1788 DIDescriptor GVContext = DI_GV.getContext();
1789 // Do not create specification DIE if context is either compile unit
1791 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1792 !GVContext.isFile() &&
1793 !isSubprogramContext(GVContext.getNode())) {
1794 // Create specification DIE.
1795 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1796 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1797 dwarf::DW_FORM_ref4, VariableDie);
1798 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1799 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1800 addLabel(Block, 0, dwarf::DW_FORM_udata,
1801 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1802 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1803 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1804 ModuleCU->addDie(VariableSpecDIE);
1806 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1807 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1808 addLabel(Block, 0, dwarf::DW_FORM_udata,
1809 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1810 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1812 addToContextOwner(VariableDie, GVContext);
1814 // Expose as global. FIXME - need to check external flag.
1815 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1817 DIType GTy = DI_GV.getType();
1818 if (GTy.isCompositeType() && !GTy.getName().empty()
1819 && !GTy.isForwardDecl()) {
1820 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1821 assert(Entry && "Missing global type!");
1822 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1827 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1830 // Check for pre-existence.
1831 if (ModuleCU->getDIE(N))
1834 if (!SP.isDefinition())
1835 // This is a method declaration which will be handled while constructing
1839 DIE *SubprogramDie = createSubprogramDIE(SP);
1842 ModuleCU->insertDIE(N, SubprogramDie);
1844 // Add to context owner.
1845 addToContextOwner(SubprogramDie, SP.getContext());
1847 // Expose as global.
1848 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1853 /// beginModule - Emit all Dwarf sections that should come prior to the
1854 /// content. Create global DIEs and emit initial debug info sections.
1855 /// This is inovked by the target AsmPrinter.
1856 void DwarfDebug::beginModule(Module *M) {
1857 if (DisableDebugInfoPrinting)
1860 DebugInfoFinder DbgFinder;
1861 DbgFinder.processModule(*M);
1863 bool HasDebugInfo = false;
1865 // Scan all the compile-units to see if there are any marked as the main unit.
1866 // if not, we do not generate debug info.
1867 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1868 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1869 if (DICompileUnit(*I).isMain()) {
1870 HasDebugInfo = true;
1875 if (!HasDebugInfo) return;
1877 // Tell MMI that we have debug info.
1878 MMI->setDebugInfoAvailability(true);
1880 // Emit initial sections.
1881 EmitSectionLabels();
1883 // Create all the compile unit DIEs.
1884 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1885 E = DbgFinder.compile_unit_end(); I != E; ++I)
1886 constructCompileUnit(*I);
1888 // Create DIEs for each subprogram.
1889 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1890 E = DbgFinder.subprogram_end(); I != E; ++I)
1891 constructSubprogramDIE(*I);
1893 // Create DIEs for each global variable.
1894 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1895 E = DbgFinder.global_variable_end(); I != E; ++I)
1896 constructGlobalVariableDIE(*I);
1898 // Prime section data.
1899 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1901 // Print out .file directives to specify files for .loc directives. These are
1902 // printed out early so that they precede any .loc directives.
1903 if (Asm->MAI->hasDotLocAndDotFile()) {
1904 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1905 // Remember source id starts at 1.
1906 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1907 // FIXME: don't use sys::path for this! This should not depend on the
1909 sys::Path FullPath(getSourceDirectoryName(Id.first));
1911 FullPath.appendComponent(getSourceFileName(Id.second));
1912 assert(AppendOk && "Could not append filename to directory!");
1914 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1919 /// endModule - Emit all Dwarf sections that should come after the content.
1921 void DwarfDebug::endModule() {
1922 if (!ModuleCU) return;
1924 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1925 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1926 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1928 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1931 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1932 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1933 DIE *SPDie = CI->first;
1934 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1936 DIE *NDie = ModuleCU->getDIE(N);
1937 if (!NDie) continue;
1938 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1941 // Standard sections final addresses.
1942 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1943 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1944 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1945 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1947 // End text sections.
1948 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1949 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1950 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1953 // Emit common frame information.
1954 emitCommonDebugFrame();
1956 // Emit function debug frame information
1957 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1958 E = DebugFrames.end(); I != E; ++I)
1959 emitFunctionDebugFrame(*I);
1961 // Compute DIE offsets and sizes.
1962 computeSizeAndOffsets();
1964 // Emit all the DIEs into a debug info section
1967 // Corresponding abbreviations into a abbrev section.
1968 emitAbbreviations();
1970 // Emit source line correspondence into a debug line section.
1973 // Emit info into a debug pubnames section.
1974 emitDebugPubNames();
1976 // Emit info into a debug pubtypes section.
1977 emitDebugPubTypes();
1979 // Emit info into a debug loc section.
1982 // Emit info into a debug aranges section.
1985 // Emit info into a debug ranges section.
1988 // Emit info into a debug macinfo section.
1991 // Emit inline info.
1992 emitDebugInlineInfo();
1994 // Emit info into a debug str section.
1998 ModuleCU = NULL; // Reset for the next Module, if any.
2001 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2002 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2004 DebugLoc ScopeLoc) {
2006 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2008 return AbsDbgVariable;
2010 LLVMContext &Ctx = Var.getNode()->getContext();
2011 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2015 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2016 NULL /* No more-abstract variable*/);
2017 Scope->addVariable(AbsDbgVariable);
2018 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2019 return AbsDbgVariable;
2022 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2023 /// FIXME : Refactor findAbstractVariable.
2024 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2025 const MachineInstr *MI,
2026 DebugLoc ScopeLoc) {
2028 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2030 return AbsDbgVariable;
2032 LLVMContext &Ctx = Var.getNode()->getContext();
2033 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2037 AbsDbgVariable = new DbgVariable(Var, MI,
2038 NULL /* No more-abstract variable*/);
2039 Scope->addVariable(AbsDbgVariable);
2040 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2041 DbgValueStartMap[MI] = AbsDbgVariable;
2042 return AbsDbgVariable;
2045 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2046 void DwarfDebug::collectVariableInfo() {
2047 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2049 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2050 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2051 VE = VMap.end(); VI != VE; ++VI) {
2052 MDNode *Var = VI->first;
2055 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2057 DbgScope *Scope = 0;
2058 if (MDNode *IA = VP.second.getInlinedAt(Ctx))
2059 Scope = ConcreteScopes.lookup(IA);
2061 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2063 // If variable scope is not found then skip this variable.
2067 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2068 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2069 Scope->addVariable(RegVar);
2072 // Collect variable information from DBG_VALUE machine instructions;
2073 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2075 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2077 const MachineInstr *MInsn = II;
2078 if (!MInsn->isDebugValue())
2081 // FIXME : Lift this restriction.
2082 if (MInsn->getNumOperands() != 3)
2085 const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2087 if (DV.getTag() == dwarf::DW_TAG_arg_variable) {
2088 // FIXME Handle inlined subroutine arguments.
2089 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2090 CurrentFnDbgScope->addVariable(ArgVar);
2091 DbgValueStartMap[MInsn] = ArgVar;
2095 DebugLoc DL = MInsn->getDebugLoc();
2096 if (DL.isUnknown()) continue;
2097 DbgScope *Scope = 0;
2098 if (MDNode *IA = DL.getInlinedAt(Ctx))
2099 Scope = ConcreteScopes.lookup(IA);
2101 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2103 // If variable scope is not found then skip this variable.
2107 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2108 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2109 DbgValueStartMap[MInsn] = RegVar;
2110 Scope->addVariable(RegVar);
2115 /// beginScope - Process beginning of a scope.
2116 void DwarfDebug::beginScope(const MachineInstr *MI) {
2118 DebugLoc DL = MI->getDebugLoc();
2122 MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2124 // FIXME: Should only verify each scope once!
2125 if (!DIScope(Scope).Verify())
2128 // DBG_VALUE instruction establishes new value.
2129 if (MI->isDebugValue()) {
2130 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2131 = DbgValueStartMap.find(MI);
2132 if (DI != DbgValueStartMap.end()) {
2133 MCSymbol *Label = NULL;
2134 if (DL == PrevInstLoc)
2137 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2141 DI->second->setDbgValueLabel(Label);
2146 // Emit a label to indicate location change. This is used for line
2147 // table even if this instruction does not start a new scope.
2148 MCSymbol *Label = NULL;
2149 if (DL == PrevInstLoc)
2152 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2157 // If this instruction begins a scope then note down corresponding label.
2158 if (InsnsBeginScopeSet.count(MI) != 0)
2159 InsnBeforeLabelMap[MI] = Label;
2162 /// endScope - Process end of a scope.
2163 void DwarfDebug::endScope(const MachineInstr *MI) {
2164 if (InsnsEndScopeSet.count(MI) != 0) {
2165 // Emit a label if this instruction ends a scope.
2166 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2167 Asm->OutStreamer.EmitLabel(Label);
2168 InsnAfterLabelMap[MI] = Label;
2172 /// getOrCreateDbgScope - Create DbgScope for the scope.
2173 DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2175 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2178 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2179 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2180 if (DIDescriptor(Scope).isLexicalBlock()) {
2182 getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2183 WScope->setParent(Parent);
2184 Parent->addScope(WScope);
2187 if (!WScope->getParent()) {
2188 StringRef SPName = DISubprogram(Scope).getLinkageName();
2189 if (SPName == Asm->MF->getFunction()->getName())
2190 CurrentFnDbgScope = WScope;
2196 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2200 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2201 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2202 DILocation DL(InlinedAt);
2204 getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2205 WScope->setParent(Parent);
2206 Parent->addScope(WScope);
2208 ConcreteScopes[InlinedAt] = WScope;
2209 getOrCreateAbstractScope(Scope);
2214 /// hasValidLocation - Return true if debug location entry attached with
2215 /// machine instruction encodes valid location info.
2216 static bool hasValidLocation(LLVMContext &Ctx,
2217 const MachineInstr *MInsn,
2218 MDNode *&Scope, MDNode *&InlinedAt) {
2219 if (MInsn->isDebugValue())
2221 DebugLoc DL = MInsn->getDebugLoc();
2222 if (DL.isUnknown()) return false;
2224 MDNode *S = DL.getScope(Ctx);
2226 // There is no need to create another DIE for compile unit. For all
2227 // other scopes, create one DbgScope now. This will be translated
2228 // into a scope DIE at the end.
2229 if (DIScope(S).isCompileUnit()) return false;
2232 InlinedAt = DL.getInlinedAt(Ctx);
2236 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2238 static void calculateDominanceGraph(DbgScope *Scope) {
2239 assert (Scope && "Unable to calculate scop edominance graph!");
2240 SmallVector<DbgScope *, 4> WorkStack;
2241 WorkStack.push_back(Scope);
2242 unsigned Counter = 0;
2243 while (!WorkStack.empty()) {
2244 DbgScope *WS = WorkStack.back();
2245 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2246 bool visitedChildren = false;
2247 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2248 SE = Children.end(); SI != SE; ++SI) {
2249 DbgScope *ChildScope = *SI;
2250 if (!ChildScope->getDFSOut()) {
2251 WorkStack.push_back(ChildScope);
2252 visitedChildren = true;
2253 ChildScope->setDFSIn(++Counter);
2257 if (!visitedChildren) {
2258 WorkStack.pop_back();
2259 WS->setDFSOut(++Counter);
2264 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2266 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2267 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2270 unsigned PrevDFSIn = 0;
2271 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2273 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2275 const MachineInstr *MInsn = II;
2276 MDNode *Scope = NULL;
2277 MDNode *InlinedAt = NULL;
2279 // Check if instruction has valid location information.
2280 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2284 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2285 MI2ScopeMap.find(MInsn);
2286 if (DI != MI2ScopeMap.end()) {
2287 DbgScope *S = DI->second;
2288 dbgs() << S->getDFSIn();
2289 PrevDFSIn = S->getDFSIn();
2291 dbgs() << PrevDFSIn;
2293 dbgs() << " [ x" << PrevDFSIn;
2301 /// extractScopeInformation - Scan machine instructions in this function
2302 /// and collect DbgScopes. Return true, if at least one scope was found.
2303 bool DwarfDebug::extractScopeInformation() {
2304 // If scope information was extracted using .dbg intrinsics then there is not
2305 // any need to extract these information by scanning each instruction.
2306 if (!DbgScopeMap.empty())
2309 // Scan each instruction and create scopes. First build working set of scopes.
2310 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2311 SmallVector<DbgRange, 4> MIRanges;
2312 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2313 MDNode *PrevScope = NULL;
2314 MDNode *PrevInlinedAt = NULL;
2315 const MachineInstr *RangeBeginMI = NULL;
2316 const MachineInstr *PrevMI = NULL;
2317 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2319 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2321 const MachineInstr *MInsn = II;
2322 MDNode *Scope = NULL;
2323 MDNode *InlinedAt = NULL;
2325 // Check if instruction has valid location information.
2326 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2331 // If scope has not changed then skip this instruction.
2332 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2338 // If we have alread seen a beginning of a instruction range and
2339 // current instruction scope does not match scope of first instruction
2340 // in this range then create a new instruction range.
2341 DbgRange R(RangeBeginMI, PrevMI);
2342 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2343 MIRanges.push_back(R);
2346 // This is a beginning of a new instruction range.
2347 RangeBeginMI = MInsn;
2349 // Reset previous markers.
2352 PrevInlinedAt = InlinedAt;
2356 // Create last instruction range.
2357 if (RangeBeginMI && PrevMI && PrevScope) {
2358 DbgRange R(RangeBeginMI, PrevMI);
2359 MIRanges.push_back(R);
2360 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2363 if (!CurrentFnDbgScope)
2366 calculateDominanceGraph(CurrentFnDbgScope);
2368 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2370 // Find ranges of instructions covered by each DbgScope;
2371 DbgScope *PrevDbgScope = NULL;
2372 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2373 RE = MIRanges.end(); RI != RE; ++RI) {
2374 const DbgRange &R = *RI;
2375 DbgScope *S = MI2ScopeMap.lookup(R.first);
2376 assert (S && "Lost DbgScope for a machine instruction!");
2377 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2378 PrevDbgScope->closeInsnRange(S);
2379 S->openInsnRange(R.first);
2380 S->extendInsnRange(R.second);
2385 PrevDbgScope->closeInsnRange();
2387 identifyScopeMarkers();
2389 return !DbgScopeMap.empty();
2392 /// identifyScopeMarkers() -
2393 /// Each DbgScope has first instruction and last instruction to mark beginning
2394 /// and end of a scope respectively. Create an inverse map that list scopes
2395 /// starts (and ends) with an instruction. One instruction may start (or end)
2396 /// multiple scopes. Ignore scopes that are not reachable.
2397 void DwarfDebug::identifyScopeMarkers() {
2398 SmallVector<DbgScope *, 4> WorkList;
2399 WorkList.push_back(CurrentFnDbgScope);
2400 while (!WorkList.empty()) {
2401 DbgScope *S = WorkList.pop_back_val();
2403 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2404 if (!Children.empty())
2405 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2406 SE = Children.end(); SI != SE; ++SI)
2407 WorkList.push_back(*SI);
2409 if (S->isAbstractScope())
2412 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2415 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2416 RE = Ranges.end(); RI != RE; ++RI) {
2417 assert(RI->first && "DbgRange does not have first instruction!");
2418 assert(RI->second && "DbgRange does not have second instruction!");
2419 InsnsBeginScopeSet.insert(RI->first);
2420 InsnsEndScopeSet.insert(RI->second);
2425 /// FindFirstDebugLoc - Find the first debug location in the function. This
2426 /// is intended to be an approximation for the source position of the
2427 /// beginning of the function.
2428 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2429 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2431 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2432 MBBI != MBBE; ++MBBI) {
2433 DebugLoc DL = MBBI->getDebugLoc();
2434 if (!DL.isUnknown())
2440 /// beginFunction - Gather pre-function debug information. Assumes being
2441 /// emitted immediately after the function entry point.
2442 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2443 if (!MMI->hasDebugInfo()) return;
2444 if (!extractScopeInformation()) return;
2446 collectVariableInfo();
2448 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2449 Asm->getFunctionNumber());
2450 // Assumes in correct section after the entry point.
2451 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2453 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2455 DebugLoc FDL = FindFirstDebugLoc(MF);
2456 if (FDL.isUnknown()) return;
2458 MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2460 DISubprogram SP = getDISubprogram(Scope);
2463 Line = SP.getLineNumber();
2466 Line = FDL.getLine();
2470 recordSourceLine(Line, Col, Scope);
2473 /// endFunction - Gather and emit post-function debug information.
2475 void DwarfDebug::endFunction(const MachineFunction *MF) {
2476 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2478 if (CurrentFnDbgScope) {
2479 // Define end label for subprogram.
2480 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2481 Asm->getFunctionNumber()));
2483 // Get function line info.
2484 if (!Lines.empty()) {
2485 // Get section line info.
2486 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2487 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2488 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2489 // Append the function info to section info.
2490 SectionLineInfos.insert(SectionLineInfos.end(),
2491 Lines.begin(), Lines.end());
2494 // Construct abstract scopes.
2495 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2496 AE = AbstractScopesList.end(); AI != AE; ++AI)
2497 constructScopeDIE(*AI);
2499 constructScopeDIE(CurrentFnDbgScope);
2501 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2502 MMI->getFrameMoves()));
2506 CurrentFnDbgScope = NULL;
2507 DeleteContainerSeconds(DbgScopeMap);
2508 InsnsBeginScopeSet.clear();
2509 InsnsEndScopeSet.clear();
2510 DbgValueStartMap.clear();
2511 ConcreteScopes.clear();
2512 DeleteContainerSeconds(AbstractScopes);
2513 AbstractScopesList.clear();
2514 AbstractVariables.clear();
2515 InsnBeforeLabelMap.clear();
2516 InsnAfterLabelMap.clear();
2521 /// recordSourceLine - Register a source line with debug info. Returns the
2522 /// unique label that was emitted and which provides correspondence to
2523 /// the source line list.
2524 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2528 DIDescriptor Scope(S);
2529 if (Scope.isCompileUnit()) {
2530 DICompileUnit CU(S);
2531 Dir = CU.getDirectory();
2532 Fn = CU.getFilename();
2533 } else if (Scope.isSubprogram()) {
2535 Dir = SP.getDirectory();
2536 Fn = SP.getFilename();
2537 } else if (Scope.isLexicalBlock()) {
2538 DILexicalBlock DB(S);
2539 Dir = DB.getDirectory();
2540 Fn = DB.getFilename();
2542 assert(0 && "Unexpected scope info");
2544 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2545 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2546 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2548 Asm->OutStreamer.EmitLabel(Label);
2552 //===----------------------------------------------------------------------===//
2554 //===----------------------------------------------------------------------===//
2556 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2559 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2560 // Get the children.
2561 const std::vector<DIE *> &Children = Die->getChildren();
2563 // If not last sibling and has children then add sibling offset attribute.
2564 if (!Last && !Children.empty())
2565 Die->addSiblingOffset(DIEValueAllocator);
2567 // Record the abbreviation.
2568 assignAbbrevNumber(Die->getAbbrev());
2570 // Get the abbreviation for this DIE.
2571 unsigned AbbrevNumber = Die->getAbbrevNumber();
2572 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2575 Die->setOffset(Offset);
2577 // Start the size with the size of abbreviation code.
2578 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2580 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2581 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2583 // Size the DIE attribute values.
2584 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2585 // Size attribute value.
2586 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2588 // Size the DIE children if any.
2589 if (!Children.empty()) {
2590 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2591 "Children flag not set");
2593 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2594 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2596 // End of children marker.
2597 Offset += sizeof(int8_t);
2600 Die->setSize(Offset - Die->getOffset());
2604 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2606 void DwarfDebug::computeSizeAndOffsets() {
2607 // Compute size of compile unit header.
2608 static unsigned Offset =
2609 sizeof(int32_t) + // Length of Compilation Unit Info
2610 sizeof(int16_t) + // DWARF version number
2611 sizeof(int32_t) + // Offset Into Abbrev. Section
2612 sizeof(int8_t); // Pointer Size (in bytes)
2614 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2617 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2618 /// temporary label to it if SymbolStem is specified.
2619 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2620 const char *SymbolStem = 0) {
2621 Asm->OutStreamer.SwitchSection(Section);
2622 if (!SymbolStem) return 0;
2624 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2625 Asm->OutStreamer.EmitLabel(TmpSym);
2629 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2630 /// the start of each one.
2631 void DwarfDebug::EmitSectionLabels() {
2632 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2634 // Dwarf sections base addresses.
2635 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2636 DwarfFrameSectionSym =
2637 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2640 DwarfInfoSectionSym =
2641 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2642 DwarfAbbrevSectionSym =
2643 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2644 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2646 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2647 EmitSectionSym(Asm, MacroInfo);
2649 EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2650 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2651 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2652 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2653 DwarfStrSectionSym =
2654 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2655 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2658 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2659 EmitSectionSym(Asm, TLOF.getDataSection());
2662 /// emitDIE - Recusively Emits a debug information entry.
2664 void DwarfDebug::emitDIE(DIE *Die) {
2665 // Get the abbreviation for this DIE.
2666 unsigned AbbrevNumber = Die->getAbbrevNumber();
2667 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2669 // Emit the code (index) for the abbreviation.
2670 if (Asm->isVerbose())
2671 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2672 Twine::utohexstr(Die->getOffset()) + ":0x" +
2673 Twine::utohexstr(Die->getSize()) + " " +
2674 dwarf::TagString(Abbrev->getTag()));
2675 Asm->EmitULEB128(AbbrevNumber);
2677 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2678 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2680 // Emit the DIE attribute values.
2681 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2682 unsigned Attr = AbbrevData[i].getAttribute();
2683 unsigned Form = AbbrevData[i].getForm();
2684 assert(Form && "Too many attributes for DIE (check abbreviation)");
2686 if (Asm->isVerbose())
2687 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2690 case dwarf::DW_AT_sibling:
2691 Asm->EmitInt32(Die->getSiblingOffset());
2693 case dwarf::DW_AT_abstract_origin: {
2694 DIEEntry *E = cast<DIEEntry>(Values[i]);
2695 DIE *Origin = E->getEntry();
2696 unsigned Addr = Origin->getOffset();
2697 Asm->EmitInt32(Addr);
2700 case dwarf::DW_AT_ranges: {
2701 // DW_AT_range Value encodes offset in debug_range section.
2702 DIEInteger *V = cast<DIEInteger>(Values[i]);
2703 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2705 DwarfDebugRangeSectionSym,
2710 // Emit an attribute using the defined form.
2711 Values[i]->EmitValue(Asm, Form);
2716 // Emit the DIE children if any.
2717 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2718 const std::vector<DIE *> &Children = Die->getChildren();
2720 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2721 emitDIE(Children[j]);
2723 if (Asm->isVerbose())
2724 Asm->OutStreamer.AddComment("End Of Children Mark");
2729 /// emitDebugInfo - Emit the debug info section.
2731 void DwarfDebug::emitDebugInfo() {
2732 // Start debug info section.
2733 Asm->OutStreamer.SwitchSection(
2734 Asm->getObjFileLowering().getDwarfInfoSection());
2735 DIE *Die = ModuleCU->getCUDie();
2737 // Emit the compile units header.
2738 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2739 ModuleCU->getID()));
2741 // Emit size of content not including length itself
2742 unsigned ContentSize = Die->getSize() +
2743 sizeof(int16_t) + // DWARF version number
2744 sizeof(int32_t) + // Offset Into Abbrev. Section
2745 sizeof(int8_t) + // Pointer Size (in bytes)
2746 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2748 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2749 Asm->EmitInt32(ContentSize);
2750 Asm->OutStreamer.AddComment("DWARF version number");
2751 Asm->EmitInt16(dwarf::DWARF_VERSION);
2752 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2753 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2754 DwarfAbbrevSectionSym);
2755 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2756 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2759 // FIXME - extra padding for gdb bug.
2760 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2765 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2768 /// emitAbbreviations - Emit the abbreviation section.
2770 void DwarfDebug::emitAbbreviations() const {
2771 // Check to see if it is worth the effort.
2772 if (!Abbreviations.empty()) {
2773 // Start the debug abbrev section.
2774 Asm->OutStreamer.SwitchSection(
2775 Asm->getObjFileLowering().getDwarfAbbrevSection());
2777 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2779 // For each abbrevation.
2780 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2781 // Get abbreviation data
2782 const DIEAbbrev *Abbrev = Abbreviations[i];
2784 // Emit the abbrevations code (base 1 index.)
2785 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2787 // Emit the abbreviations data.
2791 // Mark end of abbreviations.
2792 Asm->EmitULEB128(0, "EOM(3)");
2794 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2798 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2799 /// the line matrix.
2801 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2802 // Define last address of section.
2803 Asm->OutStreamer.AddComment("Extended Op");
2806 Asm->OutStreamer.AddComment("Op size");
2807 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2808 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2809 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2811 Asm->OutStreamer.AddComment("Section end label");
2813 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2814 Asm->getTargetData().getPointerSize(),
2817 // Mark end of matrix.
2818 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2824 /// emitDebugLines - Emit source line information.
2826 void DwarfDebug::emitDebugLines() {
2827 // If the target is using .loc/.file, the assembler will be emitting the
2828 // .debug_line table automatically.
2829 if (Asm->MAI->hasDotLocAndDotFile())
2832 // Minimum line delta, thus ranging from -10..(255-10).
2833 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2834 // Maximum line delta, thus ranging from -10..(255-10).
2835 const int MaxLineDelta = 255 + MinLineDelta;
2837 // Start the dwarf line section.
2838 Asm->OutStreamer.SwitchSection(
2839 Asm->getObjFileLowering().getDwarfLineSection());
2841 // Construct the section header.
2842 Asm->OutStreamer.AddComment("Length of Source Line Info");
2843 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2844 Asm->GetTempSymbol("line_begin"), 4);
2845 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2847 Asm->OutStreamer.AddComment("DWARF version number");
2848 Asm->EmitInt16(dwarf::DWARF_VERSION);
2850 Asm->OutStreamer.AddComment("Prolog Length");
2851 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2852 Asm->GetTempSymbol("line_prolog_begin"), 4);
2853 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2855 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2857 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2859 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2860 Asm->EmitInt8(MinLineDelta);
2861 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2862 Asm->EmitInt8(MaxLineDelta);
2863 Asm->OutStreamer.AddComment("Special Opcode Base");
2864 Asm->EmitInt8(-MinLineDelta);
2866 // Line number standard opcode encodings argument count
2867 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2869 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2871 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2873 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2875 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2877 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2879 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2881 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2883 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2886 // Emit directories.
2887 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2888 const std::string &Dir = getSourceDirectoryName(DI);
2889 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2890 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2893 Asm->OutStreamer.AddComment("End of directories");
2897 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2898 // Remember source id starts at 1.
2899 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2900 const std::string &FN = getSourceFileName(Id.second);
2901 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2902 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2904 Asm->EmitULEB128(Id.first, "Directory #");
2905 Asm->EmitULEB128(0, "Mod date");
2906 Asm->EmitULEB128(0, "File size");
2909 Asm->OutStreamer.AddComment("End of files");
2912 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2914 // A sequence for each text section.
2915 unsigned SecSrcLinesSize = SectionSourceLines.size();
2917 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2918 // Isolate current sections line info.
2919 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2921 // Dwarf assumes we start with first line of first source file.
2922 unsigned Source = 1;
2925 // Construct rows of the address, source, line, column matrix.
2926 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2927 const SrcLineInfo &LineInfo = LineInfos[i];
2928 MCSymbol *Label = LineInfo.getLabel();
2929 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2931 if (LineInfo.getLine() == 0) continue;
2933 if (Asm->isVerbose()) {
2934 std::pair<unsigned, unsigned> SrcID =
2935 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2936 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2938 Twine(getSourceFileName(SrcID.second)) +
2939 ":" + Twine(LineInfo.getLine()));
2942 // Define the line address.
2943 Asm->OutStreamer.AddComment("Extended Op");
2945 Asm->OutStreamer.AddComment("Op size");
2946 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2948 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2949 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2951 Asm->OutStreamer.AddComment("Location label");
2952 Asm->OutStreamer.EmitSymbolValue(Label,
2953 Asm->getTargetData().getPointerSize(),
2956 // If change of source, then switch to the new source.
2957 if (Source != LineInfo.getSourceID()) {
2958 Source = LineInfo.getSourceID();
2959 Asm->OutStreamer.AddComment("DW_LNS_set_file");
2960 Asm->EmitInt8(dwarf::DW_LNS_set_file);
2961 Asm->EmitULEB128(Source, "New Source");
2964 // If change of line.
2965 if (Line != LineInfo.getLine()) {
2966 // Determine offset.
2967 int Offset = LineInfo.getLine() - Line;
2968 int Delta = Offset - MinLineDelta;
2971 Line = LineInfo.getLine();
2973 // If delta is small enough and in range...
2974 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2975 // ... then use fast opcode.
2976 Asm->OutStreamer.AddComment("Line Delta");
2977 Asm->EmitInt8(Delta - MinLineDelta);
2979 // ... otherwise use long hand.
2980 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2981 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2982 Asm->EmitSLEB128(Offset, "Line Offset");
2983 Asm->OutStreamer.AddComment("DW_LNS_copy");
2984 Asm->EmitInt8(dwarf::DW_LNS_copy);
2987 // Copy the previous row (different address or source)
2988 Asm->OutStreamer.AddComment("DW_LNS_copy");
2989 Asm->EmitInt8(dwarf::DW_LNS_copy);
2993 emitEndOfLineMatrix(j + 1);
2996 if (SecSrcLinesSize == 0)
2997 // Because we're emitting a debug_line section, we still need a line
2998 // table. The linker and friends expect it to exist. If there's nothing to
2999 // put into it, emit an empty table.
3000 emitEndOfLineMatrix(1);
3002 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3005 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3007 void DwarfDebug::emitCommonDebugFrame() {
3008 if (!Asm->MAI->doesDwarfRequireFrameSection())
3011 int stackGrowth = Asm->getTargetData().getPointerSize();
3012 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3013 TargetFrameInfo::StackGrowsDown)
3016 // Start the dwarf frame section.
3017 Asm->OutStreamer.SwitchSection(
3018 Asm->getObjFileLowering().getDwarfFrameSection());
3020 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3021 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3022 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3023 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3025 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3026 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3027 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3028 Asm->OutStreamer.AddComment("CIE Version");
3029 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3030 Asm->OutStreamer.AddComment("CIE Augmentation");
3031 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3032 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3033 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3034 Asm->OutStreamer.AddComment("CIE RA Column");
3035 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3036 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3038 std::vector<MachineMove> Moves;
3039 RI->getInitialFrameState(Moves);
3041 Asm->EmitFrameMoves(Moves, 0, false);
3043 Asm->EmitAlignment(2, 0, 0, false);
3044 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3047 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3050 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3051 if (!Asm->MAI->doesDwarfRequireFrameSection())
3054 // Start the dwarf frame section.
3055 Asm->OutStreamer.SwitchSection(
3056 Asm->getObjFileLowering().getDwarfFrameSection());
3058 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3059 MCSymbol *DebugFrameBegin =
3060 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3061 MCSymbol *DebugFrameEnd =
3062 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3063 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3065 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3067 Asm->OutStreamer.AddComment("FDE CIE offset");
3068 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3069 DwarfFrameSectionSym);
3071 Asm->OutStreamer.AddComment("FDE initial location");
3072 MCSymbol *FuncBeginSym =
3073 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3074 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3075 Asm->getTargetData().getPointerSize(),
3079 Asm->OutStreamer.AddComment("FDE address range");
3080 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3081 FuncBeginSym, Asm->getTargetData().getPointerSize());
3083 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3085 Asm->EmitAlignment(2, 0, 0, false);
3086 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3089 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3091 void DwarfDebug::emitDebugPubNames() {
3092 // Start the dwarf pubnames section.
3093 Asm->OutStreamer.SwitchSection(
3094 Asm->getObjFileLowering().getDwarfPubNamesSection());
3096 Asm->OutStreamer.AddComment("Length of Public Names Info");
3097 Asm->EmitLabelDifference(
3098 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3099 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3101 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3102 ModuleCU->getID()));
3104 Asm->OutStreamer.AddComment("DWARF Version");
3105 Asm->EmitInt16(dwarf::DWARF_VERSION);
3107 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3108 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3109 DwarfInfoSectionSym);
3111 Asm->OutStreamer.AddComment("Compilation Unit Length");
3112 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3113 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3116 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3117 for (StringMap<DIE*>::const_iterator
3118 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3119 const char *Name = GI->getKeyData();
3120 DIE *Entity = GI->second;
3122 Asm->OutStreamer.AddComment("DIE offset");
3123 Asm->EmitInt32(Entity->getOffset());
3125 if (Asm->isVerbose())
3126 Asm->OutStreamer.AddComment("External Name");
3127 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3130 Asm->OutStreamer.AddComment("End Mark");
3132 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3133 ModuleCU->getID()));
3136 void DwarfDebug::emitDebugPubTypes() {
3137 // Start the dwarf pubnames section.
3138 Asm->OutStreamer.SwitchSection(
3139 Asm->getObjFileLowering().getDwarfPubTypesSection());
3140 Asm->OutStreamer.AddComment("Length of Public Types Info");
3141 Asm->EmitLabelDifference(
3142 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3143 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3145 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3146 ModuleCU->getID()));
3148 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3149 Asm->EmitInt16(dwarf::DWARF_VERSION);
3151 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3152 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3153 DwarfInfoSectionSym);
3155 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3156 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3157 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3160 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3161 for (StringMap<DIE*>::const_iterator
3162 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3163 const char *Name = GI->getKeyData();
3164 DIE * Entity = GI->second;
3166 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3167 Asm->EmitInt32(Entity->getOffset());
3169 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3170 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3173 Asm->OutStreamer.AddComment("End Mark");
3175 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3176 ModuleCU->getID()));
3179 /// emitDebugStr - Emit visible names into a debug str section.
3181 void DwarfDebug::emitDebugStr() {
3182 // Check to see if it is worth the effort.
3183 if (StringPool.empty()) return;
3185 // Start the dwarf str section.
3186 Asm->OutStreamer.SwitchSection(
3187 Asm->getObjFileLowering().getDwarfStrSection());
3189 // Get all of the string pool entries and put them in an array by their ID so
3190 // we can sort them.
3191 SmallVector<std::pair<unsigned,
3192 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3194 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3195 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3196 Entries.push_back(std::make_pair(I->second.second, &*I));
3198 array_pod_sort(Entries.begin(), Entries.end());
3200 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3201 // Emit a label for reference from debug information entries.
3202 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3204 // Emit the string itself.
3205 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3209 /// emitDebugLoc - Emit visible names into a debug loc section.
3211 void DwarfDebug::emitDebugLoc() {
3212 // Start the dwarf loc section.
3213 Asm->OutStreamer.SwitchSection(
3214 Asm->getObjFileLowering().getDwarfLocSection());
3217 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3219 void DwarfDebug::EmitDebugARanges() {
3220 // Start the dwarf aranges section.
3221 Asm->OutStreamer.SwitchSection(
3222 Asm->getObjFileLowering().getDwarfARangesSection());
3225 /// emitDebugRanges - Emit visible names into a debug ranges section.
3227 void DwarfDebug::emitDebugRanges() {
3228 // Start the dwarf ranges section.
3229 Asm->OutStreamer.SwitchSection(
3230 Asm->getObjFileLowering().getDwarfRangesSection());
3231 for (SmallVector<const MCSymbol *, 8>::const_iterator I = DebugRangeSymbols.begin(),
3232 E = DebugRangeSymbols.end(); I != E; ++I) {
3234 Asm->EmitLabelDifference(*I, TextSectionSym,
3235 Asm->getTargetData().getPointerSize());
3237 Asm->OutStreamer.EmitIntValue(0, Asm->getTargetData().getPointerSize(),
3242 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3244 void DwarfDebug::emitDebugMacInfo() {
3245 if (const MCSection *LineInfo =
3246 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3247 // Start the dwarf macinfo section.
3248 Asm->OutStreamer.SwitchSection(LineInfo);
3252 /// emitDebugInlineInfo - Emit inline info using following format.
3254 /// 1. length of section
3255 /// 2. Dwarf version number
3256 /// 3. address size.
3258 /// Entries (one "entry" for each function that was inlined):
3260 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3261 /// otherwise offset into __debug_str for regular function name.
3262 /// 2. offset into __debug_str section for regular function name.
3263 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3264 /// instances for the function.
3266 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3267 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3268 /// __debug_info section, and the low_pc is the starting address for the
3269 /// inlining instance.
3270 void DwarfDebug::emitDebugInlineInfo() {
3271 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3277 Asm->OutStreamer.SwitchSection(
3278 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3280 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3281 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3282 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3284 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3286 Asm->OutStreamer.AddComment("Dwarf Version");
3287 Asm->EmitInt16(dwarf::DWARF_VERSION);
3288 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3289 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3291 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3292 E = InlinedSPNodes.end(); I != E; ++I) {
3295 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3296 = InlineInfo.find(Node);
3297 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3298 DISubprogram SP(Node);
3299 StringRef LName = SP.getLinkageName();
3300 StringRef Name = SP.getName();
3302 Asm->OutStreamer.AddComment("MIPS linkage name");
3303 if (LName.empty()) {
3304 Asm->OutStreamer.EmitBytes(Name, 0);
3305 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3307 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3308 DwarfStrSectionSym);
3310 Asm->OutStreamer.AddComment("Function name");
3311 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3312 Asm->EmitULEB128(Labels.size(), "Inline count");
3314 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3315 LE = Labels.end(); LI != LE; ++LI) {
3316 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3317 Asm->EmitInt32(LI->second->getOffset());
3319 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3320 Asm->OutStreamer.EmitSymbolValue(LI->first,
3321 Asm->getTargetData().getPointerSize(),0);
3325 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));