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 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "dwarfdebug"
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include "llvm/Target/TargetLoweringObjectFile.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/System/Path.h"
33 static TimerGroup &getDwarfTimerGroup() {
34 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
35 return DwarfTimerGroup;
38 //===----------------------------------------------------------------------===//
40 /// Configuration values for initial hash set sizes (log2).
42 static const unsigned InitDiesSetSize = 9; // log2(512)
43 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
44 static const unsigned InitValuesSetSize = 9; // log2(512)
48 //===----------------------------------------------------------------------===//
49 /// CompileUnit - This dwarf writer support class manages information associate
50 /// with a source file.
51 class VISIBILITY_HIDDEN CompileUnit {
52 /// ID - File identifier for source.
56 /// Die - Compile unit debug information entry.
60 /// GVToDieMap - Tracks the mapping of unit level debug informaton
61 /// variables to debug information entries.
62 /// FIXME : Rename GVToDieMap -> NodeToDieMap
63 std::map<MDNode *, DIE *> GVToDieMap;
65 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
66 /// descriptors to debug information entries using a DIEEntry proxy.
68 std::map<MDNode *, DIEEntry *> GVToDIEEntryMap;
70 /// Globals - A map of globally visible named entities for this unit.
72 StringMap<DIE*> Globals;
74 /// DiesSet - Used to uniquely define dies within the compile unit.
76 FoldingSet<DIE> DiesSet;
78 CompileUnit(unsigned I, DIE *D)
79 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
80 ~CompileUnit() { delete Die; }
83 unsigned getID() const { return ID; }
84 DIE* getDie() const { return Die; }
85 StringMap<DIE*> &getGlobals() { return Globals; }
87 /// hasContent - Return true if this compile unit has something to write out.
89 bool hasContent() const { return !Die->getChildren().empty(); }
91 /// AddGlobal - Add a new global entity to the compile unit.
93 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
95 /// getDieMapSlotFor - Returns the debug information entry map slot for the
96 /// specified debug variable.
97 DIE *&getDieMapSlotFor(MDNode *N) { return GVToDieMap[N]; }
99 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
100 /// the specified debug variable.
101 DIEEntry *&getDIEEntrySlotFor(MDNode *N) {
102 return GVToDIEEntryMap[N];
105 /// AddDie - Adds or interns the DIE to the compile unit.
107 DIE *AddDie(DIE &Buffer) {
111 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
114 Die = new DIE(Buffer);
115 DiesSet.InsertNode(Die, Where);
116 this->Die->AddChild(Die);
124 //===----------------------------------------------------------------------===//
125 /// DbgVariable - This class is used to track local variable information.
127 class VISIBILITY_HIDDEN DbgVariable {
128 DIVariable Var; // Variable Descriptor.
129 unsigned FrameIndex; // Variable frame index.
130 bool InlinedFnVar; // Variable for an inlined function.
132 DbgVariable(DIVariable V, unsigned I, bool IFV)
133 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
136 DIVariable getVariable() const { return Var; }
137 unsigned getFrameIndex() const { return FrameIndex; }
138 bool isInlinedFnVar() const { return InlinedFnVar; }
141 //===----------------------------------------------------------------------===//
142 /// DbgScope - This class is used to track scope information.
144 class DbgConcreteScope;
145 class VISIBILITY_HIDDEN DbgScope {
146 DbgScope *Parent; // Parent to this scope.
147 DIDescriptor Desc; // Debug info descriptor for scope.
148 // Either subprogram or block.
149 unsigned StartLabelID; // Label ID of the beginning of scope.
150 unsigned EndLabelID; // Label ID of the end of scope.
151 const MachineInstr *LastInsn; // Last instruction of this scope.
152 const MachineInstr *FirstInsn; // First instruction of this scope.
153 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
154 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
155 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
157 // Private state for dump()
158 mutable unsigned IndentLevel;
160 DbgScope(DbgScope *P, DIDescriptor D)
161 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), LastInsn(0),
162 FirstInsn(0), IndentLevel(0) {}
166 DbgScope *getParent() const { return Parent; }
167 DIDescriptor getDesc() const { return Desc; }
168 unsigned getStartLabelID() const { return StartLabelID; }
169 unsigned getEndLabelID() const { return EndLabelID; }
170 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
171 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
172 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
173 void setStartLabelID(unsigned S) { StartLabelID = S; }
174 void setEndLabelID(unsigned E) { EndLabelID = E; }
175 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
176 const MachineInstr *getLastInsn() { return LastInsn; }
177 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
178 const MachineInstr *getFirstInsn() { return FirstInsn; }
179 /// AddScope - Add a scope to the scope.
181 void AddScope(DbgScope *S) { Scopes.push_back(S); }
183 /// AddVariable - Add a variable to the scope.
185 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
187 /// AddConcreteInst - Add a concrete instance to the scope.
189 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
191 void FixInstructionMarkers() {
192 assert (getFirstInsn() && "First instruction is missing!");
196 // If a scope does not have an instruction to mark an end then use
197 // the end of last child scope.
198 SmallVector<DbgScope *, 4> &Scopes = getScopes();
199 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
200 DbgScope *L = Scopes.back();
201 if (!L->getLastInsn())
202 L->FixInstructionMarkers();
203 setLastInsn(L->getLastInsn());
212 void DbgScope::dump() const {
213 raw_ostream &err = errs();
214 err.indent(IndentLevel);
216 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
220 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
221 if (Scopes[i] != this)
228 //===----------------------------------------------------------------------===//
229 /// DbgConcreteScope - This class is used to track a scope that holds concrete
230 /// instance information.
232 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
234 DIE *Die; // Debug info for this concrete scope.
236 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
239 DIE *getDie() const { return Die; }
240 void setDie(DIE *D) { Die = D; }
243 DbgScope::~DbgScope() {
244 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
246 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
248 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
249 delete ConcreteInsts[k];
252 } // end llvm namespace
254 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
255 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
256 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
257 ValuesSet(InitValuesSetSize), Values(), StringPool(),
258 SectionSourceLines(), didInitial(false), shouldEmit(false),
259 FunctionDbgScope(0), DebugTimer(0) {
260 if (TimePassesIsEnabled)
261 DebugTimer = new Timer("Dwarf Debug Writer",
262 getDwarfTimerGroup());
264 DwarfDebug::~DwarfDebug() {
265 for (unsigned j = 0, M = Values.size(); j < M; ++j)
268 for (DenseMap<const MDNode *, DbgScope *>::iterator
269 I = AbstractInstanceRootMap.begin(),
270 E = AbstractInstanceRootMap.end(); I != E;++I)
276 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
278 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
279 // Profile the node so that we can make it unique.
283 // Check the set for priors.
284 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
286 // If it's newly added.
287 if (InSet == &Abbrev) {
288 // Add to abbreviation list.
289 Abbreviations.push_back(&Abbrev);
291 // Assign the vector position + 1 as its number.
292 Abbrev.setNumber(Abbreviations.size());
294 // Assign existing abbreviation number.
295 Abbrev.setNumber(InSet->getNumber());
299 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
300 /// information entry.
301 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
306 DIEEntry::Profile(ID, Entry);
308 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
310 if (Value) return Value;
312 Value = new DIEEntry(Entry);
313 ValuesSet.InsertNode(Value, Where);
315 Value = new DIEEntry(Entry);
318 Values.push_back(Value);
322 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
324 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
325 Value->setEntry(Entry);
327 // Add to values set if not already there. If it is, we merely have a
328 // duplicate in the values list (no harm.)
329 ValuesSet.GetOrInsertNode(Value);
332 /// AddUInt - Add an unsigned integer attribute data and value.
334 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
335 unsigned Form, uint64_t Integer) {
336 if (!Form) Form = DIEInteger::BestForm(false, Integer);
339 DIEInteger::Profile(ID, Integer);
341 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
344 Value = new DIEInteger(Integer);
345 ValuesSet.InsertNode(Value, Where);
346 Values.push_back(Value);
349 Die->AddValue(Attribute, Form, Value);
352 /// AddSInt - Add an signed integer attribute data and value.
354 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
355 unsigned Form, int64_t Integer) {
356 if (!Form) Form = DIEInteger::BestForm(true, Integer);
359 DIEInteger::Profile(ID, (uint64_t)Integer);
361 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
364 Value = new DIEInteger(Integer);
365 ValuesSet.InsertNode(Value, Where);
366 Values.push_back(Value);
369 Die->AddValue(Attribute, Form, Value);
372 /// AddString - Add a string attribute data and value.
374 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
375 const std::string &String) {
377 DIEString::Profile(ID, String);
379 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
382 Value = new DIEString(String);
383 ValuesSet.InsertNode(Value, Where);
384 Values.push_back(Value);
387 Die->AddValue(Attribute, Form, Value);
390 /// AddLabel - Add a Dwarf label attribute data and value.
392 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
393 const DWLabel &Label) {
395 DIEDwarfLabel::Profile(ID, Label);
397 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
400 Value = new DIEDwarfLabel(Label);
401 ValuesSet.InsertNode(Value, Where);
402 Values.push_back(Value);
405 Die->AddValue(Attribute, Form, Value);
408 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
410 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
411 const std::string &Label) {
413 DIEObjectLabel::Profile(ID, Label);
415 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
418 Value = new DIEObjectLabel(Label);
419 ValuesSet.InsertNode(Value, Where);
420 Values.push_back(Value);
423 Die->AddValue(Attribute, Form, Value);
426 /// AddSectionOffset - Add a section offset label attribute data and value.
428 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
429 const DWLabel &Label, const DWLabel &Section,
430 bool isEH, bool useSet) {
432 DIESectionOffset::Profile(ID, Label, Section);
434 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
437 Value = new DIESectionOffset(Label, Section, isEH, useSet);
438 ValuesSet.InsertNode(Value, Where);
439 Values.push_back(Value);
442 Die->AddValue(Attribute, Form, Value);
445 /// AddDelta - Add a label delta attribute data and value.
447 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
448 const DWLabel &Hi, const DWLabel &Lo) {
450 DIEDelta::Profile(ID, Hi, Lo);
452 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
455 Value = new DIEDelta(Hi, Lo);
456 ValuesSet.InsertNode(Value, Where);
457 Values.push_back(Value);
460 Die->AddValue(Attribute, Form, Value);
463 /// AddBlock - Add block data.
465 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
467 Block->ComputeSize(TD);
471 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
475 ValuesSet.InsertNode(Value, Where);
476 Values.push_back(Value);
478 // Already exists, reuse the previous one.
480 Block = cast<DIEBlock>(Value);
483 Die->AddValue(Attribute, Block->BestForm(), Value);
486 /// AddSourceLine - Add location information to specified debug information
488 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
489 // If there is no compile unit specified, don't add a line #.
490 if (V->getCompileUnit().isNull())
493 unsigned Line = V->getLineNumber();
494 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
495 assert(FileID && "Invalid file id");
496 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
497 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
500 /// AddSourceLine - Add location information to specified debug information
502 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
503 // If there is no compile unit specified, don't add a line #.
504 if (G->getCompileUnit().isNull())
507 unsigned Line = G->getLineNumber();
508 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
509 assert(FileID && "Invalid file id");
510 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
511 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
514 /// AddSourceLine - Add location information to specified debug information
516 void DwarfDebug::AddSourceLine(DIE *Die, const DISubprogram *SP) {
517 // If there is no compile unit specified, don't add a line #.
518 if (SP->getCompileUnit().isNull())
520 // If the line number is 0, don't add it.
521 if (SP->getLineNumber() == 0)
525 unsigned Line = SP->getLineNumber();
526 unsigned FileID = FindCompileUnit(SP->getCompileUnit()).getID();
527 assert(FileID && "Invalid file id");
528 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
529 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
532 /// AddSourceLine - Add location information to specified debug information
534 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
535 // If there is no compile unit specified, don't add a line #.
536 DICompileUnit CU = Ty->getCompileUnit();
540 unsigned Line = Ty->getLineNumber();
541 unsigned FileID = FindCompileUnit(CU).getID();
542 assert(FileID && "Invalid file id");
543 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
544 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
547 /* Byref variables, in Blocks, are declared by the programmer as
548 "SomeType VarName;", but the compiler creates a
549 __Block_byref_x_VarName struct, and gives the variable VarName
550 either the struct, or a pointer to the struct, as its type. This
551 is necessary for various behind-the-scenes things the compiler
552 needs to do with by-reference variables in blocks.
554 However, as far as the original *programmer* is concerned, the
555 variable should still have type 'SomeType', as originally declared.
557 The following function dives into the __Block_byref_x_VarName
558 struct to find the original type of the variable. This will be
559 passed back to the code generating the type for the Debug
560 Information Entry for the variable 'VarName'. 'VarName' will then
561 have the original type 'SomeType' in its debug information.
563 The original type 'SomeType' will be the type of the field named
564 'VarName' inside the __Block_byref_x_VarName struct.
566 NOTE: In order for this to not completely fail on the debugger
567 side, the Debug Information Entry for the variable VarName needs to
568 have a DW_AT_location that tells the debugger how to unwind through
569 the pointers and __Block_byref_x_VarName struct to find the actual
570 value of the variable. The function AddBlockByrefType does this. */
572 /// Find the type the programmer originally declared the variable to be
573 /// and return that type.
575 DIType DwarfDebug::GetBlockByrefType(DIType Ty, std::string Name) {
578 unsigned tag = Ty.getTag();
580 if (tag == dwarf::DW_TAG_pointer_type) {
581 DIDerivedType DTy = DIDerivedType(Ty.getNode());
582 subType = DTy.getTypeDerivedFrom();
585 DICompositeType blockStruct = DICompositeType(subType.getNode());
587 DIArray Elements = blockStruct.getTypeArray();
589 if (Elements.isNull())
592 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
593 DIDescriptor Element = Elements.getElement(i);
594 DIDerivedType DT = DIDerivedType(Element.getNode());
595 if (strcmp(Name.c_str(), DT.getName()) == 0)
596 return (DT.getTypeDerivedFrom());
602 /// AddComplexAddress - Start with the address based on the location provided,
603 /// and generate the DWARF information necessary to find the actual variable
604 /// given the extra address information encoded in the DIVariable, starting from
605 /// the starting location. Add the DWARF information to the die.
607 void DwarfDebug::AddComplexAddress(DbgVariable *&DV, DIE *Die,
609 const MachineLocation &Location) {
610 const DIVariable &VD = DV->getVariable();
611 DIType Ty = VD.getType();
613 // Decode the original location, and use that as the start of the byref
614 // variable's location.
615 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
616 DIEBlock *Block = new DIEBlock();
618 if (Location.isReg()) {
620 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
622 Reg = Reg - dwarf::DW_OP_reg0;
623 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
624 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
628 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
630 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
631 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
634 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
637 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
638 uint64_t Element = VD.getAddrElement(i);
640 if (Element == DIFactory::OpPlus) {
641 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
642 AddUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
643 } else if (Element == DIFactory::OpDeref) {
644 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
645 } else llvm_unreachable("unknown DIFactory Opcode");
648 // Now attach the location information to the DIE.
649 AddBlock(Die, Attribute, 0, Block);
652 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
653 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
654 gives the variable VarName either the struct, or a pointer to the struct, as
655 its type. This is necessary for various behind-the-scenes things the
656 compiler needs to do with by-reference variables in Blocks.
658 However, as far as the original *programmer* is concerned, the variable
659 should still have type 'SomeType', as originally declared.
661 The function GetBlockByrefType dives into the __Block_byref_x_VarName
662 struct to find the original type of the variable, which is then assigned to
663 the variable's Debug Information Entry as its real type. So far, so good.
664 However now the debugger will expect the variable VarName to have the type
665 SomeType. So we need the location attribute for the variable to be an
666 expression that explains to the debugger how to navigate through the
667 pointers and struct to find the actual variable of type SomeType.
669 The following function does just that. We start by getting
670 the "normal" location for the variable. This will be the location
671 of either the struct __Block_byref_x_VarName or the pointer to the
672 struct __Block_byref_x_VarName.
674 The struct will look something like:
676 struct __Block_byref_x_VarName {
678 struct __Block_byref_x_VarName *forwarding;
679 ... <various other fields>
681 ... <maybe more fields>
684 If we are given the struct directly (as our starting point) we
685 need to tell the debugger to:
687 1). Add the offset of the forwarding field.
689 2). Follow that pointer to get the the real __Block_byref_x_VarName
690 struct to use (the real one may have been copied onto the heap).
692 3). Add the offset for the field VarName, to find the actual variable.
694 If we started with a pointer to the struct, then we need to
695 dereference that pointer first, before the other steps.
696 Translating this into DWARF ops, we will need to append the following
697 to the current location description for the variable:
699 DW_OP_deref -- optional, if we start with a pointer
700 DW_OP_plus_uconst <forward_fld_offset>
702 DW_OP_plus_uconst <varName_fld_offset>
704 That is what this function does. */
706 /// AddBlockByrefAddress - Start with the address based on the location
707 /// provided, and generate the DWARF information necessary to find the
708 /// actual Block variable (navigating the Block struct) based on the
709 /// starting location. Add the DWARF information to the die. For
710 /// more information, read large comment just above here.
712 void DwarfDebug::AddBlockByrefAddress(DbgVariable *&DV, DIE *Die,
714 const MachineLocation &Location) {
715 const DIVariable &VD = DV->getVariable();
716 DIType Ty = VD.getType();
718 unsigned Tag = Ty.getTag();
719 bool isPointer = false;
721 const char *varName = VD.getName();
723 if (Tag == dwarf::DW_TAG_pointer_type) {
724 DIDerivedType DTy = DIDerivedType(Ty.getNode());
725 TmpTy = DTy.getTypeDerivedFrom();
729 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
731 // Find the __forwarding field and the variable field in the __Block_byref
733 DIArray Fields = blockStruct.getTypeArray();
734 DIDescriptor varField = DIDescriptor();
735 DIDescriptor forwardingField = DIDescriptor();
738 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
739 DIDescriptor Element = Fields.getElement(i);
740 DIDerivedType DT = DIDerivedType(Element.getNode());
741 const char *fieldName = DT.getName();
742 if (strcmp(fieldName, "__forwarding") == 0)
743 forwardingField = Element;
744 else if (strcmp(fieldName, varName) == 0)
748 assert(!varField.isNull() && "Can't find byref variable in Block struct");
749 assert(!forwardingField.isNull()
750 && "Can't find forwarding field in Block struct");
752 // Get the offsets for the forwarding field and the variable field.
753 unsigned int forwardingFieldOffset =
754 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
755 unsigned int varFieldOffset =
756 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
758 // Decode the original location, and use that as the start of the byref
759 // variable's location.
760 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
761 DIEBlock *Block = new DIEBlock();
763 if (Location.isReg()) {
765 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
767 Reg = Reg - dwarf::DW_OP_reg0;
768 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
769 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
773 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
775 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
776 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
779 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
782 // If we started with a pointer to the __Block_byref... struct, then
783 // the first thing we need to do is dereference the pointer (DW_OP_deref).
785 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
787 // Next add the offset for the '__forwarding' field:
788 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
789 // adding the offset if it's 0.
790 if (forwardingFieldOffset > 0) {
791 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
792 AddUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
795 // Now dereference the __forwarding field to get to the real __Block_byref
796 // struct: DW_OP_deref.
797 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
799 // Now that we've got the real __Block_byref... struct, add the offset
800 // for the variable's field to get to the location of the actual variable:
801 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
802 if (varFieldOffset > 0) {
803 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
804 AddUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
807 // Now attach the location information to the DIE.
808 AddBlock(Die, Attribute, 0, Block);
811 /// AddAddress - Add an address attribute to a die based on the location
813 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
814 const MachineLocation &Location) {
815 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
816 DIEBlock *Block = new DIEBlock();
818 if (Location.isReg()) {
820 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
822 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
823 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
827 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
829 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
830 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
833 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
836 AddBlock(Die, Attribute, 0, Block);
839 /// AddType - Add a new type attribute to the specified entity.
840 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
844 // Check for pre-existence.
845 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getNode());
847 // If it exists then use the existing value.
849 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
854 Slot = CreateDIEEntry();
857 DIE Buffer(dwarf::DW_TAG_base_type);
858 if (Ty.isBasicType())
859 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getNode()));
860 else if (Ty.isCompositeType())
861 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getNode()));
863 assert(Ty.isDerivedType() && "Unknown kind of DIType");
864 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getNode()));
867 // Add debug information entry to entity and appropriate context.
869 DIDescriptor Context = Ty.getContext();
870 if (!Context.isNull())
871 Die = DW_Unit->getDieMapSlotFor(Context.getNode());
874 DIE *Child = new DIE(Buffer);
875 Die->AddChild(Child);
877 SetDIEEntry(Slot, Child);
879 Die = DW_Unit->AddDie(Buffer);
880 SetDIEEntry(Slot, Die);
883 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
886 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
887 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
889 // Get core information.
890 const char *Name = BTy.getName();
891 Buffer.setTag(dwarf::DW_TAG_base_type);
892 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
895 // Add name if not anonymous or intermediate type.
897 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
898 uint64_t Size = BTy.getSizeInBits() >> 3;
899 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
902 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
903 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
905 // Get core information.
906 const char *Name = DTy.getName();
907 uint64_t Size = DTy.getSizeInBits() >> 3;
908 unsigned Tag = DTy.getTag();
910 // FIXME - Workaround for templates.
911 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
915 // Map to main type, void will not have a type.
916 DIType FromTy = DTy.getTypeDerivedFrom();
917 AddType(DW_Unit, &Buffer, FromTy);
919 // Add name if not anonymous or intermediate type.
921 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
923 // Add size if non-zero (derived types might be zero-sized.)
925 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
927 // Add source line info if available and TyDesc is not a forward declaration.
928 if (!DTy.isForwardDecl())
929 AddSourceLine(&Buffer, &DTy);
932 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
933 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
934 DICompositeType CTy) {
935 // Get core information.
936 const char *Name = CTy.getName();
938 uint64_t Size = CTy.getSizeInBits() >> 3;
939 unsigned Tag = CTy.getTag();
943 case dwarf::DW_TAG_vector_type:
944 case dwarf::DW_TAG_array_type:
945 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
947 case dwarf::DW_TAG_enumeration_type: {
948 DIArray Elements = CTy.getTypeArray();
950 // Add enumerators to enumeration type.
951 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
953 DIEnumerator Enum(Elements.getElement(i).getNode());
954 if (!Enum.isNull()) {
955 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
956 Buffer.AddChild(ElemDie);
961 case dwarf::DW_TAG_subroutine_type: {
963 DIArray Elements = CTy.getTypeArray();
964 DIDescriptor RTy = Elements.getElement(0);
965 AddType(DW_Unit, &Buffer, DIType(RTy.getNode()));
967 // Add prototype flag.
968 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
971 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
972 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
973 DIDescriptor Ty = Elements.getElement(i);
974 AddType(DW_Unit, Arg, DIType(Ty.getNode()));
975 Buffer.AddChild(Arg);
979 case dwarf::DW_TAG_structure_type:
980 case dwarf::DW_TAG_union_type:
981 case dwarf::DW_TAG_class_type: {
982 // Add elements to structure type.
983 DIArray Elements = CTy.getTypeArray();
985 // A forward struct declared type may not have elements available.
986 if (Elements.isNull())
989 // Add elements to structure type.
990 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
991 DIDescriptor Element = Elements.getElement(i);
992 if (Element.isNull())
995 if (Element.getTag() == dwarf::DW_TAG_subprogram)
996 ElemDie = CreateSubprogramDIE(DW_Unit,
997 DISubprogram(Element.getNode()));
999 ElemDie = CreateMemberDIE(DW_Unit,
1000 DIDerivedType(Element.getNode()));
1001 Buffer.AddChild(ElemDie);
1004 if (CTy.isAppleBlockExtension())
1005 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1007 unsigned RLang = CTy.getRunTimeLang();
1009 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1010 dwarf::DW_FORM_data1, RLang);
1017 // Add name if not anonymous or intermediate type.
1019 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1021 if (Tag == dwarf::DW_TAG_enumeration_type ||
1022 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1023 // Add size if non-zero (derived types might be zero-sized.)
1025 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1027 // Add zero size if it is not a forward declaration.
1028 if (CTy.isForwardDecl())
1029 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1031 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1034 // Add source line info if available.
1035 if (!CTy.isForwardDecl())
1036 AddSourceLine(&Buffer, &CTy);
1040 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1041 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1042 int64_t L = SR.getLo();
1043 int64_t H = SR.getHi();
1044 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1046 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1048 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1050 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1052 Buffer.AddChild(DW_Subrange);
1055 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1056 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1057 DICompositeType *CTy) {
1058 Buffer.setTag(dwarf::DW_TAG_array_type);
1059 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1060 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1062 // Emit derived type.
1063 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1064 DIArray Elements = CTy->getTypeArray();
1066 // Construct an anonymous type for index type.
1067 DIE IdxBuffer(dwarf::DW_TAG_base_type);
1068 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1069 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1070 dwarf::DW_ATE_signed);
1071 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1073 // Add subranges to array type.
1074 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1075 DIDescriptor Element = Elements.getElement(i);
1076 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1077 ConstructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IndexTy);
1081 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1082 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1083 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1084 const char *Name = ETy->getName();
1085 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1086 int64_t Value = ETy->getEnumValue();
1087 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1091 /// CreateGlobalVariableDIE - Create new DIE using GV.
1092 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
1093 const DIGlobalVariable &GV) {
1094 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1095 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1096 GV.getDisplayName());
1098 const char *LinkageName = GV.getLinkageName();
1100 // Skip special LLVM prefix that is used to inform the asm printer to not
1101 // emit usual symbol prefix before the symbol name. This happens for
1102 // Objective-C symbol names and symbol whose name is replaced using GCC's
1103 // __asm__ attribute.
1104 if (LinkageName[0] == 1)
1105 LinkageName = &LinkageName[1];
1106 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1109 AddType(DW_Unit, GVDie, GV.getType());
1110 if (!GV.isLocalToUnit())
1111 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1112 AddSourceLine(GVDie, &GV);
1115 DIEBlock *Block = new DIEBlock();
1116 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1117 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1118 Asm->Mang->getMangledName(GV.getGlobal()));
1119 AddBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1124 /// CreateMemberDIE - Create new member DIE.
1125 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1126 DIE *MemberDie = new DIE(DT.getTag());
1127 if (const char *Name = DT.getName())
1128 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1130 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1132 AddSourceLine(MemberDie, &DT);
1134 uint64_t Size = DT.getSizeInBits();
1135 uint64_t FieldSize = DT.getOriginalTypeSize();
1137 if (Size != FieldSize) {
1139 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1140 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1142 uint64_t Offset = DT.getOffsetInBits();
1143 uint64_t FieldOffset = Offset;
1144 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1145 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1146 FieldOffset = (HiMark - FieldSize);
1147 Offset -= FieldOffset;
1149 // Maybe we need to work from the other end.
1150 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1151 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1154 DIEBlock *Block = new DIEBlock();
1155 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1156 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1157 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
1159 if (DT.isProtected())
1160 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1161 dwarf::DW_ACCESS_protected);
1162 else if (DT.isPrivate())
1163 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1164 dwarf::DW_ACCESS_private);
1169 /// CreateSubprogramDIE - Create new DIE using SP.
1170 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
1171 const DISubprogram &SP,
1174 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1176 const char * Name = SP.getName();
1177 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1179 const char *LinkageName = SP.getLinkageName();
1181 // Skip special LLVM prefix that is used to inform the asm printer to not emit
1182 // usual symbol prefix before the symbol name. This happens for Objective-C
1183 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
1184 if (LinkageName[0] == 1)
1185 LinkageName = &LinkageName[1];
1186 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1189 AddSourceLine(SPDie, &SP);
1191 DICompositeType SPTy = SP.getType();
1192 DIArray Args = SPTy.getTypeArray();
1194 // Add prototyped tag, if C or ObjC.
1195 unsigned Lang = SP.getCompileUnit().getLanguage();
1196 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1197 Lang == dwarf::DW_LANG_ObjC)
1198 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1201 unsigned SPTag = SPTy.getTag();
1202 if (!IsConstructor) {
1203 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1204 AddType(DW_Unit, SPDie, SPTy);
1206 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1209 if (!SP.isDefinition()) {
1210 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1212 // Add arguments. Do not add arguments for subprogram definition. They will
1213 // be handled through RecordVariable.
1214 if (SPTag == dwarf::DW_TAG_subroutine_type)
1215 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1216 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1217 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1218 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1219 SPDie->AddChild(Arg);
1223 if (!SP.isLocalToUnit() && !IsInlined)
1224 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1226 // DW_TAG_inlined_subroutine may refer to this DIE.
1227 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getNode());
1232 /// FindCompileUnit - Get the compile unit for the given descriptor.
1234 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
1235 DenseMap<Value *, CompileUnit *>::const_iterator I =
1236 CompileUnitMap.find(Unit.getNode());
1237 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1241 /// CreateDbgScopeVariable - Create a new scope variable.
1243 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1244 // Get the descriptor.
1245 const DIVariable &VD = DV->getVariable();
1247 // Translate tag to proper Dwarf tag. The result variable is dropped for
1250 switch (VD.getTag()) {
1251 case dwarf::DW_TAG_return_variable:
1253 case dwarf::DW_TAG_arg_variable:
1254 Tag = dwarf::DW_TAG_formal_parameter;
1256 case dwarf::DW_TAG_auto_variable: // fall thru
1258 Tag = dwarf::DW_TAG_variable;
1262 // Define variable debug information entry.
1263 DIE *VariableDie = new DIE(Tag);
1264 const char *Name = VD.getName();
1265 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1267 // Add source line info if available.
1268 AddSourceLine(VariableDie, &VD);
1270 // Add variable type.
1271 // FIXME: isBlockByrefVariable should be reformulated in terms of complex addresses instead.
1272 if (VD.isBlockByrefVariable())
1273 AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1275 AddType(Unit, VariableDie, VD.getType());
1277 // Add variable address.
1278 if (!DV->isInlinedFnVar()) {
1279 // Variables for abstract instances of inlined functions don't get a
1281 MachineLocation Location;
1282 Location.set(RI->getFrameRegister(*MF),
1283 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1286 if (VD.hasComplexAddress())
1287 AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1288 else if (VD.isBlockByrefVariable())
1289 AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1291 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1297 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1299 DbgScope *DwarfDebug::getDbgScope(MDNode *N, const MachineInstr *MI) {
1300 DbgScope *&Slot = DbgScopeMap[N];
1301 if (Slot) return Slot;
1303 DbgScope *Parent = NULL;
1305 DIDescriptor Scope(N);
1306 if (Scope.isCompileUnit()) {
1308 } else if (Scope.isSubprogram()) {
1310 DIDescriptor ParentDesc = SP.getContext();
1311 if (!ParentDesc.isNull() && !ParentDesc.isCompileUnit())
1312 Parent = getDbgScope(ParentDesc.getNode(), MI);
1313 } else if (Scope.isLexicalBlock()) {
1314 DILexicalBlock DB(N);
1315 DIDescriptor ParentDesc = DB.getContext();
1316 if (!ParentDesc.isNull())
1317 Parent = getDbgScope(ParentDesc.getNode(), MI);
1319 assert (0 && "Unexpected scope info");
1321 Slot = new DbgScope(Parent, DIDescriptor(N));
1322 Slot->setFirstInsn(MI);
1325 Parent->AddScope(Slot);
1327 // First function is top level function.
1328 if (!FunctionDbgScope)
1329 FunctionDbgScope = Slot;
1335 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1336 /// FIXME - Remove this method.
1337 DbgScope *DwarfDebug::getOrCreateScope(MDNode *N) {
1338 DbgScope *&Slot = DbgScopeMap[N];
1339 if (Slot) return Slot;
1341 DbgScope *Parent = NULL;
1342 DILexicalBlock Block(N);
1344 // Don't create a new scope if we already created one for an inlined function.
1345 DenseMap<const MDNode *, DbgScope *>::iterator
1346 II = AbstractInstanceRootMap.find(N);
1347 if (II != AbstractInstanceRootMap.end())
1348 return LexicalScopeStack.back();
1350 if (!Block.isNull()) {
1351 DIDescriptor ParentDesc = Block.getContext();
1353 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getNode());
1356 Slot = new DbgScope(Parent, DIDescriptor(N));
1359 Parent->AddScope(Slot);
1361 // First function is top level function.
1362 FunctionDbgScope = Slot;
1367 /// ConstructDbgScope - Construct the components of a scope.
1369 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1370 unsigned ParentStartID,
1371 unsigned ParentEndID,
1372 DIE *ParentDie, CompileUnit *Unit) {
1373 // Add variables to scope.
1374 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1375 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1376 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
1377 if (VariableDie) ParentDie->AddChild(VariableDie);
1380 // Add concrete instances to scope.
1381 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1382 ParentScope->getConcreteInsts();
1383 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1384 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1385 DIE *Die = ConcreteInst->getDie();
1387 unsigned StartID = ConcreteInst->getStartLabelID();
1388 unsigned EndID = ConcreteInst->getEndLabelID();
1390 // Add the scope bounds.
1392 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1393 DWLabel("label", StartID));
1395 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1396 DWLabel("func_begin", SubprogramCount));
1399 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1400 DWLabel("label", EndID));
1402 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1403 DWLabel("func_end", SubprogramCount));
1405 ParentDie->AddChild(Die);
1408 // Add nested scopes.
1409 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1410 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1411 // Define the Scope debug information entry.
1412 DbgScope *Scope = Scopes[j];
1414 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1415 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1417 // Ignore empty scopes.
1418 if (StartID == EndID && StartID != 0) continue;
1420 // Do not ignore inlined scopes even if they don't have any variables or
1422 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1423 Scope->getConcreteInsts().empty())
1426 if (StartID == ParentStartID && EndID == ParentEndID) {
1427 // Just add stuff to the parent scope.
1428 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1430 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1432 // Add the scope bounds.
1434 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1435 DWLabel("label", StartID));
1437 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1438 DWLabel("func_begin", SubprogramCount));
1441 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1442 DWLabel("label", EndID));
1444 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1445 DWLabel("func_end", SubprogramCount));
1447 // Add the scope's contents.
1448 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1449 ParentDie->AddChild(ScopeDie);
1454 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1456 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1457 bool AbstractScope) {
1458 // Exit if there is no root scope.
1459 if (!RootScope) return;
1460 DIDescriptor Desc = RootScope->getDesc();
1464 // Get the subprogram debug information entry.
1465 DISubprogram SPD(Desc.getNode());
1467 // Get the subprogram die.
1468 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getNode());
1470 ConstructSubprogram(SPD.getNode());
1471 SPDie = ModuleCU->getDieMapSlotFor(SPD.getNode());
1473 assert(SPDie && "Missing subprogram descriptor");
1475 if (!AbstractScope) {
1476 // Add the function bounds.
1477 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1478 DWLabel("func_begin", SubprogramCount));
1479 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1480 DWLabel("func_end", SubprogramCount));
1481 MachineLocation Location(RI->getFrameRegister(*MF));
1482 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1485 ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
1486 // If there are global variables at this scope then add their dies.
1487 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1488 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1489 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1491 DIGlobalVariable GV(N);
1492 if (GV.getContext().getNode() == RootScope->getDesc().getNode()) {
1493 DIE *ScopedGVDie = CreateGlobalVariableDIE(ModuleCU, GV);
1494 SPDie->AddChild(ScopedGVDie);
1499 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1501 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1502 StringMap<DIE*> &Globals = ModuleCU->getGlobals();
1503 StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
1504 if (GI != Globals.end()) {
1505 DIE *SPDie = GI->second;
1507 // Add the function bounds.
1508 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1509 DWLabel("func_begin", SubprogramCount));
1510 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1511 DWLabel("func_end", SubprogramCount));
1513 MachineLocation Location(RI->getFrameRegister(*MF));
1514 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1518 /// GetOrCreateSourceID - Look up the source id with the given directory and
1519 /// source file names. If none currently exists, create a new id and insert it
1520 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1522 unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1523 const char *FileName) {
1525 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1526 if (DI != DirectoryIdMap.end()) {
1527 DId = DI->getValue();
1529 DId = DirectoryNames.size() + 1;
1530 DirectoryIdMap[DirName] = DId;
1531 DirectoryNames.push_back(DirName);
1535 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1536 if (FI != SourceFileIdMap.end()) {
1537 FId = FI->getValue();
1539 FId = SourceFileNames.size() + 1;
1540 SourceFileIdMap[FileName] = FId;
1541 SourceFileNames.push_back(FileName);
1544 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1545 SourceIdMap.find(std::make_pair(DId, FId));
1546 if (SI != SourceIdMap.end())
1549 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1550 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1551 SourceIds.push_back(std::make_pair(DId, FId));
1556 void DwarfDebug::ConstructCompileUnit(MDNode *N) {
1557 DICompileUnit DIUnit(N);
1558 const char *FN = DIUnit.getFilename();
1559 const char *Dir = DIUnit.getDirectory();
1560 unsigned ID = GetOrCreateSourceID(Dir, FN);
1562 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1563 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1564 DWLabel("section_line", 0), DWLabel("section_line", 0),
1566 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1567 DIUnit.getProducer());
1568 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1569 DIUnit.getLanguage());
1570 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1573 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1574 if (DIUnit.isOptimized())
1575 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1577 if (const char *Flags = DIUnit.getFlags())
1578 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1580 unsigned RVer = DIUnit.getRunTimeVersion();
1582 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1583 dwarf::DW_FORM_data1, RVer);
1585 CompileUnit *Unit = new CompileUnit(ID, Die);
1586 if (!ModuleCU && DIUnit.isMain()) {
1587 // Use first compile unit marked as isMain as the compile unit
1592 CompileUnitMap[DIUnit.getNode()] = Unit;
1593 CompileUnits.push_back(Unit);
1596 void DwarfDebug::ConstructGlobalVariableDIE(MDNode *N) {
1597 DIGlobalVariable DI_GV(N);
1599 // If debug information is malformed then ignore it.
1600 if (DI_GV.Verify() == false)
1603 // Check for pre-existence.
1604 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getNode());
1608 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1613 // Add to context owner.
1614 ModuleCU->getDie()->AddChild(VariableDie);
1616 // Expose as global. FIXME - need to check external flag.
1617 ModuleCU->AddGlobal(DI_GV.getName(), VariableDie);
1621 void DwarfDebug::ConstructSubprogram(MDNode *N) {
1624 // Check for pre-existence.
1625 DIE *&Slot = ModuleCU->getDieMapSlotFor(N);
1629 if (!SP.isDefinition())
1630 // This is a method declaration which will be handled while constructing
1634 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1637 Slot = SubprogramDie;
1639 // Add to context owner.
1640 ModuleCU->getDie()->AddChild(SubprogramDie);
1642 // Expose as global.
1643 ModuleCU->AddGlobal(SP.getName(), SubprogramDie);
1647 /// BeginModule - Emit all Dwarf sections that should come prior to the
1648 /// content. Create global DIEs and emit initial debug info sections.
1649 /// This is inovked by the target AsmPrinter.
1650 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1653 if (TimePassesIsEnabled)
1654 DebugTimer->startTimer();
1656 DebugInfoFinder DbgFinder;
1657 DbgFinder.processModule(*M);
1659 // Create all the compile unit DIEs.
1660 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1661 E = DbgFinder.compile_unit_end(); I != E; ++I)
1662 ConstructCompileUnit(*I);
1664 if (CompileUnits.empty()) {
1665 if (TimePassesIsEnabled)
1666 DebugTimer->stopTimer();
1671 // If main compile unit for this module is not seen than randomly
1672 // select first compile unit.
1674 ModuleCU = CompileUnits[0];
1676 // Create DIEs for each of the externally visible global variables.
1677 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1678 E = DbgFinder.global_variable_end(); I != E; ++I) {
1679 DIGlobalVariable GV(*I);
1680 if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
1681 ScopedGVs.push_back(*I);
1683 ConstructGlobalVariableDIE(*I);
1686 // Create DIEs for each of the externally visible subprograms.
1687 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1688 E = DbgFinder.subprogram_end(); I != E; ++I)
1689 ConstructSubprogram(*I);
1693 MMI->setDebugInfoAvailability(true);
1695 // Prime section data.
1696 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1698 // Print out .file directives to specify files for .loc directives. These are
1699 // printed out early so that they precede any .loc directives.
1700 if (MAI->hasDotLocAndDotFile()) {
1701 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1702 // Remember source id starts at 1.
1703 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1704 sys::Path FullPath(getSourceDirectoryName(Id.first));
1706 FullPath.appendComponent(getSourceFileName(Id.second));
1707 assert(AppendOk && "Could not append filename to directory!");
1709 Asm->EmitFile(i, FullPath.str());
1714 // Emit initial sections
1717 if (TimePassesIsEnabled)
1718 DebugTimer->stopTimer();
1721 /// EndModule - Emit all Dwarf sections that should come after the content.
1723 void DwarfDebug::EndModule() {
1727 if (TimePassesIsEnabled)
1728 DebugTimer->startTimer();
1730 // Standard sections final addresses.
1731 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1732 EmitLabel("text_end", 0);
1733 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1734 EmitLabel("data_end", 0);
1736 // End text sections.
1737 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1738 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1739 EmitLabel("section_end", i);
1742 // Emit common frame information.
1743 EmitCommonDebugFrame();
1745 // Emit function debug frame information
1746 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1747 E = DebugFrames.end(); I != E; ++I)
1748 EmitFunctionDebugFrame(*I);
1750 // Compute DIE offsets and sizes.
1753 // Emit all the DIEs into a debug info section
1756 // Corresponding abbreviations into a abbrev section.
1757 EmitAbbreviations();
1759 // Emit source line correspondence into a debug line section.
1762 // Emit info into a debug pubnames section.
1763 EmitDebugPubNames();
1765 // Emit info into a debug str section.
1768 // Emit info into a debug loc section.
1771 // Emit info into a debug aranges section.
1774 // Emit info into a debug ranges section.
1777 // Emit info into a debug macinfo section.
1780 // Emit inline info.
1781 EmitDebugInlineInfo();
1783 if (TimePassesIsEnabled)
1784 DebugTimer->stopTimer();
1787 /// CollectVariableInfo - Populate DbgScope entries with variables' info.
1788 void DwarfDebug::CollectVariableInfo() {
1790 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1791 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1792 VE = VMap.end(); VI != VE; ++VI) {
1793 MetadataBase *MB = VI->first;
1794 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1795 DIVariable DV (Var);
1796 if (DV.isNull()) continue;
1797 unsigned VSlot = VI->second;
1798 DbgScope *Scope = getDbgScope(DV.getContext().getNode(), NULL);
1799 Scope->AddVariable(new DbgVariable(DV, VSlot, false));
1803 /// SetDbgScopeBeginLabels - Update DbgScope begin labels for the scopes that
1804 /// start with this machine instruction.
1805 void DwarfDebug::SetDbgScopeBeginLabels(const MachineInstr *MI, unsigned Label) {
1806 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1807 if (I == DbgScopeBeginMap.end())
1809 SmallVector<DbgScope *, 2> &SD = I->second;
1810 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1812 (*SDI)->setStartLabelID(Label);
1815 /// SetDbgScopeEndLabels - Update DbgScope end labels for the scopes that
1816 /// end with this machine instruction.
1817 void DwarfDebug::SetDbgScopeEndLabels(const MachineInstr *MI, unsigned Label) {
1818 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1819 if (I == DbgScopeEndMap.end())
1821 SmallVector<DbgScope *, 2> &SD = I->second;
1822 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1824 (*SDI)->setEndLabelID(Label);
1827 /// ExtractScopeInformation - Scan machine instructions in this function
1828 /// and collect DbgScopes. Return true, if atleast one scope was found.
1829 bool DwarfDebug::ExtractScopeInformation(MachineFunction *MF) {
1830 // If scope information was extracted using .dbg intrinsics then there is not
1831 // any need to extract these information by scanning each instruction.
1832 if (!DbgScopeMap.empty())
1835 // Scan each instruction and create scopes.
1836 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1838 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1840 const MachineInstr *MInsn = II;
1841 DebugLoc DL = MInsn->getDebugLoc();
1844 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1845 if (!DLT.CompileUnit)
1847 // There is no need to create another DIE for compile unit. For all
1848 // other scopes, create one DbgScope now. This will be translated
1849 // into a scope DIE at the end.
1850 DIDescriptor D(DLT.CompileUnit);
1851 if (!D.isCompileUnit()) {
1852 DbgScope *Scope = getDbgScope(DLT.CompileUnit, MInsn);
1853 Scope->setLastInsn(MInsn);
1858 // If a scope's last instruction is not set then use its child scope's
1859 // last instruction as this scope's last instrunction.
1860 for (DenseMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1861 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1862 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
1863 DI->second->FixInstructionMarkers();
1864 assert (DI->second->getLastInsn() && "Invalid last instruction!");
1867 // Each scope has first instruction and last instruction to mark beginning
1868 // and end of a scope respectively. Create an inverse map that list scopes
1869 // starts (and ends) with an instruction. One instruction may start (or end)
1871 for (DenseMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1872 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1873 DbgScope *S = DI->second;
1874 assert (S && "DbgScope is missing!");
1875 const MachineInstr *MI = S->getFirstInsn();
1876 assert (MI && "DbgScope does not have first instruction!");
1878 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
1879 if (IDI != DbgScopeBeginMap.end())
1880 IDI->second.push_back(S);
1882 DbgScopeBeginMap.insert(std::make_pair(MI,
1883 SmallVector<DbgScope *, 2>(2, S)));
1885 MI = S->getLastInsn();
1886 assert (MI && "DbgScope does not have last instruction!");
1887 IDI = DbgScopeEndMap.find(MI);
1888 if (IDI != DbgScopeEndMap.end())
1889 IDI->second.push_back(S);
1891 DbgScopeEndMap.insert(std::make_pair(MI,
1892 SmallVector<DbgScope *, 2>(2, S)));
1895 return !DbgScopeMap.empty();
1898 static DISubprogram getDISubprogram(MDNode *N) {
1902 return DISubprogram();
1904 if (D.isCompileUnit())
1905 return DISubprogram();
1907 if (D.isSubprogram())
1908 return DISubprogram(N);
1910 if (D.isLexicalBlock())
1911 return getDISubprogram(DILexicalBlock(N).getContext().getNode());
1913 llvm_unreachable("Unexpected Descriptor!");
1916 /// BeginFunction - Gather pre-function debug information. Assumes being
1917 /// emitted immediately after the function entry point.
1918 void DwarfDebug::BeginFunction(MachineFunction *MF) {
1921 if (!ShouldEmitDwarfDebug()) return;
1923 if (TimePassesIsEnabled)
1924 DebugTimer->startTimer();
1926 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1927 if (!ExtractScopeInformation(MF))
1929 CollectVariableInfo();
1932 // Begin accumulating function debug information.
1933 MMI->BeginFunction(MF);
1935 // Assumes in correct section after the entry point.
1936 EmitLabel("func_begin", ++SubprogramCount);
1938 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1940 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1941 DebugLoc FDL = MF->getDefaultDebugLoc();
1942 if (!FDL.isUnknown()) {
1943 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1944 unsigned LabelID = 0;
1945 DISubprogram SP = getDISubprogram(DLT.CompileUnit);
1947 LabelID = RecordSourceLine(SP.getLineNumber(), 0, DLT.CompileUnit);
1949 LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.CompileUnit);
1950 Asm->printLabel(LabelID);
1954 DebugLoc FDL = MF->getDefaultDebugLoc();
1955 if (!FDL.isUnknown()) {
1956 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1957 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.CompileUnit);
1958 Asm->printLabel(LabelID);
1962 if (TimePassesIsEnabled)
1963 DebugTimer->stopTimer();
1966 /// EndFunction - Gather and emit post-function debug information.
1968 void DwarfDebug::EndFunction(MachineFunction *MF) {
1969 if (!ShouldEmitDwarfDebug()) return;
1971 if (TimePassesIsEnabled)
1972 DebugTimer->startTimer();
1974 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1975 if (DbgScopeMap.empty())
1978 // Define end label for subprogram.
1979 EmitLabel("func_end", SubprogramCount);
1981 // Get function line info.
1982 if (!Lines.empty()) {
1983 // Get section line info.
1984 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
1985 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1986 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1987 // Append the function info to section info.
1988 SectionLineInfos.insert(SectionLineInfos.end(),
1989 Lines.begin(), Lines.end());
1992 // Construct the DbgScope for abstract instances.
1993 for (SmallVector<DbgScope *, 32>::iterator
1994 I = AbstractInstanceRootList.begin(),
1995 E = AbstractInstanceRootList.end(); I != E; ++I)
1996 ConstructFunctionDbgScope(*I);
1998 // Construct scopes for subprogram.
1999 if (FunctionDbgScope)
2000 ConstructFunctionDbgScope(FunctionDbgScope);
2002 // FIXME: This is wrong. We are essentially getting past a problem with
2003 // debug information not being able to handle unreachable blocks that have
2004 // debug information in them. In particular, those unreachable blocks that
2005 // have "region end" info in them. That situation results in the "root
2006 // scope" not being created. If that's the case, then emit a "default"
2007 // scope, i.e., one that encompasses the whole function. This isn't
2008 // desirable. And a better way of handling this (and all of the debugging
2009 // information) needs to be explored.
2010 ConstructDefaultDbgScope(MF);
2012 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2013 MMI->getFrameMoves()));
2016 if (FunctionDbgScope) {
2017 delete FunctionDbgScope;
2018 DbgScopeMap.clear();
2019 DbgScopeBeginMap.clear();
2020 DbgScopeEndMap.clear();
2021 DbgAbstractScopeMap.clear();
2022 DbgConcreteScopeMap.clear();
2023 FunctionDbgScope = NULL;
2024 LexicalScopeStack.clear();
2025 AbstractInstanceRootList.clear();
2026 AbstractInstanceRootMap.clear();
2031 if (TimePassesIsEnabled)
2032 DebugTimer->stopTimer();
2035 /// RecordSourceLine - Records location information and associates it with a
2036 /// label. Returns a unique label ID used to generate a label and provide
2037 /// correspondence to the source line list.
2038 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2043 if (TimePassesIsEnabled)
2044 DebugTimer->startTimer();
2046 const char *Dir = NULL;
2047 const char *Fn = NULL;
2049 DIDescriptor Scope(S);
2050 if (Scope.isCompileUnit()) {
2051 DICompileUnit CU(S);
2052 Dir = CU.getDirectory();
2053 Fn = CU.getFilename();
2054 } else if (Scope.isSubprogram()) {
2056 Dir = SP.getDirectory();
2057 Fn = SP.getFilename();
2058 } else if (Scope.isLexicalBlock()) {
2059 DILexicalBlock DB(S);
2060 Dir = DB.getDirectory();
2061 Fn = DB.getFilename();
2063 assert (0 && "Unexpected scope info");
2065 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2066 unsigned ID = MMI->NextLabelID();
2067 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2069 if (TimePassesIsEnabled)
2070 DebugTimer->stopTimer();
2075 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2076 /// timed. Look up the source id with the given directory and source file
2077 /// names. If none currently exists, create a new id and insert it in the
2078 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2080 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2081 const std::string &FileName) {
2082 if (TimePassesIsEnabled)
2083 DebugTimer->startTimer();
2085 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2087 if (TimePassesIsEnabled)
2088 DebugTimer->stopTimer();
2093 /// RecordRegionStart - Indicate the start of a region.
2094 unsigned DwarfDebug::RecordRegionStart(MDNode *N) {
2095 if (TimePassesIsEnabled)
2096 DebugTimer->startTimer();
2098 DbgScope *Scope = getOrCreateScope(N);
2099 unsigned ID = MMI->NextLabelID();
2100 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2101 LexicalScopeStack.push_back(Scope);
2103 if (TimePassesIsEnabled)
2104 DebugTimer->stopTimer();
2109 /// RecordRegionEnd - Indicate the end of a region.
2110 unsigned DwarfDebug::RecordRegionEnd(MDNode *N) {
2111 if (TimePassesIsEnabled)
2112 DebugTimer->startTimer();
2114 DbgScope *Scope = getOrCreateScope(N);
2115 unsigned ID = MMI->NextLabelID();
2116 Scope->setEndLabelID(ID);
2117 // FIXME : region.end() may not be in the last basic block.
2118 // For now, do not pop last lexical scope because next basic
2119 // block may start new inlined function's body.
2120 unsigned LSSize = LexicalScopeStack.size();
2121 if (LSSize != 0 && LSSize != 1)
2122 LexicalScopeStack.pop_back();
2124 if (TimePassesIsEnabled)
2125 DebugTimer->stopTimer();
2130 /// RecordVariable - Indicate the declaration of a local variable.
2131 void DwarfDebug::RecordVariable(MDNode *N, unsigned FrameIndex) {
2132 if (TimePassesIsEnabled)
2133 DebugTimer->startTimer();
2135 DIDescriptor Desc(N);
2136 DbgScope *Scope = NULL;
2137 bool InlinedFnVar = false;
2139 if (Desc.getTag() == dwarf::DW_TAG_variable)
2140 Scope = getOrCreateScope(DIGlobalVariable(N).getContext().getNode());
2142 bool InlinedVar = false;
2143 MDNode *Context = DIVariable(N).getContext().getNode();
2144 DISubprogram SP(Context);
2146 // SP is inserted into DbgAbstractScopeMap when inlined function
2147 // start was recorded by RecordInlineFnStart.
2148 DenseMap<MDNode *, DbgScope *>::iterator
2149 I = DbgAbstractScopeMap.find(SP.getNode());
2150 if (I != DbgAbstractScopeMap.end()) {
2156 Scope = getOrCreateScope(Context);
2159 assert(Scope && "Unable to find the variable's scope");
2160 DbgVariable *DV = new DbgVariable(DIVariable(N), FrameIndex, InlinedFnVar);
2161 Scope->AddVariable(DV);
2163 if (TimePassesIsEnabled)
2164 DebugTimer->stopTimer();
2167 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2168 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2169 unsigned Line, unsigned Col) {
2170 unsigned LabelID = MMI->NextLabelID();
2172 if (!MAI->doesDwarfUsesInlineInfoSection())
2175 if (TimePassesIsEnabled)
2176 DebugTimer->startTimer();
2178 MDNode *Node = SP.getNode();
2179 DenseMap<const MDNode *, DbgScope *>::iterator
2180 II = AbstractInstanceRootMap.find(Node);
2182 if (II == AbstractInstanceRootMap.end()) {
2183 // Create an abstract instance entry for this inlined function if it doesn't
2185 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(Node));
2187 // Get the compile unit context.
2188 DIE *SPDie = ModuleCU->getDieMapSlotFor(Node);
2190 SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
2192 // Mark as being inlined. This makes this subprogram entry an abstract
2194 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2195 // that it's defined. That probably won't change in the future. However,
2196 // this could be more elegant.
2197 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
2199 // Keep track of the abstract scope for this function.
2200 DbgAbstractScopeMap[Node] = Scope;
2202 AbstractInstanceRootMap[Node] = Scope;
2203 AbstractInstanceRootList.push_back(Scope);
2206 // Create a concrete inlined instance for this inlined function.
2207 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(Node));
2208 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
2209 ScopeDie->setAbstractCompileUnit(ModuleCU);
2211 DIE *Origin = ModuleCU->getDieMapSlotFor(Node);
2212 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
2213 dwarf::DW_FORM_ref4, Origin);
2214 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
2215 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
2216 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
2218 ConcreteScope->setDie(ScopeDie);
2219 ConcreteScope->setStartLabelID(LabelID);
2220 MMI->RecordUsedDbgLabel(LabelID);
2222 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2224 // Keep track of the concrete scope that's inlined into this function.
2225 DenseMap<MDNode *, SmallVector<DbgScope *, 8> >::iterator
2226 SI = DbgConcreteScopeMap.find(Node);
2228 if (SI == DbgConcreteScopeMap.end())
2229 DbgConcreteScopeMap[Node].push_back(ConcreteScope);
2231 SI->second.push_back(ConcreteScope);
2233 // Track the start label for this inlined function.
2234 DenseMap<MDNode *, SmallVector<unsigned, 4> >::iterator
2235 I = InlineInfo.find(Node);
2237 if (I == InlineInfo.end())
2238 InlineInfo[Node].push_back(LabelID);
2240 I->second.push_back(LabelID);
2242 if (TimePassesIsEnabled)
2243 DebugTimer->stopTimer();
2248 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2249 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2250 if (!MAI->doesDwarfUsesInlineInfoSection())
2253 if (TimePassesIsEnabled)
2254 DebugTimer->startTimer();
2256 MDNode *Node = SP.getNode();
2257 DenseMap<MDNode *, SmallVector<DbgScope *, 8> >::iterator
2258 I = DbgConcreteScopeMap.find(Node);
2260 if (I == DbgConcreteScopeMap.end()) {
2261 // FIXME: Can this situation actually happen? And if so, should it?
2262 if (TimePassesIsEnabled)
2263 DebugTimer->stopTimer();
2268 SmallVector<DbgScope *, 8> &Scopes = I->second;
2269 if (Scopes.empty()) {
2270 // Returned ID is 0 if this is unbalanced "end of inlined
2271 // scope". This could happen if optimizer eats dbg intrinsics
2272 // or "beginning of inlined scope" is not recoginized due to
2273 // missing location info. In such cases, ignore this region.end.
2277 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2278 unsigned ID = MMI->NextLabelID();
2279 MMI->RecordUsedDbgLabel(ID);
2280 Scope->setEndLabelID(ID);
2282 if (TimePassesIsEnabled)
2283 DebugTimer->stopTimer();
2288 //===----------------------------------------------------------------------===//
2290 //===----------------------------------------------------------------------===//
2292 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2294 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2295 // Get the children.
2296 const std::vector<DIE *> &Children = Die->getChildren();
2298 // If not last sibling and has children then add sibling offset attribute.
2299 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2301 // Record the abbreviation.
2302 AssignAbbrevNumber(Die->getAbbrev());
2304 // Get the abbreviation for this DIE.
2305 unsigned AbbrevNumber = Die->getAbbrevNumber();
2306 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2309 Die->setOffset(Offset);
2311 // Start the size with the size of abbreviation code.
2312 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2314 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2315 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2317 // Size the DIE attribute values.
2318 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2319 // Size attribute value.
2320 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2322 // Size the DIE children if any.
2323 if (!Children.empty()) {
2324 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2325 "Children flag not set");
2327 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2328 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2330 // End of children marker.
2331 Offset += sizeof(int8_t);
2334 Die->setSize(Offset - Die->getOffset());
2338 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2340 void DwarfDebug::SizeAndOffsets() {
2341 // Compute size of compile unit header.
2342 static unsigned Offset =
2343 sizeof(int32_t) + // Length of Compilation Unit Info
2344 sizeof(int16_t) + // DWARF version number
2345 sizeof(int32_t) + // Offset Into Abbrev. Section
2346 sizeof(int8_t); // Pointer Size (in bytes)
2348 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
2349 CompileUnitOffsets[ModuleCU] = 0;
2352 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2353 /// tools to recognize the object file contains Dwarf information.
2354 void DwarfDebug::EmitInitial() {
2355 // Check to see if we already emitted intial headers.
2356 if (didInitial) return;
2359 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2361 // Dwarf sections base addresses.
2362 if (MAI->doesDwarfRequireFrameSection()) {
2363 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2364 EmitLabel("section_debug_frame", 0);
2367 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2368 EmitLabel("section_info", 0);
2369 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2370 EmitLabel("section_abbrev", 0);
2371 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2372 EmitLabel("section_aranges", 0);
2374 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2375 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2376 EmitLabel("section_macinfo", 0);
2379 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2380 EmitLabel("section_line", 0);
2381 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2382 EmitLabel("section_loc", 0);
2383 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2384 EmitLabel("section_pubnames", 0);
2385 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2386 EmitLabel("section_str", 0);
2387 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2388 EmitLabel("section_ranges", 0);
2390 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2391 EmitLabel("text_begin", 0);
2392 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2393 EmitLabel("data_begin", 0);
2396 /// EmitDIE - Recusively Emits a debug information entry.
2398 void DwarfDebug::EmitDIE(DIE *Die) {
2399 // Get the abbreviation for this DIE.
2400 unsigned AbbrevNumber = Die->getAbbrevNumber();
2401 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2405 // Emit the code (index) for the abbreviation.
2406 Asm->EmitULEB128Bytes(AbbrevNumber);
2408 if (Asm->isVerbose())
2409 Asm->EOL(std::string("Abbrev [" +
2410 utostr(AbbrevNumber) +
2411 "] 0x" + utohexstr(Die->getOffset()) +
2412 ":0x" + utohexstr(Die->getSize()) + " " +
2413 dwarf::TagString(Abbrev->getTag())));
2417 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2418 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2420 // Emit the DIE attribute values.
2421 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2422 unsigned Attr = AbbrevData[i].getAttribute();
2423 unsigned Form = AbbrevData[i].getForm();
2424 assert(Form && "Too many attributes for DIE (check abbreviation)");
2427 case dwarf::DW_AT_sibling:
2428 Asm->EmitInt32(Die->SiblingOffset());
2430 case dwarf::DW_AT_abstract_origin: {
2431 DIEEntry *E = cast<DIEEntry>(Values[i]);
2432 DIE *Origin = E->getEntry();
2434 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
2435 Origin->getOffset();
2437 Asm->EmitInt32(Addr);
2441 // Emit an attribute using the defined form.
2442 Values[i]->EmitValue(this, Form);
2446 Asm->EOL(dwarf::AttributeString(Attr));
2449 // Emit the DIE children if any.
2450 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2451 const std::vector<DIE *> &Children = Die->getChildren();
2453 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2454 EmitDIE(Children[j]);
2456 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2460 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2462 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2463 DIE *Die = Unit->getDie();
2465 // Emit the compile units header.
2466 EmitLabel("info_begin", Unit->getID());
2468 // Emit size of content not including length itself
2469 unsigned ContentSize = Die->getSize() +
2470 sizeof(int16_t) + // DWARF version number
2471 sizeof(int32_t) + // Offset Into Abbrev. Section
2472 sizeof(int8_t) + // Pointer Size (in bytes)
2473 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2475 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2476 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2477 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2478 Asm->EOL("Offset Into Abbrev. Section");
2479 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2482 // FIXME - extra padding for gdb bug.
2483 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2484 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2485 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2486 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2487 EmitLabel("info_end", Unit->getID());
2492 void DwarfDebug::EmitDebugInfo() {
2493 // Start debug info section.
2494 Asm->OutStreamer.SwitchSection(
2495 Asm->getObjFileLowering().getDwarfInfoSection());
2497 EmitDebugInfoPerCU(ModuleCU);
2500 /// EmitAbbreviations - Emit the abbreviation section.
2502 void DwarfDebug::EmitAbbreviations() const {
2503 // Check to see if it is worth the effort.
2504 if (!Abbreviations.empty()) {
2505 // Start the debug abbrev section.
2506 Asm->OutStreamer.SwitchSection(
2507 Asm->getObjFileLowering().getDwarfAbbrevSection());
2509 EmitLabel("abbrev_begin", 0);
2511 // For each abbrevation.
2512 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2513 // Get abbreviation data
2514 const DIEAbbrev *Abbrev = Abbreviations[i];
2516 // Emit the abbrevations code (base 1 index.)
2517 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2518 Asm->EOL("Abbreviation Code");
2520 // Emit the abbreviations data.
2526 // Mark end of abbreviations.
2527 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2529 EmitLabel("abbrev_end", 0);
2534 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2535 /// the line matrix.
2537 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2538 // Define last address of section.
2539 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2540 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2541 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2542 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2544 // Mark end of matrix.
2545 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2546 Asm->EmitULEB128Bytes(1); Asm->EOL();
2547 Asm->EmitInt8(1); Asm->EOL();
2550 /// EmitDebugLines - Emit source line information.
2552 void DwarfDebug::EmitDebugLines() {
2553 // If the target is using .loc/.file, the assembler will be emitting the
2554 // .debug_line table automatically.
2555 if (MAI->hasDotLocAndDotFile())
2558 // Minimum line delta, thus ranging from -10..(255-10).
2559 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2560 // Maximum line delta, thus ranging from -10..(255-10).
2561 const int MaxLineDelta = 255 + MinLineDelta;
2563 // Start the dwarf line section.
2564 Asm->OutStreamer.SwitchSection(
2565 Asm->getObjFileLowering().getDwarfLineSection());
2567 // Construct the section header.
2568 EmitDifference("line_end", 0, "line_begin", 0, true);
2569 Asm->EOL("Length of Source Line Info");
2570 EmitLabel("line_begin", 0);
2572 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2574 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2575 Asm->EOL("Prolog Length");
2576 EmitLabel("line_prolog_begin", 0);
2578 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2580 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2582 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2584 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2586 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2588 // Line number standard opcode encodings argument count
2589 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2590 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2591 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2592 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2593 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2594 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2595 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2596 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2597 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2599 // Emit directories.
2600 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2601 Asm->EmitString(getSourceDirectoryName(DI));
2602 Asm->EOL("Directory");
2605 Asm->EmitInt8(0); Asm->EOL("End of directories");
2608 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2609 // Remember source id starts at 1.
2610 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2611 Asm->EmitString(getSourceFileName(Id.second));
2613 Asm->EmitULEB128Bytes(Id.first);
2614 Asm->EOL("Directory #");
2615 Asm->EmitULEB128Bytes(0);
2616 Asm->EOL("Mod date");
2617 Asm->EmitULEB128Bytes(0);
2618 Asm->EOL("File size");
2621 Asm->EmitInt8(0); Asm->EOL("End of files");
2623 EmitLabel("line_prolog_end", 0);
2625 // A sequence for each text section.
2626 unsigned SecSrcLinesSize = SectionSourceLines.size();
2628 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2629 // Isolate current sections line info.
2630 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2632 /*if (Asm->isVerbose()) {
2633 const MCSection *S = SectionMap[j + 1];
2634 O << '\t' << MAI->getCommentString() << " Section"
2635 << S->getName() << '\n';
2639 // Dwarf assumes we start with first line of first source file.
2640 unsigned Source = 1;
2643 // Construct rows of the address, source, line, column matrix.
2644 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2645 const SrcLineInfo &LineInfo = LineInfos[i];
2646 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2647 if (!LabelID) continue;
2649 if (LineInfo.getLine() == 0) continue;
2651 if (!Asm->isVerbose())
2654 std::pair<unsigned, unsigned> SourceID =
2655 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2656 O << '\t' << MAI->getCommentString() << ' '
2657 << getSourceDirectoryName(SourceID.first) << ' '
2658 << getSourceFileName(SourceID.second)
2659 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2662 // Define the line address.
2663 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2664 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2665 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2666 EmitReference("label", LabelID); Asm->EOL("Location label");
2668 // If change of source, then switch to the new source.
2669 if (Source != LineInfo.getSourceID()) {
2670 Source = LineInfo.getSourceID();
2671 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2672 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2675 // If change of line.
2676 if (Line != LineInfo.getLine()) {
2677 // Determine offset.
2678 int Offset = LineInfo.getLine() - Line;
2679 int Delta = Offset - MinLineDelta;
2682 Line = LineInfo.getLine();
2684 // If delta is small enough and in range...
2685 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2686 // ... then use fast opcode.
2687 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2689 // ... otherwise use long hand.
2690 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2691 Asm->EOL("DW_LNS_advance_line");
2692 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2693 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2696 // Copy the previous row (different address or source)
2697 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2701 EmitEndOfLineMatrix(j + 1);
2704 if (SecSrcLinesSize == 0)
2705 // Because we're emitting a debug_line section, we still need a line
2706 // table. The linker and friends expect it to exist. If there's nothing to
2707 // put into it, emit an empty table.
2708 EmitEndOfLineMatrix(1);
2710 EmitLabel("line_end", 0);
2714 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2716 void DwarfDebug::EmitCommonDebugFrame() {
2717 if (!MAI->doesDwarfRequireFrameSection())
2721 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2722 TargetFrameInfo::StackGrowsUp ?
2723 TD->getPointerSize() : -TD->getPointerSize();
2725 // Start the dwarf frame section.
2726 Asm->OutStreamer.SwitchSection(
2727 Asm->getObjFileLowering().getDwarfFrameSection());
2729 EmitLabel("debug_frame_common", 0);
2730 EmitDifference("debug_frame_common_end", 0,
2731 "debug_frame_common_begin", 0, true);
2732 Asm->EOL("Length of Common Information Entry");
2734 EmitLabel("debug_frame_common_begin", 0);
2735 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2736 Asm->EOL("CIE Identifier Tag");
2737 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2738 Asm->EOL("CIE Version");
2739 Asm->EmitString("");
2740 Asm->EOL("CIE Augmentation");
2741 Asm->EmitULEB128Bytes(1);
2742 Asm->EOL("CIE Code Alignment Factor");
2743 Asm->EmitSLEB128Bytes(stackGrowth);
2744 Asm->EOL("CIE Data Alignment Factor");
2745 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2746 Asm->EOL("CIE RA Column");
2748 std::vector<MachineMove> Moves;
2749 RI->getInitialFrameState(Moves);
2751 EmitFrameMoves(NULL, 0, Moves, false);
2753 Asm->EmitAlignment(2, 0, 0, false);
2754 EmitLabel("debug_frame_common_end", 0);
2759 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2762 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2763 if (!MAI->doesDwarfRequireFrameSection())
2766 // Start the dwarf frame section.
2767 Asm->OutStreamer.SwitchSection(
2768 Asm->getObjFileLowering().getDwarfFrameSection());
2770 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2771 "debug_frame_begin", DebugFrameInfo.Number, true);
2772 Asm->EOL("Length of Frame Information Entry");
2774 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2776 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2778 Asm->EOL("FDE CIE offset");
2780 EmitReference("func_begin", DebugFrameInfo.Number);
2781 Asm->EOL("FDE initial location");
2782 EmitDifference("func_end", DebugFrameInfo.Number,
2783 "func_begin", DebugFrameInfo.Number);
2784 Asm->EOL("FDE address range");
2786 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2789 Asm->EmitAlignment(2, 0, 0, false);
2790 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2795 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2796 EmitDifference("pubnames_end", Unit->getID(),
2797 "pubnames_begin", Unit->getID(), true);
2798 Asm->EOL("Length of Public Names Info");
2800 EmitLabel("pubnames_begin", Unit->getID());
2802 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2804 EmitSectionOffset("info_begin", "section_info",
2805 Unit->getID(), 0, true, false);
2806 Asm->EOL("Offset of Compilation Unit Info");
2808 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2810 Asm->EOL("Compilation Unit Length");
2812 StringMap<DIE*> &Globals = Unit->getGlobals();
2813 for (StringMap<DIE*>::const_iterator
2814 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2815 const char *Name = GI->getKeyData();
2816 DIE * Entity = GI->second;
2818 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2819 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2822 Asm->EmitInt32(0); Asm->EOL("End Mark");
2823 EmitLabel("pubnames_end", Unit->getID());
2828 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2830 void DwarfDebug::EmitDebugPubNames() {
2831 // Start the dwarf pubnames section.
2832 Asm->OutStreamer.SwitchSection(
2833 Asm->getObjFileLowering().getDwarfPubNamesSection());
2835 EmitDebugPubNamesPerCU(ModuleCU);
2838 /// EmitDebugStr - Emit visible names into a debug str section.
2840 void DwarfDebug::EmitDebugStr() {
2841 // Check to see if it is worth the effort.
2842 if (!StringPool.empty()) {
2843 // Start the dwarf str section.
2844 Asm->OutStreamer.SwitchSection(
2845 Asm->getObjFileLowering().getDwarfStrSection());
2847 // For each of strings in the string pool.
2848 for (unsigned StringID = 1, N = StringPool.size();
2849 StringID <= N; ++StringID) {
2850 // Emit a label for reference from debug information entries.
2851 EmitLabel("string", StringID);
2853 // Emit the string itself.
2854 const std::string &String = StringPool[StringID];
2855 Asm->EmitString(String); Asm->EOL();
2862 /// EmitDebugLoc - Emit visible names into a debug loc section.
2864 void DwarfDebug::EmitDebugLoc() {
2865 // Start the dwarf loc section.
2866 Asm->OutStreamer.SwitchSection(
2867 Asm->getObjFileLowering().getDwarfLocSection());
2871 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2873 void DwarfDebug::EmitDebugARanges() {
2874 // Start the dwarf aranges section.
2875 Asm->OutStreamer.SwitchSection(
2876 Asm->getObjFileLowering().getDwarfARangesSection());
2880 CompileUnit *Unit = GetBaseCompileUnit();
2882 // Don't include size of length
2883 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2885 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2887 EmitReference("info_begin", Unit->getID());
2888 Asm->EOL("Offset of Compilation Unit Info");
2890 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2892 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2894 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2895 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2898 EmitReference("text_begin", 0); Asm->EOL("Address");
2899 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2901 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2902 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2908 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2910 void DwarfDebug::EmitDebugRanges() {
2911 // Start the dwarf ranges section.
2912 Asm->OutStreamer.SwitchSection(
2913 Asm->getObjFileLowering().getDwarfRangesSection());
2917 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2919 void DwarfDebug::EmitDebugMacInfo() {
2920 if (const MCSection *LineInfo =
2921 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2922 // Start the dwarf macinfo section.
2923 Asm->OutStreamer.SwitchSection(LineInfo);
2928 /// EmitDebugInlineInfo - Emit inline info using following format.
2930 /// 1. length of section
2931 /// 2. Dwarf version number
2932 /// 3. address size.
2934 /// Entries (one "entry" for each function that was inlined):
2936 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2937 /// otherwise offset into __debug_str for regular function name.
2938 /// 2. offset into __debug_str section for regular function name.
2939 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2940 /// instances for the function.
2942 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2943 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2944 /// __debug_info section, and the low_pc is the starting address for the
2945 /// inlining instance.
2946 void DwarfDebug::EmitDebugInlineInfo() {
2947 if (!MAI->doesDwarfUsesInlineInfoSection())
2953 Asm->OutStreamer.SwitchSection(
2954 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2956 EmitDifference("debug_inlined_end", 1,
2957 "debug_inlined_begin", 1, true);
2958 Asm->EOL("Length of Debug Inlined Information Entry");
2960 EmitLabel("debug_inlined_begin", 1);
2962 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2963 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2965 for (DenseMap<MDNode *, SmallVector<unsigned, 4> >::iterator
2966 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2967 MDNode *Node = I->first;
2968 SmallVector<unsigned, 4> &Labels = I->second;
2969 DISubprogram SP(Node);
2970 const char *LName = SP.getLinkageName();
2971 const char *Name = SP.getName();
2974 Asm->EmitString(Name);
2976 // Skip special LLVM prefix that is used to inform the asm printer to not
2977 // emit usual symbol prefix before the symbol name. This happens for
2978 // Objective-C symbol names and symbol whose name is replaced using GCC's
2979 // __asm__ attribute.
2982 Asm->EmitString(LName);
2984 Asm->EOL("MIPS linkage name");
2986 Asm->EmitString(Name); Asm->EOL("Function name");
2988 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2990 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2991 LE = Labels.end(); LI != LE; ++LI) {
2992 DIE *SP = ModuleCU->getDieMapSlotFor(Node);
2993 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2995 if (TD->getPointerSize() == sizeof(int32_t))
2996 O << MAI->getData32bitsDirective();
2998 O << MAI->getData64bitsDirective();
3000 PrintLabelName("label", *LI); Asm->EOL("low_pc");
3004 EmitLabel("debug_inlined_end", 1);