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<const 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<const 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(const MDNode *N) { return GVToDieMap.lookup(N); }
128 /// insertDIE - Insert DIE into the map.
129 void insertDIE(const 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(const MDNode *N) {
136 DenseMap<const MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
137 if (I == GVToDIEEntryMap.end())
142 /// insertDIEEntry - Insert debug information entry into the map.
143 void insertDIEEntry(const 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<const 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, const 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 const MDNode *getInlinedAt() const { return InlinedAtLocation; }
235 const MDNode *getScopeNode() const { return Desc; }
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 const MDNode *N = Desc;
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) {
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 DIGlobalVariable *G) {
466 // Verify global variable.
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 // Verify subprogram.
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) {
505 unsigned Line = Ty->getLineNumber();
506 if (!Ty->getContext().Verify())
508 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
509 Ty->getContext().getFilename());
510 assert(FileID && "Invalid file id");
511 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
512 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
515 /// addSourceLine - Add location information to specified debug information
517 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
522 unsigned Line = NS->getLineNumber();
523 StringRef FN = NS->getFilename();
524 StringRef Dir = NS->getDirectory();
526 unsigned FileID = GetOrCreateSourceID(Dir, FN);
527 assert(FileID && "Invalid file id");
528 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
529 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
532 /* Byref variables, in Blocks, are declared by the programmer as
533 "SomeType VarName;", but the compiler creates a
534 __Block_byref_x_VarName struct, and gives the variable VarName
535 either the struct, or a pointer to the struct, as its type. This
536 is necessary for various behind-the-scenes things the compiler
537 needs to do with by-reference variables in blocks.
539 However, as far as the original *programmer* is concerned, the
540 variable should still have type 'SomeType', as originally declared.
542 The following function dives into the __Block_byref_x_VarName
543 struct to find the original type of the variable. This will be
544 passed back to the code generating the type for the Debug
545 Information Entry for the variable 'VarName'. 'VarName' will then
546 have the original type 'SomeType' in its debug information.
548 The original type 'SomeType' will be the type of the field named
549 'VarName' inside the __Block_byref_x_VarName struct.
551 NOTE: In order for this to not completely fail on the debugger
552 side, the Debug Information Entry for the variable VarName needs to
553 have a DW_AT_location that tells the debugger how to unwind through
554 the pointers and __Block_byref_x_VarName struct to find the actual
555 value of the variable. The function addBlockByrefType does this. */
557 /// Find the type the programmer originally declared the variable to be
558 /// and return that type.
560 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
563 unsigned tag = Ty.getTag();
565 if (tag == dwarf::DW_TAG_pointer_type) {
566 DIDerivedType DTy = DIDerivedType(Ty);
567 subType = DTy.getTypeDerivedFrom();
570 DICompositeType blockStruct = DICompositeType(subType);
571 DIArray Elements = blockStruct.getTypeArray();
573 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
574 DIDescriptor Element = Elements.getElement(i);
575 DIDerivedType DT = DIDerivedType(Element);
576 if (Name == DT.getName())
577 return (DT.getTypeDerivedFrom());
583 /// addComplexAddress - Start with the address based on the location provided,
584 /// and generate the DWARF information necessary to find the actual variable
585 /// given the extra address information encoded in the DIVariable, starting from
586 /// the starting location. Add the DWARF information to the die.
588 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
590 const MachineLocation &Location) {
591 const DIVariable &VD = DV->getVariable();
592 DIType Ty = VD.getType();
594 // Decode the original location, and use that as the start of the byref
595 // variable's location.
596 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
597 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
598 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
600 if (Location.isReg()) {
602 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
604 Reg = Reg - dwarf::DW_OP_reg0;
605 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
606 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
610 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
612 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
613 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
616 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
619 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
620 uint64_t Element = VD.getAddrElement(i);
622 if (Element == DIFactory::OpPlus) {
623 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
624 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
625 } else if (Element == DIFactory::OpDeref) {
626 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
627 } else llvm_unreachable("unknown DIFactory Opcode");
630 // Now attach the location information to the DIE.
631 addBlock(Die, Attribute, 0, Block);
634 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
635 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
636 gives the variable VarName either the struct, or a pointer to the struct, as
637 its type. This is necessary for various behind-the-scenes things the
638 compiler needs to do with by-reference variables in Blocks.
640 However, as far as the original *programmer* is concerned, the variable
641 should still have type 'SomeType', as originally declared.
643 The function getBlockByrefType dives into the __Block_byref_x_VarName
644 struct to find the original type of the variable, which is then assigned to
645 the variable's Debug Information Entry as its real type. So far, so good.
646 However now the debugger will expect the variable VarName to have the type
647 SomeType. So we need the location attribute for the variable to be an
648 expression that explains to the debugger how to navigate through the
649 pointers and struct to find the actual variable of type SomeType.
651 The following function does just that. We start by getting
652 the "normal" location for the variable. This will be the location
653 of either the struct __Block_byref_x_VarName or the pointer to the
654 struct __Block_byref_x_VarName.
656 The struct will look something like:
658 struct __Block_byref_x_VarName {
660 struct __Block_byref_x_VarName *forwarding;
661 ... <various other fields>
663 ... <maybe more fields>
666 If we are given the struct directly (as our starting point) we
667 need to tell the debugger to:
669 1). Add the offset of the forwarding field.
671 2). Follow that pointer to get the real __Block_byref_x_VarName
672 struct to use (the real one may have been copied onto the heap).
674 3). Add the offset for the field VarName, to find the actual variable.
676 If we started with a pointer to the struct, then we need to
677 dereference that pointer first, before the other steps.
678 Translating this into DWARF ops, we will need to append the following
679 to the current location description for the variable:
681 DW_OP_deref -- optional, if we start with a pointer
682 DW_OP_plus_uconst <forward_fld_offset>
684 DW_OP_plus_uconst <varName_fld_offset>
686 That is what this function does. */
688 /// addBlockByrefAddress - Start with the address based on the location
689 /// provided, and generate the DWARF information necessary to find the
690 /// actual Block variable (navigating the Block struct) based on the
691 /// starting location. Add the DWARF information to the die. For
692 /// more information, read large comment just above here.
694 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
696 const MachineLocation &Location) {
697 const DIVariable &VD = DV->getVariable();
698 DIType Ty = VD.getType();
700 unsigned Tag = Ty.getTag();
701 bool isPointer = false;
703 StringRef varName = VD.getName();
705 if (Tag == dwarf::DW_TAG_pointer_type) {
706 DIDerivedType DTy = DIDerivedType(Ty);
707 TmpTy = DTy.getTypeDerivedFrom();
711 DICompositeType blockStruct = DICompositeType(TmpTy);
713 // Find the __forwarding field and the variable field in the __Block_byref
715 DIArray Fields = blockStruct.getTypeArray();
716 DIDescriptor varField = DIDescriptor();
717 DIDescriptor forwardingField = DIDescriptor();
719 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
720 DIDescriptor Element = Fields.getElement(i);
721 DIDerivedType DT = DIDerivedType(Element);
722 StringRef fieldName = DT.getName();
723 if (fieldName == "__forwarding")
724 forwardingField = Element;
725 else if (fieldName == varName)
729 // Get the offsets for the forwarding field and the variable field.
730 unsigned forwardingFieldOffset =
731 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
732 unsigned varFieldOffset =
733 DIDerivedType(varField).getOffsetInBits() >> 3;
735 // Decode the original location, and use that as the start of the byref
736 // variable's location.
737 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
738 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
739 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
741 if (Location.isReg()) {
743 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
745 Reg = Reg - dwarf::DW_OP_reg0;
746 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
747 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
751 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
753 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
754 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
757 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
760 // If we started with a pointer to the __Block_byref... struct, then
761 // the first thing we need to do is dereference the pointer (DW_OP_deref).
763 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
765 // Next add the offset for the '__forwarding' field:
766 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
767 // adding the offset if it's 0.
768 if (forwardingFieldOffset > 0) {
769 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
770 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
773 // Now dereference the __forwarding field to get to the real __Block_byref
774 // struct: DW_OP_deref.
775 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
777 // Now that we've got the real __Block_byref... struct, add the offset
778 // for the variable's field to get to the location of the actual variable:
779 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
780 if (varFieldOffset > 0) {
781 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
782 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
785 // Now attach the location information to the DIE.
786 addBlock(Die, Attribute, 0, Block);
789 /// addAddress - Add an address attribute to a die based on the location
791 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
792 const MachineLocation &Location) {
793 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
794 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
795 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
797 if (Location.isReg()) {
799 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
801 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
802 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
806 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
808 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
809 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
812 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
815 addBlock(Die, Attribute, 0, Block);
818 /// addRegisterAddress - Add register location entry in variable DIE.
819 bool DwarfDebug::addRegisterAddress(DIE *Die, DbgVariable *DV,
820 const MachineOperand &MO) {
821 assert (MO.isReg() && "Invalid machine operand!");
824 MachineLocation Location;
825 Location.set(MO.getReg());
826 addAddress(Die, dwarf::DW_AT_location, Location);
827 if (MCSymbol *VS = DV->getDbgValueLabel())
828 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
832 /// addConstantValue - Add constant value entry in variable DIE.
833 bool DwarfDebug::addConstantValue(DIE *Die, DbgVariable *DV,
834 const MachineOperand &MO) {
835 assert (MO.isImm() && "Invalid machine operand!");
836 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
837 unsigned Imm = MO.getImm();
838 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
839 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
840 if (MCSymbol *VS = DV->getDbgValueLabel())
841 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
845 /// addConstantFPValue - Add constant value entry in variable DIE.
846 bool DwarfDebug::addConstantFPValue(DIE *Die, DbgVariable *DV,
847 const MachineOperand &MO) {
848 assert (MO.isFPImm() && "Invalid machine operand!");
849 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
850 APFloat FPImm = MO.getFPImm()->getValueAPF();
852 // Get the raw data form of the floating point.
853 const APInt FltVal = FPImm.bitcastToAPInt();
854 const char *FltPtr = (const char*)FltVal.getRawData();
856 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
857 bool LittleEndian = Asm->getTargetData().isLittleEndian();
858 int Incr = (LittleEndian ? 1 : -1);
859 int Start = (LittleEndian ? 0 : NumBytes - 1);
860 int Stop = (LittleEndian ? NumBytes : -1);
862 // Output the constant to DWARF one byte at a time.
863 for (; Start != Stop; Start += Incr)
864 addUInt(Block, 0, dwarf::DW_FORM_data1,
865 (unsigned char)0xFF & FltPtr[Start]);
867 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
869 if (MCSymbol *VS = DV->getDbgValueLabel())
870 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
876 /// addToContextOwner - Add Die into the list of its context owner's children.
877 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
878 if (Context.isType()) {
879 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
880 ContextDIE->addChild(Die);
881 } else if (Context.isNameSpace()) {
882 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
883 ContextDIE->addChild(Die);
884 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context))
885 ContextDIE->addChild(Die);
887 ModuleCU->addDie(Die);
890 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
892 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
893 DIE *TyDIE = ModuleCU->getDIE(Ty);
898 TyDIE = new DIE(dwarf::DW_TAG_base_type);
899 ModuleCU->insertDIE(Ty, TyDIE);
900 if (Ty.isBasicType())
901 constructTypeDIE(*TyDIE, DIBasicType(Ty));
902 else if (Ty.isCompositeType())
903 constructTypeDIE(*TyDIE, DICompositeType(Ty));
905 assert(Ty.isDerivedType() && "Unknown kind of DIType");
906 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
909 addToContextOwner(TyDIE, Ty.getContext());
913 /// addType - Add a new type attribute to the specified entity.
914 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
918 // Check for pre-existence.
919 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty);
920 // If it exists then use the existing value.
922 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
927 DIE *Buffer = getOrCreateTypeDIE(Ty);
930 Entry = createDIEEntry(Buffer);
931 ModuleCU->insertDIEEntry(Ty, Entry);
933 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
936 /// constructTypeDIE - Construct basic type die from DIBasicType.
937 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
938 // Get core information.
939 StringRef Name = BTy.getName();
940 Buffer.setTag(dwarf::DW_TAG_base_type);
941 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
944 // Add name if not anonymous or intermediate type.
946 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
947 uint64_t Size = BTy.getSizeInBits() >> 3;
948 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
951 /// constructTypeDIE - Construct derived type die from DIDerivedType.
952 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
953 // Get core information.
954 StringRef Name = DTy.getName();
955 uint64_t Size = DTy.getSizeInBits() >> 3;
956 unsigned Tag = DTy.getTag();
958 // FIXME - Workaround for templates.
959 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
963 // Map to main type, void will not have a type.
964 DIType FromTy = DTy.getTypeDerivedFrom();
965 addType(&Buffer, FromTy);
967 // Add name if not anonymous or intermediate type.
969 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
971 // Add size if non-zero (derived types might be zero-sized.)
973 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
975 // Add source line info if available and TyDesc is not a forward declaration.
976 if (!DTy.isForwardDecl())
977 addSourceLine(&Buffer, &DTy);
980 /// constructTypeDIE - Construct type DIE from DICompositeType.
981 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
982 // Get core information.
983 StringRef Name = CTy.getName();
985 uint64_t Size = CTy.getSizeInBits() >> 3;
986 unsigned Tag = CTy.getTag();
990 case dwarf::DW_TAG_vector_type:
991 case dwarf::DW_TAG_array_type:
992 constructArrayTypeDIE(Buffer, &CTy);
994 case dwarf::DW_TAG_enumeration_type: {
995 DIArray Elements = CTy.getTypeArray();
997 // Add enumerators to enumeration type.
998 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1000 DIDescriptor Enum(Elements.getElement(i));
1001 if (Enum.isEnumerator()) {
1002 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1003 Buffer.addChild(ElemDie);
1008 case dwarf::DW_TAG_subroutine_type: {
1010 DIArray Elements = CTy.getTypeArray();
1011 DIDescriptor RTy = Elements.getElement(0);
1012 addType(&Buffer, DIType(RTy));
1014 // Add prototype flag.
1015 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1018 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1019 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1020 DIDescriptor Ty = Elements.getElement(i);
1021 addType(Arg, DIType(Ty));
1022 Buffer.addChild(Arg);
1026 case dwarf::DW_TAG_structure_type:
1027 case dwarf::DW_TAG_union_type:
1028 case dwarf::DW_TAG_class_type: {
1029 // Add elements to structure type.
1030 DIArray Elements = CTy.getTypeArray();
1032 // A forward struct declared type may not have elements available.
1033 unsigned N = Elements.getNumElements();
1037 // Add elements to structure type.
1038 for (unsigned i = 0; i < N; ++i) {
1039 DIDescriptor Element = Elements.getElement(i);
1040 DIE *ElemDie = NULL;
1041 if (Element.isSubprogram())
1042 ElemDie = createSubprogramDIE(DISubprogram(Element));
1043 else if (Element.isVariable()) {
1044 DIVariable DV(Element);
1045 ElemDie = new DIE(dwarf::DW_TAG_variable);
1046 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1048 addType(ElemDie, DV.getType());
1049 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1050 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1051 addSourceLine(ElemDie, &DV);
1052 } else if (Element.isDerivedType())
1053 ElemDie = createMemberDIE(DIDerivedType(Element));
1056 Buffer.addChild(ElemDie);
1059 if (CTy.isAppleBlockExtension())
1060 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1062 unsigned RLang = CTy.getRunTimeLang();
1064 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1065 dwarf::DW_FORM_data1, RLang);
1067 DICompositeType ContainingType = CTy.getContainingType();
1068 if (DIDescriptor(ContainingType).isCompositeType())
1069 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1070 getOrCreateTypeDIE(DIType(ContainingType)));
1077 // Add name if not anonymous or intermediate type.
1079 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1081 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1082 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1083 // Add size if non-zero (derived types might be zero-sized.)
1085 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1087 // Add zero size if it is not a forward declaration.
1088 if (CTy.isForwardDecl())
1089 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1091 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1094 // Add source line info if available.
1095 if (!CTy.isForwardDecl())
1096 addSourceLine(&Buffer, &CTy);
1100 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1101 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1102 int64_t L = SR.getLo();
1103 int64_t H = SR.getHi();
1104 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1106 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1108 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1109 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1111 Buffer.addChild(DW_Subrange);
1114 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1115 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1116 DICompositeType *CTy) {
1117 Buffer.setTag(dwarf::DW_TAG_array_type);
1118 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1119 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1121 // Emit derived type.
1122 addType(&Buffer, CTy->getTypeDerivedFrom());
1123 DIArray Elements = CTy->getTypeArray();
1125 // Get an anonymous type for index type.
1126 DIE *IdxTy = ModuleCU->getIndexTyDie();
1128 // Construct an anonymous type for index type.
1129 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1130 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1131 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1132 dwarf::DW_ATE_signed);
1133 ModuleCU->addDie(IdxTy);
1134 ModuleCU->setIndexTyDie(IdxTy);
1137 // Add subranges to array type.
1138 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1139 DIDescriptor Element = Elements.getElement(i);
1140 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1141 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1145 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1146 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1147 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1148 StringRef Name = ETy.getName();
1149 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1150 int64_t Value = ETy.getEnumValue();
1151 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1155 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1156 /// printer to not emit usual symbol prefix before the symbol name is used then
1157 /// return linkage name after skipping this special LLVM prefix.
1158 static StringRef getRealLinkageName(StringRef LinkageName) {
1160 if (LinkageName.startswith(StringRef(&One, 1)))
1161 return LinkageName.substr(1);
1165 /// createGlobalVariableDIE - Create new DIE using GV.
1166 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1167 // If the global variable was optmized out then no need to create debug info
1169 if (!GV.getGlobal()) return NULL;
1170 if (GV.getDisplayName().empty()) return NULL;
1172 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1173 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1174 GV.getDisplayName());
1176 StringRef LinkageName = GV.getLinkageName();
1177 if (!LinkageName.empty())
1178 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1179 getRealLinkageName(LinkageName));
1181 addType(GVDie, GV.getType());
1182 if (!GV.isLocalToUnit())
1183 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1184 addSourceLine(GVDie, &GV);
1189 /// createMemberDIE - Create new member DIE.
1190 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1191 DIE *MemberDie = new DIE(DT.getTag());
1192 StringRef Name = DT.getName();
1194 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1196 addType(MemberDie, DT.getTypeDerivedFrom());
1198 addSourceLine(MemberDie, &DT);
1200 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1201 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1203 uint64_t Size = DT.getSizeInBits();
1204 uint64_t FieldSize = DT.getOriginalTypeSize();
1206 if (Size != FieldSize) {
1208 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1209 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1211 uint64_t Offset = DT.getOffsetInBits();
1212 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1213 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1214 uint64_t FieldOffset = (HiMark - FieldSize);
1215 Offset -= FieldOffset;
1217 // Maybe we need to work from the other end.
1218 if (Asm->getTargetData().isLittleEndian())
1219 Offset = FieldSize - (Offset + Size);
1220 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1222 // Here WD_AT_data_member_location points to the anonymous
1223 // field that includes this bit field.
1224 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1227 // This is not a bitfield.
1228 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1230 if (DT.getTag() == dwarf::DW_TAG_inheritance
1231 && DT.isVirtual()) {
1233 // For C++, virtual base classes are not at fixed offset. Use following
1234 // expression to extract appropriate offset from vtable.
1235 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1237 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1238 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1239 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1240 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1241 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1242 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1243 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1244 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1246 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1249 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1251 if (DT.isProtected())
1252 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1253 dwarf::DW_ACCESS_protected);
1254 else if (DT.isPrivate())
1255 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1256 dwarf::DW_ACCESS_private);
1257 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1258 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1259 dwarf::DW_ACCESS_public);
1261 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1262 dwarf::DW_VIRTUALITY_virtual);
1266 /// createSubprogramDIE - Create new DIE using SP.
1267 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1268 DIE *SPDie = ModuleCU->getDIE(SP);
1272 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1273 // Constructors and operators for anonymous aggregates do not have names.
1274 if (!SP.getName().empty())
1275 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1277 StringRef LinkageName = SP.getLinkageName();
1278 if (!LinkageName.empty())
1279 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1280 getRealLinkageName(LinkageName));
1282 addSourceLine(SPDie, &SP);
1284 // Add prototyped tag, if C or ObjC.
1285 unsigned Lang = SP.getCompileUnit().getLanguage();
1286 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1287 Lang == dwarf::DW_LANG_ObjC)
1288 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1291 DICompositeType SPTy = SP.getType();
1292 DIArray Args = SPTy.getTypeArray();
1293 unsigned SPTag = SPTy.getTag();
1295 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1296 addType(SPDie, SPTy);
1298 addType(SPDie, DIType(Args.getElement(0)));
1300 unsigned VK = SP.getVirtuality();
1302 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1303 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1304 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1305 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1306 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1307 ContainingTypeMap.insert(std::make_pair(SPDie,
1308 SP.getContainingType()));
1311 if (MakeDecl || !SP.isDefinition()) {
1312 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1314 // Add arguments. Do not add arguments for subprogram definition. They will
1315 // be handled while processing variables.
1316 DICompositeType SPTy = SP.getType();
1317 DIArray Args = SPTy.getTypeArray();
1318 unsigned SPTag = SPTy.getTag();
1320 if (SPTag == dwarf::DW_TAG_subroutine_type)
1321 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1322 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1323 DIType ATy = DIType(DIType(Args.getElement(i)));
1325 if (ATy.isArtificial())
1326 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1327 SPDie->addChild(Arg);
1331 if (SP.isArtificial())
1332 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1334 if (!SP.isLocalToUnit())
1335 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1337 if (SP.isOptimized())
1338 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1340 // DW_TAG_inlined_subroutine may refer to this DIE.
1341 ModuleCU->insertDIE(SP, SPDie);
1346 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1347 assert(N && "Invalid Scope encoding!");
1349 DbgScope *AScope = AbstractScopes.lookup(N);
1353 DbgScope *Parent = NULL;
1355 DIDescriptor Scope(N);
1356 if (Scope.isLexicalBlock()) {
1357 DILexicalBlock DB(N);
1358 DIDescriptor ParentDesc = DB.getContext();
1359 Parent = getOrCreateAbstractScope(ParentDesc);
1362 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1365 Parent->addScope(AScope);
1366 AScope->setAbstractScope();
1367 AbstractScopes[N] = AScope;
1368 if (DIDescriptor(N).isSubprogram())
1369 AbstractScopesList.push_back(AScope);
1373 /// isSubprogramContext - Return true if Context is either a subprogram
1374 /// or another context nested inside a subprogram.
1375 static bool isSubprogramContext(const MDNode *Context) {
1378 DIDescriptor D(Context);
1379 if (D.isSubprogram())
1382 return isSubprogramContext(DIType(Context).getContext());
1386 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1387 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1388 /// If there are global variables in this scope then create and insert
1389 /// DIEs for these variables.
1390 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1391 DIE *SPDie = ModuleCU->getDIE(SPNode);
1392 assert(SPDie && "Unable to find subprogram DIE!");
1393 DISubprogram SP(SPNode);
1395 // There is not any need to generate specification DIE for a function
1396 // defined at compile unit level. If a function is defined inside another
1397 // function then gdb prefers the definition at top level and but does not
1398 // expect specification DIE in parent function. So avoid creating
1399 // specification DIE for a function defined inside a function.
1400 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1401 !SP.getContext().isFile() &&
1402 !isSubprogramContext(SP.getContext())) {
1403 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1406 DICompositeType SPTy = SP.getType();
1407 DIArray Args = SPTy.getTypeArray();
1408 unsigned SPTag = SPTy.getTag();
1409 if (SPTag == dwarf::DW_TAG_subroutine_type)
1410 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1411 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1412 DIType ATy = DIType(DIType(Args.getElement(i)));
1414 if (ATy.isArtificial())
1415 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1416 SPDie->addChild(Arg);
1418 DIE *SPDeclDie = SPDie;
1419 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1420 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1422 ModuleCU->addDie(SPDie);
1425 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1426 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1427 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1428 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1429 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1430 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1431 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1436 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1437 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1438 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1440 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1441 if (Scope->isAbstractScope())
1444 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1448 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1449 if (Ranges.size() > 1) {
1450 // .debug_range section has not been laid out yet. Emit offset in
1451 // .debug_range as a uint, size 4, for now. emitDIE will handle
1452 // DW_AT_ranges appropriately.
1453 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1454 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1455 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1456 RE = Ranges.end(); RI != RE; ++RI) {
1457 DebugRangeSymbols.push_back(LabelsBeforeInsn.lookup(RI->first));
1458 DebugRangeSymbols.push_back(LabelsAfterInsn.lookup(RI->second));
1460 DebugRangeSymbols.push_back(NULL);
1461 DebugRangeSymbols.push_back(NULL);
1465 MCSymbol *Start = LabelsBeforeInsn.lookup(RI->first);
1466 MCSymbol *End = LabelsAfterInsn.lookup(RI->second);
1468 if (Start == 0 || End == 0) return 0;
1470 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1471 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1473 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1474 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1479 /// constructInlinedScopeDIE - This scope represents inlined body of
1480 /// a function. Construct DIE to represent this concrete inlined copy
1481 /// of the function.
1482 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1484 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1485 assert (Ranges.empty() == false
1486 && "DbgScope does not have instruction markers!");
1488 // FIXME : .debug_inlined section specification does not clearly state how
1489 // to emit inlined scope that is split into multiple instruction ranges.
1490 // For now, use first instruction range and emit low_pc/high_pc pair and
1491 // corresponding .debug_inlined section entry for this pair.
1492 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1493 MCSymbol *StartLabel = LabelsBeforeInsn.lookup(RI->first);
1494 MCSymbol *EndLabel = LabelsAfterInsn.lookup(RI->second);
1496 if (StartLabel == 0 || EndLabel == 0) {
1497 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1500 assert(StartLabel->isDefined() &&
1501 "Invalid starting label for an inlined scope!");
1502 assert(EndLabel->isDefined() &&
1503 "Invalid end label for an inlined scope!");
1505 if (!Scope->getScopeNode())
1507 DIScope DS(Scope->getScopeNode());
1508 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1510 DISubprogram InlinedSP = getDISubprogram(DS);
1511 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP);
1512 assert(OriginDIE && "Unable to find Origin DIE!");
1513 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1514 dwarf::DW_FORM_ref4, OriginDIE);
1516 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1517 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1519 InlinedSubprogramDIEs.insert(OriginDIE);
1521 // Track the start label for this inlined function.
1522 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1523 I = InlineInfo.find(InlinedSP);
1525 if (I == InlineInfo.end()) {
1526 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1528 InlinedSPNodes.push_back(InlinedSP);
1530 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1532 DILocation DL(Scope->getInlinedAt());
1533 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1534 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1540 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1541 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1542 // Get the descriptor.
1543 const DIVariable &VD = DV->getVariable();
1544 StringRef Name = VD.getName();
1548 // Translate tag to proper Dwarf tag. The result variable is dropped for
1551 switch (VD.getTag()) {
1552 case dwarf::DW_TAG_return_variable:
1554 case dwarf::DW_TAG_arg_variable:
1555 Tag = dwarf::DW_TAG_formal_parameter;
1557 case dwarf::DW_TAG_auto_variable: // fall thru
1559 Tag = dwarf::DW_TAG_variable;
1563 // Define variable debug information entry.
1564 DIE *VariableDie = new DIE(Tag);
1568 if (DbgVariable *AV = DV->getAbstractVariable())
1569 AbsDIE = AV->getDIE();
1572 DIScope DS(Scope->getScopeNode());
1573 DISubprogram InlinedSP = getDISubprogram(DS);
1574 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP);
1576 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1577 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1578 assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1579 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1580 dwarf::DW_FORM_ref4, AbsDIE);
1583 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1584 addSourceLine(VariableDie, &VD);
1586 // Add variable type.
1587 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1588 // addresses instead.
1589 if (VD.isBlockByrefVariable())
1590 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1592 addType(VariableDie, VD.getType());
1595 // Add variable address.
1596 if (!Scope->isAbstractScope()) {
1597 // Check if variable is described by DBG_VALUE instruction.
1598 if (const MachineInstr *DVInsn = DV->getDbgValue()) {
1599 bool updated = false;
1600 // FIXME : Handle getNumOperands != 3
1601 if (DVInsn->getNumOperands() == 3) {
1602 if (DVInsn->getOperand(0).isReg())
1603 updated = addRegisterAddress(VariableDie, DV, DVInsn->getOperand(0));
1604 else if (DVInsn->getOperand(0).isImm())
1605 updated = addConstantValue(VariableDie, DV, DVInsn->getOperand(0));
1606 else if (DVInsn->getOperand(0).isFPImm())
1607 updated = addConstantFPValue(VariableDie, DV, DVInsn->getOperand(0));
1609 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1610 if (Location.getReg()) {
1611 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1612 if (MCSymbol *VS = DV->getDbgValueLabel())
1613 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1619 // If variableDie is not updated then DBG_VALUE instruction does not
1620 // have valid variable info.
1626 MachineLocation Location;
1628 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1629 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1631 Location.set(FrameReg, Offset);
1633 if (VD.hasComplexAddress())
1634 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1635 else if (VD.isBlockByrefVariable())
1636 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1638 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1642 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1643 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1644 DV->setDIE(VariableDie);
1649 void DwarfDebug::addPubTypes(DISubprogram SP) {
1650 DICompositeType SPTy = SP.getType();
1651 unsigned SPTag = SPTy.getTag();
1652 if (SPTag != dwarf::DW_TAG_subroutine_type)
1655 DIArray Args = SPTy.getTypeArray();
1656 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1657 DIType ATy(Args.getElement(i));
1660 DICompositeType CATy = getDICompositeType(ATy);
1661 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1662 && !CATy.isForwardDecl()) {
1663 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy))
1664 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1669 /// constructScopeDIE - Construct a DIE for this scope.
1670 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1671 if (!Scope || !Scope->getScopeNode())
1674 DIScope DS(Scope->getScopeNode());
1675 DIE *ScopeDIE = NULL;
1676 if (Scope->getInlinedAt())
1677 ScopeDIE = constructInlinedScopeDIE(Scope);
1678 else if (DS.isSubprogram()) {
1679 if (Scope->isAbstractScope())
1680 ScopeDIE = ModuleCU->getDIE(DS);
1682 ScopeDIE = updateSubprogramScopeDIE(DS);
1685 ScopeDIE = constructLexicalScopeDIE(Scope);
1686 if (!ScopeDIE) return NULL;
1688 // Add variables to scope.
1689 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1690 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1691 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1693 ScopeDIE->addChild(VariableDIE);
1696 // Add nested scopes.
1697 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1698 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1699 // Define the Scope debug information entry.
1700 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1702 ScopeDIE->addChild(NestedDIE);
1705 if (DS.isSubprogram())
1706 addPubTypes(DISubprogram(DS));
1711 /// GetOrCreateSourceID - Look up the source id with the given directory and
1712 /// source file names. If none currently exists, create a new id and insert it
1713 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1715 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1717 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1718 if (DI != DirectoryIdMap.end()) {
1719 DId = DI->getValue();
1721 DId = DirectoryNames.size() + 1;
1722 DirectoryIdMap[DirName] = DId;
1723 DirectoryNames.push_back(DirName);
1727 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1728 if (FI != SourceFileIdMap.end()) {
1729 FId = FI->getValue();
1731 FId = SourceFileNames.size() + 1;
1732 SourceFileIdMap[FileName] = FId;
1733 SourceFileNames.push_back(FileName);
1736 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1737 SourceIdMap.find(std::make_pair(DId, FId));
1738 if (SI != SourceIdMap.end())
1741 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1742 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1743 SourceIds.push_back(std::make_pair(DId, FId));
1748 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1749 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1750 DIE *NDie = ModuleCU->getDIE(NS);
1753 NDie = new DIE(dwarf::DW_TAG_namespace);
1754 ModuleCU->insertDIE(NS, NDie);
1755 if (!NS.getName().empty())
1756 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1757 addSourceLine(NDie, &NS);
1758 addToContextOwner(NDie, NS.getContext());
1762 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1763 DICompileUnit DIUnit(N);
1764 // Use first compile unit marked as isMain as the compile unit for this
1766 if (ModuleCU || !DIUnit.isMain())
1768 StringRef FN = DIUnit.getFilename();
1769 StringRef Dir = DIUnit.getDirectory();
1770 unsigned ID = GetOrCreateSourceID(Dir, FN);
1772 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1773 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1774 DIUnit.getProducer());
1775 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1776 DIUnit.getLanguage());
1777 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1778 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1779 // simplifies debug range entries.
1780 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_data4, 0);
1781 // DW_AT_stmt_list is a offset of line number information for this
1782 // compile unit in debug_line section. It is always zero when only one
1783 // compile unit is emitted in one object file.
1784 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1787 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1788 if (DIUnit.isOptimized())
1789 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1791 StringRef Flags = DIUnit.getFlags();
1793 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1795 unsigned RVer = DIUnit.getRunTimeVersion();
1797 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1798 dwarf::DW_FORM_data1, RVer);
1801 "ModuleCU assigned since the top of constructCompileUnit");
1802 ModuleCU = new CompileUnit(ID, Die);
1805 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1806 DIGlobalVariable DI_GV(N);
1808 // If debug information is malformed then ignore it.
1809 if (DI_GV.Verify() == false)
1812 // Check for pre-existence.
1813 if (ModuleCU->getDIE(DI_GV))
1816 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1821 ModuleCU->insertDIE(N, VariableDie);
1823 // Add to context owner.
1824 DIDescriptor GVContext = DI_GV.getContext();
1825 // Do not create specification DIE if context is either compile unit
1827 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1828 !GVContext.isFile() &&
1829 !isSubprogramContext(GVContext)) {
1830 // Create specification DIE.
1831 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1832 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1833 dwarf::DW_FORM_ref4, VariableDie);
1834 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1835 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1836 addLabel(Block, 0, dwarf::DW_FORM_udata,
1837 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1838 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1839 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1840 ModuleCU->addDie(VariableSpecDIE);
1842 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1843 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1844 addLabel(Block, 0, dwarf::DW_FORM_udata,
1845 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1846 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1848 addToContextOwner(VariableDie, GVContext);
1850 // Expose as global. FIXME - need to check external flag.
1851 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1853 DIType GTy = DI_GV.getType();
1854 if (GTy.isCompositeType() && !GTy.getName().empty()
1855 && !GTy.isForwardDecl()) {
1856 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy);
1857 assert(Entry && "Missing global type!");
1858 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1863 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1866 // Check for pre-existence.
1867 if (ModuleCU->getDIE(N))
1870 if (!SP.isDefinition())
1871 // This is a method declaration which will be handled while constructing
1875 DIE *SubprogramDie = createSubprogramDIE(SP);
1878 ModuleCU->insertDIE(N, SubprogramDie);
1880 // Add to context owner.
1881 addToContextOwner(SubprogramDie, SP.getContext());
1883 // Expose as global.
1884 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1889 /// beginModule - Emit all Dwarf sections that should come prior to the
1890 /// content. Create global DIEs and emit initial debug info sections.
1891 /// This is inovked by the target AsmPrinter.
1892 void DwarfDebug::beginModule(Module *M) {
1893 if (DisableDebugInfoPrinting)
1896 DebugInfoFinder DbgFinder;
1897 DbgFinder.processModule(*M);
1899 bool HasDebugInfo = false;
1901 // Scan all the compile-units to see if there are any marked as the main unit.
1902 // if not, we do not generate debug info.
1903 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1904 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1905 if (DICompileUnit(*I).isMain()) {
1906 HasDebugInfo = true;
1911 if (!HasDebugInfo) return;
1913 // Tell MMI that we have debug info.
1914 MMI->setDebugInfoAvailability(true);
1916 // Emit initial sections.
1917 EmitSectionLabels();
1919 // Create all the compile unit DIEs.
1920 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1921 E = DbgFinder.compile_unit_end(); I != E; ++I)
1922 constructCompileUnit(*I);
1924 // Create DIEs for each subprogram.
1925 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1926 E = DbgFinder.subprogram_end(); I != E; ++I)
1927 constructSubprogramDIE(*I);
1929 // Create DIEs for each global variable.
1930 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1931 E = DbgFinder.global_variable_end(); I != E; ++I)
1932 constructGlobalVariableDIE(*I);
1934 // Prime section data.
1935 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1937 // Print out .file directives to specify files for .loc directives. These are
1938 // printed out early so that they precede any .loc directives.
1939 if (Asm->MAI->hasDotLocAndDotFile()) {
1940 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1941 // Remember source id starts at 1.
1942 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1943 // FIXME: don't use sys::path for this! This should not depend on the
1945 sys::Path FullPath(getSourceDirectoryName(Id.first));
1947 FullPath.appendComponent(getSourceFileName(Id.second));
1948 assert(AppendOk && "Could not append filename to directory!");
1950 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1955 /// endModule - Emit all Dwarf sections that should come after the content.
1957 void DwarfDebug::endModule() {
1958 if (!ModuleCU) return;
1960 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1961 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1962 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1964 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1967 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1968 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1969 DIE *SPDie = CI->first;
1970 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1972 DIE *NDie = ModuleCU->getDIE(N);
1973 if (!NDie) continue;
1974 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1977 // Standard sections final addresses.
1978 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1979 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1980 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1981 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1983 // End text sections.
1984 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1985 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1986 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1989 // Emit common frame information.
1990 emitCommonDebugFrame();
1992 // Emit function debug frame information
1993 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1994 E = DebugFrames.end(); I != E; ++I)
1995 emitFunctionDebugFrame(*I);
1997 // Compute DIE offsets and sizes.
1998 computeSizeAndOffsets();
2000 // Emit all the DIEs into a debug info section
2003 // Corresponding abbreviations into a abbrev section.
2004 emitAbbreviations();
2006 // Emit source line correspondence into a debug line section.
2009 // Emit info into a debug pubnames section.
2010 emitDebugPubNames();
2012 // Emit info into a debug pubtypes section.
2013 emitDebugPubTypes();
2015 // Emit info into a debug loc section.
2018 // Emit info into a debug aranges section.
2021 // Emit info into a debug ranges section.
2024 // Emit info into a debug macinfo section.
2027 // Emit inline info.
2028 emitDebugInlineInfo();
2030 // Emit info into a debug str section.
2034 ModuleCU = NULL; // Reset for the next Module, if any.
2037 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2038 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2040 DebugLoc ScopeLoc) {
2042 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2044 return AbsDbgVariable;
2046 LLVMContext &Ctx = Var->getContext();
2047 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2051 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2052 NULL /* No more-abstract variable*/);
2053 Scope->addVariable(AbsDbgVariable);
2054 AbstractVariables[Var] = AbsDbgVariable;
2055 return AbsDbgVariable;
2058 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2059 /// FIXME : Refactor findAbstractVariable.
2060 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2061 const MachineInstr *MI,
2062 DebugLoc ScopeLoc) {
2064 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2066 return AbsDbgVariable;
2068 LLVMContext &Ctx = Var->getContext();
2069 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2073 AbsDbgVariable = new DbgVariable(Var, MI,
2074 NULL /* No more-abstract variable*/);
2075 Scope->addVariable(AbsDbgVariable);
2076 AbstractVariables[Var] = AbsDbgVariable;
2077 DbgValueStartMap[MI] = AbsDbgVariable;
2078 return AbsDbgVariable;
2081 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2082 void DwarfDebug::collectVariableInfo() {
2083 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2085 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2086 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2087 VE = VMap.end(); VI != VE; ++VI) {
2088 const MDNode *Var = VI->first;
2091 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2093 DbgScope *Scope = 0;
2094 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2095 Scope = ConcreteScopes.lookup(IA);
2097 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2099 // If variable scope is not found then skip this variable.
2103 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2104 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2105 Scope->addVariable(RegVar);
2108 // Collect variable information from DBG_VALUE machine instructions;
2109 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2111 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2113 const MachineInstr *MInsn = II;
2114 if (!MInsn->isDebugValue())
2117 // Ignore Undef values.
2118 if (MInsn->getOperand(0).isReg() && !MInsn->getOperand(0).getReg())
2122 const_cast<const MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2124 if (DV.getTag() == dwarf::DW_TAG_arg_variable) {
2125 // FIXME Handle inlined subroutine arguments.
2126 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2127 CurrentFnDbgScope->addVariable(ArgVar);
2128 DbgValueStartMap[MInsn] = ArgVar;
2132 DebugLoc DL = MInsn->getDebugLoc();
2133 if (DL.isUnknown()) continue;
2134 DbgScope *Scope = 0;
2135 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2136 Scope = ConcreteScopes.lookup(IA);
2138 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2140 // If variable scope is not found then skip this variable.
2144 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2145 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2146 DbgValueStartMap[MInsn] = RegVar;
2147 Scope->addVariable(RegVar);
2152 /// beginScope - Process beginning of a scope.
2153 void DwarfDebug::beginScope(const MachineInstr *MI) {
2155 DebugLoc DL = MI->getDebugLoc();
2156 if (DL.isUnknown()) {
2157 if (UnknownLocations) {
2158 // This instruction has no debug location. If the preceding instruction
2159 // did, emit debug location information to indicate that the debug
2160 // location is now unknown.
2161 MCSymbol *Label = NULL;
2162 if (DL == PrevInstLoc)
2165 Label = recordSourceLine(DL.getLine(), DL.getCol(), 0);
2170 // If this instruction begins a scope then note down corresponding label.
2171 if (InsnsBeginScopeSet.count(MI) != 0)
2172 LabelsBeforeInsn[MI] = Label;
2178 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2180 // FIXME: Should only verify each scope once!
2181 if (!DIScope(Scope).Verify())
2184 // DBG_VALUE instruction establishes new value.
2185 if (MI->isDebugValue()) {
2186 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2187 = DbgValueStartMap.find(MI);
2188 if (DI != DbgValueStartMap.end()) {
2189 MCSymbol *Label = NULL;
2190 if (DL == PrevInstLoc)
2193 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2197 DI->second->setDbgValueLabel(Label);
2202 // Emit a label to indicate location change. This is used for line
2203 // table even if this instruction does not start a new scope.
2204 MCSymbol *Label = NULL;
2205 if (DL == PrevInstLoc)
2208 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2213 // If this instruction begins a scope then note down corresponding label.
2214 if (InsnsBeginScopeSet.count(MI) != 0)
2215 LabelsBeforeInsn[MI] = Label;
2218 /// endScope - Process end of a scope.
2219 void DwarfDebug::endScope(const MachineInstr *MI) {
2220 if (InsnsEndScopeSet.count(MI) != 0) {
2221 // Emit a label if this instruction ends a scope.
2222 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2223 Asm->OutStreamer.EmitLabel(Label);
2224 LabelsAfterInsn[MI] = Label;
2228 /// getOrCreateDbgScope - Create DbgScope for the scope.
2229 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope, const MDNode *InlinedAt) {
2231 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2234 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2235 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2236 if (DIDescriptor(Scope).isLexicalBlock()) {
2238 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2239 WScope->setParent(Parent);
2240 Parent->addScope(WScope);
2243 if (!WScope->getParent()) {
2244 StringRef SPName = DISubprogram(Scope).getLinkageName();
2245 if (SPName == Asm->MF->getFunction()->getName())
2246 CurrentFnDbgScope = WScope;
2252 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2256 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2257 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2258 DILocation DL(InlinedAt);
2260 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2261 WScope->setParent(Parent);
2262 Parent->addScope(WScope);
2264 ConcreteScopes[InlinedAt] = WScope;
2265 getOrCreateAbstractScope(Scope);
2270 /// hasValidLocation - Return true if debug location entry attached with
2271 /// machine instruction encodes valid location info.
2272 static bool hasValidLocation(LLVMContext &Ctx,
2273 const MachineInstr *MInsn,
2274 const MDNode *&Scope, const MDNode *&InlinedAt) {
2275 if (MInsn->isDebugValue())
2277 DebugLoc DL = MInsn->getDebugLoc();
2278 if (DL.isUnknown()) return false;
2280 const MDNode *S = DL.getScope(Ctx);
2282 // There is no need to create another DIE for compile unit. For all
2283 // other scopes, create one DbgScope now. This will be translated
2284 // into a scope DIE at the end.
2285 if (DIScope(S).isCompileUnit()) return false;
2288 InlinedAt = DL.getInlinedAt(Ctx);
2292 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2294 static void calculateDominanceGraph(DbgScope *Scope) {
2295 assert (Scope && "Unable to calculate scop edominance graph!");
2296 SmallVector<DbgScope *, 4> WorkStack;
2297 WorkStack.push_back(Scope);
2298 unsigned Counter = 0;
2299 while (!WorkStack.empty()) {
2300 DbgScope *WS = WorkStack.back();
2301 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2302 bool visitedChildren = false;
2303 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2304 SE = Children.end(); SI != SE; ++SI) {
2305 DbgScope *ChildScope = *SI;
2306 if (!ChildScope->getDFSOut()) {
2307 WorkStack.push_back(ChildScope);
2308 visitedChildren = true;
2309 ChildScope->setDFSIn(++Counter);
2313 if (!visitedChildren) {
2314 WorkStack.pop_back();
2315 WS->setDFSOut(++Counter);
2320 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2322 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2323 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2326 unsigned PrevDFSIn = 0;
2327 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2329 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2331 const MachineInstr *MInsn = II;
2332 const MDNode *Scope = NULL;
2333 const MDNode *InlinedAt = NULL;
2335 // Check if instruction has valid location information.
2336 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2340 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2341 MI2ScopeMap.find(MInsn);
2342 if (DI != MI2ScopeMap.end()) {
2343 DbgScope *S = DI->second;
2344 dbgs() << S->getDFSIn();
2345 PrevDFSIn = S->getDFSIn();
2347 dbgs() << PrevDFSIn;
2349 dbgs() << " [ x" << PrevDFSIn;
2357 /// extractScopeInformation - Scan machine instructions in this function
2358 /// and collect DbgScopes. Return true, if at least one scope was found.
2359 bool DwarfDebug::extractScopeInformation() {
2360 // If scope information was extracted using .dbg intrinsics then there is not
2361 // any need to extract these information by scanning each instruction.
2362 if (!DbgScopeMap.empty())
2365 // Scan each instruction and create scopes. First build working set of scopes.
2366 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2367 SmallVector<DbgRange, 4> MIRanges;
2368 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2369 const MDNode *PrevScope = NULL;
2370 const MDNode *PrevInlinedAt = NULL;
2371 const MachineInstr *RangeBeginMI = NULL;
2372 const MachineInstr *PrevMI = NULL;
2373 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2375 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2377 const MachineInstr *MInsn = II;
2378 const MDNode *Scope = NULL;
2379 const MDNode *InlinedAt = NULL;
2381 // Check if instruction has valid location information.
2382 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2387 // If scope has not changed then skip this instruction.
2388 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2394 // If we have alread seen a beginning of a instruction range and
2395 // current instruction scope does not match scope of first instruction
2396 // in this range then create a new instruction range.
2397 DbgRange R(RangeBeginMI, PrevMI);
2398 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2399 MIRanges.push_back(R);
2402 // This is a beginning of a new instruction range.
2403 RangeBeginMI = MInsn;
2405 // Reset previous markers.
2408 PrevInlinedAt = InlinedAt;
2412 // Create last instruction range.
2413 if (RangeBeginMI && PrevMI && PrevScope) {
2414 DbgRange R(RangeBeginMI, PrevMI);
2415 MIRanges.push_back(R);
2416 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2419 if (!CurrentFnDbgScope)
2422 calculateDominanceGraph(CurrentFnDbgScope);
2424 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2426 // Find ranges of instructions covered by each DbgScope;
2427 DbgScope *PrevDbgScope = NULL;
2428 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2429 RE = MIRanges.end(); RI != RE; ++RI) {
2430 const DbgRange &R = *RI;
2431 DbgScope *S = MI2ScopeMap.lookup(R.first);
2432 assert (S && "Lost DbgScope for a machine instruction!");
2433 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2434 PrevDbgScope->closeInsnRange(S);
2435 S->openInsnRange(R.first);
2436 S->extendInsnRange(R.second);
2441 PrevDbgScope->closeInsnRange();
2443 identifyScopeMarkers();
2445 return !DbgScopeMap.empty();
2448 /// identifyScopeMarkers() -
2449 /// Each DbgScope has first instruction and last instruction to mark beginning
2450 /// and end of a scope respectively. Create an inverse map that list scopes
2451 /// starts (and ends) with an instruction. One instruction may start (or end)
2452 /// multiple scopes. Ignore scopes that are not reachable.
2453 void DwarfDebug::identifyScopeMarkers() {
2454 SmallVector<DbgScope *, 4> WorkList;
2455 WorkList.push_back(CurrentFnDbgScope);
2456 while (!WorkList.empty()) {
2457 DbgScope *S = WorkList.pop_back_val();
2459 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2460 if (!Children.empty())
2461 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2462 SE = Children.end(); SI != SE; ++SI)
2463 WorkList.push_back(*SI);
2465 if (S->isAbstractScope())
2468 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2471 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2472 RE = Ranges.end(); RI != RE; ++RI) {
2473 assert(RI->first && "DbgRange does not have first instruction!");
2474 assert(RI->second && "DbgRange does not have second instruction!");
2475 InsnsBeginScopeSet.insert(RI->first);
2476 InsnsEndScopeSet.insert(RI->second);
2481 /// FindFirstDebugLoc - Find the first debug location in the function. This
2482 /// is intended to be an approximation for the source position of the
2483 /// beginning of the function.
2484 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2485 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2487 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2488 MBBI != MBBE; ++MBBI) {
2489 DebugLoc DL = MBBI->getDebugLoc();
2490 if (!DL.isUnknown())
2496 /// beginFunction - Gather pre-function debug information. Assumes being
2497 /// emitted immediately after the function entry point.
2498 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2499 if (!MMI->hasDebugInfo()) return;
2500 if (!extractScopeInformation()) return;
2502 collectVariableInfo();
2504 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2505 Asm->getFunctionNumber());
2506 // Assumes in correct section after the entry point.
2507 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2509 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2511 DebugLoc FDL = FindFirstDebugLoc(MF);
2512 if (FDL.isUnknown()) return;
2514 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2516 DISubprogram SP = getDISubprogram(Scope);
2519 Line = SP.getLineNumber();
2522 Line = FDL.getLine();
2526 recordSourceLine(Line, Col, Scope);
2529 /// endFunction - Gather and emit post-function debug information.
2531 void DwarfDebug::endFunction(const MachineFunction *MF) {
2532 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2534 if (CurrentFnDbgScope) {
2535 // Define end label for subprogram.
2536 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2537 Asm->getFunctionNumber()));
2539 // Get function line info.
2540 if (!Lines.empty()) {
2541 // Get section line info.
2542 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2543 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2544 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2545 // Append the function info to section info.
2546 SectionLineInfos.insert(SectionLineInfos.end(),
2547 Lines.begin(), Lines.end());
2550 // Construct abstract scopes.
2551 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2552 AE = AbstractScopesList.end(); AI != AE; ++AI)
2553 constructScopeDIE(*AI);
2555 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2557 if (!DisableFramePointerElim(*MF))
2558 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2559 dwarf::DW_FORM_flag, 1);
2562 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2563 MMI->getFrameMoves()));
2567 CurrentFnDbgScope = NULL;
2568 DeleteContainerSeconds(DbgScopeMap);
2569 InsnsBeginScopeSet.clear();
2570 InsnsEndScopeSet.clear();
2571 DbgValueStartMap.clear();
2572 ConcreteScopes.clear();
2573 DeleteContainerSeconds(AbstractScopes);
2574 AbstractScopesList.clear();
2575 AbstractVariables.clear();
2576 LabelsBeforeInsn.clear();
2577 LabelsAfterInsn.clear();
2582 /// recordSourceLine - Register a source line with debug info. Returns the
2583 /// unique label that was emitted and which provides correspondence to
2584 /// the source line list.
2585 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S) {
2591 DIDescriptor Scope(S);
2593 if (Scope.isCompileUnit()) {
2594 DICompileUnit CU(S);
2595 Dir = CU.getDirectory();
2596 Fn = CU.getFilename();
2597 } else if (Scope.isSubprogram()) {
2599 Dir = SP.getDirectory();
2600 Fn = SP.getFilename();
2601 } else if (Scope.isLexicalBlock()) {
2602 DILexicalBlock DB(S);
2603 Dir = DB.getDirectory();
2604 Fn = DB.getFilename();
2606 assert(0 && "Unexpected scope info");
2608 Src = GetOrCreateSourceID(Dir, Fn);
2611 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2612 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2614 Asm->OutStreamer.EmitLabel(Label);
2618 //===----------------------------------------------------------------------===//
2620 //===----------------------------------------------------------------------===//
2622 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2625 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2626 // Get the children.
2627 const std::vector<DIE *> &Children = Die->getChildren();
2629 // If not last sibling and has children then add sibling offset attribute.
2630 if (!Last && !Children.empty())
2631 Die->addSiblingOffset(DIEValueAllocator);
2633 // Record the abbreviation.
2634 assignAbbrevNumber(Die->getAbbrev());
2636 // Get the abbreviation for this DIE.
2637 unsigned AbbrevNumber = Die->getAbbrevNumber();
2638 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2641 Die->setOffset(Offset);
2643 // Start the size with the size of abbreviation code.
2644 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2646 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2647 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2649 // Size the DIE attribute values.
2650 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2651 // Size attribute value.
2652 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2654 // Size the DIE children if any.
2655 if (!Children.empty()) {
2656 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2657 "Children flag not set");
2659 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2660 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2662 // End of children marker.
2663 Offset += sizeof(int8_t);
2666 Die->setSize(Offset - Die->getOffset());
2670 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2672 void DwarfDebug::computeSizeAndOffsets() {
2673 // Compute size of compile unit header.
2674 static unsigned Offset =
2675 sizeof(int32_t) + // Length of Compilation Unit Info
2676 sizeof(int16_t) + // DWARF version number
2677 sizeof(int32_t) + // Offset Into Abbrev. Section
2678 sizeof(int8_t); // Pointer Size (in bytes)
2680 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2683 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2684 /// temporary label to it if SymbolStem is specified.
2685 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2686 const char *SymbolStem = 0) {
2687 Asm->OutStreamer.SwitchSection(Section);
2688 if (!SymbolStem) return 0;
2690 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2691 Asm->OutStreamer.EmitLabel(TmpSym);
2695 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2696 /// the start of each one.
2697 void DwarfDebug::EmitSectionLabels() {
2698 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2700 // Dwarf sections base addresses.
2701 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2702 DwarfFrameSectionSym =
2703 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2706 DwarfInfoSectionSym =
2707 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2708 DwarfAbbrevSectionSym =
2709 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2710 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2712 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2713 EmitSectionSym(Asm, MacroInfo);
2715 EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2716 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2717 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2718 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2719 DwarfStrSectionSym =
2720 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2721 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2724 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2725 EmitSectionSym(Asm, TLOF.getDataSection());
2728 /// emitDIE - Recusively Emits a debug information entry.
2730 void DwarfDebug::emitDIE(DIE *Die) {
2731 // Get the abbreviation for this DIE.
2732 unsigned AbbrevNumber = Die->getAbbrevNumber();
2733 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2735 // Emit the code (index) for the abbreviation.
2736 if (Asm->isVerbose())
2737 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2738 Twine::utohexstr(Die->getOffset()) + ":0x" +
2739 Twine::utohexstr(Die->getSize()) + " " +
2740 dwarf::TagString(Abbrev->getTag()));
2741 Asm->EmitULEB128(AbbrevNumber);
2743 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2744 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2746 // Emit the DIE attribute values.
2747 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2748 unsigned Attr = AbbrevData[i].getAttribute();
2749 unsigned Form = AbbrevData[i].getForm();
2750 assert(Form && "Too many attributes for DIE (check abbreviation)");
2752 if (Asm->isVerbose())
2753 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2756 case dwarf::DW_AT_sibling:
2757 Asm->EmitInt32(Die->getSiblingOffset());
2759 case dwarf::DW_AT_abstract_origin: {
2760 DIEEntry *E = cast<DIEEntry>(Values[i]);
2761 DIE *Origin = E->getEntry();
2762 unsigned Addr = Origin->getOffset();
2763 Asm->EmitInt32(Addr);
2766 case dwarf::DW_AT_ranges: {
2767 // DW_AT_range Value encodes offset in debug_range section.
2768 DIEInteger *V = cast<DIEInteger>(Values[i]);
2769 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2771 DwarfDebugRangeSectionSym,
2776 // Emit an attribute using the defined form.
2777 Values[i]->EmitValue(Asm, Form);
2782 // Emit the DIE children if any.
2783 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2784 const std::vector<DIE *> &Children = Die->getChildren();
2786 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2787 emitDIE(Children[j]);
2789 if (Asm->isVerbose())
2790 Asm->OutStreamer.AddComment("End Of Children Mark");
2795 /// emitDebugInfo - Emit the debug info section.
2797 void DwarfDebug::emitDebugInfo() {
2798 // Start debug info section.
2799 Asm->OutStreamer.SwitchSection(
2800 Asm->getObjFileLowering().getDwarfInfoSection());
2801 DIE *Die = ModuleCU->getCUDie();
2803 // Emit the compile units header.
2804 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2805 ModuleCU->getID()));
2807 // Emit size of content not including length itself
2808 unsigned ContentSize = Die->getSize() +
2809 sizeof(int16_t) + // DWARF version number
2810 sizeof(int32_t) + // Offset Into Abbrev. Section
2811 sizeof(int8_t) + // Pointer Size (in bytes)
2812 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2814 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2815 Asm->EmitInt32(ContentSize);
2816 Asm->OutStreamer.AddComment("DWARF version number");
2817 Asm->EmitInt16(dwarf::DWARF_VERSION);
2818 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2819 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2820 DwarfAbbrevSectionSym);
2821 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2822 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2825 // FIXME - extra padding for gdb bug.
2826 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2831 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2834 /// emitAbbreviations - Emit the abbreviation section.
2836 void DwarfDebug::emitAbbreviations() const {
2837 // Check to see if it is worth the effort.
2838 if (!Abbreviations.empty()) {
2839 // Start the debug abbrev section.
2840 Asm->OutStreamer.SwitchSection(
2841 Asm->getObjFileLowering().getDwarfAbbrevSection());
2843 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2845 // For each abbrevation.
2846 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2847 // Get abbreviation data
2848 const DIEAbbrev *Abbrev = Abbreviations[i];
2850 // Emit the abbrevations code (base 1 index.)
2851 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2853 // Emit the abbreviations data.
2857 // Mark end of abbreviations.
2858 Asm->EmitULEB128(0, "EOM(3)");
2860 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2864 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2865 /// the line matrix.
2867 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2868 // Define last address of section.
2869 Asm->OutStreamer.AddComment("Extended Op");
2872 Asm->OutStreamer.AddComment("Op size");
2873 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2874 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2875 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2877 Asm->OutStreamer.AddComment("Section end label");
2879 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2880 Asm->getTargetData().getPointerSize(),
2883 // Mark end of matrix.
2884 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2890 /// emitDebugLines - Emit source line information.
2892 void DwarfDebug::emitDebugLines() {
2893 // If the target is using .loc/.file, the assembler will be emitting the
2894 // .debug_line table automatically.
2895 if (Asm->MAI->hasDotLocAndDotFile())
2898 // Minimum line delta, thus ranging from -10..(255-10).
2899 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2900 // Maximum line delta, thus ranging from -10..(255-10).
2901 const int MaxLineDelta = 255 + MinLineDelta;
2903 // Start the dwarf line section.
2904 Asm->OutStreamer.SwitchSection(
2905 Asm->getObjFileLowering().getDwarfLineSection());
2907 // Construct the section header.
2908 Asm->OutStreamer.AddComment("Length of Source Line Info");
2909 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2910 Asm->GetTempSymbol("line_begin"), 4);
2911 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2913 Asm->OutStreamer.AddComment("DWARF version number");
2914 Asm->EmitInt16(dwarf::DWARF_VERSION);
2916 Asm->OutStreamer.AddComment("Prolog Length");
2917 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2918 Asm->GetTempSymbol("line_prolog_begin"), 4);
2919 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2921 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2923 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2925 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2926 Asm->EmitInt8(MinLineDelta);
2927 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2928 Asm->EmitInt8(MaxLineDelta);
2929 Asm->OutStreamer.AddComment("Special Opcode Base");
2930 Asm->EmitInt8(-MinLineDelta);
2932 // Line number standard opcode encodings argument count
2933 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2935 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2937 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2939 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2941 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2943 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2945 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2947 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2949 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2952 // Emit directories.
2953 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2954 const std::string &Dir = getSourceDirectoryName(DI);
2955 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2956 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2959 Asm->OutStreamer.AddComment("End of directories");
2963 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2964 // Remember source id starts at 1.
2965 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2966 const std::string &FN = getSourceFileName(Id.second);
2967 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2968 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2970 Asm->EmitULEB128(Id.first, "Directory #");
2971 Asm->EmitULEB128(0, "Mod date");
2972 Asm->EmitULEB128(0, "File size");
2975 Asm->OutStreamer.AddComment("End of files");
2978 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2980 // A sequence for each text section.
2981 unsigned SecSrcLinesSize = SectionSourceLines.size();
2983 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2984 // Isolate current sections line info.
2985 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2987 // Dwarf assumes we start with first line of first source file.
2988 unsigned Source = 1;
2991 // Construct rows of the address, source, line, column matrix.
2992 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2993 const SrcLineInfo &LineInfo = LineInfos[i];
2994 MCSymbol *Label = LineInfo.getLabel();
2995 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2997 if (Asm->isVerbose()) {
2998 std::pair<unsigned, unsigned> SrcID =
2999 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3000 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3002 Twine(getSourceFileName(SrcID.second)) +
3003 ":" + Twine(LineInfo.getLine()));
3006 // Define the line address.
3007 Asm->OutStreamer.AddComment("Extended Op");
3009 Asm->OutStreamer.AddComment("Op size");
3010 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3012 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3013 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3015 Asm->OutStreamer.AddComment("Location label");
3016 Asm->OutStreamer.EmitSymbolValue(Label,
3017 Asm->getTargetData().getPointerSize(),
3020 // If change of source, then switch to the new source.
3021 if (Source != LineInfo.getSourceID()) {
3022 Source = LineInfo.getSourceID();
3023 Asm->OutStreamer.AddComment("DW_LNS_set_file");
3024 Asm->EmitInt8(dwarf::DW_LNS_set_file);
3025 Asm->EmitULEB128(Source, "New Source");
3028 // If change of line.
3029 if (Line != LineInfo.getLine()) {
3030 // Determine offset.
3031 int Offset = LineInfo.getLine() - Line;
3032 int Delta = Offset - MinLineDelta;
3035 Line = LineInfo.getLine();
3037 // If delta is small enough and in range...
3038 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3039 // ... then use fast opcode.
3040 Asm->OutStreamer.AddComment("Line Delta");
3041 Asm->EmitInt8(Delta - MinLineDelta);
3043 // ... otherwise use long hand.
3044 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3045 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3046 Asm->EmitSLEB128(Offset, "Line Offset");
3047 Asm->OutStreamer.AddComment("DW_LNS_copy");
3048 Asm->EmitInt8(dwarf::DW_LNS_copy);
3051 // Copy the previous row (different address or source)
3052 Asm->OutStreamer.AddComment("DW_LNS_copy");
3053 Asm->EmitInt8(dwarf::DW_LNS_copy);
3057 emitEndOfLineMatrix(j + 1);
3060 if (SecSrcLinesSize == 0)
3061 // Because we're emitting a debug_line section, we still need a line
3062 // table. The linker and friends expect it to exist. If there's nothing to
3063 // put into it, emit an empty table.
3064 emitEndOfLineMatrix(1);
3066 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3069 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3071 void DwarfDebug::emitCommonDebugFrame() {
3072 if (!Asm->MAI->doesDwarfRequireFrameSection())
3075 int stackGrowth = Asm->getTargetData().getPointerSize();
3076 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3077 TargetFrameInfo::StackGrowsDown)
3080 // Start the dwarf frame section.
3081 Asm->OutStreamer.SwitchSection(
3082 Asm->getObjFileLowering().getDwarfFrameSection());
3084 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3085 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3086 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3087 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3089 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3090 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3091 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3092 Asm->OutStreamer.AddComment("CIE Version");
3093 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3094 Asm->OutStreamer.AddComment("CIE Augmentation");
3095 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3096 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3097 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3098 Asm->OutStreamer.AddComment("CIE RA Column");
3099 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3100 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3102 std::vector<MachineMove> Moves;
3103 RI->getInitialFrameState(Moves);
3105 Asm->EmitFrameMoves(Moves, 0, false);
3107 Asm->EmitAlignment(2);
3108 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3111 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3114 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3115 if (!Asm->MAI->doesDwarfRequireFrameSection())
3118 // Start the dwarf frame section.
3119 Asm->OutStreamer.SwitchSection(
3120 Asm->getObjFileLowering().getDwarfFrameSection());
3122 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3123 MCSymbol *DebugFrameBegin =
3124 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3125 MCSymbol *DebugFrameEnd =
3126 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3127 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3129 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3131 Asm->OutStreamer.AddComment("FDE CIE offset");
3132 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3133 DwarfFrameSectionSym);
3135 Asm->OutStreamer.AddComment("FDE initial location");
3136 MCSymbol *FuncBeginSym =
3137 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3138 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3139 Asm->getTargetData().getPointerSize(),
3143 Asm->OutStreamer.AddComment("FDE address range");
3144 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3145 FuncBeginSym, Asm->getTargetData().getPointerSize());
3147 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3149 Asm->EmitAlignment(2);
3150 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3153 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3155 void DwarfDebug::emitDebugPubNames() {
3156 // Start the dwarf pubnames section.
3157 Asm->OutStreamer.SwitchSection(
3158 Asm->getObjFileLowering().getDwarfPubNamesSection());
3160 Asm->OutStreamer.AddComment("Length of Public Names Info");
3161 Asm->EmitLabelDifference(
3162 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3163 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3165 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3166 ModuleCU->getID()));
3168 Asm->OutStreamer.AddComment("DWARF Version");
3169 Asm->EmitInt16(dwarf::DWARF_VERSION);
3171 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3172 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3173 DwarfInfoSectionSym);
3175 Asm->OutStreamer.AddComment("Compilation Unit Length");
3176 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3177 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3180 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3181 for (StringMap<DIE*>::const_iterator
3182 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3183 const char *Name = GI->getKeyData();
3184 DIE *Entity = GI->second;
3186 Asm->OutStreamer.AddComment("DIE offset");
3187 Asm->EmitInt32(Entity->getOffset());
3189 if (Asm->isVerbose())
3190 Asm->OutStreamer.AddComment("External Name");
3191 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3194 Asm->OutStreamer.AddComment("End Mark");
3196 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3197 ModuleCU->getID()));
3200 void DwarfDebug::emitDebugPubTypes() {
3201 // Start the dwarf pubnames section.
3202 Asm->OutStreamer.SwitchSection(
3203 Asm->getObjFileLowering().getDwarfPubTypesSection());
3204 Asm->OutStreamer.AddComment("Length of Public Types Info");
3205 Asm->EmitLabelDifference(
3206 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3207 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3209 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3210 ModuleCU->getID()));
3212 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3213 Asm->EmitInt16(dwarf::DWARF_VERSION);
3215 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3216 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3217 DwarfInfoSectionSym);
3219 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3220 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3221 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3224 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3225 for (StringMap<DIE*>::const_iterator
3226 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3227 const char *Name = GI->getKeyData();
3228 DIE * Entity = GI->second;
3230 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3231 Asm->EmitInt32(Entity->getOffset());
3233 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3234 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3237 Asm->OutStreamer.AddComment("End Mark");
3239 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3240 ModuleCU->getID()));
3243 /// emitDebugStr - Emit visible names into a debug str section.
3245 void DwarfDebug::emitDebugStr() {
3246 // Check to see if it is worth the effort.
3247 if (StringPool.empty()) return;
3249 // Start the dwarf str section.
3250 Asm->OutStreamer.SwitchSection(
3251 Asm->getObjFileLowering().getDwarfStrSection());
3253 // Get all of the string pool entries and put them in an array by their ID so
3254 // we can sort them.
3255 SmallVector<std::pair<unsigned,
3256 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3258 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3259 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3260 Entries.push_back(std::make_pair(I->second.second, &*I));
3262 array_pod_sort(Entries.begin(), Entries.end());
3264 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3265 // Emit a label for reference from debug information entries.
3266 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3268 // Emit the string itself.
3269 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3273 /// emitDebugLoc - Emit visible names into a debug loc section.
3275 void DwarfDebug::emitDebugLoc() {
3276 // Start the dwarf loc section.
3277 Asm->OutStreamer.SwitchSection(
3278 Asm->getObjFileLowering().getDwarfLocSection());
3281 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3283 void DwarfDebug::EmitDebugARanges() {
3284 // Start the dwarf aranges section.
3285 Asm->OutStreamer.SwitchSection(
3286 Asm->getObjFileLowering().getDwarfARangesSection());
3289 /// emitDebugRanges - Emit visible names into a debug ranges section.
3291 void DwarfDebug::emitDebugRanges() {
3292 // Start the dwarf ranges section.
3293 Asm->OutStreamer.SwitchSection(
3294 Asm->getObjFileLowering().getDwarfRangesSection());
3295 unsigned char Size = Asm->getTargetData().getPointerSize();
3296 for (SmallVector<const MCSymbol *, 8>::iterator
3297 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3300 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3302 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3306 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3308 void DwarfDebug::emitDebugMacInfo() {
3309 if (const MCSection *LineInfo =
3310 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3311 // Start the dwarf macinfo section.
3312 Asm->OutStreamer.SwitchSection(LineInfo);
3316 /// emitDebugInlineInfo - Emit inline info using following format.
3318 /// 1. length of section
3319 /// 2. Dwarf version number
3320 /// 3. address size.
3322 /// Entries (one "entry" for each function that was inlined):
3324 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3325 /// otherwise offset into __debug_str for regular function name.
3326 /// 2. offset into __debug_str section for regular function name.
3327 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3328 /// instances for the function.
3330 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3331 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3332 /// __debug_info section, and the low_pc is the starting address for the
3333 /// inlining instance.
3334 void DwarfDebug::emitDebugInlineInfo() {
3335 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3341 Asm->OutStreamer.SwitchSection(
3342 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3344 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3345 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3346 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3348 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3350 Asm->OutStreamer.AddComment("Dwarf Version");
3351 Asm->EmitInt16(dwarf::DWARF_VERSION);
3352 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3353 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3355 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3356 E = InlinedSPNodes.end(); I != E; ++I) {
3358 const MDNode *Node = *I;
3359 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3360 = InlineInfo.find(Node);
3361 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3362 DISubprogram SP(Node);
3363 StringRef LName = SP.getLinkageName();
3364 StringRef Name = SP.getName();
3366 Asm->OutStreamer.AddComment("MIPS linkage name");
3367 if (LName.empty()) {
3368 Asm->OutStreamer.EmitBytes(Name, 0);
3369 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3371 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3372 DwarfStrSectionSym);
3374 Asm->OutStreamer.AddComment("Function name");
3375 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3376 Asm->EmitULEB128(Labels.size(), "Inline count");
3378 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3379 LE = Labels.end(); LI != LE; ++LI) {
3380 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3381 Asm->EmitInt32(LI->second->getOffset());
3383 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3384 Asm->OutStreamer.EmitSymbolValue(LI->first,
3385 Asm->getTargetData().getPointerSize(),0);
3389 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));