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/Mangler.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/System/Path.h"
32 static TimerGroup &getDwarfTimerGroup() {
33 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
34 return DwarfTimerGroup;
37 //===----------------------------------------------------------------------===//
39 /// Configuration values for initial hash set sizes (log2).
41 static const unsigned InitDiesSetSize = 9; // log2(512)
42 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
43 static const unsigned InitValuesSetSize = 9; // log2(512)
47 //===----------------------------------------------------------------------===//
48 /// CompileUnit - This dwarf writer support class manages information associate
49 /// with a source file.
50 class VISIBILITY_HIDDEN CompileUnit {
51 /// ID - File identifier for source.
55 /// Die - Compile unit debug information entry.
59 /// GVToDieMap - Tracks the mapping of unit level debug informaton
60 /// variables to debug information entries.
61 /// FIXME : Rename GVToDieMap -> NodeToDieMap
62 std::map<MDNode *, DIE *> GVToDieMap;
64 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
65 /// descriptors to debug information entries using a DIEEntry proxy.
67 std::map<MDNode *, DIEEntry *> GVToDIEEntryMap;
69 /// Globals - A map of globally visible named entities for this unit.
71 StringMap<DIE*> Globals;
73 /// DiesSet - Used to uniquely define dies within the compile unit.
75 FoldingSet<DIE> DiesSet;
77 CompileUnit(unsigned I, DIE *D)
78 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
79 ~CompileUnit() { delete Die; }
82 unsigned getID() const { return ID; }
83 DIE* getDie() const { return Die; }
84 StringMap<DIE*> &getGlobals() { return Globals; }
86 /// hasContent - Return true if this compile unit has something to write out.
88 bool hasContent() const { return !Die->getChildren().empty(); }
90 /// AddGlobal - Add a new global entity to the compile unit.
92 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
94 /// getDieMapSlotFor - Returns the debug information entry map slot for the
95 /// specified debug variable.
96 DIE *&getDieMapSlotFor(MDNode *N) { return GVToDieMap[N]; }
98 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
99 /// the specified debug variable.
100 DIEEntry *&getDIEEntrySlotFor(MDNode *N) {
101 return GVToDIEEntryMap[N];
104 /// AddDie - Adds or interns the DIE to the compile unit.
106 DIE *AddDie(DIE &Buffer) {
110 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
113 Die = new DIE(Buffer);
114 DiesSet.InsertNode(Die, Where);
115 this->Die->AddChild(Die);
123 //===----------------------------------------------------------------------===//
124 /// DbgVariable - This class is used to track local variable information.
126 class VISIBILITY_HIDDEN DbgVariable {
127 DIVariable Var; // Variable Descriptor.
128 unsigned FrameIndex; // Variable frame index.
129 bool InlinedFnVar; // Variable for an inlined function.
131 DbgVariable(DIVariable V, unsigned I, bool IFV)
132 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
135 DIVariable getVariable() const { return Var; }
136 unsigned getFrameIndex() const { return FrameIndex; }
137 bool isInlinedFnVar() const { return InlinedFnVar; }
140 //===----------------------------------------------------------------------===//
141 /// DbgScope - This class is used to track scope information.
143 class DbgConcreteScope;
144 class VISIBILITY_HIDDEN DbgScope {
145 DbgScope *Parent; // Parent to this scope.
146 DIDescriptor Desc; // Debug info descriptor for scope.
147 // Either subprogram or block.
148 unsigned StartLabelID; // Label ID of the beginning of scope.
149 unsigned EndLabelID; // Label ID of the end of scope.
150 const MachineInstr *LastInsn; // Last instruction of this scope.
151 const MachineInstr *FirstInsn; // First instruction of this scope.
152 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
153 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
154 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
156 // Private state for dump()
157 mutable unsigned IndentLevel;
159 DbgScope(DbgScope *P, DIDescriptor D)
160 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), LastInsn(0),
161 FirstInsn(0), IndentLevel(0) {}
165 DbgScope *getParent() const { return Parent; }
166 DIDescriptor getDesc() const { return Desc; }
167 unsigned getStartLabelID() const { return StartLabelID; }
168 unsigned getEndLabelID() const { return EndLabelID; }
169 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
170 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
171 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
172 void setStartLabelID(unsigned S) { StartLabelID = S; }
173 void setEndLabelID(unsigned E) { EndLabelID = E; }
174 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
175 const MachineInstr *getLastInsn() { return LastInsn; }
176 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
177 const MachineInstr *getFirstInsn() { return FirstInsn; }
178 /// AddScope - Add a scope to the scope.
180 void AddScope(DbgScope *S) { Scopes.push_back(S); }
182 /// AddVariable - Add a variable to the scope.
184 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
186 /// AddConcreteInst - Add a concrete instance to the scope.
188 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
190 void FixInstructionMarkers() {
191 assert (getFirstInsn() && "First instruction is missing!");
195 // If a scope does not have an instruction to mark an end then use
196 // the end of last child scope.
197 SmallVector<DbgScope *, 4> &Scopes = getScopes();
198 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
199 DbgScope *L = Scopes.back();
200 if (!L->getLastInsn())
201 L->FixInstructionMarkers();
202 setLastInsn(L->getLastInsn());
211 void DbgScope::dump() const {
212 raw_ostream &err = errs();
213 err.indent(IndentLevel);
215 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
219 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
220 if (Scopes[i] != this)
227 //===----------------------------------------------------------------------===//
228 /// DbgConcreteScope - This class is used to track a scope that holds concrete
229 /// instance information.
231 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
233 DIE *Die; // Debug info for this concrete scope.
235 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
238 DIE *getDie() const { return Die; }
239 void setDie(DIE *D) { Die = D; }
242 DbgScope::~DbgScope() {
243 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
245 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
247 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
248 delete ConcreteInsts[k];
251 } // end llvm namespace
253 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
254 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
255 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
256 ValuesSet(InitValuesSetSize), Values(), StringPool(),
257 SectionSourceLines(), didInitial(false), shouldEmit(false),
258 FunctionDbgScope(0), DebugTimer(0) {
259 if (TimePassesIsEnabled)
260 DebugTimer = new Timer("Dwarf Debug Writer",
261 getDwarfTimerGroup());
263 DwarfDebug::~DwarfDebug() {
264 for (unsigned j = 0, M = Values.size(); j < M; ++j)
267 for (DenseMap<const MDNode *, DbgScope *>::iterator
268 I = AbstractInstanceRootMap.begin(),
269 E = AbstractInstanceRootMap.end(); I != E;++I)
275 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
277 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
278 // Profile the node so that we can make it unique.
282 // Check the set for priors.
283 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
285 // If it's newly added.
286 if (InSet == &Abbrev) {
287 // Add to abbreviation list.
288 Abbreviations.push_back(&Abbrev);
290 // Assign the vector position + 1 as its number.
291 Abbrev.setNumber(Abbreviations.size());
293 // Assign existing abbreviation number.
294 Abbrev.setNumber(InSet->getNumber());
298 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
299 /// information entry.
300 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
305 DIEEntry::Profile(ID, Entry);
307 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
309 if (Value) return Value;
311 Value = new DIEEntry(Entry);
312 ValuesSet.InsertNode(Value, Where);
314 Value = new DIEEntry(Entry);
317 Values.push_back(Value);
321 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
323 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
324 Value->setEntry(Entry);
326 // Add to values set if not already there. If it is, we merely have a
327 // duplicate in the values list (no harm.)
328 ValuesSet.GetOrInsertNode(Value);
331 /// AddUInt - Add an unsigned integer attribute data and value.
333 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
334 unsigned Form, uint64_t Integer) {
335 if (!Form) Form = DIEInteger::BestForm(false, Integer);
338 DIEInteger::Profile(ID, Integer);
340 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
343 Value = new DIEInteger(Integer);
344 ValuesSet.InsertNode(Value, Where);
345 Values.push_back(Value);
348 Die->AddValue(Attribute, Form, Value);
351 /// AddSInt - Add an signed integer attribute data and value.
353 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
354 unsigned Form, int64_t Integer) {
355 if (!Form) Form = DIEInteger::BestForm(true, Integer);
358 DIEInteger::Profile(ID, (uint64_t)Integer);
360 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
363 Value = new DIEInteger(Integer);
364 ValuesSet.InsertNode(Value, Where);
365 Values.push_back(Value);
368 Die->AddValue(Attribute, Form, Value);
371 /// AddString - Add a string attribute data and value.
373 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
374 const std::string &String) {
376 DIEString::Profile(ID, String);
378 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
381 Value = new DIEString(String);
382 ValuesSet.InsertNode(Value, Where);
383 Values.push_back(Value);
386 Die->AddValue(Attribute, Form, Value);
389 /// AddLabel - Add a Dwarf label attribute data and value.
391 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
392 const DWLabel &Label) {
394 DIEDwarfLabel::Profile(ID, Label);
396 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
399 Value = new DIEDwarfLabel(Label);
400 ValuesSet.InsertNode(Value, Where);
401 Values.push_back(Value);
404 Die->AddValue(Attribute, Form, Value);
407 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
409 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
410 const std::string &Label) {
412 DIEObjectLabel::Profile(ID, Label);
414 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
417 Value = new DIEObjectLabel(Label);
418 ValuesSet.InsertNode(Value, Where);
419 Values.push_back(Value);
422 Die->AddValue(Attribute, Form, Value);
425 /// AddSectionOffset - Add a section offset label attribute data and value.
427 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
428 const DWLabel &Label, const DWLabel &Section,
429 bool isEH, bool useSet) {
431 DIESectionOffset::Profile(ID, Label, Section);
433 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
436 Value = new DIESectionOffset(Label, Section, isEH, useSet);
437 ValuesSet.InsertNode(Value, Where);
438 Values.push_back(Value);
441 Die->AddValue(Attribute, Form, Value);
444 /// AddDelta - Add a label delta attribute data and value.
446 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
447 const DWLabel &Hi, const DWLabel &Lo) {
449 DIEDelta::Profile(ID, Hi, Lo);
451 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
454 Value = new DIEDelta(Hi, Lo);
455 ValuesSet.InsertNode(Value, Where);
456 Values.push_back(Value);
459 Die->AddValue(Attribute, Form, Value);
462 /// AddBlock - Add block data.
464 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
466 Block->ComputeSize(TD);
470 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
474 ValuesSet.InsertNode(Value, Where);
475 Values.push_back(Value);
477 // Already exists, reuse the previous one.
479 Block = cast<DIEBlock>(Value);
482 Die->AddValue(Attribute, Block->BestForm(), Value);
485 /// AddSourceLine - Add location information to specified debug information
487 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
488 // If there is no compile unit specified, don't add a line #.
489 if (V->getCompileUnit().isNull())
492 unsigned Line = V->getLineNumber();
493 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
494 assert(FileID && "Invalid file id");
495 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
496 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
499 /// AddSourceLine - Add location information to specified debug information
501 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
502 // If there is no compile unit specified, don't add a line #.
503 if (G->getCompileUnit().isNull())
506 unsigned Line = G->getLineNumber();
507 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
508 assert(FileID && "Invalid file id");
509 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
510 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
513 /// AddSourceLine - Add location information to specified debug information
515 void DwarfDebug::AddSourceLine(DIE *Die, const DISubprogram *SP) {
516 // If there is no compile unit specified, don't add a line #.
517 if (SP->getCompileUnit().isNull())
519 // If the line number is 0, don't add it.
520 if (SP->getLineNumber() == 0)
524 unsigned Line = SP->getLineNumber();
525 unsigned FileID = FindCompileUnit(SP->getCompileUnit()).getID();
526 assert(FileID && "Invalid file id");
527 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
528 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
531 /// AddSourceLine - Add location information to specified debug information
533 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
534 // If there is no compile unit specified, don't add a line #.
535 DICompileUnit CU = Ty->getCompileUnit();
539 unsigned Line = Ty->getLineNumber();
540 unsigned FileID = FindCompileUnit(CU).getID();
541 assert(FileID && "Invalid file id");
542 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
543 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
546 /* Byref variables, in Blocks, are declared by the programmer as
547 "SomeType VarName;", but the compiler creates a
548 __Block_byref_x_VarName struct, and gives the variable VarName
549 either the struct, or a pointer to the struct, as its type. This
550 is necessary for various behind-the-scenes things the compiler
551 needs to do with by-reference variables in blocks.
553 However, as far as the original *programmer* is concerned, the
554 variable should still have type 'SomeType', as originally declared.
556 The following function dives into the __Block_byref_x_VarName
557 struct to find the original type of the variable. This will be
558 passed back to the code generating the type for the Debug
559 Information Entry for the variable 'VarName'. 'VarName' will then
560 have the original type 'SomeType' in its debug information.
562 The original type 'SomeType' will be the type of the field named
563 'VarName' inside the __Block_byref_x_VarName struct.
565 NOTE: In order for this to not completely fail on the debugger
566 side, the Debug Information Entry for the variable VarName needs to
567 have a DW_AT_location that tells the debugger how to unwind through
568 the pointers and __Block_byref_x_VarName struct to find the actual
569 value of the variable. The function AddBlockByrefType does this. */
571 /// Find the type the programmer originally declared the variable to be
572 /// and return that type.
574 DIType DwarfDebug::GetBlockByrefType(DIType Ty, std::string Name) {
577 unsigned tag = Ty.getTag();
579 if (tag == dwarf::DW_TAG_pointer_type) {
580 DIDerivedType DTy = DIDerivedType(Ty.getNode());
581 subType = DTy.getTypeDerivedFrom();
584 DICompositeType blockStruct = DICompositeType(subType.getNode());
586 DIArray Elements = blockStruct.getTypeArray();
588 if (Elements.isNull())
591 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
592 DIDescriptor Element = Elements.getElement(i);
593 DIDerivedType DT = DIDerivedType(Element.getNode());
594 if (strcmp(Name.c_str(), DT.getName()) == 0)
595 return (DT.getTypeDerivedFrom());
601 /// AddComplexAddress - Start with the address based on the location provided,
602 /// and generate the DWARF information necessary to find the actual variable
603 /// given the extra address information encoded in the DIVariable, starting from
604 /// the starting location. Add the DWARF information to the die.
606 void DwarfDebug::AddComplexAddress(DbgVariable *&DV, DIE *Die,
608 const MachineLocation &Location) {
609 const DIVariable &VD = DV->getVariable();
610 DIType Ty = VD.getType();
612 // Decode the original location, and use that as the start of the byref
613 // variable's location.
614 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
615 DIEBlock *Block = new DIEBlock();
617 if (Location.isReg()) {
619 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
621 Reg = Reg - dwarf::DW_OP_reg0;
622 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
623 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
627 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
629 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
630 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
633 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
636 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
637 uint64_t Element = VD.getAddrElement(i);
639 if (Element == DIFactory::OpPlus) {
640 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
641 AddUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
642 } else if (Element == DIFactory::OpDeref) {
643 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
644 } else llvm_unreachable("unknown DIFactory Opcode");
647 // Now attach the location information to the DIE.
648 AddBlock(Die, Attribute, 0, Block);
651 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
652 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
653 gives the variable VarName either the struct, or a pointer to the struct, as
654 its type. This is necessary for various behind-the-scenes things the
655 compiler needs to do with by-reference variables in Blocks.
657 However, as far as the original *programmer* is concerned, the variable
658 should still have type 'SomeType', as originally declared.
660 The function GetBlockByrefType dives into the __Block_byref_x_VarName
661 struct to find the original type of the variable, which is then assigned to
662 the variable's Debug Information Entry as its real type. So far, so good.
663 However now the debugger will expect the variable VarName to have the type
664 SomeType. So we need the location attribute for the variable to be an
665 expression that explains to the debugger how to navigate through the
666 pointers and struct to find the actual variable of type SomeType.
668 The following function does just that. We start by getting
669 the "normal" location for the variable. This will be the location
670 of either the struct __Block_byref_x_VarName or the pointer to the
671 struct __Block_byref_x_VarName.
673 The struct will look something like:
675 struct __Block_byref_x_VarName {
677 struct __Block_byref_x_VarName *forwarding;
678 ... <various other fields>
680 ... <maybe more fields>
683 If we are given the struct directly (as our starting point) we
684 need to tell the debugger to:
686 1). Add the offset of the forwarding field.
688 2). Follow that pointer to get the the real __Block_byref_x_VarName
689 struct to use (the real one may have been copied onto the heap).
691 3). Add the offset for the field VarName, to find the actual variable.
693 If we started with a pointer to the struct, then we need to
694 dereference that pointer first, before the other steps.
695 Translating this into DWARF ops, we will need to append the following
696 to the current location description for the variable:
698 DW_OP_deref -- optional, if we start with a pointer
699 DW_OP_plus_uconst <forward_fld_offset>
701 DW_OP_plus_uconst <varName_fld_offset>
703 That is what this function does. */
705 /// AddBlockByrefAddress - Start with the address based on the location
706 /// provided, and generate the DWARF information necessary to find the
707 /// actual Block variable (navigating the Block struct) based on the
708 /// starting location. Add the DWARF information to the die. For
709 /// more information, read large comment just above here.
711 void DwarfDebug::AddBlockByrefAddress(DbgVariable *&DV, DIE *Die,
713 const MachineLocation &Location) {
714 const DIVariable &VD = DV->getVariable();
715 DIType Ty = VD.getType();
717 unsigned Tag = Ty.getTag();
718 bool isPointer = false;
720 const char *varName = VD.getName();
722 if (Tag == dwarf::DW_TAG_pointer_type) {
723 DIDerivedType DTy = DIDerivedType(Ty.getNode());
724 TmpTy = DTy.getTypeDerivedFrom();
728 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
730 // Find the __forwarding field and the variable field in the __Block_byref
732 DIArray Fields = blockStruct.getTypeArray();
733 DIDescriptor varField = DIDescriptor();
734 DIDescriptor forwardingField = DIDescriptor();
737 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
738 DIDescriptor Element = Fields.getElement(i);
739 DIDerivedType DT = DIDerivedType(Element.getNode());
740 const char *fieldName = DT.getName();
741 if (strcmp(fieldName, "__forwarding") == 0)
742 forwardingField = Element;
743 else if (strcmp(fieldName, varName) == 0)
747 assert(!varField.isNull() && "Can't find byref variable in Block struct");
748 assert(!forwardingField.isNull()
749 && "Can't find forwarding field in Block struct");
751 // Get the offsets for the forwarding field and the variable field.
752 unsigned int forwardingFieldOffset =
753 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
754 unsigned int varFieldOffset =
755 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
757 // Decode the original location, and use that as the start of the byref
758 // variable's location.
759 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
760 DIEBlock *Block = new DIEBlock();
762 if (Location.isReg()) {
764 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
766 Reg = Reg - dwarf::DW_OP_reg0;
767 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
768 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
772 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
774 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
775 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
778 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
781 // If we started with a pointer to the __Block_byref... struct, then
782 // the first thing we need to do is dereference the pointer (DW_OP_deref).
784 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
786 // Next add the offset for the '__forwarding' field:
787 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
788 // adding the offset if it's 0.
789 if (forwardingFieldOffset > 0) {
790 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
791 AddUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
794 // Now dereference the __forwarding field to get to the real __Block_byref
795 // struct: DW_OP_deref.
796 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
798 // Now that we've got the real __Block_byref... struct, add the offset
799 // for the variable's field to get to the location of the actual variable:
800 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
801 if (varFieldOffset > 0) {
802 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
803 AddUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
806 // Now attach the location information to the DIE.
807 AddBlock(Die, Attribute, 0, Block);
810 /// AddAddress - Add an address attribute to a die based on the location
812 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
813 const MachineLocation &Location) {
814 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
815 DIEBlock *Block = new DIEBlock();
817 if (Location.isReg()) {
819 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
821 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
822 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
826 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
828 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
829 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
832 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
835 AddBlock(Die, Attribute, 0, Block);
838 /// AddType - Add a new type attribute to the specified entity.
839 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
843 // Check for pre-existence.
844 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getNode());
846 // If it exists then use the existing value.
848 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
853 Slot = CreateDIEEntry();
856 DIE Buffer(dwarf::DW_TAG_base_type);
857 if (Ty.isBasicType())
858 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getNode()));
859 else if (Ty.isCompositeType())
860 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getNode()));
862 assert(Ty.isDerivedType() && "Unknown kind of DIType");
863 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getNode()));
866 // Add debug information entry to entity and appropriate context.
868 DIDescriptor Context = Ty.getContext();
869 if (!Context.isNull())
870 Die = DW_Unit->getDieMapSlotFor(Context.getNode());
873 DIE *Child = new DIE(Buffer);
874 Die->AddChild(Child);
876 SetDIEEntry(Slot, Child);
878 Die = DW_Unit->AddDie(Buffer);
879 SetDIEEntry(Slot, Die);
882 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
885 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
886 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
888 // Get core information.
889 const char *Name = BTy.getName();
890 Buffer.setTag(dwarf::DW_TAG_base_type);
891 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
894 // Add name if not anonymous or intermediate type.
896 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
897 uint64_t Size = BTy.getSizeInBits() >> 3;
898 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
901 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
902 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
904 // Get core information.
905 const char *Name = DTy.getName();
906 uint64_t Size = DTy.getSizeInBits() >> 3;
907 unsigned Tag = DTy.getTag();
909 // FIXME - Workaround for templates.
910 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
914 // Map to main type, void will not have a type.
915 DIType FromTy = DTy.getTypeDerivedFrom();
916 AddType(DW_Unit, &Buffer, FromTy);
918 // Add name if not anonymous or intermediate type.
920 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
922 // Add size if non-zero (derived types might be zero-sized.)
924 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
926 // Add source line info if available and TyDesc is not a forward declaration.
927 if (!DTy.isForwardDecl())
928 AddSourceLine(&Buffer, &DTy);
931 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
932 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
933 DICompositeType CTy) {
934 // Get core information.
935 const char *Name = CTy.getName();
937 uint64_t Size = CTy.getSizeInBits() >> 3;
938 unsigned Tag = CTy.getTag();
942 case dwarf::DW_TAG_vector_type:
943 case dwarf::DW_TAG_array_type:
944 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
946 case dwarf::DW_TAG_enumeration_type: {
947 DIArray Elements = CTy.getTypeArray();
949 // Add enumerators to enumeration type.
950 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
952 DIEnumerator Enum(Elements.getElement(i).getNode());
953 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
954 Buffer.AddChild(ElemDie);
958 case dwarf::DW_TAG_subroutine_type: {
960 DIArray Elements = CTy.getTypeArray();
961 DIDescriptor RTy = Elements.getElement(0);
962 AddType(DW_Unit, &Buffer, DIType(RTy.getNode()));
964 // Add prototype flag.
965 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
968 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
969 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
970 DIDescriptor Ty = Elements.getElement(i);
971 AddType(DW_Unit, Arg, DIType(Ty.getNode()));
972 Buffer.AddChild(Arg);
976 case dwarf::DW_TAG_structure_type:
977 case dwarf::DW_TAG_union_type:
978 case dwarf::DW_TAG_class_type: {
979 // Add elements to structure type.
980 DIArray Elements = CTy.getTypeArray();
982 // A forward struct declared type may not have elements available.
983 if (Elements.isNull())
986 // Add elements to structure type.
987 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
988 DIDescriptor Element = Elements.getElement(i);
989 if (Element.isNull())
992 if (Element.getTag() == dwarf::DW_TAG_subprogram)
993 ElemDie = CreateSubprogramDIE(DW_Unit,
994 DISubprogram(Element.getNode()));
996 ElemDie = CreateMemberDIE(DW_Unit,
997 DIDerivedType(Element.getNode()));
998 Buffer.AddChild(ElemDie);
1001 if (CTy.isAppleBlockExtension())
1002 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1004 unsigned RLang = CTy.getRunTimeLang();
1006 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1007 dwarf::DW_FORM_data1, RLang);
1014 // Add name if not anonymous or intermediate type.
1016 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1018 if (Tag == dwarf::DW_TAG_enumeration_type ||
1019 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1020 // Add size if non-zero (derived types might be zero-sized.)
1022 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1024 // Add zero size if it is not a forward declaration.
1025 if (CTy.isForwardDecl())
1026 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1028 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1031 // Add source line info if available.
1032 if (!CTy.isForwardDecl())
1033 AddSourceLine(&Buffer, &CTy);
1037 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1038 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1039 int64_t L = SR.getLo();
1040 int64_t H = SR.getHi();
1041 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1043 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1045 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1047 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1049 Buffer.AddChild(DW_Subrange);
1052 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1053 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1054 DICompositeType *CTy) {
1055 Buffer.setTag(dwarf::DW_TAG_array_type);
1056 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1057 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1059 // Emit derived type.
1060 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1061 DIArray Elements = CTy->getTypeArray();
1063 // Construct an anonymous type for index type.
1064 DIE IdxBuffer(dwarf::DW_TAG_base_type);
1065 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1066 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1067 dwarf::DW_ATE_signed);
1068 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1070 // Add subranges to array type.
1071 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1072 DIDescriptor Element = Elements.getElement(i);
1073 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1074 ConstructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IndexTy);
1078 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1079 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1080 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1081 const char *Name = ETy->getName();
1082 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1083 int64_t Value = ETy->getEnumValue();
1084 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1088 /// CreateGlobalVariableDIE - Create new DIE using GV.
1089 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
1090 const DIGlobalVariable &GV) {
1091 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1092 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1093 GV.getDisplayName());
1095 const char *LinkageName = GV.getLinkageName();
1097 // Skip special LLVM prefix that is used to inform the asm printer to not
1098 // emit usual symbol prefix before the symbol name. This happens for
1099 // Objective-C symbol names and symbol whose name is replaced using GCC's
1100 // __asm__ attribute.
1101 if (LinkageName[0] == 1)
1102 LinkageName = &LinkageName[1];
1103 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1106 AddType(DW_Unit, GVDie, GV.getType());
1107 if (!GV.isLocalToUnit())
1108 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1109 AddSourceLine(GVDie, &GV);
1113 /// CreateMemberDIE - Create new member DIE.
1114 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1115 DIE *MemberDie = new DIE(DT.getTag());
1116 if (const char *Name = DT.getName())
1117 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1119 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1121 AddSourceLine(MemberDie, &DT);
1123 uint64_t Size = DT.getSizeInBits();
1124 uint64_t FieldSize = DT.getOriginalTypeSize();
1126 if (Size != FieldSize) {
1128 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1129 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1131 uint64_t Offset = DT.getOffsetInBits();
1132 uint64_t FieldOffset = Offset;
1133 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1134 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1135 FieldOffset = (HiMark - FieldSize);
1136 Offset -= FieldOffset;
1138 // Maybe we need to work from the other end.
1139 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1140 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1143 DIEBlock *Block = new DIEBlock();
1144 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1145 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1146 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
1148 if (DT.isProtected())
1149 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1150 dwarf::DW_ACCESS_protected);
1151 else if (DT.isPrivate())
1152 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1153 dwarf::DW_ACCESS_private);
1158 /// CreateSubprogramDIE - Create new DIE using SP.
1159 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
1160 const DISubprogram &SP,
1163 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1165 const char * Name = SP.getName();
1166 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1168 const char *LinkageName = SP.getLinkageName();
1170 // Skip special LLVM prefix that is used to inform the asm printer to not emit
1171 // usual symbol prefix before the symbol name. This happens for Objective-C
1172 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
1173 if (LinkageName[0] == 1)
1174 LinkageName = &LinkageName[1];
1175 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1178 AddSourceLine(SPDie, &SP);
1180 DICompositeType SPTy = SP.getType();
1181 DIArray Args = SPTy.getTypeArray();
1183 // Add prototyped tag, if C or ObjC.
1184 unsigned Lang = SP.getCompileUnit().getLanguage();
1185 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1186 Lang == dwarf::DW_LANG_ObjC)
1187 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1190 unsigned SPTag = SPTy.getTag();
1191 if (!IsConstructor) {
1192 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1193 AddType(DW_Unit, SPDie, SPTy);
1195 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1198 if (!SP.isDefinition()) {
1199 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1201 // Add arguments. Do not add arguments for subprogram definition. They will
1202 // be handled through RecordVariable.
1203 if (SPTag == dwarf::DW_TAG_subroutine_type)
1204 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1205 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1206 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1207 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1208 SPDie->AddChild(Arg);
1212 if (!SP.isLocalToUnit() && !IsInlined)
1213 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1215 // DW_TAG_inlined_subroutine may refer to this DIE.
1216 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getNode());
1221 /// FindCompileUnit - Get the compile unit for the given descriptor.
1223 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
1224 DenseMap<Value *, CompileUnit *>::const_iterator I =
1225 CompileUnitMap.find(Unit.getNode());
1226 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1230 /// CreateDbgScopeVariable - Create a new scope variable.
1232 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1233 // Get the descriptor.
1234 const DIVariable &VD = DV->getVariable();
1236 // Translate tag to proper Dwarf tag. The result variable is dropped for
1239 switch (VD.getTag()) {
1240 case dwarf::DW_TAG_return_variable:
1242 case dwarf::DW_TAG_arg_variable:
1243 Tag = dwarf::DW_TAG_formal_parameter;
1245 case dwarf::DW_TAG_auto_variable: // fall thru
1247 Tag = dwarf::DW_TAG_variable;
1251 // Define variable debug information entry.
1252 DIE *VariableDie = new DIE(Tag);
1253 const char *Name = VD.getName();
1254 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1256 // Add source line info if available.
1257 AddSourceLine(VariableDie, &VD);
1259 // Add variable type.
1260 // FIXME: isBlockByrefVariable should be reformulated in terms of complex addresses instead.
1261 if (VD.isBlockByrefVariable())
1262 AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1264 AddType(Unit, VariableDie, VD.getType());
1266 // Add variable address.
1267 if (!DV->isInlinedFnVar()) {
1268 // Variables for abstract instances of inlined functions don't get a
1270 MachineLocation Location;
1271 Location.set(RI->getFrameRegister(*MF),
1272 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1275 if (VD.hasComplexAddress())
1276 AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1277 else if (VD.isBlockByrefVariable())
1278 AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1280 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1286 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1288 DbgScope *DwarfDebug::getDbgScope(MDNode *N, const MachineInstr *MI) {
1289 DbgScope *&Slot = DbgScopeMap[N];
1290 if (Slot) return Slot;
1292 DbgScope *Parent = NULL;
1294 DIDescriptor Scope(N);
1295 if (Scope.isCompileUnit()) {
1297 } else if (Scope.isSubprogram()) {
1299 DIDescriptor ParentDesc = SP.getContext();
1300 if (!ParentDesc.isNull() && !ParentDesc.isCompileUnit())
1301 Parent = getDbgScope(ParentDesc.getNode(), MI);
1302 } else if (Scope.isLexicalBlock()) {
1303 DILexicalBlock DB(N);
1304 DIDescriptor ParentDesc = DB.getContext();
1305 if (!ParentDesc.isNull())
1306 Parent = getDbgScope(ParentDesc.getNode(), MI);
1308 assert (0 && "Unexpected scope info");
1310 Slot = new DbgScope(Parent, DIDescriptor(N));
1311 Slot->setFirstInsn(MI);
1314 Parent->AddScope(Slot);
1316 // First function is top level function.
1317 // FIXME - Dpatel - What is FunctionDbgScope ?
1318 if (!FunctionDbgScope)
1319 FunctionDbgScope = Slot;
1325 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1326 /// FIXME - Remove this method.
1327 DbgScope *DwarfDebug::getOrCreateScope(MDNode *N) {
1328 DbgScope *&Slot = DbgScopeMap[N];
1329 if (Slot) return Slot;
1331 DbgScope *Parent = NULL;
1332 DILexicalBlock Block(N);
1334 // Don't create a new scope if we already created one for an inlined function.
1335 DenseMap<const MDNode *, DbgScope *>::iterator
1336 II = AbstractInstanceRootMap.find(N);
1337 if (II != AbstractInstanceRootMap.end())
1338 return LexicalScopeStack.back();
1340 if (!Block.isNull()) {
1341 DIDescriptor ParentDesc = Block.getContext();
1343 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getNode());
1346 Slot = new DbgScope(Parent, DIDescriptor(N));
1349 Parent->AddScope(Slot);
1351 // First function is top level function.
1352 FunctionDbgScope = Slot;
1357 /// ConstructDbgScope - Construct the components of a scope.
1359 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1360 unsigned ParentStartID,
1361 unsigned ParentEndID,
1362 DIE *ParentDie, CompileUnit *Unit) {
1363 // Add variables to scope.
1364 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1365 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1366 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
1367 if (VariableDie) ParentDie->AddChild(VariableDie);
1370 // Add concrete instances to scope.
1371 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1372 ParentScope->getConcreteInsts();
1373 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1374 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1375 DIE *Die = ConcreteInst->getDie();
1377 unsigned StartID = ConcreteInst->getStartLabelID();
1378 unsigned EndID = ConcreteInst->getEndLabelID();
1380 // Add the scope bounds.
1382 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1383 DWLabel("label", StartID));
1385 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1386 DWLabel("func_begin", SubprogramCount));
1389 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1390 DWLabel("label", EndID));
1392 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1393 DWLabel("func_end", SubprogramCount));
1395 ParentDie->AddChild(Die);
1398 // Add nested scopes.
1399 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1400 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1401 // Define the Scope debug information entry.
1402 DbgScope *Scope = Scopes[j];
1404 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1405 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1407 // Ignore empty scopes.
1408 if (StartID == EndID && StartID != 0) continue;
1410 // Do not ignore inlined scopes even if they don't have any variables or
1412 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1413 Scope->getConcreteInsts().empty())
1416 if (StartID == ParentStartID && EndID == ParentEndID) {
1417 // Just add stuff to the parent scope.
1418 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1420 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1422 // Add the scope bounds.
1424 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1425 DWLabel("label", StartID));
1427 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1428 DWLabel("func_begin", SubprogramCount));
1431 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1432 DWLabel("label", EndID));
1434 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1435 DWLabel("func_end", SubprogramCount));
1437 // Add the scope's contents.
1438 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1439 ParentDie->AddChild(ScopeDie);
1444 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1446 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1447 bool AbstractScope) {
1448 // Exit if there is no root scope.
1449 if (!RootScope) return;
1450 DIDescriptor Desc = RootScope->getDesc();
1454 // Get the subprogram debug information entry.
1455 DISubprogram SPD(Desc.getNode());
1457 // Get the subprogram die.
1458 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getNode());
1459 assert(SPDie && "Missing subprogram descriptor");
1461 if (!AbstractScope) {
1462 // Add the function bounds.
1463 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1464 DWLabel("func_begin", SubprogramCount));
1465 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1466 DWLabel("func_end", SubprogramCount));
1467 MachineLocation Location(RI->getFrameRegister(*MF));
1468 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1471 ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
1474 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1476 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1477 StringMap<DIE*> &Globals = ModuleCU->getGlobals();
1478 StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
1479 if (GI != Globals.end()) {
1480 DIE *SPDie = GI->second;
1482 // Add the function bounds.
1483 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1484 DWLabel("func_begin", SubprogramCount));
1485 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1486 DWLabel("func_end", SubprogramCount));
1488 MachineLocation Location(RI->getFrameRegister(*MF));
1489 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1493 /// GetOrCreateSourceID - Look up the source id with the given directory and
1494 /// source file names. If none currently exists, create a new id and insert it
1495 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1497 unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1498 const char *FileName) {
1500 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1501 if (DI != DirectoryIdMap.end()) {
1502 DId = DI->getValue();
1504 DId = DirectoryNames.size() + 1;
1505 DirectoryIdMap[DirName] = DId;
1506 DirectoryNames.push_back(DirName);
1510 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1511 if (FI != SourceFileIdMap.end()) {
1512 FId = FI->getValue();
1514 FId = SourceFileNames.size() + 1;
1515 SourceFileIdMap[FileName] = FId;
1516 SourceFileNames.push_back(FileName);
1519 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1520 SourceIdMap.find(std::make_pair(DId, FId));
1521 if (SI != SourceIdMap.end())
1524 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1525 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1526 SourceIds.push_back(std::make_pair(DId, FId));
1531 void DwarfDebug::ConstructCompileUnit(MDNode *N) {
1532 DICompileUnit DIUnit(N);
1533 const char *FN = DIUnit.getFilename();
1534 const char *Dir = DIUnit.getDirectory();
1535 unsigned ID = GetOrCreateSourceID(Dir, FN);
1537 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1538 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1539 DWLabel("section_line", 0), DWLabel("section_line", 0),
1541 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1542 DIUnit.getProducer());
1543 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1544 DIUnit.getLanguage());
1545 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1548 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1549 if (DIUnit.isOptimized())
1550 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1552 if (const char *Flags = DIUnit.getFlags())
1553 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1555 unsigned RVer = DIUnit.getRunTimeVersion();
1557 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1558 dwarf::DW_FORM_data1, RVer);
1560 CompileUnit *Unit = new CompileUnit(ID, Die);
1561 if (!ModuleCU && DIUnit.isMain()) {
1562 // Use first compile unit marked as isMain as the compile unit
1567 CompileUnitMap[DIUnit.getNode()] = Unit;
1568 CompileUnits.push_back(Unit);
1571 void DwarfDebug::ConstructGlobalVariableDIE(MDNode *N) {
1572 DIGlobalVariable DI_GV(N);
1574 // If debug information is malformed then ignore it.
1575 if (DI_GV.Verify() == false)
1578 // Check for pre-existence.
1579 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getNode());
1583 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1586 DIEBlock *Block = new DIEBlock();
1587 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1588 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1589 Asm->Mang->getMangledName(DI_GV.getGlobal()));
1590 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1595 // Add to context owner.
1596 ModuleCU->getDie()->AddChild(VariableDie);
1598 // Expose as global. FIXME - need to check external flag.
1599 ModuleCU->AddGlobal(DI_GV.getName(), VariableDie);
1603 void DwarfDebug::ConstructSubprogram(MDNode *N) {
1606 // Check for pre-existence.
1607 DIE *&Slot = ModuleCU->getDieMapSlotFor(N);
1611 if (!SP.isDefinition())
1612 // This is a method declaration which will be handled while constructing
1616 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1619 Slot = SubprogramDie;
1621 // Add to context owner.
1622 ModuleCU->getDie()->AddChild(SubprogramDie);
1624 // Expose as global.
1625 ModuleCU->AddGlobal(SP.getName(), SubprogramDie);
1629 /// BeginModule - Emit all Dwarf sections that should come prior to the
1630 /// content. Create global DIEs and emit initial debug info sections.
1631 /// This is inovked by the target AsmPrinter.
1632 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1635 if (TimePassesIsEnabled)
1636 DebugTimer->startTimer();
1638 DebugInfoFinder DbgFinder;
1639 DbgFinder.processModule(*M);
1641 // Create all the compile unit DIEs.
1642 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1643 E = DbgFinder.compile_unit_end(); I != E; ++I)
1644 ConstructCompileUnit(*I);
1646 if (CompileUnits.empty()) {
1647 if (TimePassesIsEnabled)
1648 DebugTimer->stopTimer();
1653 // If main compile unit for this module is not seen than randomly
1654 // select first compile unit.
1656 ModuleCU = CompileUnits[0];
1658 // If there is not any debug info available for any global variables and any
1659 // subprograms then there is not any debug info to emit.
1660 if (DbgFinder.global_variable_count() == 0
1661 && DbgFinder.subprogram_count() == 0) {
1662 if (TimePassesIsEnabled)
1663 DebugTimer->stopTimer();
1667 // Create DIEs for each of the externally visible global variables.
1668 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1669 E = DbgFinder.global_variable_end(); I != E; ++I)
1670 ConstructGlobalVariableDIE(*I);
1672 // Create DIEs for each of the externally visible subprograms.
1673 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1674 E = DbgFinder.subprogram_end(); I != E; ++I)
1675 ConstructSubprogram(*I);
1679 MMI->setDebugInfoAvailability(true);
1681 // Prime section data.
1682 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1684 // Print out .file directives to specify files for .loc directives. These are
1685 // printed out early so that they precede any .loc directives.
1686 if (MAI->hasDotLocAndDotFile()) {
1687 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1688 // Remember source id starts at 1.
1689 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1690 sys::Path FullPath(getSourceDirectoryName(Id.first));
1692 FullPath.appendComponent(getSourceFileName(Id.second));
1693 assert(AppendOk && "Could not append filename to directory!");
1695 Asm->EmitFile(i, FullPath.str());
1700 // Emit initial sections
1703 if (TimePassesIsEnabled)
1704 DebugTimer->stopTimer();
1707 /// EndModule - Emit all Dwarf sections that should come after the content.
1709 void DwarfDebug::EndModule() {
1710 if (!ShouldEmitDwarfDebug())
1713 if (TimePassesIsEnabled)
1714 DebugTimer->startTimer();
1716 // Standard sections final addresses.
1717 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1718 EmitLabel("text_end", 0);
1719 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1720 EmitLabel("data_end", 0);
1722 // End text sections.
1723 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1724 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1725 EmitLabel("section_end", i);
1728 // Emit common frame information.
1729 EmitCommonDebugFrame();
1731 // Emit function debug frame information
1732 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1733 E = DebugFrames.end(); I != E; ++I)
1734 EmitFunctionDebugFrame(*I);
1736 // Compute DIE offsets and sizes.
1739 // Emit all the DIEs into a debug info section
1742 // Corresponding abbreviations into a abbrev section.
1743 EmitAbbreviations();
1745 // Emit source line correspondence into a debug line section.
1748 // Emit info into a debug pubnames section.
1749 EmitDebugPubNames();
1751 // Emit info into a debug str section.
1754 // Emit info into a debug loc section.
1757 // Emit info into a debug aranges section.
1760 // Emit info into a debug ranges section.
1763 // Emit info into a debug macinfo section.
1766 // Emit inline info.
1767 EmitDebugInlineInfo();
1769 if (TimePassesIsEnabled)
1770 DebugTimer->stopTimer();
1773 /// ExtractScopeInformation - Scan machine instructions in this function
1774 /// and collect DbgScopes. Return true, if atleast one scope was found.
1775 bool DwarfDebug::ExtractScopeInformation(MachineFunction *MF) {
1776 // If scope information was extracted using .dbg intrinsics then there is not
1777 // any need to extract these information by scanning each instruction.
1778 if (!DbgScopeMap.empty())
1781 // Scan each instruction and create scopes.
1782 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1784 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1786 const MachineInstr *MInsn = II;
1787 DebugLoc DL = MInsn->getDebugLoc();
1790 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1791 if (!DLT.CompileUnit)
1793 // There is no need to create another DIE for compile unit. For all
1794 // other scopes, create one DbgScope now. This will be translated
1795 // into a scope DIE at the end.
1796 DIDescriptor D(DLT.CompileUnit);
1797 if (!D.isCompileUnit()) {
1798 DbgScope *Scope = getDbgScope(DLT.CompileUnit, MInsn);
1799 Scope->setLastInsn(MInsn);
1804 // If a scope's last instruction is not set then use its child scope's
1805 // last instruction as this scope's last instrunction.
1806 for (DenseMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1807 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1808 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
1809 DI->second->FixInstructionMarkers();
1810 assert (DI->second->getLastInsn() && "Invalid last instruction!");
1813 // Each scope has first instruction and last instruction to mark beginning
1814 // and end of a scope respectively. Create an inverse map that list scopes
1815 // starts (and ends) with an instruction. One instruction may start (or end)
1817 for (DenseMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1818 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1819 DbgScope *S = DI->second;
1820 assert (S && "DbgScope is missing!");
1821 const MachineInstr *MI = S->getFirstInsn();
1822 assert (MI && "DbgScope does not have first instruction!");
1824 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
1825 if (IDI != DbgScopeBeginMap.end())
1826 IDI->second.push_back(S);
1828 DbgScopeBeginMap.insert(std::make_pair(MI,
1829 SmallVector<DbgScope *, 2>(2, S)));
1831 MI = S->getLastInsn();
1832 assert (MI && "DbgScope does not have last instruction!");
1833 IDI = DbgScopeEndMap.find(MI);
1834 if (IDI != DbgScopeEndMap.end())
1835 IDI->second.push_back(S);
1837 DbgScopeEndMap.insert(std::make_pair(MI,
1838 SmallVector<DbgScope *, 2>(2, S)));
1841 return !DbgScopeMap.empty();
1844 /// BeginFunction - Gather pre-function debug information. Assumes being
1845 /// emitted immediately after the function entry point.
1846 void DwarfDebug::BeginFunction(MachineFunction *MF) {
1849 if (!ShouldEmitDwarfDebug()) return;
1851 if (TimePassesIsEnabled)
1852 DebugTimer->startTimer();
1854 // Begin accumulating function debug information.
1855 MMI->BeginFunction(MF);
1857 // Assumes in correct section after the entry point.
1858 EmitLabel("func_begin", ++SubprogramCount);
1860 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1862 DebugLoc FDL = MF->getDefaultDebugLoc();
1863 if (!FDL.isUnknown()) {
1864 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1865 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.CompileUnit);
1866 Asm->printLabel(LabelID);
1870 if (TimePassesIsEnabled)
1871 DebugTimer->stopTimer();
1874 /// EndFunction - Gather and emit post-function debug information.
1876 void DwarfDebug::EndFunction(MachineFunction *MF) {
1877 if (!ShouldEmitDwarfDebug()) return;
1879 if (TimePassesIsEnabled)
1880 DebugTimer->startTimer();
1882 // Define end label for subprogram.
1883 EmitLabel("func_end", SubprogramCount);
1885 // Get function line info.
1886 if (!Lines.empty()) {
1887 // Get section line info.
1888 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
1889 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1890 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1891 // Append the function info to section info.
1892 SectionLineInfos.insert(SectionLineInfos.end(),
1893 Lines.begin(), Lines.end());
1896 // Construct the DbgScope for abstract instances.
1897 for (SmallVector<DbgScope *, 32>::iterator
1898 I = AbstractInstanceRootList.begin(),
1899 E = AbstractInstanceRootList.end(); I != E; ++I)
1900 ConstructFunctionDbgScope(*I);
1902 // Construct scopes for subprogram.
1903 if (FunctionDbgScope)
1904 ConstructFunctionDbgScope(FunctionDbgScope);
1906 // FIXME: This is wrong. We are essentially getting past a problem with
1907 // debug information not being able to handle unreachable blocks that have
1908 // debug information in them. In particular, those unreachable blocks that
1909 // have "region end" info in them. That situation results in the "root
1910 // scope" not being created. If that's the case, then emit a "default"
1911 // scope, i.e., one that encompasses the whole function. This isn't
1912 // desirable. And a better way of handling this (and all of the debugging
1913 // information) needs to be explored.
1914 ConstructDefaultDbgScope(MF);
1916 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1917 MMI->getFrameMoves()));
1920 if (FunctionDbgScope) {
1921 delete FunctionDbgScope;
1922 DbgScopeMap.clear();
1923 DbgScopeBeginMap.clear();
1924 DbgScopeEndMap.clear();
1925 DbgAbstractScopeMap.clear();
1926 DbgConcreteScopeMap.clear();
1927 FunctionDbgScope = NULL;
1928 LexicalScopeStack.clear();
1929 AbstractInstanceRootList.clear();
1930 AbstractInstanceRootMap.clear();
1935 if (TimePassesIsEnabled)
1936 DebugTimer->stopTimer();
1939 /// RecordSourceLine - Records location information and associates it with a
1940 /// label. Returns a unique label ID used to generate a label and provide
1941 /// correspondence to the source line list.
1942 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1943 if (TimePassesIsEnabled)
1944 DebugTimer->startTimer();
1946 CompileUnit *Unit = CompileUnitMap[V];
1947 assert(Unit && "Unable to find CompileUnit");
1948 unsigned ID = MMI->NextLabelID();
1949 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1951 if (TimePassesIsEnabled)
1952 DebugTimer->stopTimer();
1957 /// RecordSourceLine - Records location information and associates it with a
1958 /// label. Returns a unique label ID used to generate a label and provide
1959 /// correspondence to the source line list.
1960 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1965 if (TimePassesIsEnabled)
1966 DebugTimer->startTimer();
1968 const char *Dir = NULL;
1969 const char *Fn = NULL;
1971 DIDescriptor Scope(S);
1972 if (Scope.isCompileUnit()) {
1973 DICompileUnit CU(S);
1974 Dir = CU.getDirectory();
1975 Fn = CU.getFilename();
1976 } else if (Scope.isSubprogram()) {
1978 Dir = SP.getDirectory();
1979 Fn = SP.getFilename();
1980 } else if (Scope.isLexicalBlock()) {
1981 DILexicalBlock DB(S);
1982 Dir = DB.getDirectory();
1983 Fn = DB.getFilename();
1985 assert (0 && "Unexpected scope info");
1987 unsigned Src = GetOrCreateSourceID(Dir, Fn);
1988 unsigned ID = MMI->NextLabelID();
1989 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1991 if (TimePassesIsEnabled)
1992 DebugTimer->stopTimer();
1997 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1998 /// timed. Look up the source id with the given directory and source file
1999 /// names. If none currently exists, create a new id and insert it in the
2000 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2002 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2003 const std::string &FileName) {
2004 if (TimePassesIsEnabled)
2005 DebugTimer->startTimer();
2007 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2009 if (TimePassesIsEnabled)
2010 DebugTimer->stopTimer();
2015 /// RecordRegionStart - Indicate the start of a region.
2016 unsigned DwarfDebug::RecordRegionStart(MDNode *N) {
2017 if (TimePassesIsEnabled)
2018 DebugTimer->startTimer();
2020 DbgScope *Scope = getOrCreateScope(N);
2021 unsigned ID = MMI->NextLabelID();
2022 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2023 LexicalScopeStack.push_back(Scope);
2025 if (TimePassesIsEnabled)
2026 DebugTimer->stopTimer();
2031 /// RecordRegionEnd - Indicate the end of a region.
2032 unsigned DwarfDebug::RecordRegionEnd(MDNode *N) {
2033 if (TimePassesIsEnabled)
2034 DebugTimer->startTimer();
2036 DbgScope *Scope = getOrCreateScope(N);
2037 unsigned ID = MMI->NextLabelID();
2038 Scope->setEndLabelID(ID);
2039 // FIXME : region.end() may not be in the last basic block.
2040 // For now, do not pop last lexical scope because next basic
2041 // block may start new inlined function's body.
2042 unsigned LSSize = LexicalScopeStack.size();
2043 if (LSSize != 0 && LSSize != 1)
2044 LexicalScopeStack.pop_back();
2046 if (TimePassesIsEnabled)
2047 DebugTimer->stopTimer();
2052 /// RecordVariable - Indicate the declaration of a local variable.
2053 void DwarfDebug::RecordVariable(MDNode *N, unsigned FrameIndex) {
2054 if (TimePassesIsEnabled)
2055 DebugTimer->startTimer();
2057 DIDescriptor Desc(N);
2058 DbgScope *Scope = NULL;
2059 bool InlinedFnVar = false;
2061 if (Desc.getTag() == dwarf::DW_TAG_variable)
2062 Scope = getOrCreateScope(DIGlobalVariable(N).getContext().getNode());
2064 bool InlinedVar = false;
2065 MDNode *Context = DIVariable(N).getContext().getNode();
2066 DISubprogram SP(Context);
2068 // SP is inserted into DbgAbstractScopeMap when inlined function
2069 // start was recorded by RecordInlineFnStart.
2070 DenseMap<MDNode *, DbgScope *>::iterator
2071 I = DbgAbstractScopeMap.find(SP.getNode());
2072 if (I != DbgAbstractScopeMap.end()) {
2078 Scope = getOrCreateScope(Context);
2081 assert(Scope && "Unable to find the variable's scope");
2082 DbgVariable *DV = new DbgVariable(DIVariable(N), FrameIndex, InlinedFnVar);
2083 Scope->AddVariable(DV);
2085 if (TimePassesIsEnabled)
2086 DebugTimer->stopTimer();
2089 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2090 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2091 unsigned Line, unsigned Col) {
2092 unsigned LabelID = MMI->NextLabelID();
2094 if (!MAI->doesDwarfUsesInlineInfoSection())
2097 if (TimePassesIsEnabled)
2098 DebugTimer->startTimer();
2100 MDNode *Node = SP.getNode();
2101 DenseMap<const MDNode *, DbgScope *>::iterator
2102 II = AbstractInstanceRootMap.find(Node);
2104 if (II == AbstractInstanceRootMap.end()) {
2105 // Create an abstract instance entry for this inlined function if it doesn't
2107 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(Node));
2109 // Get the compile unit context.
2110 DIE *SPDie = ModuleCU->getDieMapSlotFor(Node);
2112 SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
2114 // Mark as being inlined. This makes this subprogram entry an abstract
2116 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2117 // that it's defined. That probably won't change in the future. However,
2118 // this could be more elegant.
2119 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
2121 // Keep track of the abstract scope for this function.
2122 DbgAbstractScopeMap[Node] = Scope;
2124 AbstractInstanceRootMap[Node] = Scope;
2125 AbstractInstanceRootList.push_back(Scope);
2128 // Create a concrete inlined instance for this inlined function.
2129 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(Node));
2130 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
2131 ScopeDie->setAbstractCompileUnit(ModuleCU);
2133 DIE *Origin = ModuleCU->getDieMapSlotFor(Node);
2134 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
2135 dwarf::DW_FORM_ref4, Origin);
2136 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
2137 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
2138 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
2140 ConcreteScope->setDie(ScopeDie);
2141 ConcreteScope->setStartLabelID(LabelID);
2142 MMI->RecordUsedDbgLabel(LabelID);
2144 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2146 // Keep track of the concrete scope that's inlined into this function.
2147 DenseMap<MDNode *, SmallVector<DbgScope *, 8> >::iterator
2148 SI = DbgConcreteScopeMap.find(Node);
2150 if (SI == DbgConcreteScopeMap.end())
2151 DbgConcreteScopeMap[Node].push_back(ConcreteScope);
2153 SI->second.push_back(ConcreteScope);
2155 // Track the start label for this inlined function.
2156 DenseMap<MDNode *, SmallVector<unsigned, 4> >::iterator
2157 I = InlineInfo.find(Node);
2159 if (I == InlineInfo.end())
2160 InlineInfo[Node].push_back(LabelID);
2162 I->second.push_back(LabelID);
2164 if (TimePassesIsEnabled)
2165 DebugTimer->stopTimer();
2170 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2171 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2172 if (!MAI->doesDwarfUsesInlineInfoSection())
2175 if (TimePassesIsEnabled)
2176 DebugTimer->startTimer();
2178 MDNode *Node = SP.getNode();
2179 DenseMap<MDNode *, SmallVector<DbgScope *, 8> >::iterator
2180 I = DbgConcreteScopeMap.find(Node);
2182 if (I == DbgConcreteScopeMap.end()) {
2183 // FIXME: Can this situation actually happen? And if so, should it?
2184 if (TimePassesIsEnabled)
2185 DebugTimer->stopTimer();
2190 SmallVector<DbgScope *, 8> &Scopes = I->second;
2191 if (Scopes.empty()) {
2192 // Returned ID is 0 if this is unbalanced "end of inlined
2193 // scope". This could happen if optimizer eats dbg intrinsics
2194 // or "beginning of inlined scope" is not recoginized due to
2195 // missing location info. In such cases, ignore this region.end.
2199 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2200 unsigned ID = MMI->NextLabelID();
2201 MMI->RecordUsedDbgLabel(ID);
2202 Scope->setEndLabelID(ID);
2204 if (TimePassesIsEnabled)
2205 DebugTimer->stopTimer();
2210 //===----------------------------------------------------------------------===//
2212 //===----------------------------------------------------------------------===//
2214 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2216 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2217 // Get the children.
2218 const std::vector<DIE *> &Children = Die->getChildren();
2220 // If not last sibling and has children then add sibling offset attribute.
2221 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2223 // Record the abbreviation.
2224 AssignAbbrevNumber(Die->getAbbrev());
2226 // Get the abbreviation for this DIE.
2227 unsigned AbbrevNumber = Die->getAbbrevNumber();
2228 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2231 Die->setOffset(Offset);
2233 // Start the size with the size of abbreviation code.
2234 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2236 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2237 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2239 // Size the DIE attribute values.
2240 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2241 // Size attribute value.
2242 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2244 // Size the DIE children if any.
2245 if (!Children.empty()) {
2246 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2247 "Children flag not set");
2249 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2250 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2252 // End of children marker.
2253 Offset += sizeof(int8_t);
2256 Die->setSize(Offset - Die->getOffset());
2260 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2262 void DwarfDebug::SizeAndOffsets() {
2263 // Compute size of compile unit header.
2264 static unsigned Offset =
2265 sizeof(int32_t) + // Length of Compilation Unit Info
2266 sizeof(int16_t) + // DWARF version number
2267 sizeof(int32_t) + // Offset Into Abbrev. Section
2268 sizeof(int8_t); // Pointer Size (in bytes)
2270 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
2271 CompileUnitOffsets[ModuleCU] = 0;
2274 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2275 /// tools to recognize the object file contains Dwarf information.
2276 void DwarfDebug::EmitInitial() {
2277 // Check to see if we already emitted intial headers.
2278 if (didInitial) return;
2281 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2283 // Dwarf sections base addresses.
2284 if (MAI->doesDwarfRequireFrameSection()) {
2285 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2286 EmitLabel("section_debug_frame", 0);
2289 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2290 EmitLabel("section_info", 0);
2291 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2292 EmitLabel("section_abbrev", 0);
2293 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2294 EmitLabel("section_aranges", 0);
2296 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2297 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2298 EmitLabel("section_macinfo", 0);
2301 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2302 EmitLabel("section_line", 0);
2303 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2304 EmitLabel("section_loc", 0);
2305 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2306 EmitLabel("section_pubnames", 0);
2307 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2308 EmitLabel("section_str", 0);
2309 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2310 EmitLabel("section_ranges", 0);
2312 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2313 EmitLabel("text_begin", 0);
2314 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2315 EmitLabel("data_begin", 0);
2318 /// EmitDIE - Recusively Emits a debug information entry.
2320 void DwarfDebug::EmitDIE(DIE *Die) {
2321 // Get the abbreviation for this DIE.
2322 unsigned AbbrevNumber = Die->getAbbrevNumber();
2323 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2327 // Emit the code (index) for the abbreviation.
2328 Asm->EmitULEB128Bytes(AbbrevNumber);
2330 if (Asm->isVerbose())
2331 Asm->EOL(std::string("Abbrev [" +
2332 utostr(AbbrevNumber) +
2333 "] 0x" + utohexstr(Die->getOffset()) +
2334 ":0x" + utohexstr(Die->getSize()) + " " +
2335 dwarf::TagString(Abbrev->getTag())));
2339 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2340 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2342 // Emit the DIE attribute values.
2343 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2344 unsigned Attr = AbbrevData[i].getAttribute();
2345 unsigned Form = AbbrevData[i].getForm();
2346 assert(Form && "Too many attributes for DIE (check abbreviation)");
2349 case dwarf::DW_AT_sibling:
2350 Asm->EmitInt32(Die->SiblingOffset());
2352 case dwarf::DW_AT_abstract_origin: {
2353 DIEEntry *E = cast<DIEEntry>(Values[i]);
2354 DIE *Origin = E->getEntry();
2356 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
2357 Origin->getOffset();
2359 Asm->EmitInt32(Addr);
2363 // Emit an attribute using the defined form.
2364 Values[i]->EmitValue(this, Form);
2368 Asm->EOL(dwarf::AttributeString(Attr));
2371 // Emit the DIE children if any.
2372 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2373 const std::vector<DIE *> &Children = Die->getChildren();
2375 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2376 EmitDIE(Children[j]);
2378 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2382 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2384 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2385 DIE *Die = Unit->getDie();
2387 // Emit the compile units header.
2388 EmitLabel("info_begin", Unit->getID());
2390 // Emit size of content not including length itself
2391 unsigned ContentSize = Die->getSize() +
2392 sizeof(int16_t) + // DWARF version number
2393 sizeof(int32_t) + // Offset Into Abbrev. Section
2394 sizeof(int8_t) + // Pointer Size (in bytes)
2395 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2397 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2398 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2399 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2400 Asm->EOL("Offset Into Abbrev. Section");
2401 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2404 // FIXME - extra padding for gdb bug.
2405 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2406 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2407 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2408 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2409 EmitLabel("info_end", Unit->getID());
2414 void DwarfDebug::EmitDebugInfo() {
2415 // Start debug info section.
2416 Asm->OutStreamer.SwitchSection(
2417 Asm->getObjFileLowering().getDwarfInfoSection());
2419 EmitDebugInfoPerCU(ModuleCU);
2422 /// EmitAbbreviations - Emit the abbreviation section.
2424 void DwarfDebug::EmitAbbreviations() const {
2425 // Check to see if it is worth the effort.
2426 if (!Abbreviations.empty()) {
2427 // Start the debug abbrev section.
2428 Asm->OutStreamer.SwitchSection(
2429 Asm->getObjFileLowering().getDwarfAbbrevSection());
2431 EmitLabel("abbrev_begin", 0);
2433 // For each abbrevation.
2434 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2435 // Get abbreviation data
2436 const DIEAbbrev *Abbrev = Abbreviations[i];
2438 // Emit the abbrevations code (base 1 index.)
2439 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2440 Asm->EOL("Abbreviation Code");
2442 // Emit the abbreviations data.
2448 // Mark end of abbreviations.
2449 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2451 EmitLabel("abbrev_end", 0);
2456 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2457 /// the line matrix.
2459 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2460 // Define last address of section.
2461 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2462 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2463 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2464 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2466 // Mark end of matrix.
2467 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2468 Asm->EmitULEB128Bytes(1); Asm->EOL();
2469 Asm->EmitInt8(1); Asm->EOL();
2472 /// EmitDebugLines - Emit source line information.
2474 void DwarfDebug::EmitDebugLines() {
2475 // If the target is using .loc/.file, the assembler will be emitting the
2476 // .debug_line table automatically.
2477 if (MAI->hasDotLocAndDotFile())
2480 // Minimum line delta, thus ranging from -10..(255-10).
2481 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2482 // Maximum line delta, thus ranging from -10..(255-10).
2483 const int MaxLineDelta = 255 + MinLineDelta;
2485 // Start the dwarf line section.
2486 Asm->OutStreamer.SwitchSection(
2487 Asm->getObjFileLowering().getDwarfLineSection());
2489 // Construct the section header.
2490 EmitDifference("line_end", 0, "line_begin", 0, true);
2491 Asm->EOL("Length of Source Line Info");
2492 EmitLabel("line_begin", 0);
2494 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2496 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2497 Asm->EOL("Prolog Length");
2498 EmitLabel("line_prolog_begin", 0);
2500 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2502 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2504 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2506 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2508 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2510 // Line number standard opcode encodings argument count
2511 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2512 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2513 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2514 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2515 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2516 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2517 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2518 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2519 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2521 // Emit directories.
2522 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2523 Asm->EmitString(getSourceDirectoryName(DI));
2524 Asm->EOL("Directory");
2527 Asm->EmitInt8(0); Asm->EOL("End of directories");
2530 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2531 // Remember source id starts at 1.
2532 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2533 Asm->EmitString(getSourceFileName(Id.second));
2535 Asm->EmitULEB128Bytes(Id.first);
2536 Asm->EOL("Directory #");
2537 Asm->EmitULEB128Bytes(0);
2538 Asm->EOL("Mod date");
2539 Asm->EmitULEB128Bytes(0);
2540 Asm->EOL("File size");
2543 Asm->EmitInt8(0); Asm->EOL("End of files");
2545 EmitLabel("line_prolog_end", 0);
2547 // A sequence for each text section.
2548 unsigned SecSrcLinesSize = SectionSourceLines.size();
2550 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2551 // Isolate current sections line info.
2552 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2554 /*if (Asm->isVerbose()) {
2555 const MCSection *S = SectionMap[j + 1];
2556 O << '\t' << MAI->getCommentString() << " Section"
2557 << S->getName() << '\n';
2561 // Dwarf assumes we start with first line of first source file.
2562 unsigned Source = 1;
2565 // Construct rows of the address, source, line, column matrix.
2566 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2567 const SrcLineInfo &LineInfo = LineInfos[i];
2568 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2569 if (!LabelID) continue;
2571 if (LineInfo.getLine() == 0) continue;
2573 if (!Asm->isVerbose())
2576 std::pair<unsigned, unsigned> SourceID =
2577 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2578 O << '\t' << MAI->getCommentString() << ' '
2579 << getSourceDirectoryName(SourceID.first) << ' '
2580 << getSourceFileName(SourceID.second)
2581 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2584 // Define the line address.
2585 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2586 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2587 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2588 EmitReference("label", LabelID); Asm->EOL("Location label");
2590 // If change of source, then switch to the new source.
2591 if (Source != LineInfo.getSourceID()) {
2592 Source = LineInfo.getSourceID();
2593 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2594 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2597 // If change of line.
2598 if (Line != LineInfo.getLine()) {
2599 // Determine offset.
2600 int Offset = LineInfo.getLine() - Line;
2601 int Delta = Offset - MinLineDelta;
2604 Line = LineInfo.getLine();
2606 // If delta is small enough and in range...
2607 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2608 // ... then use fast opcode.
2609 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2611 // ... otherwise use long hand.
2612 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2613 Asm->EOL("DW_LNS_advance_line");
2614 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2615 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2618 // Copy the previous row (different address or source)
2619 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2623 EmitEndOfLineMatrix(j + 1);
2626 if (SecSrcLinesSize == 0)
2627 // Because we're emitting a debug_line section, we still need a line
2628 // table. The linker and friends expect it to exist. If there's nothing to
2629 // put into it, emit an empty table.
2630 EmitEndOfLineMatrix(1);
2632 EmitLabel("line_end", 0);
2636 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2638 void DwarfDebug::EmitCommonDebugFrame() {
2639 if (!MAI->doesDwarfRequireFrameSection())
2643 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2644 TargetFrameInfo::StackGrowsUp ?
2645 TD->getPointerSize() : -TD->getPointerSize();
2647 // Start the dwarf frame section.
2648 Asm->OutStreamer.SwitchSection(
2649 Asm->getObjFileLowering().getDwarfFrameSection());
2651 EmitLabel("debug_frame_common", 0);
2652 EmitDifference("debug_frame_common_end", 0,
2653 "debug_frame_common_begin", 0, true);
2654 Asm->EOL("Length of Common Information Entry");
2656 EmitLabel("debug_frame_common_begin", 0);
2657 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2658 Asm->EOL("CIE Identifier Tag");
2659 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2660 Asm->EOL("CIE Version");
2661 Asm->EmitString("");
2662 Asm->EOL("CIE Augmentation");
2663 Asm->EmitULEB128Bytes(1);
2664 Asm->EOL("CIE Code Alignment Factor");
2665 Asm->EmitSLEB128Bytes(stackGrowth);
2666 Asm->EOL("CIE Data Alignment Factor");
2667 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2668 Asm->EOL("CIE RA Column");
2670 std::vector<MachineMove> Moves;
2671 RI->getInitialFrameState(Moves);
2673 EmitFrameMoves(NULL, 0, Moves, false);
2675 Asm->EmitAlignment(2, 0, 0, false);
2676 EmitLabel("debug_frame_common_end", 0);
2681 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2684 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2685 if (!MAI->doesDwarfRequireFrameSection())
2688 // Start the dwarf frame section.
2689 Asm->OutStreamer.SwitchSection(
2690 Asm->getObjFileLowering().getDwarfFrameSection());
2692 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2693 "debug_frame_begin", DebugFrameInfo.Number, true);
2694 Asm->EOL("Length of Frame Information Entry");
2696 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2698 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2700 Asm->EOL("FDE CIE offset");
2702 EmitReference("func_begin", DebugFrameInfo.Number);
2703 Asm->EOL("FDE initial location");
2704 EmitDifference("func_end", DebugFrameInfo.Number,
2705 "func_begin", DebugFrameInfo.Number);
2706 Asm->EOL("FDE address range");
2708 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2711 Asm->EmitAlignment(2, 0, 0, false);
2712 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2717 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2718 EmitDifference("pubnames_end", Unit->getID(),
2719 "pubnames_begin", Unit->getID(), true);
2720 Asm->EOL("Length of Public Names Info");
2722 EmitLabel("pubnames_begin", Unit->getID());
2724 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2726 EmitSectionOffset("info_begin", "section_info",
2727 Unit->getID(), 0, true, false);
2728 Asm->EOL("Offset of Compilation Unit Info");
2730 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2732 Asm->EOL("Compilation Unit Length");
2734 StringMap<DIE*> &Globals = Unit->getGlobals();
2735 for (StringMap<DIE*>::const_iterator
2736 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2737 const char *Name = GI->getKeyData();
2738 DIE * Entity = GI->second;
2740 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2741 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2744 Asm->EmitInt32(0); Asm->EOL("End Mark");
2745 EmitLabel("pubnames_end", Unit->getID());
2750 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2752 void DwarfDebug::EmitDebugPubNames() {
2753 // Start the dwarf pubnames section.
2754 Asm->OutStreamer.SwitchSection(
2755 Asm->getObjFileLowering().getDwarfPubNamesSection());
2757 EmitDebugPubNamesPerCU(ModuleCU);
2760 /// EmitDebugStr - Emit visible names into a debug str section.
2762 void DwarfDebug::EmitDebugStr() {
2763 // Check to see if it is worth the effort.
2764 if (!StringPool.empty()) {
2765 // Start the dwarf str section.
2766 Asm->OutStreamer.SwitchSection(
2767 Asm->getObjFileLowering().getDwarfStrSection());
2769 // For each of strings in the string pool.
2770 for (unsigned StringID = 1, N = StringPool.size();
2771 StringID <= N; ++StringID) {
2772 // Emit a label for reference from debug information entries.
2773 EmitLabel("string", StringID);
2775 // Emit the string itself.
2776 const std::string &String = StringPool[StringID];
2777 Asm->EmitString(String); Asm->EOL();
2784 /// EmitDebugLoc - Emit visible names into a debug loc section.
2786 void DwarfDebug::EmitDebugLoc() {
2787 // Start the dwarf loc section.
2788 Asm->OutStreamer.SwitchSection(
2789 Asm->getObjFileLowering().getDwarfLocSection());
2793 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2795 void DwarfDebug::EmitDebugARanges() {
2796 // Start the dwarf aranges section.
2797 Asm->OutStreamer.SwitchSection(
2798 Asm->getObjFileLowering().getDwarfARangesSection());
2802 CompileUnit *Unit = GetBaseCompileUnit();
2804 // Don't include size of length
2805 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2807 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2809 EmitReference("info_begin", Unit->getID());
2810 Asm->EOL("Offset of Compilation Unit Info");
2812 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2814 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2816 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2817 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2820 EmitReference("text_begin", 0); Asm->EOL("Address");
2821 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2823 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2824 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2830 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2832 void DwarfDebug::EmitDebugRanges() {
2833 // Start the dwarf ranges section.
2834 Asm->OutStreamer.SwitchSection(
2835 Asm->getObjFileLowering().getDwarfRangesSection());
2839 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2841 void DwarfDebug::EmitDebugMacInfo() {
2842 if (const MCSection *LineInfo =
2843 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2844 // Start the dwarf macinfo section.
2845 Asm->OutStreamer.SwitchSection(LineInfo);
2850 /// EmitDebugInlineInfo - Emit inline info using following format.
2852 /// 1. length of section
2853 /// 2. Dwarf version number
2854 /// 3. address size.
2856 /// Entries (one "entry" for each function that was inlined):
2858 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2859 /// otherwise offset into __debug_str for regular function name.
2860 /// 2. offset into __debug_str section for regular function name.
2861 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2862 /// instances for the function.
2864 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2865 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2866 /// __debug_info section, and the low_pc is the starting address for the
2867 /// inlining instance.
2868 void DwarfDebug::EmitDebugInlineInfo() {
2869 if (!MAI->doesDwarfUsesInlineInfoSection())
2875 Asm->OutStreamer.SwitchSection(
2876 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2878 EmitDifference("debug_inlined_end", 1,
2879 "debug_inlined_begin", 1, true);
2880 Asm->EOL("Length of Debug Inlined Information Entry");
2882 EmitLabel("debug_inlined_begin", 1);
2884 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2885 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2887 for (DenseMap<MDNode *, SmallVector<unsigned, 4> >::iterator
2888 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2889 MDNode *Node = I->first;
2890 SmallVector<unsigned, 4> &Labels = I->second;
2891 DISubprogram SP(Node);
2892 const char *LName = SP.getLinkageName();
2893 const char *Name = SP.getName();
2896 Asm->EmitString(Name);
2898 // Skip special LLVM prefix that is used to inform the asm printer to not
2899 // emit usual symbol prefix before the symbol name. This happens for
2900 // Objective-C symbol names and symbol whose name is replaced using GCC's
2901 // __asm__ attribute.
2904 Asm->EmitString(LName);
2906 Asm->EOL("MIPS linkage name");
2908 Asm->EmitString(Name); Asm->EOL("Function name");
2910 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2912 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2913 LE = Labels.end(); LI != LE; ++LI) {
2914 DIE *SP = ModuleCU->getDieMapSlotFor(Node);
2915 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2917 if (TD->getPointerSize() == sizeof(int32_t))
2918 O << MAI->getData32bitsDirective();
2920 O << MAI->getData64bitsDirective();
2922 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2926 EmitLabel("debug_inlined_end", 1);