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"));
50 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
51 cl::desc("Make an absense of debug location information explicit."),
55 const char *DWARFGroupName = "DWARF Emission";
56 const char *DbgTimerName = "DWARF Debug Writer";
57 } // end anonymous namespace
59 //===----------------------------------------------------------------------===//
61 /// Configuration values for initial hash set sizes (log2).
63 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
67 //===----------------------------------------------------------------------===//
68 /// CompileUnit - This dwarf writer support class manages information associate
69 /// with a source file.
71 /// ID - File identifier for source.
75 /// Die - Compile unit debug information entry.
77 const OwningPtr<DIE> CUDie;
79 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
82 /// GVToDieMap - Tracks the mapping of unit level debug informaton
83 /// variables to debug information entries.
84 /// FIXME : Rename GVToDieMap -> NodeToDieMap
85 DenseMap<MDNode *, DIE *> GVToDieMap;
87 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
88 /// descriptors to debug information entries using a DIEEntry proxy.
90 DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
92 /// Globals - A map of globally visible named entities for this unit.
94 StringMap<DIE*> Globals;
96 /// GlobalTypes - A map of globally visible types for this unit.
98 StringMap<DIE*> GlobalTypes;
101 CompileUnit(unsigned I, DIE *D)
102 : ID(I), CUDie(D), IndexTyDie(0) {}
105 unsigned getID() const { return ID; }
106 DIE* getCUDie() const { return CUDie.get(); }
107 const StringMap<DIE*> &getGlobals() const { return Globals; }
108 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
110 /// hasContent - Return true if this compile unit has something to write out.
112 bool hasContent() const { return !CUDie->getChildren().empty(); }
114 /// addGlobal - Add a new global entity to the compile unit.
116 void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
118 /// addGlobalType - Add a new global type to the compile unit.
120 void addGlobalType(StringRef Name, DIE *Die) {
121 GlobalTypes[Name] = Die;
124 /// getDIE - Returns the debug information entry map slot for the
125 /// specified debug variable.
126 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
128 /// insertDIE - Insert DIE into the map.
129 void insertDIE(MDNode *N, DIE *D) {
130 GVToDieMap.insert(std::make_pair(N, D));
133 /// getDIEEntry - Returns the debug information entry for the speciefied
135 DIEEntry *getDIEEntry(MDNode *N) {
136 DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
137 if (I == GVToDIEEntryMap.end())
142 /// insertDIEEntry - Insert debug information entry into the map.
143 void insertDIEEntry(MDNode *N, DIEEntry *E) {
144 GVToDIEEntryMap.insert(std::make_pair(N, E));
147 /// addDie - Adds or interns the DIE to the compile unit.
149 void addDie(DIE *Buffer) {
150 this->CUDie->addChild(Buffer);
153 // getIndexTyDie - Get an anonymous type for index type.
154 DIE *getIndexTyDie() {
158 // setIndexTyDie - Set D as anonymous type for index which can be reused
160 void setIndexTyDie(DIE *D) {
166 //===----------------------------------------------------------------------===//
167 /// DbgVariable - This class is used to track local variable information.
170 DIVariable Var; // Variable Descriptor.
171 unsigned FrameIndex; // Variable frame index.
172 const MachineInstr *DbgValueMInsn; // DBG_VALUE
173 // DbgValueLabel - DBG_VALUE is effective from this label.
174 MCSymbol *DbgValueLabel;
175 DbgVariable *const AbstractVar; // Abstract variable for this variable.
178 // AbsVar may be NULL.
179 DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
180 : Var(V), FrameIndex(I), DbgValueMInsn(0),
181 DbgValueLabel(0), AbstractVar(AbsVar), TheDIE(0) {}
182 DbgVariable(DIVariable V, const MachineInstr *MI, DbgVariable *AbsVar)
183 : Var(V), FrameIndex(0), DbgValueMInsn(MI), DbgValueLabel(0),
184 AbstractVar(AbsVar), TheDIE(0)
188 DIVariable getVariable() const { return Var; }
189 unsigned getFrameIndex() const { return FrameIndex; }
190 const MachineInstr *getDbgValue() const { return DbgValueMInsn; }
191 MCSymbol *getDbgValueLabel() const { return DbgValueLabel; }
192 void setDbgValueLabel(MCSymbol *L) { DbgValueLabel = L; }
193 DbgVariable *getAbstractVariable() const { return AbstractVar; }
194 void setDIE(DIE *D) { TheDIE = D; }
195 DIE *getDIE() const { return TheDIE; }
198 //===----------------------------------------------------------------------===//
199 /// DbgRange - This is used to track range of instructions with identical
200 /// debug info scope.
202 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
204 //===----------------------------------------------------------------------===//
205 /// DbgScope - This class is used to track scope information.
208 DbgScope *Parent; // Parent to this scope.
209 DIDescriptor Desc; // Debug info descriptor for scope.
210 // Location at which this scope is inlined.
211 AssertingVH<MDNode> InlinedAtLocation;
212 bool AbstractScope; // Abstract Scope
213 const MachineInstr *LastInsn; // Last instruction of this scope.
214 const MachineInstr *FirstInsn; // First instruction of this scope.
215 unsigned DFSIn, DFSOut;
216 // Scopes defined in scope. Contents not owned.
217 SmallVector<DbgScope *, 4> Scopes;
218 // Variables declared in scope. Contents owned.
219 SmallVector<DbgVariable *, 8> Variables;
220 SmallVector<DbgRange, 4> Ranges;
221 // Private state for dump()
222 mutable unsigned IndentLevel;
224 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
225 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
226 LastInsn(0), FirstInsn(0),
227 DFSIn(0), DFSOut(0), IndentLevel(0) {}
231 DbgScope *getParent() const { return Parent; }
232 void setParent(DbgScope *P) { Parent = P; }
233 DIDescriptor getDesc() const { return Desc; }
234 MDNode *getInlinedAt() const { return InlinedAtLocation; }
235 MDNode *getScopeNode() const { return Desc.getNode(); }
236 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
237 const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
238 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
240 /// openInsnRange - This scope covers instruction range starting from MI.
241 void openInsnRange(const MachineInstr *MI) {
246 Parent->openInsnRange(MI);
249 /// extendInsnRange - Extend the current instruction range covered by
251 void extendInsnRange(const MachineInstr *MI) {
252 assert (FirstInsn && "MI Range is not open!");
255 Parent->extendInsnRange(MI);
258 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
259 /// until now. This is used when a new scope is encountered while walking
260 /// machine instructions.
261 void closeInsnRange(DbgScope *NewScope = NULL) {
262 assert (LastInsn && "Last insn missing!");
263 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
266 // If Parent dominates NewScope then do not close Parent's instruction
268 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
269 Parent->closeInsnRange(NewScope);
272 void setAbstractScope() { AbstractScope = true; }
273 bool isAbstractScope() const { return AbstractScope; }
275 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
276 unsigned getDFSOut() const { return DFSOut; }
277 void setDFSOut(unsigned O) { DFSOut = O; }
278 unsigned getDFSIn() const { return DFSIn; }
279 void setDFSIn(unsigned I) { DFSIn = I; }
280 bool dominates(const DbgScope *S) {
283 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
288 /// addScope - Add a scope to the scope.
290 void addScope(DbgScope *S) { Scopes.push_back(S); }
292 /// addVariable - Add a variable to the scope.
294 void addVariable(DbgVariable *V) { Variables.push_back(V); }
301 } // end llvm namespace
304 void DbgScope::dump() const {
305 raw_ostream &err = dbgs();
306 err.indent(IndentLevel);
307 MDNode *N = Desc.getNode();
310 err << "Abstract Scope\n";
314 err << "Children ...\n";
315 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
316 if (Scopes[i] != this)
323 DbgScope::~DbgScope() {
324 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
328 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
329 : Asm(A), MMI(Asm->MMI), ModuleCU(0),
330 AbbreviationsSet(InitAbbreviationsSetSize),
331 CurrentFnDbgScope(0), PrevLabel(NULL) {
332 NextStringPoolNumber = 0;
334 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
335 DwarfStrSectionSym = TextSectionSym = 0;
336 DwarfDebugRangeSectionSym = 0;
337 FunctionBeginSym = 0;
338 if (TimePassesIsEnabled) {
339 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
345 DwarfDebug::~DwarfDebug() {
346 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
347 DIEBlocks[j]->~DIEBlock();
350 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
351 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
352 if (Entry.first) return Entry.first;
354 Entry.second = NextStringPoolNumber++;
355 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
359 /// assignAbbrevNumber - Define a unique number for the abbreviation.
361 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
362 // Profile the node so that we can make it unique.
366 // Check the set for priors.
367 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
369 // If it's newly added.
370 if (InSet == &Abbrev) {
371 // Add to abbreviation list.
372 Abbreviations.push_back(&Abbrev);
374 // Assign the vector position + 1 as its number.
375 Abbrev.setNumber(Abbreviations.size());
377 // Assign existing abbreviation number.
378 Abbrev.setNumber(InSet->getNumber());
382 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
383 /// information entry.
384 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
385 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
389 /// addUInt - Add an unsigned integer attribute data and value.
391 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
392 unsigned Form, uint64_t Integer) {
393 if (!Form) Form = DIEInteger::BestForm(false, Integer);
394 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
395 Die->addValue(Attribute, Form, Value);
398 /// addSInt - Add an signed integer attribute data and value.
400 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
401 unsigned Form, int64_t Integer) {
402 if (!Form) Form = DIEInteger::BestForm(true, Integer);
403 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
404 Die->addValue(Attribute, Form, Value);
407 /// addString - Add a string attribute data and value. DIEString only
408 /// keeps string reference.
409 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
411 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
412 Die->addValue(Attribute, Form, Value);
415 /// addLabel - Add a Dwarf label attribute data and value.
417 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
418 const MCSymbol *Label) {
419 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
420 Die->addValue(Attribute, Form, Value);
423 /// addDelta - Add a label delta attribute data and value.
425 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
426 const MCSymbol *Hi, const MCSymbol *Lo) {
427 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
428 Die->addValue(Attribute, Form, Value);
431 /// addDIEEntry - Add a DIE attribute data and value.
433 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
435 Die->addValue(Attribute, Form, createDIEEntry(Entry));
439 /// addBlock - Add block data.
441 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
443 Block->ComputeSize(Asm);
444 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
445 Die->addValue(Attribute, Block->BestForm(), Block);
448 /// addSourceLine - Add location information to specified debug information
450 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
451 // If there is no compile unit specified, don't add a line #.
452 if (!V->getCompileUnit().Verify())
455 unsigned Line = V->getLineNumber();
456 unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
457 V->getContext().getFilename());
458 assert(FileID && "Invalid file id");
459 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
460 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
463 /// addSourceLine - Add location information to specified debug information
465 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
466 // If there is no compile unit specified, don't add a line #.
467 if (!G->getCompileUnit().Verify())
470 unsigned Line = G->getLineNumber();
471 unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
472 G->getContext().getFilename());
473 assert(FileID && "Invalid file id");
474 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
475 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
478 /// addSourceLine - Add location information to specified debug information
480 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
481 // If there is no compile unit specified, don't add a line #.
482 if (!SP->getCompileUnit().Verify())
484 // If the line number is 0, don't add it.
485 if (SP->getLineNumber() == 0)
488 unsigned Line = SP->getLineNumber();
489 if (!SP->getContext().Verify())
491 unsigned FileID = GetOrCreateSourceID(SP->getDirectory(),
493 assert(FileID && "Invalid file id");
494 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
495 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
498 /// addSourceLine - Add location information to specified debug information
500 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
501 // If there is no compile unit specified, don't add a line #.
502 DICompileUnit CU = Ty->getCompileUnit();
506 unsigned Line = Ty->getLineNumber();
507 if (!Ty->getContext().Verify())
509 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
510 Ty->getContext().getFilename());
511 assert(FileID && "Invalid file id");
512 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
513 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
516 /// addSourceLine - Add location information to specified debug information
518 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
519 // If there is no compile unit specified, don't add a line #.
520 if (!NS->getCompileUnit().Verify())
523 unsigned Line = NS->getLineNumber();
524 StringRef FN = NS->getFilename();
525 StringRef Dir = NS->getDirectory();
527 unsigned FileID = GetOrCreateSourceID(Dir, FN);
528 assert(FileID && "Invalid file id");
529 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
530 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
533 /* Byref variables, in Blocks, are declared by the programmer as
534 "SomeType VarName;", but the compiler creates a
535 __Block_byref_x_VarName struct, and gives the variable VarName
536 either the struct, or a pointer to the struct, as its type. This
537 is necessary for various behind-the-scenes things the compiler
538 needs to do with by-reference variables in blocks.
540 However, as far as the original *programmer* is concerned, the
541 variable should still have type 'SomeType', as originally declared.
543 The following function dives into the __Block_byref_x_VarName
544 struct to find the original type of the variable. This will be
545 passed back to the code generating the type for the Debug
546 Information Entry for the variable 'VarName'. 'VarName' will then
547 have the original type 'SomeType' in its debug information.
549 The original type 'SomeType' will be the type of the field named
550 'VarName' inside the __Block_byref_x_VarName struct.
552 NOTE: In order for this to not completely fail on the debugger
553 side, the Debug Information Entry for the variable VarName needs to
554 have a DW_AT_location that tells the debugger how to unwind through
555 the pointers and __Block_byref_x_VarName struct to find the actual
556 value of the variable. The function addBlockByrefType does this. */
558 /// Find the type the programmer originally declared the variable to be
559 /// and return that type.
561 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
564 unsigned tag = Ty.getTag();
566 if (tag == dwarf::DW_TAG_pointer_type) {
567 DIDerivedType DTy = DIDerivedType(Ty.getNode());
568 subType = DTy.getTypeDerivedFrom();
571 DICompositeType blockStruct = DICompositeType(subType.getNode());
572 DIArray Elements = blockStruct.getTypeArray();
574 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
575 DIDescriptor Element = Elements.getElement(i);
576 DIDerivedType DT = DIDerivedType(Element.getNode());
577 if (Name == DT.getName())
578 return (DT.getTypeDerivedFrom());
584 /// addComplexAddress - Start with the address based on the location provided,
585 /// and generate the DWARF information necessary to find the actual variable
586 /// given the extra address information encoded in the DIVariable, starting from
587 /// the starting location. Add the DWARF information to the die.
589 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
591 const MachineLocation &Location) {
592 const DIVariable &VD = DV->getVariable();
593 DIType Ty = VD.getType();
595 // Decode the original location, and use that as the start of the byref
596 // variable's location.
597 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
598 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
599 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
601 if (Location.isReg()) {
603 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
605 Reg = Reg - dwarf::DW_OP_reg0;
606 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
607 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
611 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
613 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
614 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
617 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
620 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
621 uint64_t Element = VD.getAddrElement(i);
623 if (Element == DIFactory::OpPlus) {
624 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
625 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
626 } else if (Element == DIFactory::OpDeref) {
627 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
628 } else llvm_unreachable("unknown DIFactory Opcode");
631 // Now attach the location information to the DIE.
632 addBlock(Die, Attribute, 0, Block);
635 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
636 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
637 gives the variable VarName either the struct, or a pointer to the struct, as
638 its type. This is necessary for various behind-the-scenes things the
639 compiler needs to do with by-reference variables in Blocks.
641 However, as far as the original *programmer* is concerned, the variable
642 should still have type 'SomeType', as originally declared.
644 The function getBlockByrefType dives into the __Block_byref_x_VarName
645 struct to find the original type of the variable, which is then assigned to
646 the variable's Debug Information Entry as its real type. So far, so good.
647 However now the debugger will expect the variable VarName to have the type
648 SomeType. So we need the location attribute for the variable to be an
649 expression that explains to the debugger how to navigate through the
650 pointers and struct to find the actual variable of type SomeType.
652 The following function does just that. We start by getting
653 the "normal" location for the variable. This will be the location
654 of either the struct __Block_byref_x_VarName or the pointer to the
655 struct __Block_byref_x_VarName.
657 The struct will look something like:
659 struct __Block_byref_x_VarName {
661 struct __Block_byref_x_VarName *forwarding;
662 ... <various other fields>
664 ... <maybe more fields>
667 If we are given the struct directly (as our starting point) we
668 need to tell the debugger to:
670 1). Add the offset of the forwarding field.
672 2). Follow that pointer to get the real __Block_byref_x_VarName
673 struct to use (the real one may have been copied onto the heap).
675 3). Add the offset for the field VarName, to find the actual variable.
677 If we started with a pointer to the struct, then we need to
678 dereference that pointer first, before the other steps.
679 Translating this into DWARF ops, we will need to append the following
680 to the current location description for the variable:
682 DW_OP_deref -- optional, if we start with a pointer
683 DW_OP_plus_uconst <forward_fld_offset>
685 DW_OP_plus_uconst <varName_fld_offset>
687 That is what this function does. */
689 /// addBlockByrefAddress - Start with the address based on the location
690 /// provided, and generate the DWARF information necessary to find the
691 /// actual Block variable (navigating the Block struct) based on the
692 /// starting location. Add the DWARF information to the die. For
693 /// more information, read large comment just above here.
695 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
697 const MachineLocation &Location) {
698 const DIVariable &VD = DV->getVariable();
699 DIType Ty = VD.getType();
701 unsigned Tag = Ty.getTag();
702 bool isPointer = false;
704 StringRef varName = VD.getName();
706 if (Tag == dwarf::DW_TAG_pointer_type) {
707 DIDerivedType DTy = DIDerivedType(Ty.getNode());
708 TmpTy = DTy.getTypeDerivedFrom();
712 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
714 // Find the __forwarding field and the variable field in the __Block_byref
716 DIArray Fields = blockStruct.getTypeArray();
717 DIDescriptor varField = DIDescriptor();
718 DIDescriptor forwardingField = DIDescriptor();
720 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
721 DIDescriptor Element = Fields.getElement(i);
722 DIDerivedType DT = DIDerivedType(Element.getNode());
723 StringRef fieldName = DT.getName();
724 if (fieldName == "__forwarding")
725 forwardingField = Element;
726 else if (fieldName == varName)
730 // Get the offsets for the forwarding field and the variable field.
731 unsigned forwardingFieldOffset =
732 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
733 unsigned varFieldOffset =
734 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
736 // Decode the original location, and use that as the start of the byref
737 // variable's location.
738 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
739 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
740 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
742 if (Location.isReg()) {
744 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
746 Reg = Reg - dwarf::DW_OP_reg0;
747 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
748 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
752 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
754 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
755 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
758 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
761 // If we started with a pointer to the __Block_byref... struct, then
762 // the first thing we need to do is dereference the pointer (DW_OP_deref).
764 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
766 // Next add the offset for the '__forwarding' field:
767 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
768 // adding the offset if it's 0.
769 if (forwardingFieldOffset > 0) {
770 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
771 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
774 // Now dereference the __forwarding field to get to the real __Block_byref
775 // struct: DW_OP_deref.
776 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
778 // Now that we've got the real __Block_byref... struct, add the offset
779 // for the variable's field to get to the location of the actual variable:
780 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
781 if (varFieldOffset > 0) {
782 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
783 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
786 // Now attach the location information to the DIE.
787 addBlock(Die, Attribute, 0, Block);
790 /// addAddress - Add an address attribute to a die based on the location
792 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
793 const MachineLocation &Location) {
794 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
795 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
796 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
798 if (Location.isReg()) {
800 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
802 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
803 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
807 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
809 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
810 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
813 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
816 addBlock(Die, Attribute, 0, Block);
819 /// addRegisterAddress - Add register location entry in variable DIE.
820 bool DwarfDebug::addRegisterAddress(DIE *Die, DbgVariable *DV,
821 const MachineOperand &MO) {
822 assert (MO.isReg() && "Invalid machine operand!");
825 MachineLocation Location;
826 Location.set(MO.getReg());
827 addAddress(Die, dwarf::DW_AT_location, Location);
828 if (MCSymbol *VS = DV->getDbgValueLabel())
829 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
833 /// addConstantValue - Add constant value entry in variable DIE.
834 bool DwarfDebug::addConstantValue(DIE *Die, DbgVariable *DV,
835 const MachineOperand &MO) {
836 assert (MO.isImm() && "Invalid machine operand!");
837 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
838 unsigned Imm = MO.getImm();
839 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
840 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
841 if (MCSymbol *VS = DV->getDbgValueLabel())
842 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
846 /// addConstantFPValue - Add constant value entry in variable DIE.
847 bool DwarfDebug::addConstantFPValue(DIE *Die, DbgVariable *DV,
848 const MachineOperand &MO) {
849 assert (MO.isFPImm() && "Invalid machine operand!");
850 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
851 APFloat FPImm = MO.getFPImm()->getValueAPF();
853 // Get the raw data form of the floating point.
854 const APInt FltVal = FPImm.bitcastToAPInt();
855 const char *FltPtr = (const char*)FltVal.getRawData();
857 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
858 bool LittleEndian = Asm->getTargetData().isLittleEndian();
859 int Incr = (LittleEndian ? 1 : -1);
860 int Start = (LittleEndian ? 0 : NumBytes - 1);
861 int Stop = (LittleEndian ? NumBytes : -1);
863 // Output the constant to DWARF one byte at a time.
864 for (; Start != Stop; Start += Incr)
865 addUInt(Block, 0, dwarf::DW_FORM_data1,
866 (unsigned char)0xFF & FltPtr[Start]);
868 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
870 if (MCSymbol *VS = DV->getDbgValueLabel())
871 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
877 /// addToContextOwner - Add Die into the list of its context owner's children.
878 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
879 if (Context.isType()) {
880 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
881 ContextDIE->addChild(Die);
882 } else if (Context.isNameSpace()) {
883 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
884 ContextDIE->addChild(Die);
885 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
886 ContextDIE->addChild(Die);
888 ModuleCU->addDie(Die);
891 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
893 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
894 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
899 TyDIE = new DIE(dwarf::DW_TAG_base_type);
900 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
901 if (Ty.isBasicType())
902 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
903 else if (Ty.isCompositeType())
904 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
906 assert(Ty.isDerivedType() && "Unknown kind of DIType");
907 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
910 addToContextOwner(TyDIE, Ty.getContext());
914 /// addType - Add a new type attribute to the specified entity.
915 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
919 // Check for pre-existence.
920 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
921 // If it exists then use the existing value.
923 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
928 DIE *Buffer = getOrCreateTypeDIE(Ty);
931 Entry = createDIEEntry(Buffer);
932 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
934 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
937 /// constructTypeDIE - Construct basic type die from DIBasicType.
938 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
939 // Get core information.
940 StringRef Name = BTy.getName();
941 Buffer.setTag(dwarf::DW_TAG_base_type);
942 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
945 // Add name if not anonymous or intermediate type.
947 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
948 uint64_t Size = BTy.getSizeInBits() >> 3;
949 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
952 /// constructTypeDIE - Construct derived type die from DIDerivedType.
953 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
954 // Get core information.
955 StringRef Name = DTy.getName();
956 uint64_t Size = DTy.getSizeInBits() >> 3;
957 unsigned Tag = DTy.getTag();
959 // FIXME - Workaround for templates.
960 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
964 // Map to main type, void will not have a type.
965 DIType FromTy = DTy.getTypeDerivedFrom();
966 addType(&Buffer, FromTy);
968 // Add name if not anonymous or intermediate type.
970 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
972 // Add size if non-zero (derived types might be zero-sized.)
974 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
976 // Add source line info if available and TyDesc is not a forward declaration.
977 if (!DTy.isForwardDecl())
978 addSourceLine(&Buffer, &DTy);
981 /// constructTypeDIE - Construct type DIE from DICompositeType.
982 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
983 // Get core information.
984 StringRef Name = CTy.getName();
986 uint64_t Size = CTy.getSizeInBits() >> 3;
987 unsigned Tag = CTy.getTag();
991 case dwarf::DW_TAG_vector_type:
992 case dwarf::DW_TAG_array_type:
993 constructArrayTypeDIE(Buffer, &CTy);
995 case dwarf::DW_TAG_enumeration_type: {
996 DIArray Elements = CTy.getTypeArray();
998 // Add enumerators to enumeration type.
999 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1000 DIE *ElemDie = NULL;
1001 DIDescriptor Enum(Elements.getElement(i).getNode());
1002 if (Enum.isEnumerator()) {
1003 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
1004 Buffer.addChild(ElemDie);
1009 case dwarf::DW_TAG_subroutine_type: {
1011 DIArray Elements = CTy.getTypeArray();
1012 DIDescriptor RTy = Elements.getElement(0);
1013 addType(&Buffer, DIType(RTy.getNode()));
1015 // Add prototype flag.
1016 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1019 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1020 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1021 DIDescriptor Ty = Elements.getElement(i);
1022 addType(Arg, DIType(Ty.getNode()));
1023 Buffer.addChild(Arg);
1027 case dwarf::DW_TAG_structure_type:
1028 case dwarf::DW_TAG_union_type:
1029 case dwarf::DW_TAG_class_type: {
1030 // Add elements to structure type.
1031 DIArray Elements = CTy.getTypeArray();
1033 // A forward struct declared type may not have elements available.
1034 unsigned N = Elements.getNumElements();
1038 // Add elements to structure type.
1039 for (unsigned i = 0; i < N; ++i) {
1040 DIDescriptor Element = Elements.getElement(i);
1041 DIE *ElemDie = NULL;
1042 if (Element.isSubprogram())
1043 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
1044 else if (Element.isVariable()) {
1045 DIVariable DV(Element.getNode());
1046 ElemDie = new DIE(dwarf::DW_TAG_variable);
1047 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1049 addType(ElemDie, DV.getType());
1050 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1051 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1052 addSourceLine(ElemDie, &DV);
1053 } else if (Element.isDerivedType())
1054 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
1057 Buffer.addChild(ElemDie);
1060 if (CTy.isAppleBlockExtension())
1061 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1063 unsigned RLang = CTy.getRunTimeLang();
1065 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1066 dwarf::DW_FORM_data1, RLang);
1068 DICompositeType ContainingType = CTy.getContainingType();
1069 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
1070 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1071 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
1078 // Add name if not anonymous or intermediate type.
1080 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1082 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1083 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1084 // Add size if non-zero (derived types might be zero-sized.)
1086 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1088 // Add zero size if it is not a forward declaration.
1089 if (CTy.isForwardDecl())
1090 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1092 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1095 // Add source line info if available.
1096 if (!CTy.isForwardDecl())
1097 addSourceLine(&Buffer, &CTy);
1101 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1102 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1103 int64_t L = SR.getLo();
1104 int64_t H = SR.getHi();
1105 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1107 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1109 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1110 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1112 Buffer.addChild(DW_Subrange);
1115 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1116 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1117 DICompositeType *CTy) {
1118 Buffer.setTag(dwarf::DW_TAG_array_type);
1119 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1120 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1122 // Emit derived type.
1123 addType(&Buffer, CTy->getTypeDerivedFrom());
1124 DIArray Elements = CTy->getTypeArray();
1126 // Get an anonymous type for index type.
1127 DIE *IdxTy = ModuleCU->getIndexTyDie();
1129 // Construct an anonymous type for index type.
1130 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1131 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1132 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1133 dwarf::DW_ATE_signed);
1134 ModuleCU->addDie(IdxTy);
1135 ModuleCU->setIndexTyDie(IdxTy);
1138 // Add subranges to array type.
1139 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1140 DIDescriptor Element = Elements.getElement(i);
1141 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1142 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1146 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1147 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1148 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1149 StringRef Name = ETy.getName();
1150 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1151 int64_t Value = ETy.getEnumValue();
1152 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1156 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1157 /// printer to not emit usual symbol prefix before the symbol name is used then
1158 /// return linkage name after skipping this special LLVM prefix.
1159 static StringRef getRealLinkageName(StringRef LinkageName) {
1161 if (LinkageName.startswith(StringRef(&One, 1)))
1162 return LinkageName.substr(1);
1166 /// createGlobalVariableDIE - Create new DIE using GV.
1167 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1168 // If the global variable was optmized out then no need to create debug info
1170 if (!GV.getGlobal()) return NULL;
1171 if (GV.getDisplayName().empty()) return NULL;
1173 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1174 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1175 GV.getDisplayName());
1177 StringRef LinkageName = GV.getLinkageName();
1178 if (!LinkageName.empty())
1179 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1180 getRealLinkageName(LinkageName));
1182 addType(GVDie, GV.getType());
1183 if (!GV.isLocalToUnit())
1184 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1185 addSourceLine(GVDie, &GV);
1190 /// createMemberDIE - Create new member DIE.
1191 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1192 DIE *MemberDie = new DIE(DT.getTag());
1193 StringRef Name = DT.getName();
1195 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1197 addType(MemberDie, DT.getTypeDerivedFrom());
1199 addSourceLine(MemberDie, &DT);
1201 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1202 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1204 uint64_t Size = DT.getSizeInBits();
1205 uint64_t FieldSize = DT.getOriginalTypeSize();
1207 if (Size != FieldSize) {
1209 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1210 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1212 uint64_t Offset = DT.getOffsetInBits();
1213 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1214 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1215 uint64_t FieldOffset = (HiMark - FieldSize);
1216 Offset -= FieldOffset;
1218 // Maybe we need to work from the other end.
1219 if (Asm->getTargetData().isLittleEndian())
1220 Offset = FieldSize - (Offset + Size);
1221 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1223 // Here WD_AT_data_member_location points to the anonymous
1224 // field that includes this bit field.
1225 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1228 // This is not a bitfield.
1229 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1231 if (DT.getTag() == dwarf::DW_TAG_inheritance
1232 && DT.isVirtual()) {
1234 // For C++, virtual base classes are not at fixed offset. Use following
1235 // expression to extract appropriate offset from vtable.
1236 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1238 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1239 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1240 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1241 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1242 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1243 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1244 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1245 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1247 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1250 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1252 if (DT.isProtected())
1253 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1254 dwarf::DW_ACCESS_protected);
1255 else if (DT.isPrivate())
1256 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1257 dwarf::DW_ACCESS_private);
1258 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1259 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1260 dwarf::DW_ACCESS_public);
1262 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1263 dwarf::DW_VIRTUALITY_virtual);
1267 /// createSubprogramDIE - Create new DIE using SP.
1268 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1269 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1273 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1274 // Constructors and operators for anonymous aggregates do not have names.
1275 if (!SP.getName().empty())
1276 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1278 StringRef LinkageName = SP.getLinkageName();
1279 if (!LinkageName.empty())
1280 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1281 getRealLinkageName(LinkageName));
1283 addSourceLine(SPDie, &SP);
1285 // Add prototyped tag, if C or ObjC.
1286 unsigned Lang = SP.getCompileUnit().getLanguage();
1287 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1288 Lang == dwarf::DW_LANG_ObjC)
1289 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1292 DICompositeType SPTy = SP.getType();
1293 DIArray Args = SPTy.getTypeArray();
1294 unsigned SPTag = SPTy.getTag();
1296 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1297 addType(SPDie, SPTy);
1299 addType(SPDie, DIType(Args.getElement(0).getNode()));
1301 unsigned VK = SP.getVirtuality();
1303 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1304 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1305 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1306 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1307 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1308 ContainingTypeMap.insert(std::make_pair(SPDie,
1309 SP.getContainingType().getNode()));
1312 if (MakeDecl || !SP.isDefinition()) {
1313 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1315 // Add arguments. Do not add arguments for subprogram definition. They will
1316 // be handled while processing variables.
1317 DICompositeType SPTy = SP.getType();
1318 DIArray Args = SPTy.getTypeArray();
1319 unsigned SPTag = SPTy.getTag();
1321 if (SPTag == dwarf::DW_TAG_subroutine_type)
1322 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1323 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1324 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1326 if (ATy.isArtificial())
1327 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1328 SPDie->addChild(Arg);
1332 if (SP.isArtificial())
1333 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1335 if (!SP.isLocalToUnit())
1336 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1338 if (SP.isOptimized())
1339 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1341 // DW_TAG_inlined_subroutine may refer to this DIE.
1342 ModuleCU->insertDIE(SP.getNode(), SPDie);
1347 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1348 assert(N && "Invalid Scope encoding!");
1350 DbgScope *AScope = AbstractScopes.lookup(N);
1354 DbgScope *Parent = NULL;
1356 DIDescriptor Scope(N);
1357 if (Scope.isLexicalBlock()) {
1358 DILexicalBlock DB(N);
1359 DIDescriptor ParentDesc = DB.getContext();
1360 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1363 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1366 Parent->addScope(AScope);
1367 AScope->setAbstractScope();
1368 AbstractScopes[N] = AScope;
1369 if (DIDescriptor(N).isSubprogram())
1370 AbstractScopesList.push_back(AScope);
1374 /// isSubprogramContext - Return true if Context is either a subprogram
1375 /// or another context nested inside a subprogram.
1376 static bool isSubprogramContext(MDNode *Context) {
1379 DIDescriptor D(Context);
1380 if (D.isSubprogram())
1383 return isSubprogramContext(DIType(Context).getContext().getNode());
1387 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1388 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1389 /// If there are global variables in this scope then create and insert
1390 /// DIEs for these variables.
1391 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1392 DIE *SPDie = ModuleCU->getDIE(SPNode);
1393 assert(SPDie && "Unable to find subprogram DIE!");
1394 DISubprogram SP(SPNode);
1396 // There is not any need to generate specification DIE for a function
1397 // defined at compile unit level. If a function is defined inside another
1398 // function then gdb prefers the definition at top level and but does not
1399 // expect specification DIE in parent function. So avoid creating
1400 // specification DIE for a function defined inside a function.
1401 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1402 !SP.getContext().isFile() &&
1403 !isSubprogramContext(SP.getContext().getNode())) {
1404 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1407 DICompositeType SPTy = SP.getType();
1408 DIArray Args = SPTy.getTypeArray();
1409 unsigned SPTag = SPTy.getTag();
1410 if (SPTag == dwarf::DW_TAG_subroutine_type)
1411 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1412 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1413 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1415 if (ATy.isArtificial())
1416 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1417 SPDie->addChild(Arg);
1419 DIE *SPDeclDie = SPDie;
1420 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1421 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1423 ModuleCU->addDie(SPDie);
1426 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1427 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1428 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1429 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1430 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1431 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1432 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1437 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1438 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1439 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1441 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1442 if (Scope->isAbstractScope())
1445 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1449 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1450 if (Ranges.size() > 1) {
1451 // .debug_range section has not been laid out yet. Emit offset in
1452 // .debug_range as a uint, size 4, for now. emitDIE will handle
1453 // DW_AT_ranges appropriately.
1454 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1455 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1456 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1457 RE = Ranges.end(); RI != RE; ++RI) {
1458 DebugRangeSymbols.push_back(LabelsBeforeInsn.lookup(RI->first));
1459 DebugRangeSymbols.push_back(LabelsAfterInsn.lookup(RI->second));
1461 DebugRangeSymbols.push_back(NULL);
1462 DebugRangeSymbols.push_back(NULL);
1466 MCSymbol *Start = LabelsBeforeInsn.lookup(RI->first);
1467 MCSymbol *End = LabelsAfterInsn.lookup(RI->second);
1469 if (Start == 0 || End == 0) return 0;
1471 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1472 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1474 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1475 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1480 /// constructInlinedScopeDIE - This scope represents inlined body of
1481 /// a function. Construct DIE to represent this concrete inlined copy
1482 /// of the function.
1483 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1485 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1486 assert (Ranges.empty() == false
1487 && "DbgScope does not have instruction markers!");
1489 // FIXME : .debug_inlined section specification does not clearly state how
1490 // to emit inlined scope that is split into multiple instruction ranges.
1491 // For now, use first instruction range and emit low_pc/high_pc pair and
1492 // corresponding .debug_inlined section entry for this pair.
1493 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1494 MCSymbol *StartLabel = LabelsBeforeInsn.lookup(RI->first);
1495 MCSymbol *EndLabel = LabelsAfterInsn.lookup(RI->second);
1497 if (StartLabel == 0 || EndLabel == 0) {
1498 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1501 assert(StartLabel->isDefined() &&
1502 "Invalid starting label for an inlined scope!");
1503 assert(EndLabel->isDefined() &&
1504 "Invalid end label for an inlined scope!");
1506 if (!Scope->getScopeNode())
1508 DIScope DS(Scope->getScopeNode());
1509 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1511 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1512 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1513 assert(OriginDIE && "Unable to find Origin DIE!");
1514 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1515 dwarf::DW_FORM_ref4, OriginDIE);
1517 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1518 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1520 InlinedSubprogramDIEs.insert(OriginDIE);
1522 // Track the start label for this inlined function.
1523 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1524 I = InlineInfo.find(InlinedSP.getNode());
1526 if (I == InlineInfo.end()) {
1527 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1529 InlinedSPNodes.push_back(InlinedSP.getNode());
1531 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1533 DILocation DL(Scope->getInlinedAt());
1534 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1535 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1541 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1542 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1543 // Get the descriptor.
1544 const DIVariable &VD = DV->getVariable();
1545 StringRef Name = VD.getName();
1549 // Translate tag to proper Dwarf tag. The result variable is dropped for
1552 switch (VD.getTag()) {
1553 case dwarf::DW_TAG_return_variable:
1555 case dwarf::DW_TAG_arg_variable:
1556 Tag = dwarf::DW_TAG_formal_parameter;
1558 case dwarf::DW_TAG_auto_variable: // fall thru
1560 Tag = dwarf::DW_TAG_variable;
1564 // Define variable debug information entry.
1565 DIE *VariableDie = new DIE(Tag);
1569 if (DbgVariable *AV = DV->getAbstractVariable())
1570 AbsDIE = AV->getDIE();
1573 DIScope DS(Scope->getScopeNode());
1574 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1575 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1577 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1578 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1579 assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1580 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1581 dwarf::DW_FORM_ref4, AbsDIE);
1584 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1585 addSourceLine(VariableDie, &VD);
1587 // Add variable type.
1588 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1589 // addresses instead.
1590 if (VD.isBlockByrefVariable())
1591 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1593 addType(VariableDie, VD.getType());
1596 // Add variable address.
1597 if (!Scope->isAbstractScope()) {
1598 // Check if variable is described by DBG_VALUE instruction.
1599 if (const MachineInstr *DVInsn = DV->getDbgValue()) {
1600 bool updated = false;
1601 // FIXME : Handle getNumOperands != 3
1602 if (DVInsn->getNumOperands() == 3) {
1603 if (DVInsn->getOperand(0).isReg())
1604 updated = addRegisterAddress(VariableDie, DV, DVInsn->getOperand(0));
1605 else if (DVInsn->getOperand(0).isImm())
1606 updated = addConstantValue(VariableDie, DV, DVInsn->getOperand(0));
1607 else if (DVInsn->getOperand(0).isFPImm())
1608 updated = addConstantFPValue(VariableDie, DV, DVInsn->getOperand(0));
1610 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1611 if (Location.getReg()) {
1612 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1613 if (MCSymbol *VS = DV->getDbgValueLabel())
1614 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1620 // If variableDie is not updated then DBG_VALUE instruction does not
1621 // have valid variable info.
1627 MachineLocation Location;
1629 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1630 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1632 Location.set(FrameReg, Offset);
1634 if (VD.hasComplexAddress())
1635 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1636 else if (VD.isBlockByrefVariable())
1637 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1639 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1643 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1644 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1645 DV->setDIE(VariableDie);
1650 void DwarfDebug::addPubTypes(DISubprogram SP) {
1651 DICompositeType SPTy = SP.getType();
1652 unsigned SPTag = SPTy.getTag();
1653 if (SPTag != dwarf::DW_TAG_subroutine_type)
1656 DIArray Args = SPTy.getTypeArray();
1657 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1658 DIType ATy(Args.getElement(i).getNode());
1661 DICompositeType CATy = getDICompositeType(ATy);
1662 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()
1663 && !CATy.isForwardDecl()) {
1664 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1665 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1670 /// constructScopeDIE - Construct a DIE for this scope.
1671 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1672 if (!Scope || !Scope->getScopeNode())
1675 DIScope DS(Scope->getScopeNode());
1676 DIE *ScopeDIE = NULL;
1677 if (Scope->getInlinedAt())
1678 ScopeDIE = constructInlinedScopeDIE(Scope);
1679 else if (DS.isSubprogram()) {
1680 if (Scope->isAbstractScope())
1681 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1683 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1686 ScopeDIE = constructLexicalScopeDIE(Scope);
1687 if (!ScopeDIE) return NULL;
1689 // Add variables to scope.
1690 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1691 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1692 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1694 ScopeDIE->addChild(VariableDIE);
1697 // Add nested scopes.
1698 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1699 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1700 // Define the Scope debug information entry.
1701 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1703 ScopeDIE->addChild(NestedDIE);
1706 if (DS.isSubprogram())
1707 addPubTypes(DISubprogram(DS.getNode()));
1712 /// GetOrCreateSourceID - Look up the source id with the given directory and
1713 /// source file names. If none currently exists, create a new id and insert it
1714 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1716 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1718 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1719 if (DI != DirectoryIdMap.end()) {
1720 DId = DI->getValue();
1722 DId = DirectoryNames.size() + 1;
1723 DirectoryIdMap[DirName] = DId;
1724 DirectoryNames.push_back(DirName);
1728 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1729 if (FI != SourceFileIdMap.end()) {
1730 FId = FI->getValue();
1732 FId = SourceFileNames.size() + 1;
1733 SourceFileIdMap[FileName] = FId;
1734 SourceFileNames.push_back(FileName);
1737 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1738 SourceIdMap.find(std::make_pair(DId, FId));
1739 if (SI != SourceIdMap.end())
1742 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1743 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1744 SourceIds.push_back(std::make_pair(DId, FId));
1749 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1750 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1751 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1754 NDie = new DIE(dwarf::DW_TAG_namespace);
1755 ModuleCU->insertDIE(NS.getNode(), NDie);
1756 if (!NS.getName().empty())
1757 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1758 addSourceLine(NDie, &NS);
1759 addToContextOwner(NDie, NS.getContext());
1763 void DwarfDebug::constructCompileUnit(MDNode *N) {
1764 DICompileUnit DIUnit(N);
1765 // Use first compile unit marked as isMain as the compile unit for this
1767 if (ModuleCU || !DIUnit.isMain())
1769 StringRef FN = DIUnit.getFilename();
1770 StringRef Dir = DIUnit.getDirectory();
1771 unsigned ID = GetOrCreateSourceID(Dir, FN);
1773 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1774 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1775 DIUnit.getProducer());
1776 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1777 DIUnit.getLanguage());
1778 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1779 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1780 // simplifies debug range entries.
1781 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_data4, 0);
1782 // DW_AT_stmt_list is a offset of line number information for this
1783 // compile unit in debug_line section. It is always zero when only one
1784 // compile unit is emitted in one object file.
1785 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1788 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1789 if (DIUnit.isOptimized())
1790 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1792 StringRef Flags = DIUnit.getFlags();
1794 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1796 unsigned RVer = DIUnit.getRunTimeVersion();
1798 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1799 dwarf::DW_FORM_data1, RVer);
1802 "ModuleCU assigned since the top of constructCompileUnit");
1803 ModuleCU = new CompileUnit(ID, Die);
1806 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1807 DIGlobalVariable DI_GV(N);
1809 // If debug information is malformed then ignore it.
1810 if (DI_GV.Verify() == false)
1813 // Check for pre-existence.
1814 if (ModuleCU->getDIE(DI_GV.getNode()))
1817 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1822 ModuleCU->insertDIE(N, VariableDie);
1824 // Add to context owner.
1825 DIDescriptor GVContext = DI_GV.getContext();
1826 // Do not create specification DIE if context is either compile unit
1828 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1829 !GVContext.isFile() &&
1830 !isSubprogramContext(GVContext.getNode())) {
1831 // Create specification DIE.
1832 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1833 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1834 dwarf::DW_FORM_ref4, VariableDie);
1835 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1836 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1837 addLabel(Block, 0, dwarf::DW_FORM_udata,
1838 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1839 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1840 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1841 ModuleCU->addDie(VariableSpecDIE);
1843 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1844 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1845 addLabel(Block, 0, dwarf::DW_FORM_udata,
1846 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1847 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1849 addToContextOwner(VariableDie, GVContext);
1851 // Expose as global. FIXME - need to check external flag.
1852 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1854 DIType GTy = DI_GV.getType();
1855 if (GTy.isCompositeType() && !GTy.getName().empty()
1856 && !GTy.isForwardDecl()) {
1857 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1858 assert(Entry && "Missing global type!");
1859 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1864 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1867 // Check for pre-existence.
1868 if (ModuleCU->getDIE(N))
1871 if (!SP.isDefinition())
1872 // This is a method declaration which will be handled while constructing
1876 DIE *SubprogramDie = createSubprogramDIE(SP);
1879 ModuleCU->insertDIE(N, SubprogramDie);
1881 // Add to context owner.
1882 addToContextOwner(SubprogramDie, SP.getContext());
1884 // Expose as global.
1885 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1890 /// beginModule - Emit all Dwarf sections that should come prior to the
1891 /// content. Create global DIEs and emit initial debug info sections.
1892 /// This is inovked by the target AsmPrinter.
1893 void DwarfDebug::beginModule(Module *M) {
1894 if (DisableDebugInfoPrinting)
1897 DebugInfoFinder DbgFinder;
1898 DbgFinder.processModule(*M);
1900 bool HasDebugInfo = false;
1902 // Scan all the compile-units to see if there are any marked as the main unit.
1903 // if not, we do not generate debug info.
1904 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1905 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1906 if (DICompileUnit(*I).isMain()) {
1907 HasDebugInfo = true;
1912 if (!HasDebugInfo) return;
1914 // Tell MMI that we have debug info.
1915 MMI->setDebugInfoAvailability(true);
1917 // Emit initial sections.
1918 EmitSectionLabels();
1920 // Create all the compile unit DIEs.
1921 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1922 E = DbgFinder.compile_unit_end(); I != E; ++I)
1923 constructCompileUnit(*I);
1925 // Create DIEs for each subprogram.
1926 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1927 E = DbgFinder.subprogram_end(); I != E; ++I)
1928 constructSubprogramDIE(*I);
1930 // Create DIEs for each global variable.
1931 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1932 E = DbgFinder.global_variable_end(); I != E; ++I)
1933 constructGlobalVariableDIE(*I);
1935 // Prime section data.
1936 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1938 // Print out .file directives to specify files for .loc directives. These are
1939 // printed out early so that they precede any .loc directives.
1940 if (Asm->MAI->hasDotLocAndDotFile()) {
1941 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1942 // Remember source id starts at 1.
1943 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1944 // FIXME: don't use sys::path for this! This should not depend on the
1946 sys::Path FullPath(getSourceDirectoryName(Id.first));
1948 FullPath.appendComponent(getSourceFileName(Id.second));
1949 assert(AppendOk && "Could not append filename to directory!");
1951 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1956 /// endModule - Emit all Dwarf sections that should come after the content.
1958 void DwarfDebug::endModule() {
1959 if (!ModuleCU) return;
1961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1962 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1963 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1965 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1968 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1969 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1970 DIE *SPDie = CI->first;
1971 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1973 DIE *NDie = ModuleCU->getDIE(N);
1974 if (!NDie) continue;
1975 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1978 // Standard sections final addresses.
1979 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1980 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1981 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1982 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1984 // End text sections.
1985 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1986 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1987 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1990 // Emit common frame information.
1991 emitCommonDebugFrame();
1993 // Emit function debug frame information
1994 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1995 E = DebugFrames.end(); I != E; ++I)
1996 emitFunctionDebugFrame(*I);
1998 // Compute DIE offsets and sizes.
1999 computeSizeAndOffsets();
2001 // Emit all the DIEs into a debug info section
2004 // Corresponding abbreviations into a abbrev section.
2005 emitAbbreviations();
2007 // Emit source line correspondence into a debug line section.
2010 // Emit info into a debug pubnames section.
2011 emitDebugPubNames();
2013 // Emit info into a debug pubtypes section.
2014 emitDebugPubTypes();
2016 // Emit info into a debug loc section.
2019 // Emit info into a debug aranges section.
2022 // Emit info into a debug ranges section.
2025 // Emit info into a debug macinfo section.
2028 // Emit inline info.
2029 emitDebugInlineInfo();
2031 // Emit info into a debug str section.
2035 ModuleCU = NULL; // Reset for the next Module, if any.
2038 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2039 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2041 DebugLoc ScopeLoc) {
2043 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2045 return AbsDbgVariable;
2047 LLVMContext &Ctx = Var.getNode()->getContext();
2048 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2052 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2053 NULL /* No more-abstract variable*/);
2054 Scope->addVariable(AbsDbgVariable);
2055 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2056 return AbsDbgVariable;
2059 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2060 /// FIXME : Refactor findAbstractVariable.
2061 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2062 const MachineInstr *MI,
2063 DebugLoc ScopeLoc) {
2065 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2067 return AbsDbgVariable;
2069 LLVMContext &Ctx = Var.getNode()->getContext();
2070 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2074 AbsDbgVariable = new DbgVariable(Var, MI,
2075 NULL /* No more-abstract variable*/);
2076 Scope->addVariable(AbsDbgVariable);
2077 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2078 DbgValueStartMap[MI] = AbsDbgVariable;
2079 return AbsDbgVariable;
2082 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2083 void DwarfDebug::collectVariableInfo() {
2084 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2086 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2087 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2088 VE = VMap.end(); VI != VE; ++VI) {
2089 MDNode *Var = VI->first;
2092 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2094 DbgScope *Scope = 0;
2095 if (MDNode *IA = VP.second.getInlinedAt(Ctx))
2096 Scope = ConcreteScopes.lookup(IA);
2098 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2100 // If variable scope is not found then skip this variable.
2104 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2105 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2106 Scope->addVariable(RegVar);
2109 // Collect variable information from DBG_VALUE machine instructions;
2110 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2112 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2114 const MachineInstr *MInsn = II;
2115 if (!MInsn->isDebugValue())
2118 // Ignore Undef values.
2119 if (MInsn->getOperand(0).isReg() && !MInsn->getOperand(0).getReg())
2123 const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2125 if (DV.getTag() == dwarf::DW_TAG_arg_variable) {
2126 // FIXME Handle inlined subroutine arguments.
2127 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2128 CurrentFnDbgScope->addVariable(ArgVar);
2129 DbgValueStartMap[MInsn] = ArgVar;
2133 DebugLoc DL = MInsn->getDebugLoc();
2134 if (DL.isUnknown()) continue;
2135 DbgScope *Scope = 0;
2136 if (MDNode *IA = DL.getInlinedAt(Ctx))
2137 Scope = ConcreteScopes.lookup(IA);
2139 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2141 // If variable scope is not found then skip this variable.
2145 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2146 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2147 DbgValueStartMap[MInsn] = RegVar;
2148 Scope->addVariable(RegVar);
2153 /// beginScope - Process beginning of a scope.
2154 void DwarfDebug::beginScope(const MachineInstr *MI) {
2156 DebugLoc DL = MI->getDebugLoc();
2157 if (DL.isUnknown()) {
2158 if (UnknownLocations) {
2159 // This instruction has no debug location. If the preceding instruction
2160 // did, emit debug location information to indicate that the debug
2161 // location is now unknown.
2162 MCSymbol *Label = NULL;
2163 if (DL == PrevInstLoc)
2166 Label = recordSourceLine(DL.getLine(), DL.getCol(), 0);
2171 // If this instruction begins a scope then note down corresponding label.
2172 if (InsnsBeginScopeSet.count(MI) != 0)
2173 LabelsBeforeInsn[MI] = Label;
2179 MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2181 // FIXME: Should only verify each scope once!
2182 if (!DIScope(Scope).Verify())
2185 // DBG_VALUE instruction establishes new value.
2186 if (MI->isDebugValue()) {
2187 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2188 = DbgValueStartMap.find(MI);
2189 if (DI != DbgValueStartMap.end()) {
2190 MCSymbol *Label = NULL;
2191 if (DL == PrevInstLoc)
2194 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2198 DI->second->setDbgValueLabel(Label);
2203 // Emit a label to indicate location change. This is used for line
2204 // table even if this instruction does not start a new scope.
2205 MCSymbol *Label = NULL;
2206 if (DL == PrevInstLoc)
2209 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2214 // If this instruction begins a scope then note down corresponding label.
2215 if (InsnsBeginScopeSet.count(MI) != 0)
2216 LabelsBeforeInsn[MI] = Label;
2219 /// endScope - Process end of a scope.
2220 void DwarfDebug::endScope(const MachineInstr *MI) {
2221 if (InsnsEndScopeSet.count(MI) != 0) {
2222 // Emit a label if this instruction ends a scope.
2223 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2224 Asm->OutStreamer.EmitLabel(Label);
2225 LabelsAfterInsn[MI] = Label;
2229 /// getOrCreateDbgScope - Create DbgScope for the scope.
2230 DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2232 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2235 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2236 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2237 if (DIDescriptor(Scope).isLexicalBlock()) {
2239 getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2240 WScope->setParent(Parent);
2241 Parent->addScope(WScope);
2244 if (!WScope->getParent()) {
2245 StringRef SPName = DISubprogram(Scope).getLinkageName();
2246 if (SPName == Asm->MF->getFunction()->getName())
2247 CurrentFnDbgScope = WScope;
2253 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2257 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2258 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2259 DILocation DL(InlinedAt);
2261 getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2262 WScope->setParent(Parent);
2263 Parent->addScope(WScope);
2265 ConcreteScopes[InlinedAt] = WScope;
2266 getOrCreateAbstractScope(Scope);
2271 /// hasValidLocation - Return true if debug location entry attached with
2272 /// machine instruction encodes valid location info.
2273 static bool hasValidLocation(LLVMContext &Ctx,
2274 const MachineInstr *MInsn,
2275 MDNode *&Scope, MDNode *&InlinedAt) {
2276 if (MInsn->isDebugValue())
2278 DebugLoc DL = MInsn->getDebugLoc();
2279 if (DL.isUnknown()) return false;
2281 MDNode *S = DL.getScope(Ctx);
2283 // There is no need to create another DIE for compile unit. For all
2284 // other scopes, create one DbgScope now. This will be translated
2285 // into a scope DIE at the end.
2286 if (DIScope(S).isCompileUnit()) return false;
2289 InlinedAt = DL.getInlinedAt(Ctx);
2293 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2295 static void calculateDominanceGraph(DbgScope *Scope) {
2296 assert (Scope && "Unable to calculate scop edominance graph!");
2297 SmallVector<DbgScope *, 4> WorkStack;
2298 WorkStack.push_back(Scope);
2299 unsigned Counter = 0;
2300 while (!WorkStack.empty()) {
2301 DbgScope *WS = WorkStack.back();
2302 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2303 bool visitedChildren = false;
2304 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2305 SE = Children.end(); SI != SE; ++SI) {
2306 DbgScope *ChildScope = *SI;
2307 if (!ChildScope->getDFSOut()) {
2308 WorkStack.push_back(ChildScope);
2309 visitedChildren = true;
2310 ChildScope->setDFSIn(++Counter);
2314 if (!visitedChildren) {
2315 WorkStack.pop_back();
2316 WS->setDFSOut(++Counter);
2321 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2323 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2324 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2327 unsigned PrevDFSIn = 0;
2328 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2330 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2332 const MachineInstr *MInsn = II;
2333 MDNode *Scope = NULL;
2334 MDNode *InlinedAt = NULL;
2336 // Check if instruction has valid location information.
2337 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2341 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2342 MI2ScopeMap.find(MInsn);
2343 if (DI != MI2ScopeMap.end()) {
2344 DbgScope *S = DI->second;
2345 dbgs() << S->getDFSIn();
2346 PrevDFSIn = S->getDFSIn();
2348 dbgs() << PrevDFSIn;
2350 dbgs() << " [ x" << PrevDFSIn;
2358 /// extractScopeInformation - Scan machine instructions in this function
2359 /// and collect DbgScopes. Return true, if at least one scope was found.
2360 bool DwarfDebug::extractScopeInformation() {
2361 // If scope information was extracted using .dbg intrinsics then there is not
2362 // any need to extract these information by scanning each instruction.
2363 if (!DbgScopeMap.empty())
2366 // Scan each instruction and create scopes. First build working set of scopes.
2367 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2368 SmallVector<DbgRange, 4> MIRanges;
2369 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2370 MDNode *PrevScope = NULL;
2371 MDNode *PrevInlinedAt = NULL;
2372 const MachineInstr *RangeBeginMI = NULL;
2373 const MachineInstr *PrevMI = NULL;
2374 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2376 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2378 const MachineInstr *MInsn = II;
2379 MDNode *Scope = NULL;
2380 MDNode *InlinedAt = NULL;
2382 // Check if instruction has valid location information.
2383 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2388 // If scope has not changed then skip this instruction.
2389 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2395 // If we have alread seen a beginning of a instruction range and
2396 // current instruction scope does not match scope of first instruction
2397 // in this range then create a new instruction range.
2398 DbgRange R(RangeBeginMI, PrevMI);
2399 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2400 MIRanges.push_back(R);
2403 // This is a beginning of a new instruction range.
2404 RangeBeginMI = MInsn;
2406 // Reset previous markers.
2409 PrevInlinedAt = InlinedAt;
2413 // Create last instruction range.
2414 if (RangeBeginMI && PrevMI && PrevScope) {
2415 DbgRange R(RangeBeginMI, PrevMI);
2416 MIRanges.push_back(R);
2417 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2420 if (!CurrentFnDbgScope)
2423 calculateDominanceGraph(CurrentFnDbgScope);
2425 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2427 // Find ranges of instructions covered by each DbgScope;
2428 DbgScope *PrevDbgScope = NULL;
2429 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2430 RE = MIRanges.end(); RI != RE; ++RI) {
2431 const DbgRange &R = *RI;
2432 DbgScope *S = MI2ScopeMap.lookup(R.first);
2433 assert (S && "Lost DbgScope for a machine instruction!");
2434 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2435 PrevDbgScope->closeInsnRange(S);
2436 S->openInsnRange(R.first);
2437 S->extendInsnRange(R.second);
2442 PrevDbgScope->closeInsnRange();
2444 identifyScopeMarkers();
2446 return !DbgScopeMap.empty();
2449 /// identifyScopeMarkers() -
2450 /// Each DbgScope has first instruction and last instruction to mark beginning
2451 /// and end of a scope respectively. Create an inverse map that list scopes
2452 /// starts (and ends) with an instruction. One instruction may start (or end)
2453 /// multiple scopes. Ignore scopes that are not reachable.
2454 void DwarfDebug::identifyScopeMarkers() {
2455 SmallVector<DbgScope *, 4> WorkList;
2456 WorkList.push_back(CurrentFnDbgScope);
2457 while (!WorkList.empty()) {
2458 DbgScope *S = WorkList.pop_back_val();
2460 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2461 if (!Children.empty())
2462 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2463 SE = Children.end(); SI != SE; ++SI)
2464 WorkList.push_back(*SI);
2466 if (S->isAbstractScope())
2469 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2472 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2473 RE = Ranges.end(); RI != RE; ++RI) {
2474 assert(RI->first && "DbgRange does not have first instruction!");
2475 assert(RI->second && "DbgRange does not have second instruction!");
2476 InsnsBeginScopeSet.insert(RI->first);
2477 InsnsEndScopeSet.insert(RI->second);
2482 /// FindFirstDebugLoc - Find the first debug location in the function. This
2483 /// is intended to be an approximation for the source position of the
2484 /// beginning of the function.
2485 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2486 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2488 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2489 MBBI != MBBE; ++MBBI) {
2490 DebugLoc DL = MBBI->getDebugLoc();
2491 if (!DL.isUnknown())
2497 /// beginFunction - Gather pre-function debug information. Assumes being
2498 /// emitted immediately after the function entry point.
2499 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2500 if (!MMI->hasDebugInfo()) return;
2501 if (!extractScopeInformation()) return;
2503 collectVariableInfo();
2505 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2506 Asm->getFunctionNumber());
2507 // Assumes in correct section after the entry point.
2508 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2510 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2512 DebugLoc FDL = FindFirstDebugLoc(MF);
2513 if (FDL.isUnknown()) return;
2515 MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2517 DISubprogram SP = getDISubprogram(Scope);
2520 Line = SP.getLineNumber();
2523 Line = FDL.getLine();
2527 recordSourceLine(Line, Col, Scope);
2530 /// endFunction - Gather and emit post-function debug information.
2532 void DwarfDebug::endFunction(const MachineFunction *MF) {
2533 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2535 if (CurrentFnDbgScope) {
2536 // Define end label for subprogram.
2537 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2538 Asm->getFunctionNumber()));
2540 // Get function line info.
2541 if (!Lines.empty()) {
2542 // Get section line info.
2543 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2544 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2545 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2546 // Append the function info to section info.
2547 SectionLineInfos.insert(SectionLineInfos.end(),
2548 Lines.begin(), Lines.end());
2551 // Construct abstract scopes.
2552 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2553 AE = AbstractScopesList.end(); AI != AE; ++AI)
2554 constructScopeDIE(*AI);
2556 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2558 if (!DisableFramePointerElim(*MF))
2559 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2560 dwarf::DW_FORM_flag, 1);
2563 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2564 MMI->getFrameMoves()));
2568 CurrentFnDbgScope = NULL;
2569 DeleteContainerSeconds(DbgScopeMap);
2570 InsnsBeginScopeSet.clear();
2571 InsnsEndScopeSet.clear();
2572 DbgValueStartMap.clear();
2573 ConcreteScopes.clear();
2574 DeleteContainerSeconds(AbstractScopes);
2575 AbstractScopesList.clear();
2576 AbstractVariables.clear();
2577 LabelsBeforeInsn.clear();
2578 LabelsAfterInsn.clear();
2583 /// recordSourceLine - Register a source line with debug info. Returns the
2584 /// unique label that was emitted and which provides correspondence to
2585 /// the source line list.
2586 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2592 DIDescriptor Scope(S);
2594 if (Scope.isCompileUnit()) {
2595 DICompileUnit CU(S);
2596 Dir = CU.getDirectory();
2597 Fn = CU.getFilename();
2598 } else if (Scope.isSubprogram()) {
2600 Dir = SP.getDirectory();
2601 Fn = SP.getFilename();
2602 } else if (Scope.isLexicalBlock()) {
2603 DILexicalBlock DB(S);
2604 Dir = DB.getDirectory();
2605 Fn = DB.getFilename();
2607 assert(0 && "Unexpected scope info");
2609 Src = GetOrCreateSourceID(Dir, Fn);
2612 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2613 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2615 Asm->OutStreamer.EmitLabel(Label);
2619 //===----------------------------------------------------------------------===//
2621 //===----------------------------------------------------------------------===//
2623 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2626 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2627 // Get the children.
2628 const std::vector<DIE *> &Children = Die->getChildren();
2630 // If not last sibling and has children then add sibling offset attribute.
2631 if (!Last && !Children.empty())
2632 Die->addSiblingOffset(DIEValueAllocator);
2634 // Record the abbreviation.
2635 assignAbbrevNumber(Die->getAbbrev());
2637 // Get the abbreviation for this DIE.
2638 unsigned AbbrevNumber = Die->getAbbrevNumber();
2639 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2642 Die->setOffset(Offset);
2644 // Start the size with the size of abbreviation code.
2645 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2647 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2648 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2650 // Size the DIE attribute values.
2651 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2652 // Size attribute value.
2653 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2655 // Size the DIE children if any.
2656 if (!Children.empty()) {
2657 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2658 "Children flag not set");
2660 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2661 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2663 // End of children marker.
2664 Offset += sizeof(int8_t);
2667 Die->setSize(Offset - Die->getOffset());
2671 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2673 void DwarfDebug::computeSizeAndOffsets() {
2674 // Compute size of compile unit header.
2675 static unsigned Offset =
2676 sizeof(int32_t) + // Length of Compilation Unit Info
2677 sizeof(int16_t) + // DWARF version number
2678 sizeof(int32_t) + // Offset Into Abbrev. Section
2679 sizeof(int8_t); // Pointer Size (in bytes)
2681 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2684 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2685 /// temporary label to it if SymbolStem is specified.
2686 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2687 const char *SymbolStem = 0) {
2688 Asm->OutStreamer.SwitchSection(Section);
2689 if (!SymbolStem) return 0;
2691 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2692 Asm->OutStreamer.EmitLabel(TmpSym);
2696 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2697 /// the start of each one.
2698 void DwarfDebug::EmitSectionLabels() {
2699 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2701 // Dwarf sections base addresses.
2702 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2703 DwarfFrameSectionSym =
2704 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2707 DwarfInfoSectionSym =
2708 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2709 DwarfAbbrevSectionSym =
2710 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2711 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2713 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2714 EmitSectionSym(Asm, MacroInfo);
2716 EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2717 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2718 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2719 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2720 DwarfStrSectionSym =
2721 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2722 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2725 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2726 EmitSectionSym(Asm, TLOF.getDataSection());
2729 /// emitDIE - Recusively Emits a debug information entry.
2731 void DwarfDebug::emitDIE(DIE *Die) {
2732 // Get the abbreviation for this DIE.
2733 unsigned AbbrevNumber = Die->getAbbrevNumber();
2734 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2736 // Emit the code (index) for the abbreviation.
2737 if (Asm->isVerbose())
2738 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2739 Twine::utohexstr(Die->getOffset()) + ":0x" +
2740 Twine::utohexstr(Die->getSize()) + " " +
2741 dwarf::TagString(Abbrev->getTag()));
2742 Asm->EmitULEB128(AbbrevNumber);
2744 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2745 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2747 // Emit the DIE attribute values.
2748 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2749 unsigned Attr = AbbrevData[i].getAttribute();
2750 unsigned Form = AbbrevData[i].getForm();
2751 assert(Form && "Too many attributes for DIE (check abbreviation)");
2753 if (Asm->isVerbose())
2754 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2757 case dwarf::DW_AT_sibling:
2758 Asm->EmitInt32(Die->getSiblingOffset());
2760 case dwarf::DW_AT_abstract_origin: {
2761 DIEEntry *E = cast<DIEEntry>(Values[i]);
2762 DIE *Origin = E->getEntry();
2763 unsigned Addr = Origin->getOffset();
2764 Asm->EmitInt32(Addr);
2767 case dwarf::DW_AT_ranges: {
2768 // DW_AT_range Value encodes offset in debug_range section.
2769 DIEInteger *V = cast<DIEInteger>(Values[i]);
2770 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2772 DwarfDebugRangeSectionSym,
2777 // Emit an attribute using the defined form.
2778 Values[i]->EmitValue(Asm, Form);
2783 // Emit the DIE children if any.
2784 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2785 const std::vector<DIE *> &Children = Die->getChildren();
2787 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2788 emitDIE(Children[j]);
2790 if (Asm->isVerbose())
2791 Asm->OutStreamer.AddComment("End Of Children Mark");
2796 /// emitDebugInfo - Emit the debug info section.
2798 void DwarfDebug::emitDebugInfo() {
2799 // Start debug info section.
2800 Asm->OutStreamer.SwitchSection(
2801 Asm->getObjFileLowering().getDwarfInfoSection());
2802 DIE *Die = ModuleCU->getCUDie();
2804 // Emit the compile units header.
2805 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2806 ModuleCU->getID()));
2808 // Emit size of content not including length itself
2809 unsigned ContentSize = Die->getSize() +
2810 sizeof(int16_t) + // DWARF version number
2811 sizeof(int32_t) + // Offset Into Abbrev. Section
2812 sizeof(int8_t) + // Pointer Size (in bytes)
2813 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2815 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2816 Asm->EmitInt32(ContentSize);
2817 Asm->OutStreamer.AddComment("DWARF version number");
2818 Asm->EmitInt16(dwarf::DWARF_VERSION);
2819 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2820 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2821 DwarfAbbrevSectionSym);
2822 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2823 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2826 // FIXME - extra padding for gdb bug.
2827 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2832 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2835 /// emitAbbreviations - Emit the abbreviation section.
2837 void DwarfDebug::emitAbbreviations() const {
2838 // Check to see if it is worth the effort.
2839 if (!Abbreviations.empty()) {
2840 // Start the debug abbrev section.
2841 Asm->OutStreamer.SwitchSection(
2842 Asm->getObjFileLowering().getDwarfAbbrevSection());
2844 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2846 // For each abbrevation.
2847 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2848 // Get abbreviation data
2849 const DIEAbbrev *Abbrev = Abbreviations[i];
2851 // Emit the abbrevations code (base 1 index.)
2852 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2854 // Emit the abbreviations data.
2858 // Mark end of abbreviations.
2859 Asm->EmitULEB128(0, "EOM(3)");
2861 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2865 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2866 /// the line matrix.
2868 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2869 // Define last address of section.
2870 Asm->OutStreamer.AddComment("Extended Op");
2873 Asm->OutStreamer.AddComment("Op size");
2874 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2875 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2876 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2878 Asm->OutStreamer.AddComment("Section end label");
2880 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2881 Asm->getTargetData().getPointerSize(),
2884 // Mark end of matrix.
2885 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2891 /// emitDebugLines - Emit source line information.
2893 void DwarfDebug::emitDebugLines() {
2894 // If the target is using .loc/.file, the assembler will be emitting the
2895 // .debug_line table automatically.
2896 if (Asm->MAI->hasDotLocAndDotFile())
2899 // Minimum line delta, thus ranging from -10..(255-10).
2900 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2901 // Maximum line delta, thus ranging from -10..(255-10).
2902 const int MaxLineDelta = 255 + MinLineDelta;
2904 // Start the dwarf line section.
2905 Asm->OutStreamer.SwitchSection(
2906 Asm->getObjFileLowering().getDwarfLineSection());
2908 // Construct the section header.
2909 Asm->OutStreamer.AddComment("Length of Source Line Info");
2910 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2911 Asm->GetTempSymbol("line_begin"), 4);
2912 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2914 Asm->OutStreamer.AddComment("DWARF version number");
2915 Asm->EmitInt16(dwarf::DWARF_VERSION);
2917 Asm->OutStreamer.AddComment("Prolog Length");
2918 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2919 Asm->GetTempSymbol("line_prolog_begin"), 4);
2920 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2922 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2924 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2926 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2927 Asm->EmitInt8(MinLineDelta);
2928 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2929 Asm->EmitInt8(MaxLineDelta);
2930 Asm->OutStreamer.AddComment("Special Opcode Base");
2931 Asm->EmitInt8(-MinLineDelta);
2933 // Line number standard opcode encodings argument count
2934 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2936 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2938 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2940 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2942 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2944 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2946 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2948 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2950 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2953 // Emit directories.
2954 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2955 const std::string &Dir = getSourceDirectoryName(DI);
2956 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2957 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2960 Asm->OutStreamer.AddComment("End of directories");
2964 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2965 // Remember source id starts at 1.
2966 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2967 const std::string &FN = getSourceFileName(Id.second);
2968 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2969 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2971 Asm->EmitULEB128(Id.first, "Directory #");
2972 Asm->EmitULEB128(0, "Mod date");
2973 Asm->EmitULEB128(0, "File size");
2976 Asm->OutStreamer.AddComment("End of files");
2979 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2981 // A sequence for each text section.
2982 unsigned SecSrcLinesSize = SectionSourceLines.size();
2984 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2985 // Isolate current sections line info.
2986 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2988 // Dwarf assumes we start with first line of first source file.
2989 unsigned Source = 1;
2992 // Construct rows of the address, source, line, column matrix.
2993 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2994 const SrcLineInfo &LineInfo = LineInfos[i];
2995 MCSymbol *Label = LineInfo.getLabel();
2996 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2998 if (Asm->isVerbose()) {
2999 std::pair<unsigned, unsigned> SrcID =
3000 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3001 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3003 Twine(getSourceFileName(SrcID.second)) +
3004 ":" + Twine(LineInfo.getLine()));
3007 // Define the line address.
3008 Asm->OutStreamer.AddComment("Extended Op");
3010 Asm->OutStreamer.AddComment("Op size");
3011 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3013 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3014 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3016 Asm->OutStreamer.AddComment("Location label");
3017 Asm->OutStreamer.EmitSymbolValue(Label,
3018 Asm->getTargetData().getPointerSize(),
3021 // If change of source, then switch to the new source.
3022 if (Source != LineInfo.getSourceID()) {
3023 Source = LineInfo.getSourceID();
3024 Asm->OutStreamer.AddComment("DW_LNS_set_file");
3025 Asm->EmitInt8(dwarf::DW_LNS_set_file);
3026 Asm->EmitULEB128(Source, "New Source");
3029 // If change of line.
3030 if (Line != LineInfo.getLine()) {
3031 // Determine offset.
3032 int Offset = LineInfo.getLine() - Line;
3033 int Delta = Offset - MinLineDelta;
3036 Line = LineInfo.getLine();
3038 // If delta is small enough and in range...
3039 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3040 // ... then use fast opcode.
3041 Asm->OutStreamer.AddComment("Line Delta");
3042 Asm->EmitInt8(Delta - MinLineDelta);
3044 // ... otherwise use long hand.
3045 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3046 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3047 Asm->EmitSLEB128(Offset, "Line Offset");
3048 Asm->OutStreamer.AddComment("DW_LNS_copy");
3049 Asm->EmitInt8(dwarf::DW_LNS_copy);
3052 // Copy the previous row (different address or source)
3053 Asm->OutStreamer.AddComment("DW_LNS_copy");
3054 Asm->EmitInt8(dwarf::DW_LNS_copy);
3058 emitEndOfLineMatrix(j + 1);
3061 if (SecSrcLinesSize == 0)
3062 // Because we're emitting a debug_line section, we still need a line
3063 // table. The linker and friends expect it to exist. If there's nothing to
3064 // put into it, emit an empty table.
3065 emitEndOfLineMatrix(1);
3067 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3070 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3072 void DwarfDebug::emitCommonDebugFrame() {
3073 if (!Asm->MAI->doesDwarfRequireFrameSection())
3076 int stackGrowth = Asm->getTargetData().getPointerSize();
3077 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3078 TargetFrameInfo::StackGrowsDown)
3081 // Start the dwarf frame section.
3082 Asm->OutStreamer.SwitchSection(
3083 Asm->getObjFileLowering().getDwarfFrameSection());
3085 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3086 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3087 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3088 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3090 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3091 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3092 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3093 Asm->OutStreamer.AddComment("CIE Version");
3094 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3095 Asm->OutStreamer.AddComment("CIE Augmentation");
3096 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3097 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3098 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3099 Asm->OutStreamer.AddComment("CIE RA Column");
3100 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3101 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3103 std::vector<MachineMove> Moves;
3104 RI->getInitialFrameState(Moves);
3106 Asm->EmitFrameMoves(Moves, 0, false);
3108 Asm->EmitAlignment(2);
3109 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3112 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3115 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3116 if (!Asm->MAI->doesDwarfRequireFrameSection())
3119 // Start the dwarf frame section.
3120 Asm->OutStreamer.SwitchSection(
3121 Asm->getObjFileLowering().getDwarfFrameSection());
3123 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3124 MCSymbol *DebugFrameBegin =
3125 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3126 MCSymbol *DebugFrameEnd =
3127 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3128 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3130 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3132 Asm->OutStreamer.AddComment("FDE CIE offset");
3133 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3134 DwarfFrameSectionSym);
3136 Asm->OutStreamer.AddComment("FDE initial location");
3137 MCSymbol *FuncBeginSym =
3138 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3139 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3140 Asm->getTargetData().getPointerSize(),
3144 Asm->OutStreamer.AddComment("FDE address range");
3145 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3146 FuncBeginSym, Asm->getTargetData().getPointerSize());
3148 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3150 Asm->EmitAlignment(2);
3151 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3154 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3156 void DwarfDebug::emitDebugPubNames() {
3157 // Start the dwarf pubnames section.
3158 Asm->OutStreamer.SwitchSection(
3159 Asm->getObjFileLowering().getDwarfPubNamesSection());
3161 Asm->OutStreamer.AddComment("Length of Public Names Info");
3162 Asm->EmitLabelDifference(
3163 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3164 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3166 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3167 ModuleCU->getID()));
3169 Asm->OutStreamer.AddComment("DWARF Version");
3170 Asm->EmitInt16(dwarf::DWARF_VERSION);
3172 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3173 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3174 DwarfInfoSectionSym);
3176 Asm->OutStreamer.AddComment("Compilation Unit Length");
3177 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3178 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3181 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3182 for (StringMap<DIE*>::const_iterator
3183 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3184 const char *Name = GI->getKeyData();
3185 DIE *Entity = GI->second;
3187 Asm->OutStreamer.AddComment("DIE offset");
3188 Asm->EmitInt32(Entity->getOffset());
3190 if (Asm->isVerbose())
3191 Asm->OutStreamer.AddComment("External Name");
3192 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3195 Asm->OutStreamer.AddComment("End Mark");
3197 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3198 ModuleCU->getID()));
3201 void DwarfDebug::emitDebugPubTypes() {
3202 // Start the dwarf pubnames section.
3203 Asm->OutStreamer.SwitchSection(
3204 Asm->getObjFileLowering().getDwarfPubTypesSection());
3205 Asm->OutStreamer.AddComment("Length of Public Types Info");
3206 Asm->EmitLabelDifference(
3207 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3208 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3210 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3211 ModuleCU->getID()));
3213 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3214 Asm->EmitInt16(dwarf::DWARF_VERSION);
3216 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3217 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3218 DwarfInfoSectionSym);
3220 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3221 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3222 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3225 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3226 for (StringMap<DIE*>::const_iterator
3227 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3228 const char *Name = GI->getKeyData();
3229 DIE * Entity = GI->second;
3231 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3232 Asm->EmitInt32(Entity->getOffset());
3234 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3235 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3238 Asm->OutStreamer.AddComment("End Mark");
3240 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3241 ModuleCU->getID()));
3244 /// emitDebugStr - Emit visible names into a debug str section.
3246 void DwarfDebug::emitDebugStr() {
3247 // Check to see if it is worth the effort.
3248 if (StringPool.empty()) return;
3250 // Start the dwarf str section.
3251 Asm->OutStreamer.SwitchSection(
3252 Asm->getObjFileLowering().getDwarfStrSection());
3254 // Get all of the string pool entries and put them in an array by their ID so
3255 // we can sort them.
3256 SmallVector<std::pair<unsigned,
3257 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3259 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3260 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3261 Entries.push_back(std::make_pair(I->second.second, &*I));
3263 array_pod_sort(Entries.begin(), Entries.end());
3265 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3266 // Emit a label for reference from debug information entries.
3267 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3269 // Emit the string itself.
3270 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3274 /// emitDebugLoc - Emit visible names into a debug loc section.
3276 void DwarfDebug::emitDebugLoc() {
3277 // Start the dwarf loc section.
3278 Asm->OutStreamer.SwitchSection(
3279 Asm->getObjFileLowering().getDwarfLocSection());
3282 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3284 void DwarfDebug::EmitDebugARanges() {
3285 // Start the dwarf aranges section.
3286 Asm->OutStreamer.SwitchSection(
3287 Asm->getObjFileLowering().getDwarfARangesSection());
3290 /// emitDebugRanges - Emit visible names into a debug ranges section.
3292 void DwarfDebug::emitDebugRanges() {
3293 // Start the dwarf ranges section.
3294 Asm->OutStreamer.SwitchSection(
3295 Asm->getObjFileLowering().getDwarfRangesSection());
3296 unsigned char Size = Asm->getTargetData().getPointerSize();
3297 for (SmallVector<const MCSymbol *, 8>::iterator
3298 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3301 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3303 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3307 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3309 void DwarfDebug::emitDebugMacInfo() {
3310 if (const MCSection *LineInfo =
3311 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3312 // Start the dwarf macinfo section.
3313 Asm->OutStreamer.SwitchSection(LineInfo);
3317 /// emitDebugInlineInfo - Emit inline info using following format.
3319 /// 1. length of section
3320 /// 2. Dwarf version number
3321 /// 3. address size.
3323 /// Entries (one "entry" for each function that was inlined):
3325 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3326 /// otherwise offset into __debug_str for regular function name.
3327 /// 2. offset into __debug_str section for regular function name.
3328 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3329 /// instances for the function.
3331 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3332 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3333 /// __debug_info section, and the low_pc is the starting address for the
3334 /// inlining instance.
3335 void DwarfDebug::emitDebugInlineInfo() {
3336 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3342 Asm->OutStreamer.SwitchSection(
3343 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3345 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3346 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3347 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3349 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3351 Asm->OutStreamer.AddComment("Dwarf Version");
3352 Asm->EmitInt16(dwarf::DWARF_VERSION);
3353 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3354 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3356 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3357 E = InlinedSPNodes.end(); I != E; ++I) {
3360 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3361 = InlineInfo.find(Node);
3362 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3363 DISubprogram SP(Node);
3364 StringRef LName = SP.getLinkageName();
3365 StringRef Name = SP.getName();
3367 Asm->OutStreamer.AddComment("MIPS linkage name");
3368 if (LName.empty()) {
3369 Asm->OutStreamer.EmitBytes(Name, 0);
3370 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3372 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3373 DwarfStrSectionSym);
3375 Asm->OutStreamer.AddComment("Function name");
3376 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3377 Asm->EmitULEB128(Labels.size(), "Inline count");
3379 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3380 LE = Labels.end(); LI != LE; ++LI) {
3381 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3382 Asm->EmitInt32(LI->second->getOffset());
3384 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3385 Asm->OutStreamer.EmitSymbolValue(LI->first,
3386 Asm->getTargetData().getPointerSize(),0);
3390 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));