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.
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.
128 DIVariable Var; // Variable Descriptor.
129 unsigned FrameIndex; // Variable frame index.
130 DbgVariable *AbstractVar; // Abstract variable for this variable.
133 DbgVariable(DIVariable V, unsigned I)
134 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
137 DIVariable getVariable() const { return Var; }
138 unsigned getFrameIndex() const { return FrameIndex; }
139 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
140 DbgVariable *getAbstractVariable() const { return AbstractVar; }
141 void setDIE(DIE *D) { TheDIE = D; }
142 DIE *getDIE() const { return TheDIE; }
145 //===----------------------------------------------------------------------===//
146 /// DbgScope - This class is used to track scope information.
149 DbgScope *Parent; // Parent to this scope.
150 DIDescriptor Desc; // Debug info descriptor for scope.
151 WeakVH InlinedAtLocation; // Location at which scope is inlined.
152 bool AbstractScope; // Abstract Scope
153 unsigned StartLabelID; // Label ID of the beginning of scope.
154 unsigned EndLabelID; // Label ID of the end of scope.
155 const MachineInstr *LastInsn; // Last instruction of this scope.
156 const MachineInstr *FirstInsn; // First instruction of this scope.
157 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
158 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
160 // Private state for dump()
161 mutable unsigned IndentLevel;
163 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
164 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
165 StartLabelID(0), EndLabelID(0),
166 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
170 DbgScope *getParent() const { return Parent; }
171 void setParent(DbgScope *P) { Parent = P; }
172 DIDescriptor getDesc() const { return Desc; }
173 MDNode *getInlinedAt() const {
174 return dyn_cast_or_null<MDNode>(InlinedAtLocation);
176 MDNode *getScopeNode() const { return Desc.getNode(); }
177 unsigned getStartLabelID() const { return StartLabelID; }
178 unsigned getEndLabelID() const { return EndLabelID; }
179 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
180 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
181 void setStartLabelID(unsigned S) { StartLabelID = S; }
182 void setEndLabelID(unsigned E) { EndLabelID = E; }
183 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
184 const MachineInstr *getLastInsn() { return LastInsn; }
185 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
186 void setAbstractScope() { AbstractScope = true; }
187 bool isAbstractScope() const { return AbstractScope; }
188 const MachineInstr *getFirstInsn() { return FirstInsn; }
190 /// AddScope - Add a scope to the scope.
192 void AddScope(DbgScope *S) { Scopes.push_back(S); }
194 /// AddVariable - Add a variable to the scope.
196 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
198 void FixInstructionMarkers() {
199 assert (getFirstInsn() && "First instruction is missing!");
203 // If a scope does not have an instruction to mark an end then use
204 // the end of last child scope.
205 SmallVector<DbgScope *, 4> &Scopes = getScopes();
206 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
207 DbgScope *L = Scopes.back();
208 if (!L->getLastInsn())
209 L->FixInstructionMarkers();
210 setLastInsn(L->getLastInsn());
219 void DbgScope::dump() const {
220 raw_ostream &err = errs();
221 err.indent(IndentLevel);
222 MDNode *N = Desc.getNode();
224 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
226 err << "Abstract Scope\n";
230 err << "Children ...\n";
231 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
232 if (Scopes[i] != this)
239 //===----------------------------------------------------------------------===//
240 /// DbgConcreteScope - This class is used to track a scope that holds concrete
241 /// instance information.
243 class DbgConcreteScope : public DbgScope {
245 DIE *Die; // Debug info for this concrete scope.
247 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
250 DIE *getDie() const { return Die; }
251 void setDie(DIE *D) { Die = D; }
254 DbgScope::~DbgScope() {
255 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
257 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
261 } // end llvm namespace
263 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
264 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
265 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
266 ValuesSet(InitValuesSetSize), Values(), StringPool(),
267 SectionSourceLines(), didInitial(false), shouldEmit(false),
268 CurrentFnDbgScope(0), DebugTimer(0) {
269 if (TimePassesIsEnabled)
270 DebugTimer = new Timer("Dwarf Debug Writer",
271 getDwarfTimerGroup());
273 DwarfDebug::~DwarfDebug() {
274 for (unsigned j = 0, M = Values.size(); j < M; ++j)
280 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
282 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
283 // Profile the node so that we can make it unique.
287 // Check the set for priors.
288 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
290 // If it's newly added.
291 if (InSet == &Abbrev) {
292 // Add to abbreviation list.
293 Abbreviations.push_back(&Abbrev);
295 // Assign the vector position + 1 as its number.
296 Abbrev.setNumber(Abbreviations.size());
298 // Assign existing abbreviation number.
299 Abbrev.setNumber(InSet->getNumber());
303 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
304 /// information entry.
305 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
310 DIEEntry::Profile(ID, Entry);
312 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
314 if (Value) return Value;
316 Value = new DIEEntry(Entry);
317 ValuesSet.InsertNode(Value, Where);
319 Value = new DIEEntry(Entry);
322 Values.push_back(Value);
326 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
328 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
329 Value->setEntry(Entry);
331 // Add to values set if not already there. If it is, we merely have a
332 // duplicate in the values list (no harm.)
333 ValuesSet.GetOrInsertNode(Value);
336 /// AddUInt - Add an unsigned integer attribute data and value.
338 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
339 unsigned Form, uint64_t Integer) {
340 if (!Form) Form = DIEInteger::BestForm(false, Integer);
343 DIEInteger::Profile(ID, Integer);
345 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
348 Value = new DIEInteger(Integer);
349 ValuesSet.InsertNode(Value, Where);
350 Values.push_back(Value);
353 Die->AddValue(Attribute, Form, Value);
356 /// AddSInt - Add an signed integer attribute data and value.
358 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
359 unsigned Form, int64_t Integer) {
360 if (!Form) Form = DIEInteger::BestForm(true, Integer);
363 DIEInteger::Profile(ID, (uint64_t)Integer);
365 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
368 Value = new DIEInteger(Integer);
369 ValuesSet.InsertNode(Value, Where);
370 Values.push_back(Value);
373 Die->AddValue(Attribute, Form, Value);
376 /// AddString - Add a string attribute data and value.
378 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
379 const std::string &String) {
381 DIEString::Profile(ID, String);
383 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
386 Value = new DIEString(String);
387 ValuesSet.InsertNode(Value, Where);
388 Values.push_back(Value);
391 Die->AddValue(Attribute, Form, Value);
394 /// AddLabel - Add a Dwarf label attribute data and value.
396 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
397 const DWLabel &Label) {
399 DIEDwarfLabel::Profile(ID, Label);
401 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
404 Value = new DIEDwarfLabel(Label);
405 ValuesSet.InsertNode(Value, Where);
406 Values.push_back(Value);
409 Die->AddValue(Attribute, Form, Value);
412 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
414 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
415 const std::string &Label) {
417 DIEObjectLabel::Profile(ID, Label);
419 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
422 Value = new DIEObjectLabel(Label);
423 ValuesSet.InsertNode(Value, Where);
424 Values.push_back(Value);
427 Die->AddValue(Attribute, Form, Value);
430 /// AddSectionOffset - Add a section offset label attribute data and value.
432 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
433 const DWLabel &Label, const DWLabel &Section,
434 bool isEH, bool useSet) {
436 DIESectionOffset::Profile(ID, Label, Section);
438 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
441 Value = new DIESectionOffset(Label, Section, isEH, useSet);
442 ValuesSet.InsertNode(Value, Where);
443 Values.push_back(Value);
446 Die->AddValue(Attribute, Form, Value);
449 /// AddDelta - Add a label delta attribute data and value.
451 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
452 const DWLabel &Hi, const DWLabel &Lo) {
454 DIEDelta::Profile(ID, Hi, Lo);
456 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
459 Value = new DIEDelta(Hi, Lo);
460 ValuesSet.InsertNode(Value, Where);
461 Values.push_back(Value);
464 Die->AddValue(Attribute, Form, Value);
467 /// AddBlock - Add block data.
469 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
471 Block->ComputeSize(TD);
475 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
479 ValuesSet.InsertNode(Value, Where);
480 Values.push_back(Value);
482 // Already exists, reuse the previous one.
484 Block = cast<DIEBlock>(Value);
487 Die->AddValue(Attribute, Block->BestForm(), Value);
490 /// AddSourceLine - Add location information to specified debug information
492 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
493 // If there is no compile unit specified, don't add a line #.
494 if (V->getCompileUnit().isNull())
497 unsigned Line = V->getLineNumber();
498 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
499 assert(FileID && "Invalid file id");
500 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
501 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
504 /// AddSourceLine - Add location information to specified debug information
506 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
507 // If there is no compile unit specified, don't add a line #.
508 if (G->getCompileUnit().isNull())
511 unsigned Line = G->getLineNumber();
512 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
513 assert(FileID && "Invalid file id");
514 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
515 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
518 /// AddSourceLine - Add location information to specified debug information
520 void DwarfDebug::AddSourceLine(DIE *Die, const DISubprogram *SP) {
521 // If there is no compile unit specified, don't add a line #.
522 if (SP->getCompileUnit().isNull())
524 // If the line number is 0, don't add it.
525 if (SP->getLineNumber() == 0)
529 unsigned Line = SP->getLineNumber();
530 unsigned FileID = FindCompileUnit(SP->getCompileUnit()).getID();
531 assert(FileID && "Invalid file id");
532 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
533 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
536 /// AddSourceLine - Add location information to specified debug information
538 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
539 // If there is no compile unit specified, don't add a line #.
540 DICompileUnit CU = Ty->getCompileUnit();
544 unsigned Line = Ty->getLineNumber();
545 unsigned FileID = FindCompileUnit(CU).getID();
546 assert(FileID && "Invalid file id");
547 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
548 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
551 /* Byref variables, in Blocks, are declared by the programmer as
552 "SomeType VarName;", but the compiler creates a
553 __Block_byref_x_VarName struct, and gives the variable VarName
554 either the struct, or a pointer to the struct, as its type. This
555 is necessary for various behind-the-scenes things the compiler
556 needs to do with by-reference variables in blocks.
558 However, as far as the original *programmer* is concerned, the
559 variable should still have type 'SomeType', as originally declared.
561 The following function dives into the __Block_byref_x_VarName
562 struct to find the original type of the variable. This will be
563 passed back to the code generating the type for the Debug
564 Information Entry for the variable 'VarName'. 'VarName' will then
565 have the original type 'SomeType' in its debug information.
567 The original type 'SomeType' will be the type of the field named
568 'VarName' inside the __Block_byref_x_VarName struct.
570 NOTE: In order for this to not completely fail on the debugger
571 side, the Debug Information Entry for the variable VarName needs to
572 have a DW_AT_location that tells the debugger how to unwind through
573 the pointers and __Block_byref_x_VarName struct to find the actual
574 value of the variable. The function AddBlockByrefType does this. */
576 /// Find the type the programmer originally declared the variable to be
577 /// and return that type.
579 DIType DwarfDebug::GetBlockByrefType(DIType Ty, std::string Name) {
582 unsigned tag = Ty.getTag();
584 if (tag == dwarf::DW_TAG_pointer_type) {
585 DIDerivedType DTy = DIDerivedType(Ty.getNode());
586 subType = DTy.getTypeDerivedFrom();
589 DICompositeType blockStruct = DICompositeType(subType.getNode());
591 DIArray Elements = blockStruct.getTypeArray();
593 if (Elements.isNull())
596 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
597 DIDescriptor Element = Elements.getElement(i);
598 DIDerivedType DT = DIDerivedType(Element.getNode());
599 if (strcmp(Name.c_str(), DT.getName()) == 0)
600 return (DT.getTypeDerivedFrom());
606 /// AddComplexAddress - Start with the address based on the location provided,
607 /// and generate the DWARF information necessary to find the actual variable
608 /// given the extra address information encoded in the DIVariable, starting from
609 /// the starting location. Add the DWARF information to the die.
611 void DwarfDebug::AddComplexAddress(DbgVariable *&DV, DIE *Die,
613 const MachineLocation &Location) {
614 const DIVariable &VD = DV->getVariable();
615 DIType Ty = VD.getType();
617 // Decode the original location, and use that as the start of the byref
618 // variable's location.
619 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
620 DIEBlock *Block = new DIEBlock();
622 if (Location.isReg()) {
624 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
626 Reg = Reg - dwarf::DW_OP_reg0;
627 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
628 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
632 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
634 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
635 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
638 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
641 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
642 uint64_t Element = VD.getAddrElement(i);
644 if (Element == DIFactory::OpPlus) {
645 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
646 AddUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
647 } else if (Element == DIFactory::OpDeref) {
648 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
649 } else llvm_unreachable("unknown DIFactory Opcode");
652 // Now attach the location information to the DIE.
653 AddBlock(Die, Attribute, 0, Block);
656 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
657 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
658 gives the variable VarName either the struct, or a pointer to the struct, as
659 its type. This is necessary for various behind-the-scenes things the
660 compiler needs to do with by-reference variables in Blocks.
662 However, as far as the original *programmer* is concerned, the variable
663 should still have type 'SomeType', as originally declared.
665 The function GetBlockByrefType dives into the __Block_byref_x_VarName
666 struct to find the original type of the variable, which is then assigned to
667 the variable's Debug Information Entry as its real type. So far, so good.
668 However now the debugger will expect the variable VarName to have the type
669 SomeType. So we need the location attribute for the variable to be an
670 expression that explains to the debugger how to navigate through the
671 pointers and struct to find the actual variable of type SomeType.
673 The following function does just that. We start by getting
674 the "normal" location for the variable. This will be the location
675 of either the struct __Block_byref_x_VarName or the pointer to the
676 struct __Block_byref_x_VarName.
678 The struct will look something like:
680 struct __Block_byref_x_VarName {
682 struct __Block_byref_x_VarName *forwarding;
683 ... <various other fields>
685 ... <maybe more fields>
688 If we are given the struct directly (as our starting point) we
689 need to tell the debugger to:
691 1). Add the offset of the forwarding field.
693 2). Follow that pointer to get the the real __Block_byref_x_VarName
694 struct to use (the real one may have been copied onto the heap).
696 3). Add the offset for the field VarName, to find the actual variable.
698 If we started with a pointer to the struct, then we need to
699 dereference that pointer first, before the other steps.
700 Translating this into DWARF ops, we will need to append the following
701 to the current location description for the variable:
703 DW_OP_deref -- optional, if we start with a pointer
704 DW_OP_plus_uconst <forward_fld_offset>
706 DW_OP_plus_uconst <varName_fld_offset>
708 That is what this function does. */
710 /// AddBlockByrefAddress - Start with the address based on the location
711 /// provided, and generate the DWARF information necessary to find the
712 /// actual Block variable (navigating the Block struct) based on the
713 /// starting location. Add the DWARF information to the die. For
714 /// more information, read large comment just above here.
716 void DwarfDebug::AddBlockByrefAddress(DbgVariable *&DV, DIE *Die,
718 const MachineLocation &Location) {
719 const DIVariable &VD = DV->getVariable();
720 DIType Ty = VD.getType();
722 unsigned Tag = Ty.getTag();
723 bool isPointer = false;
725 const char *varName = VD.getName();
727 if (Tag == dwarf::DW_TAG_pointer_type) {
728 DIDerivedType DTy = DIDerivedType(Ty.getNode());
729 TmpTy = DTy.getTypeDerivedFrom();
733 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
735 // Find the __forwarding field and the variable field in the __Block_byref
737 DIArray Fields = blockStruct.getTypeArray();
738 DIDescriptor varField = DIDescriptor();
739 DIDescriptor forwardingField = DIDescriptor();
742 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
743 DIDescriptor Element = Fields.getElement(i);
744 DIDerivedType DT = DIDerivedType(Element.getNode());
745 const char *fieldName = DT.getName();
746 if (strcmp(fieldName, "__forwarding") == 0)
747 forwardingField = Element;
748 else if (strcmp(fieldName, varName) == 0)
752 assert(!varField.isNull() && "Can't find byref variable in Block struct");
753 assert(!forwardingField.isNull()
754 && "Can't find forwarding field in Block struct");
756 // Get the offsets for the forwarding field and the variable field.
757 unsigned int forwardingFieldOffset =
758 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
759 unsigned int varFieldOffset =
760 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
762 // Decode the original location, and use that as the start of the byref
763 // variable's location.
764 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
765 DIEBlock *Block = new DIEBlock();
767 if (Location.isReg()) {
769 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
771 Reg = Reg - dwarf::DW_OP_reg0;
772 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
773 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
777 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
779 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
780 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
783 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
786 // If we started with a pointer to the __Block_byref... struct, then
787 // the first thing we need to do is dereference the pointer (DW_OP_deref).
789 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
791 // Next add the offset for the '__forwarding' field:
792 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
793 // adding the offset if it's 0.
794 if (forwardingFieldOffset > 0) {
795 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
796 AddUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
799 // Now dereference the __forwarding field to get to the real __Block_byref
800 // struct: DW_OP_deref.
801 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
803 // Now that we've got the real __Block_byref... struct, add the offset
804 // for the variable's field to get to the location of the actual variable:
805 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
806 if (varFieldOffset > 0) {
807 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
808 AddUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
811 // Now attach the location information to the DIE.
812 AddBlock(Die, Attribute, 0, Block);
815 /// AddAddress - Add an address attribute to a die based on the location
817 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
818 const MachineLocation &Location) {
819 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
820 DIEBlock *Block = new DIEBlock();
822 if (Location.isReg()) {
824 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
826 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
827 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
831 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
833 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
834 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
837 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
840 AddBlock(Die, Attribute, 0, Block);
843 /// AddType - Add a new type attribute to the specified entity.
844 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
848 // Check for pre-existence.
849 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getNode());
851 // If it exists then use the existing value.
853 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
858 Slot = CreateDIEEntry();
861 DIE Buffer(dwarf::DW_TAG_base_type);
862 if (Ty.isBasicType())
863 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getNode()));
864 else if (Ty.isCompositeType())
865 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getNode()));
867 assert(Ty.isDerivedType() && "Unknown kind of DIType");
868 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getNode()));
871 // Add debug information entry to entity and appropriate context.
873 DIDescriptor Context = Ty.getContext();
874 if (!Context.isNull())
875 Die = DW_Unit->getDieMapSlotFor(Context.getNode());
878 DIE *Child = new DIE(Buffer);
879 Die->AddChild(Child);
881 SetDIEEntry(Slot, Child);
883 Die = DW_Unit->AddDie(Buffer);
884 SetDIEEntry(Slot, Die);
887 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
890 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
891 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
893 // Get core information.
894 const char *Name = BTy.getName();
895 Buffer.setTag(dwarf::DW_TAG_base_type);
896 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
899 // Add name if not anonymous or intermediate type.
901 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
902 uint64_t Size = BTy.getSizeInBits() >> 3;
903 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
906 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
907 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
909 // Get core information.
910 const char *Name = DTy.getName();
911 uint64_t Size = DTy.getSizeInBits() >> 3;
912 unsigned Tag = DTy.getTag();
914 // FIXME - Workaround for templates.
915 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
919 // Map to main type, void will not have a type.
920 DIType FromTy = DTy.getTypeDerivedFrom();
921 AddType(DW_Unit, &Buffer, FromTy);
923 // Add name if not anonymous or intermediate type.
924 if (Name && Tag != dwarf::DW_TAG_pointer_type)
925 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
927 // Add size if non-zero (derived types might be zero-sized.)
929 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
931 // Add source line info if available and TyDesc is not a forward declaration.
932 if (!DTy.isForwardDecl() && Tag != dwarf::DW_TAG_pointer_type)
933 AddSourceLine(&Buffer, &DTy);
936 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
937 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
938 DICompositeType CTy) {
939 // Get core information.
940 const char *Name = CTy.getName();
942 uint64_t Size = CTy.getSizeInBits() >> 3;
943 unsigned Tag = CTy.getTag();
947 case dwarf::DW_TAG_vector_type:
948 case dwarf::DW_TAG_array_type:
949 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
951 case dwarf::DW_TAG_enumeration_type: {
952 DIArray Elements = CTy.getTypeArray();
954 // Add enumerators to enumeration type.
955 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
957 DIEnumerator Enum(Elements.getElement(i).getNode());
958 if (!Enum.isNull()) {
959 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
960 Buffer.AddChild(ElemDie);
965 case dwarf::DW_TAG_subroutine_type: {
967 DIArray Elements = CTy.getTypeArray();
968 DIDescriptor RTy = Elements.getElement(0);
969 AddType(DW_Unit, &Buffer, DIType(RTy.getNode()));
971 // Add prototype flag.
972 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
975 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
976 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
977 DIDescriptor Ty = Elements.getElement(i);
978 AddType(DW_Unit, Arg, DIType(Ty.getNode()));
979 Buffer.AddChild(Arg);
983 case dwarf::DW_TAG_structure_type:
984 case dwarf::DW_TAG_union_type:
985 case dwarf::DW_TAG_class_type: {
986 // Add elements to structure type.
987 DIArray Elements = CTy.getTypeArray();
989 // A forward struct declared type may not have elements available.
990 if (Elements.isNull())
993 // Add elements to structure type.
994 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
995 DIDescriptor Element = Elements.getElement(i);
996 if (Element.isNull())
999 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1000 ElemDie = CreateSubprogramDIE(DW_Unit,
1001 DISubprogram(Element.getNode()));
1003 ElemDie = CreateMemberDIE(DW_Unit,
1004 DIDerivedType(Element.getNode()));
1005 Buffer.AddChild(ElemDie);
1008 if (CTy.isAppleBlockExtension())
1009 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1011 unsigned RLang = CTy.getRunTimeLang();
1013 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1014 dwarf::DW_FORM_data1, RLang);
1021 // Add name if not anonymous or intermediate type.
1023 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1025 if (Tag == dwarf::DW_TAG_enumeration_type ||
1026 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1027 // Add size if non-zero (derived types might be zero-sized.)
1029 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1031 // Add zero size if it is not a forward declaration.
1032 if (CTy.isForwardDecl())
1033 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1035 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1038 // Add source line info if available.
1039 if (!CTy.isForwardDecl())
1040 AddSourceLine(&Buffer, &CTy);
1044 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1045 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1046 int64_t L = SR.getLo();
1047 int64_t H = SR.getHi();
1048 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1050 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1052 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1054 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1056 Buffer.AddChild(DW_Subrange);
1059 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1060 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1061 DICompositeType *CTy) {
1062 Buffer.setTag(dwarf::DW_TAG_array_type);
1063 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1064 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1066 // Emit derived type.
1067 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1068 DIArray Elements = CTy->getTypeArray();
1070 // Construct an anonymous type for index type.
1071 DIE IdxBuffer(dwarf::DW_TAG_base_type);
1072 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1073 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1074 dwarf::DW_ATE_signed);
1075 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1077 // Add subranges to array type.
1078 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1079 DIDescriptor Element = Elements.getElement(i);
1080 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1081 ConstructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IndexTy);
1085 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1086 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1087 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1088 const char *Name = ETy->getName();
1089 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1090 int64_t Value = ETy->getEnumValue();
1091 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1095 /// CreateGlobalVariableDIE - Create new DIE using GV.
1096 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
1097 const DIGlobalVariable &GV) {
1098 // If the global variable was optmized out then no need to create debug info entry.
1099 if (!GV.getGlobal()) return NULL;
1100 if (!GV.getDisplayName()) return NULL;
1102 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1103 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1104 GV.getDisplayName());
1106 const char *LinkageName = GV.getLinkageName();
1108 // Skip special LLVM prefix that is used to inform the asm printer to not
1109 // emit usual symbol prefix before the symbol name. This happens for
1110 // Objective-C symbol names and symbol whose name is replaced using GCC's
1111 // __asm__ attribute.
1112 if (LinkageName[0] == 1)
1113 LinkageName = &LinkageName[1];
1114 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1117 AddType(DW_Unit, GVDie, GV.getType());
1118 if (!GV.isLocalToUnit())
1119 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1120 AddSourceLine(GVDie, &GV);
1123 DIEBlock *Block = new DIEBlock();
1124 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1125 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1126 Asm->Mang->getMangledName(GV.getGlobal()));
1127 AddBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1132 /// CreateMemberDIE - Create new member DIE.
1133 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1134 DIE *MemberDie = new DIE(DT.getTag());
1135 if (const char *Name = DT.getName())
1136 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1138 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1140 AddSourceLine(MemberDie, &DT);
1142 DIEBlock *MemLocationDie = new DIEBlock();
1143 AddUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1145 uint64_t Size = DT.getSizeInBits();
1146 uint64_t FieldSize = DT.getOriginalTypeSize();
1148 if (Size != FieldSize) {
1150 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1151 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1153 uint64_t Offset = DT.getOffsetInBits();
1154 uint64_t FieldOffset = Offset;
1155 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1156 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1157 FieldOffset = (HiMark - FieldSize);
1158 Offset -= FieldOffset;
1160 // Maybe we need to work from the other end.
1161 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1162 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1164 // Here WD_AT_data_member_location points to the anonymous
1165 // field that includes this bit field.
1166 AddUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1169 // This is not a bitfield.
1170 AddUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1172 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1174 if (DT.isProtected())
1175 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1176 dwarf::DW_ACCESS_protected);
1177 else if (DT.isPrivate())
1178 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1179 dwarf::DW_ACCESS_private);
1184 /// CreateSubprogramDIE - Create new DIE using SP.
1185 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
1186 const DISubprogram &SP,
1189 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1191 const char * Name = SP.getName();
1192 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1194 const char *LinkageName = SP.getLinkageName();
1196 // Skip special LLVM prefix that is used to inform the asm printer to not emit
1197 // usual symbol prefix before the symbol name. This happens for Objective-C
1198 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
1199 if (LinkageName[0] == 1)
1200 LinkageName = &LinkageName[1];
1201 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1204 AddSourceLine(SPDie, &SP);
1206 DICompositeType SPTy = SP.getType();
1207 DIArray Args = SPTy.getTypeArray();
1209 // Add prototyped tag, if C or ObjC.
1210 unsigned Lang = SP.getCompileUnit().getLanguage();
1211 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1212 Lang == dwarf::DW_LANG_ObjC)
1213 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1216 unsigned SPTag = SPTy.getTag();
1217 if (!IsConstructor) {
1218 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1219 AddType(DW_Unit, SPDie, SPTy);
1221 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1224 if (!SP.isDefinition()) {
1225 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1227 // Add arguments. Do not add arguments for subprogram definition. They will
1228 // be handled through RecordVariable.
1229 if (SPTag == dwarf::DW_TAG_subroutine_type)
1230 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1231 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1232 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1233 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1234 SPDie->AddChild(Arg);
1238 // DW_TAG_inlined_subroutine may refer to this DIE.
1239 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getNode());
1244 /// FindCompileUnit - Get the compile unit for the given descriptor.
1246 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
1247 DenseMap<Value *, CompileUnit *>::const_iterator I =
1248 CompileUnitMap.find(Unit.getNode());
1249 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1253 /// CreateDbgScopeVariable - Create a new scope variable.
1255 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1256 // Get the descriptor.
1257 const DIVariable &VD = DV->getVariable();
1258 const char *Name = VD.getName();
1262 // Translate tag to proper Dwarf tag. The result variable is dropped for
1265 switch (VD.getTag()) {
1266 case dwarf::DW_TAG_return_variable:
1268 case dwarf::DW_TAG_arg_variable:
1269 Tag = dwarf::DW_TAG_formal_parameter;
1271 case dwarf::DW_TAG_auto_variable: // fall thru
1273 Tag = dwarf::DW_TAG_variable;
1277 // Define variable debug information entry.
1278 DIE *VariableDie = new DIE(Tag);
1279 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1281 // Add source line info if available.
1282 AddSourceLine(VariableDie, &VD);
1284 // Add variable type.
1285 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1286 // addresses instead.
1287 if (VD.isBlockByrefVariable())
1288 AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1290 AddType(Unit, VariableDie, VD.getType());
1292 // Add variable address.
1293 // Variables for abstract instances of inlined functions don't get a
1295 MachineLocation Location;
1296 Location.set(RI->getFrameRegister(*MF),
1297 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1300 if (VD.hasComplexAddress())
1301 AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1302 else if (VD.isBlockByrefVariable())
1303 AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1305 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1310 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1311 /// Initialize scope and update scope hierarchy.
1312 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1313 MDNode *InlinedAt) {
1314 assert (N && "Invalid Scope encoding!");
1315 assert (MI && "Missing machine instruction!");
1316 bool GetConcreteScope = (MI && InlinedAt);
1318 DbgScope *NScope = NULL;
1321 NScope = DbgScopeMap.lookup(InlinedAt);
1323 NScope = DbgScopeMap.lookup(N);
1324 assert (NScope && "Unable to find working scope!");
1326 if (NScope->getFirstInsn())
1329 DbgScope *Parent = NULL;
1330 if (GetConcreteScope) {
1331 DILocation IL(InlinedAt);
1332 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1333 IL.getOrigLocation().getNode());
1334 assert (Parent && "Unable to find Parent scope!");
1335 NScope->setParent(Parent);
1336 Parent->AddScope(NScope);
1337 } else if (DIDescriptor(N).isLexicalBlock()) {
1338 DILexicalBlock DB(N);
1339 if (!DB.getContext().isNull()) {
1340 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1341 NScope->setParent(Parent);
1342 Parent->AddScope(NScope);
1346 NScope->setFirstInsn(MI);
1348 if (!Parent && !InlinedAt) {
1349 StringRef SPName = DISubprogram(N).getLinkageName();
1350 if (SPName == MF->getFunction()->getName())
1351 CurrentFnDbgScope = NScope;
1354 if (GetConcreteScope) {
1355 ConcreteScopes[InlinedAt] = NScope;
1356 getOrCreateAbstractScope(N);
1362 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1363 assert (N && "Invalid Scope encoding!");
1365 DbgScope *AScope = AbstractScopes.lookup(N);
1369 DbgScope *Parent = NULL;
1371 DIDescriptor Scope(N);
1372 if (Scope.isLexicalBlock()) {
1373 DILexicalBlock DB(N);
1374 DIDescriptor ParentDesc = DB.getContext();
1375 if (!ParentDesc.isNull())
1376 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1379 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1382 Parent->AddScope(AScope);
1383 AScope->setAbstractScope();
1384 AbstractScopes[N] = AScope;
1385 if (DIDescriptor(N).isSubprogram())
1386 AbstractScopesList.push_back(AScope);
1390 static DISubprogram getDISubprogram(MDNode *N) {
1394 return DISubprogram();
1396 if (D.isCompileUnit())
1397 return DISubprogram();
1399 if (D.isSubprogram())
1400 return DISubprogram(N);
1402 if (D.isLexicalBlock())
1403 return getDISubprogram(DILexicalBlock(N).getContext().getNode());
1405 llvm_unreachable("Unexpected Descriptor!");
1408 DIE *DwarfDebug::UpdateSubprogramScopeDIE(MDNode *SPNode) {
1410 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPNode);
1411 assert (SPDie && "Unable to find subprogram DIE!");
1412 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1413 DWLabel("func_begin", SubprogramCount));
1414 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1415 DWLabel("func_end", SubprogramCount));
1416 MachineLocation Location(RI->getFrameRegister(*MF));
1417 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1419 if (!DISubprogram(SPNode).isLocalToUnit())
1420 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1422 // If there are global variables at this scope then add their dies.
1423 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1424 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1425 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1427 DIGlobalVariable GV(N);
1428 if (GV.getContext().getNode() == SPNode) {
1429 DIE *ScopedGVDie = CreateGlobalVariableDIE(ModuleCU, GV);
1431 SPDie->AddChild(ScopedGVDie);
1437 DIE *DwarfDebug::ConstructLexicalScopeDIE(DbgScope *Scope) {
1438 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1439 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1441 // Ignore empty scopes.
1442 if (StartID == EndID && StartID != 0)
1445 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1446 if (Scope->isAbstractScope())
1449 AddLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1451 DWLabel("label", StartID)
1452 : DWLabel("func_begin", SubprogramCount));
1453 AddLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1455 DWLabel("label", EndID)
1456 : DWLabel("func_end", SubprogramCount));
1463 DIE *DwarfDebug::ConstructInlinedScopeDIE(DbgScope *Scope) {
1464 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1465 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1466 assert (StartID && "Invalid starting label for an inlined scope!");
1467 assert (EndID && "Invalid end label for an inlined scope!");
1468 // Ignore empty scopes.
1469 if (StartID == EndID && StartID != 0)
1472 DIScope DS(Scope->getScopeNode());
1475 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1477 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1478 DIE *&OriginDIE = ModuleCU->getDieMapSlotFor(InlinedSP.getNode());
1479 assert (OriginDIE && "Unable to find Origin DIE!");
1480 AddDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1481 dwarf::DW_FORM_ref4, OriginDIE);
1483 AddLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1484 DWLabel("label", StartID));
1485 AddLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1486 DWLabel("label", EndID));
1488 InlinedSubprogramDIEs.insert(OriginDIE);
1490 // Track the start label for this inlined function.
1491 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1492 I = InlineInfo.find(InlinedSP.getNode());
1494 if (I == InlineInfo.end()) {
1495 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID, ScopeDIE));
1496 InlinedSPNodes.push_back(InlinedSP.getNode());
1498 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1500 StringPool.insert(InlinedSP.getName());
1501 StringPool.insert(InlinedSP.getLinkageName());
1502 DILocation DL(Scope->getInlinedAt());
1503 AddUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1504 AddUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1509 DIE *DwarfDebug::ConstructVariableDIE(DbgVariable *DV,
1510 DbgScope *Scope, CompileUnit *Unit) {
1511 // Get the descriptor.
1512 const DIVariable &VD = DV->getVariable();
1513 const char *Name = VD.getName();
1517 // Translate tag to proper Dwarf tag. The result variable is dropped for
1520 switch (VD.getTag()) {
1521 case dwarf::DW_TAG_return_variable:
1523 case dwarf::DW_TAG_arg_variable:
1524 Tag = dwarf::DW_TAG_formal_parameter;
1526 case dwarf::DW_TAG_auto_variable: // fall thru
1528 Tag = dwarf::DW_TAG_variable;
1532 // Define variable debug information entry.
1533 DIE *VariableDie = new DIE(Tag);
1537 if (DbgVariable *AV = DV->getAbstractVariable())
1538 AbsDIE = AV->getDIE();
1541 DIScope DS(Scope->getScopeNode());
1542 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1543 DIE *&OriginSPDIE = ModuleCU->getDieMapSlotFor(InlinedSP.getNode());
1545 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1546 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1547 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1548 AddDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1549 dwarf::DW_FORM_ref4, AbsDIE);
1552 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1553 AddSourceLine(VariableDie, &VD);
1555 // Add variable type.
1556 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1557 // addresses instead.
1558 if (VD.isBlockByrefVariable())
1559 AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1561 AddType(Unit, VariableDie, VD.getType());
1564 // Add variable address.
1565 if (!Scope->isAbstractScope()) {
1566 MachineLocation Location;
1567 Location.set(RI->getFrameRegister(*MF),
1568 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1571 if (VD.hasComplexAddress())
1572 AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1573 else if (VD.isBlockByrefVariable())
1574 AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1576 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1578 DV->setDIE(VariableDie);
1582 DIE *DwarfDebug::ConstructScopeDIE(DbgScope *Scope) {
1585 DIScope DS(Scope->getScopeNode());
1589 DIE *ScopeDIE = NULL;
1590 if (Scope->getInlinedAt())
1591 ScopeDIE = ConstructInlinedScopeDIE(Scope);
1592 else if (DS.isSubprogram()) {
1593 if (Scope->isAbstractScope())
1594 ScopeDIE = ModuleCU->getDieMapSlotFor(DS.getNode());
1596 ScopeDIE = UpdateSubprogramScopeDIE(DS.getNode());
1599 ScopeDIE = ConstructLexicalScopeDIE(Scope);
1600 if (!ScopeDIE) return NULL;
1603 // Add variables to scope.
1604 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1605 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1606 DIE *VariableDIE = ConstructVariableDIE(Variables[i], Scope, ModuleCU);
1608 ScopeDIE->AddChild(VariableDIE);
1611 // Add nested scopes.
1612 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1613 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1614 // Define the Scope debug information entry.
1615 DIE *NestedDIE = ConstructScopeDIE(Scopes[j]);
1617 ScopeDIE->AddChild(NestedDIE);
1622 /// GetOrCreateSourceID - Look up the source id with the given directory and
1623 /// source file names. If none currently exists, create a new id and insert it
1624 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1626 unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1627 const char *FileName) {
1629 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1630 if (DI != DirectoryIdMap.end()) {
1631 DId = DI->getValue();
1633 DId = DirectoryNames.size() + 1;
1634 DirectoryIdMap[DirName] = DId;
1635 DirectoryNames.push_back(DirName);
1639 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1640 if (FI != SourceFileIdMap.end()) {
1641 FId = FI->getValue();
1643 FId = SourceFileNames.size() + 1;
1644 SourceFileIdMap[FileName] = FId;
1645 SourceFileNames.push_back(FileName);
1648 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1649 SourceIdMap.find(std::make_pair(DId, FId));
1650 if (SI != SourceIdMap.end())
1653 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1654 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1655 SourceIds.push_back(std::make_pair(DId, FId));
1660 void DwarfDebug::ConstructCompileUnit(MDNode *N) {
1661 DICompileUnit DIUnit(N);
1662 const char *FN = DIUnit.getFilename();
1663 const char *Dir = DIUnit.getDirectory();
1664 unsigned ID = GetOrCreateSourceID(Dir, FN);
1666 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1667 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1668 DWLabel("section_line", 0), DWLabel("section_line", 0),
1670 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1671 DIUnit.getProducer());
1672 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1673 DIUnit.getLanguage());
1674 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1677 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1678 if (DIUnit.isOptimized())
1679 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1681 if (const char *Flags = DIUnit.getFlags())
1682 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1684 unsigned RVer = DIUnit.getRunTimeVersion();
1686 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1687 dwarf::DW_FORM_data1, RVer);
1689 CompileUnit *Unit = new CompileUnit(ID, Die);
1690 if (!ModuleCU && DIUnit.isMain()) {
1691 // Use first compile unit marked as isMain as the compile unit
1696 CompileUnitMap[DIUnit.getNode()] = Unit;
1697 CompileUnits.push_back(Unit);
1700 void DwarfDebug::ConstructGlobalVariableDIE(MDNode *N) {
1701 DIGlobalVariable DI_GV(N);
1703 // If debug information is malformed then ignore it.
1704 if (DI_GV.Verify() == false)
1707 // Check for pre-existence.
1708 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getNode());
1712 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1717 // Add to context owner.
1718 ModuleCU->getDie()->AddChild(VariableDie);
1720 // Expose as global. FIXME - need to check external flag.
1721 ModuleCU->AddGlobal(DI_GV.getName(), VariableDie);
1725 void DwarfDebug::ConstructSubprogram(MDNode *N) {
1728 // Check for pre-existence.
1729 DIE *&Slot = ModuleCU->getDieMapSlotFor(N);
1733 if (!SP.isDefinition())
1734 // This is a method declaration which will be handled while constructing
1738 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1741 Slot = SubprogramDie;
1743 // Add to context owner.
1744 ModuleCU->getDie()->AddChild(SubprogramDie);
1746 // Expose as global.
1747 ModuleCU->AddGlobal(SP.getName(), SubprogramDie);
1751 /// BeginModule - Emit all Dwarf sections that should come prior to the
1752 /// content. Create global DIEs and emit initial debug info sections.
1753 /// This is inovked by the target AsmPrinter.
1754 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1757 if (TimePassesIsEnabled)
1758 DebugTimer->startTimer();
1760 if (!MAI->doesSupportDebugInformation())
1763 DebugInfoFinder DbgFinder;
1764 DbgFinder.processModule(*M);
1766 // Create all the compile unit DIEs.
1767 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1768 E = DbgFinder.compile_unit_end(); I != E; ++I)
1769 ConstructCompileUnit(*I);
1771 if (CompileUnits.empty()) {
1772 if (TimePassesIsEnabled)
1773 DebugTimer->stopTimer();
1778 // If main compile unit for this module is not seen than randomly
1779 // select first compile unit.
1781 ModuleCU = CompileUnits[0];
1783 // Create DIEs for each of the externally visible global variables.
1784 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1785 E = DbgFinder.global_variable_end(); I != E; ++I) {
1786 DIGlobalVariable GV(*I);
1787 if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
1788 ScopedGVs.push_back(*I);
1790 ConstructGlobalVariableDIE(*I);
1793 // Create DIEs for each subprogram.
1794 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1795 E = DbgFinder.subprogram_end(); I != E; ++I)
1796 ConstructSubprogram(*I);
1800 MMI->setDebugInfoAvailability(true);
1802 // Prime section data.
1803 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1805 // Print out .file directives to specify files for .loc directives. These are
1806 // printed out early so that they precede any .loc directives.
1807 if (MAI->hasDotLocAndDotFile()) {
1808 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1809 // Remember source id starts at 1.
1810 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1811 sys::Path FullPath(getSourceDirectoryName(Id.first));
1813 FullPath.appendComponent(getSourceFileName(Id.second));
1814 assert(AppendOk && "Could not append filename to directory!");
1816 Asm->EmitFile(i, FullPath.str());
1821 // Emit initial sections
1824 if (TimePassesIsEnabled)
1825 DebugTimer->stopTimer();
1828 /// EndModule - Emit all Dwarf sections that should come after the content.
1830 void DwarfDebug::EndModule() {
1834 if (TimePassesIsEnabled)
1835 DebugTimer->startTimer();
1837 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1838 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1839 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1841 AddUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1844 // Standard sections final addresses.
1845 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1846 EmitLabel("text_end", 0);
1847 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1848 EmitLabel("data_end", 0);
1850 // End text sections.
1851 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1852 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1853 EmitLabel("section_end", i);
1856 // Emit common frame information.
1857 EmitCommonDebugFrame();
1859 // Emit function debug frame information
1860 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1861 E = DebugFrames.end(); I != E; ++I)
1862 EmitFunctionDebugFrame(*I);
1864 // Compute DIE offsets and sizes.
1867 // Emit all the DIEs into a debug info section
1870 // Corresponding abbreviations into a abbrev section.
1871 EmitAbbreviations();
1873 // Emit source line correspondence into a debug line section.
1876 // Emit info into a debug pubnames section.
1877 EmitDebugPubNames();
1879 // Emit info into a debug str section.
1882 // Emit info into a debug loc section.
1885 // Emit info into a debug aranges section.
1888 // Emit info into a debug ranges section.
1891 // Emit info into a debug macinfo section.
1894 // Emit inline info.
1895 EmitDebugInlineInfo();
1897 if (TimePassesIsEnabled)
1898 DebugTimer->stopTimer();
1901 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1902 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var, unsigned FrameIdx,
1903 DILocation &ScopeLoc) {
1905 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1907 return AbsDbgVariable;
1909 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1913 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1914 Scope->AddVariable(AbsDbgVariable);
1915 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1916 return AbsDbgVariable;
1919 /// CollectVariableInfo - Populate DbgScope entries with variables' info.
1920 void DwarfDebug::CollectVariableInfo() {
1923 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1924 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1925 VE = VMap.end(); VI != VE; ++VI) {
1926 MetadataBase *MB = VI->first;
1927 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1929 DIVariable DV (Var);
1930 std::pair< unsigned, MDNode *> VP = VI->second;
1931 DILocation ScopeLoc(VP.second);
1934 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1936 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1937 // If variable scope is not found then skip this variable.
1941 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1942 Scope->AddVariable(RegVar);
1943 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, ScopeLoc))
1944 RegVar->setAbstractVariable(AbsDbgVariable);
1948 /// BeginScope - Process beginning of a scope starting at Label.
1949 void DwarfDebug::BeginScope(const MachineInstr *MI, unsigned Label) {
1950 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1951 if (I == DbgScopeBeginMap.end())
1953 ScopeVector &SD = DbgScopeBeginMap[MI];
1954 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1956 (*SDI)->setStartLabelID(Label);
1959 /// EndScope - Process end of a scope.
1960 void DwarfDebug::EndScope(const MachineInstr *MI) {
1961 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1962 if (I == DbgScopeEndMap.end())
1965 unsigned Label = MMI->NextLabelID();
1966 Asm->printLabel(Label);
1968 SmallVector<DbgScope *, 2> &SD = I->second;
1969 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1971 (*SDI)->setEndLabelID(Label);
1975 /// createDbgScope - Create DbgScope for the scope.
1976 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1979 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1982 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1983 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1984 if (DIDescriptor(Scope).isLexicalBlock())
1985 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1989 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1993 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1994 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1995 DILocation DL(InlinedAt);
1996 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
1999 /// ExtractScopeInformation - Scan machine instructions in this function
2000 /// and collect DbgScopes. Return true, if atleast one scope was found.
2001 bool DwarfDebug::ExtractScopeInformation(MachineFunction *MF) {
2002 // If scope information was extracted using .dbg intrinsics then there is not
2003 // any need to extract these information by scanning each instruction.
2004 if (!DbgScopeMap.empty())
2007 // Scan each instruction and create scopes. First build working set of scopes.
2008 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2010 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2012 const MachineInstr *MInsn = II;
2013 DebugLoc DL = MInsn->getDebugLoc();
2014 if (DL.isUnknown()) continue;
2015 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2016 if (!DLT.Scope) continue;
2017 // There is no need to create another DIE for compile unit. For all
2018 // other scopes, create one DbgScope now. This will be translated
2019 // into a scope DIE at the end.
2020 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2021 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
2026 // Build scope hierarchy using working set of scopes.
2027 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2029 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2031 const MachineInstr *MInsn = II;
2032 DebugLoc DL = MInsn->getDebugLoc();
2033 if (DL.isUnknown()) continue;
2034 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2035 if (!DLT.Scope) continue;
2036 // There is no need to create another DIE for compile unit. For all
2037 // other scopes, create one DbgScope now. This will be translated
2038 // into a scope DIE at the end.
2039 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2040 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
2041 Scope->setLastInsn(MInsn);
2045 // If a scope's last instruction is not set then use its child scope's
2046 // last instruction as this scope's last instrunction.
2047 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2048 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2049 if (DI->second->isAbstractScope())
2051 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
2052 DI->second->FixInstructionMarkers();
2053 assert (DI->second->getLastInsn() && "Invalid last instruction!");
2056 // Each scope has first instruction and last instruction to mark beginning
2057 // and end of a scope respectively. Create an inverse map that list scopes
2058 // starts (and ends) with an instruction. One instruction may start (or end)
2060 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2061 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2062 DbgScope *S = DI->second;
2063 if (S->isAbstractScope())
2065 const MachineInstr *MI = S->getFirstInsn();
2066 assert (MI && "DbgScope does not have first instruction!");
2068 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2069 if (IDI != DbgScopeBeginMap.end())
2070 IDI->second.push_back(S);
2072 DbgScopeBeginMap[MI].push_back(S);
2074 MI = S->getLastInsn();
2075 assert (MI && "DbgScope does not have last instruction!");
2076 IDI = DbgScopeEndMap.find(MI);
2077 if (IDI != DbgScopeEndMap.end())
2078 IDI->second.push_back(S);
2080 DbgScopeEndMap[MI].push_back(S);
2083 return !DbgScopeMap.empty();
2086 /// BeginFunction - Gather pre-function debug information. Assumes being
2087 /// emitted immediately after the function entry point.
2088 void DwarfDebug::BeginFunction(MachineFunction *MF) {
2091 if (!ShouldEmitDwarfDebug()) return;
2093 if (TimePassesIsEnabled)
2094 DebugTimer->startTimer();
2096 if (!ExtractScopeInformation(MF))
2098 CollectVariableInfo();
2100 // Begin accumulating function debug information.
2101 MMI->BeginFunction(MF);
2103 // Assumes in correct section after the entry point.
2104 EmitLabel("func_begin", ++SubprogramCount);
2106 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2108 DebugLoc FDL = MF->getDefaultDebugLoc();
2109 if (!FDL.isUnknown()) {
2110 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2111 unsigned LabelID = 0;
2112 DISubprogram SP = getDISubprogram(DLT.Scope);
2114 LabelID = RecordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2116 LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2117 Asm->printLabel(LabelID);
2120 if (TimePassesIsEnabled)
2121 DebugTimer->stopTimer();
2124 /// EndFunction - Gather and emit post-function debug information.
2126 void DwarfDebug::EndFunction(MachineFunction *MF) {
2127 if (!ShouldEmitDwarfDebug()) return;
2129 if (TimePassesIsEnabled)
2130 DebugTimer->startTimer();
2132 if (DbgScopeMap.empty())
2135 // Define end label for subprogram.
2136 EmitLabel("func_end", SubprogramCount);
2138 // Get function line info.
2139 if (!Lines.empty()) {
2140 // Get section line info.
2141 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2142 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2143 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2144 // Append the function info to section info.
2145 SectionLineInfos.insert(SectionLineInfos.end(),
2146 Lines.begin(), Lines.end());
2149 // Construct abstract scopes.
2150 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2151 AE = AbstractScopesList.end(); AI != AE; ++AI)
2152 ConstructScopeDIE(*AI);
2154 ConstructScopeDIE(CurrentFnDbgScope);
2156 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2157 MMI->getFrameMoves()));
2160 if (CurrentFnDbgScope) {
2161 CurrentFnDbgScope = NULL;
2162 DbgScopeMap.clear();
2163 DbgScopeBeginMap.clear();
2164 DbgScopeEndMap.clear();
2165 ConcreteScopes.clear();
2166 AbstractScopesList.clear();
2171 if (TimePassesIsEnabled)
2172 DebugTimer->stopTimer();
2175 /// RecordSourceLine - Records location information and associates it with a
2176 /// label. Returns a unique label ID used to generate a label and provide
2177 /// correspondence to the source line list.
2178 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2183 if (TimePassesIsEnabled)
2184 DebugTimer->startTimer();
2186 const char *Dir = NULL;
2187 const char *Fn = NULL;
2189 DIDescriptor Scope(S);
2190 if (Scope.isCompileUnit()) {
2191 DICompileUnit CU(S);
2192 Dir = CU.getDirectory();
2193 Fn = CU.getFilename();
2194 } else if (Scope.isSubprogram()) {
2196 Dir = SP.getDirectory();
2197 Fn = SP.getFilename();
2198 } else if (Scope.isLexicalBlock()) {
2199 DILexicalBlock DB(S);
2200 Dir = DB.getDirectory();
2201 Fn = DB.getFilename();
2203 assert (0 && "Unexpected scope info");
2205 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2206 unsigned ID = MMI->NextLabelID();
2207 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2209 if (TimePassesIsEnabled)
2210 DebugTimer->stopTimer();
2215 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2216 /// timed. Look up the source id with the given directory and source file
2217 /// names. If none currently exists, create a new id and insert it in the
2218 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2220 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2221 const std::string &FileName) {
2222 if (TimePassesIsEnabled)
2223 DebugTimer->startTimer();
2225 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2227 if (TimePassesIsEnabled)
2228 DebugTimer->stopTimer();
2233 //===----------------------------------------------------------------------===//
2235 //===----------------------------------------------------------------------===//
2237 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2239 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2240 // Get the children.
2241 const std::vector<DIE *> &Children = Die->getChildren();
2243 // If not last sibling and has children then add sibling offset attribute.
2244 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2246 // Record the abbreviation.
2247 AssignAbbrevNumber(Die->getAbbrev());
2249 // Get the abbreviation for this DIE.
2250 unsigned AbbrevNumber = Die->getAbbrevNumber();
2251 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2254 Die->setOffset(Offset);
2256 // Start the size with the size of abbreviation code.
2257 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2259 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2260 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2262 // Size the DIE attribute values.
2263 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2264 // Size attribute value.
2265 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2267 // Size the DIE children if any.
2268 if (!Children.empty()) {
2269 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2270 "Children flag not set");
2272 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2273 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2275 // End of children marker.
2276 Offset += sizeof(int8_t);
2279 Die->setSize(Offset - Die->getOffset());
2283 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2285 void DwarfDebug::SizeAndOffsets() {
2286 // Compute size of compile unit header.
2287 static unsigned Offset =
2288 sizeof(int32_t) + // Length of Compilation Unit Info
2289 sizeof(int16_t) + // DWARF version number
2290 sizeof(int32_t) + // Offset Into Abbrev. Section
2291 sizeof(int8_t); // Pointer Size (in bytes)
2293 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
2294 CompileUnitOffsets[ModuleCU] = 0;
2297 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2298 /// tools to recognize the object file contains Dwarf information.
2299 void DwarfDebug::EmitInitial() {
2300 // Check to see if we already emitted intial headers.
2301 if (didInitial) return;
2304 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2306 // Dwarf sections base addresses.
2307 if (MAI->doesDwarfRequireFrameSection()) {
2308 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2309 EmitLabel("section_debug_frame", 0);
2312 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2313 EmitLabel("section_info", 0);
2314 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2315 EmitLabel("section_abbrev", 0);
2316 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2317 EmitLabel("section_aranges", 0);
2319 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2320 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2321 EmitLabel("section_macinfo", 0);
2324 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2325 EmitLabel("section_line", 0);
2326 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2327 EmitLabel("section_loc", 0);
2328 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2329 EmitLabel("section_pubnames", 0);
2330 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2331 EmitLabel("section_str", 0);
2332 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2333 EmitLabel("section_ranges", 0);
2335 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2336 EmitLabel("text_begin", 0);
2337 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2338 EmitLabel("data_begin", 0);
2341 /// EmitDIE - Recusively Emits a debug information entry.
2343 void DwarfDebug::EmitDIE(DIE *Die) {
2344 // Get the abbreviation for this DIE.
2345 unsigned AbbrevNumber = Die->getAbbrevNumber();
2346 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2350 // Emit the code (index) for the abbreviation.
2351 Asm->EmitULEB128Bytes(AbbrevNumber);
2353 if (Asm->isVerbose())
2354 Asm->EOL(std::string("Abbrev [" +
2355 utostr(AbbrevNumber) +
2356 "] 0x" + utohexstr(Die->getOffset()) +
2357 ":0x" + utohexstr(Die->getSize()) + " " +
2358 dwarf::TagString(Abbrev->getTag())));
2362 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2363 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2365 // Emit the DIE attribute values.
2366 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2367 unsigned Attr = AbbrevData[i].getAttribute();
2368 unsigned Form = AbbrevData[i].getForm();
2369 assert(Form && "Too many attributes for DIE (check abbreviation)");
2372 case dwarf::DW_AT_sibling:
2373 Asm->EmitInt32(Die->SiblingOffset());
2375 case dwarf::DW_AT_abstract_origin: {
2376 DIEEntry *E = cast<DIEEntry>(Values[i]);
2377 DIE *Origin = E->getEntry();
2378 unsigned Addr = Origin->getOffset();
2379 Asm->EmitInt32(Addr);
2383 // Emit an attribute using the defined form.
2384 Values[i]->EmitValue(this, Form);
2388 Asm->EOL(dwarf::AttributeString(Attr));
2391 // Emit the DIE children if any.
2392 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2393 const std::vector<DIE *> &Children = Die->getChildren();
2395 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2396 EmitDIE(Children[j]);
2398 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2402 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2404 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2405 DIE *Die = Unit->getDie();
2407 // Emit the compile units header.
2408 EmitLabel("info_begin", Unit->getID());
2410 // Emit size of content not including length itself
2411 unsigned ContentSize = Die->getSize() +
2412 sizeof(int16_t) + // DWARF version number
2413 sizeof(int32_t) + // Offset Into Abbrev. Section
2414 sizeof(int8_t) + // Pointer Size (in bytes)
2415 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2417 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2418 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2419 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2420 Asm->EOL("Offset Into Abbrev. Section");
2421 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2424 // FIXME - extra padding for gdb bug.
2425 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2426 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2427 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2428 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2429 EmitLabel("info_end", Unit->getID());
2434 void DwarfDebug::EmitDebugInfo() {
2435 // Start debug info section.
2436 Asm->OutStreamer.SwitchSection(
2437 Asm->getObjFileLowering().getDwarfInfoSection());
2439 EmitDebugInfoPerCU(ModuleCU);
2442 /// EmitAbbreviations - Emit the abbreviation section.
2444 void DwarfDebug::EmitAbbreviations() const {
2445 // Check to see if it is worth the effort.
2446 if (!Abbreviations.empty()) {
2447 // Start the debug abbrev section.
2448 Asm->OutStreamer.SwitchSection(
2449 Asm->getObjFileLowering().getDwarfAbbrevSection());
2451 EmitLabel("abbrev_begin", 0);
2453 // For each abbrevation.
2454 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2455 // Get abbreviation data
2456 const DIEAbbrev *Abbrev = Abbreviations[i];
2458 // Emit the abbrevations code (base 1 index.)
2459 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2460 Asm->EOL("Abbreviation Code");
2462 // Emit the abbreviations data.
2468 // Mark end of abbreviations.
2469 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2471 EmitLabel("abbrev_end", 0);
2476 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2477 /// the line matrix.
2479 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2480 // Define last address of section.
2481 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2482 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2483 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2484 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2486 // Mark end of matrix.
2487 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2488 Asm->EmitULEB128Bytes(1); Asm->EOL();
2489 Asm->EmitInt8(1); Asm->EOL();
2492 /// EmitDebugLines - Emit source line information.
2494 void DwarfDebug::EmitDebugLines() {
2495 // If the target is using .loc/.file, the assembler will be emitting the
2496 // .debug_line table automatically.
2497 if (MAI->hasDotLocAndDotFile())
2500 // Minimum line delta, thus ranging from -10..(255-10).
2501 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2502 // Maximum line delta, thus ranging from -10..(255-10).
2503 const int MaxLineDelta = 255 + MinLineDelta;
2505 // Start the dwarf line section.
2506 Asm->OutStreamer.SwitchSection(
2507 Asm->getObjFileLowering().getDwarfLineSection());
2509 // Construct the section header.
2510 EmitDifference("line_end", 0, "line_begin", 0, true);
2511 Asm->EOL("Length of Source Line Info");
2512 EmitLabel("line_begin", 0);
2514 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2516 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2517 Asm->EOL("Prolog Length");
2518 EmitLabel("line_prolog_begin", 0);
2520 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2522 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2524 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2526 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2528 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2530 // Line number standard opcode encodings argument count
2531 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2532 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2533 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2534 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2535 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2536 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2537 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2538 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2539 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2541 // Emit directories.
2542 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2543 Asm->EmitString(getSourceDirectoryName(DI));
2544 Asm->EOL("Directory");
2547 Asm->EmitInt8(0); Asm->EOL("End of directories");
2550 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2551 // Remember source id starts at 1.
2552 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2553 Asm->EmitString(getSourceFileName(Id.second));
2555 Asm->EmitULEB128Bytes(Id.first);
2556 Asm->EOL("Directory #");
2557 Asm->EmitULEB128Bytes(0);
2558 Asm->EOL("Mod date");
2559 Asm->EmitULEB128Bytes(0);
2560 Asm->EOL("File size");
2563 Asm->EmitInt8(0); Asm->EOL("End of files");
2565 EmitLabel("line_prolog_end", 0);
2567 // A sequence for each text section.
2568 unsigned SecSrcLinesSize = SectionSourceLines.size();
2570 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2571 // Isolate current sections line info.
2572 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2574 /*if (Asm->isVerbose()) {
2575 const MCSection *S = SectionMap[j + 1];
2576 O << '\t' << MAI->getCommentString() << " Section"
2577 << S->getName() << '\n';
2581 // Dwarf assumes we start with first line of first source file.
2582 unsigned Source = 1;
2585 // Construct rows of the address, source, line, column matrix.
2586 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2587 const SrcLineInfo &LineInfo = LineInfos[i];
2588 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2589 if (!LabelID) continue;
2591 if (LineInfo.getLine() == 0) continue;
2593 if (!Asm->isVerbose())
2596 std::pair<unsigned, unsigned> SourceID =
2597 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2598 O << '\t' << MAI->getCommentString() << ' '
2599 << getSourceDirectoryName(SourceID.first) << ' '
2600 << getSourceFileName(SourceID.second)
2601 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2604 // Define the line address.
2605 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2606 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2607 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2608 EmitReference("label", LabelID); Asm->EOL("Location label");
2610 // If change of source, then switch to the new source.
2611 if (Source != LineInfo.getSourceID()) {
2612 Source = LineInfo.getSourceID();
2613 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2614 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2617 // If change of line.
2618 if (Line != LineInfo.getLine()) {
2619 // Determine offset.
2620 int Offset = LineInfo.getLine() - Line;
2621 int Delta = Offset - MinLineDelta;
2624 Line = LineInfo.getLine();
2626 // If delta is small enough and in range...
2627 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2628 // ... then use fast opcode.
2629 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2631 // ... otherwise use long hand.
2632 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2633 Asm->EOL("DW_LNS_advance_line");
2634 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2635 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2638 // Copy the previous row (different address or source)
2639 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2643 EmitEndOfLineMatrix(j + 1);
2646 if (SecSrcLinesSize == 0)
2647 // Because we're emitting a debug_line section, we still need a line
2648 // table. The linker and friends expect it to exist. If there's nothing to
2649 // put into it, emit an empty table.
2650 EmitEndOfLineMatrix(1);
2652 EmitLabel("line_end", 0);
2656 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2658 void DwarfDebug::EmitCommonDebugFrame() {
2659 if (!MAI->doesDwarfRequireFrameSection())
2663 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2664 TargetFrameInfo::StackGrowsUp ?
2665 TD->getPointerSize() : -TD->getPointerSize();
2667 // Start the dwarf frame section.
2668 Asm->OutStreamer.SwitchSection(
2669 Asm->getObjFileLowering().getDwarfFrameSection());
2671 EmitLabel("debug_frame_common", 0);
2672 EmitDifference("debug_frame_common_end", 0,
2673 "debug_frame_common_begin", 0, true);
2674 Asm->EOL("Length of Common Information Entry");
2676 EmitLabel("debug_frame_common_begin", 0);
2677 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2678 Asm->EOL("CIE Identifier Tag");
2679 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2680 Asm->EOL("CIE Version");
2681 Asm->EmitString("");
2682 Asm->EOL("CIE Augmentation");
2683 Asm->EmitULEB128Bytes(1);
2684 Asm->EOL("CIE Code Alignment Factor");
2685 Asm->EmitSLEB128Bytes(stackGrowth);
2686 Asm->EOL("CIE Data Alignment Factor");
2687 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2688 Asm->EOL("CIE RA Column");
2690 std::vector<MachineMove> Moves;
2691 RI->getInitialFrameState(Moves);
2693 EmitFrameMoves(NULL, 0, Moves, false);
2695 Asm->EmitAlignment(2, 0, 0, false);
2696 EmitLabel("debug_frame_common_end", 0);
2701 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2704 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2705 if (!MAI->doesDwarfRequireFrameSection())
2708 // Start the dwarf frame section.
2709 Asm->OutStreamer.SwitchSection(
2710 Asm->getObjFileLowering().getDwarfFrameSection());
2712 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2713 "debug_frame_begin", DebugFrameInfo.Number, true);
2714 Asm->EOL("Length of Frame Information Entry");
2716 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2718 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2720 Asm->EOL("FDE CIE offset");
2722 EmitReference("func_begin", DebugFrameInfo.Number);
2723 Asm->EOL("FDE initial location");
2724 EmitDifference("func_end", DebugFrameInfo.Number,
2725 "func_begin", DebugFrameInfo.Number);
2726 Asm->EOL("FDE address range");
2728 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2731 Asm->EmitAlignment(2, 0, 0, false);
2732 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2737 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2738 EmitDifference("pubnames_end", Unit->getID(),
2739 "pubnames_begin", Unit->getID(), true);
2740 Asm->EOL("Length of Public Names Info");
2742 EmitLabel("pubnames_begin", Unit->getID());
2744 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2746 EmitSectionOffset("info_begin", "section_info",
2747 Unit->getID(), 0, true, false);
2748 Asm->EOL("Offset of Compilation Unit Info");
2750 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2752 Asm->EOL("Compilation Unit Length");
2754 StringMap<DIE*> &Globals = Unit->getGlobals();
2755 for (StringMap<DIE*>::const_iterator
2756 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2757 const char *Name = GI->getKeyData();
2758 DIE * Entity = GI->second;
2760 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2761 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2764 Asm->EmitInt32(0); Asm->EOL("End Mark");
2765 EmitLabel("pubnames_end", Unit->getID());
2770 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2772 void DwarfDebug::EmitDebugPubNames() {
2773 // Start the dwarf pubnames section.
2774 Asm->OutStreamer.SwitchSection(
2775 Asm->getObjFileLowering().getDwarfPubNamesSection());
2777 EmitDebugPubNamesPerCU(ModuleCU);
2780 /// EmitDebugStr - Emit visible names into a debug str section.
2782 void DwarfDebug::EmitDebugStr() {
2783 // Check to see if it is worth the effort.
2784 if (!StringPool.empty()) {
2785 // Start the dwarf str section.
2786 Asm->OutStreamer.SwitchSection(
2787 Asm->getObjFileLowering().getDwarfStrSection());
2789 // For each of strings in the string pool.
2790 for (unsigned StringID = 1, N = StringPool.size();
2791 StringID <= N; ++StringID) {
2792 // Emit a label for reference from debug information entries.
2793 EmitLabel("string", StringID);
2795 // Emit the string itself.
2796 const std::string &String = StringPool[StringID];
2797 Asm->EmitString(String); Asm->EOL();
2804 /// EmitDebugLoc - Emit visible names into a debug loc section.
2806 void DwarfDebug::EmitDebugLoc() {
2807 // Start the dwarf loc section.
2808 Asm->OutStreamer.SwitchSection(
2809 Asm->getObjFileLowering().getDwarfLocSection());
2813 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2815 void DwarfDebug::EmitDebugARanges() {
2816 // Start the dwarf aranges section.
2817 Asm->OutStreamer.SwitchSection(
2818 Asm->getObjFileLowering().getDwarfARangesSection());
2822 CompileUnit *Unit = GetBaseCompileUnit();
2824 // Don't include size of length
2825 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2827 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2829 EmitReference("info_begin", Unit->getID());
2830 Asm->EOL("Offset of Compilation Unit Info");
2832 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2834 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2836 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2837 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2840 EmitReference("text_begin", 0); Asm->EOL("Address");
2841 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2843 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2844 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2850 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2852 void DwarfDebug::EmitDebugRanges() {
2853 // Start the dwarf ranges section.
2854 Asm->OutStreamer.SwitchSection(
2855 Asm->getObjFileLowering().getDwarfRangesSection());
2859 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2861 void DwarfDebug::EmitDebugMacInfo() {
2862 if (const MCSection *LineInfo =
2863 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2864 // Start the dwarf macinfo section.
2865 Asm->OutStreamer.SwitchSection(LineInfo);
2870 /// EmitDebugInlineInfo - Emit inline info using following format.
2872 /// 1. length of section
2873 /// 2. Dwarf version number
2874 /// 3. address size.
2876 /// Entries (one "entry" for each function that was inlined):
2878 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2879 /// otherwise offset into __debug_str for regular function name.
2880 /// 2. offset into __debug_str section for regular function name.
2881 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2882 /// instances for the function.
2884 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2885 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2886 /// __debug_info section, and the low_pc is the starting address for the
2887 /// inlining instance.
2888 void DwarfDebug::EmitDebugInlineInfo() {
2889 if (!MAI->doesDwarfUsesInlineInfoSection())
2895 Asm->OutStreamer.SwitchSection(
2896 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2898 EmitDifference("debug_inlined_end", 1,
2899 "debug_inlined_begin", 1, true);
2900 Asm->EOL("Length of Debug Inlined Information Entry");
2902 EmitLabel("debug_inlined_begin", 1);
2904 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2905 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2907 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2908 E = InlinedSPNodes.end(); I != E; ++I) {
2910 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2911 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2913 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II = InlineInfo.find(Node);
2914 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2915 DISubprogram SP(Node);
2916 const char *LName = SP.getLinkageName();
2917 const char *Name = SP.getName();
2920 Asm->EmitString(Name);
2922 // Skip special LLVM prefix that is used to inform the asm printer to not
2923 // emit usual symbol prefix before the symbol name. This happens for
2924 // Objective-C symbol names and symbol whose name is replaced using GCC's
2925 // __asm__ attribute.
2928 // Asm->EmitString(LName);
2929 EmitSectionOffset("string", "section_str",
2930 StringPool.idFor(LName), false, true);
2933 Asm->EOL("MIPS linkage name");
2934 // Asm->EmitString(Name);
2935 EmitSectionOffset("string", "section_str",
2936 StringPool.idFor(Name), false, true);
2937 Asm->EOL("Function name");
2938 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2940 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2941 LE = Labels.end(); LI != LE; ++LI) {
2942 DIE *SP = LI->second;
2943 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2945 if (TD->getPointerSize() == sizeof(int32_t))
2946 O << MAI->getData32bitsDirective();
2948 O << MAI->getData64bitsDirective();
2950 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2954 EmitLabel("debug_inlined_end", 1);