1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/Target/TargetAsmInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
25 static TimerGroup &getDwarfTimerGroup() {
26 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
27 return DwarfTimerGroup;
30 //===----------------------------------------------------------------------===//
32 /// Configuration values for initial hash set sizes (log2).
34 static const unsigned InitDiesSetSize = 9; // log2(512)
35 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
36 static const unsigned InitValuesSetSize = 9; // log2(512)
40 //===----------------------------------------------------------------------===//
41 /// CompileUnit - This dwarf writer support class manages information associate
42 /// with a source file.
43 class VISIBILITY_HIDDEN CompileUnit {
44 /// ID - File identifier for source.
48 /// Die - Compile unit debug information entry.
52 /// GVToDieMap - Tracks the mapping of unit level debug informaton
53 /// variables to debug information entries.
54 std::map<GlobalVariable *, DIE *> GVToDieMap;
56 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
57 /// descriptors to debug information entries using a DIEEntry proxy.
58 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
60 /// Globals - A map of globally visible named entities for this unit.
62 StringMap<DIE*> Globals;
64 /// DiesSet - Used to uniquely define dies within the compile unit.
66 FoldingSet<DIE> DiesSet;
68 CompileUnit(unsigned I, DIE *D)
69 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
70 ~CompileUnit() { delete Die; }
73 unsigned getID() const { return ID; }
74 DIE* getDie() const { return Die; }
75 StringMap<DIE*> &getGlobals() { return Globals; }
77 /// hasContent - Return true if this compile unit has something to write out.
79 bool hasContent() const { return !Die->getChildren().empty(); }
81 /// AddGlobal - Add a new global entity to the compile unit.
83 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
85 /// getDieMapSlotFor - Returns the debug information entry map slot for the
86 /// specified debug variable.
87 DIE *&getDieMapSlotFor(GlobalVariable *GV) { return GVToDieMap[GV]; }
89 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
90 /// specified debug variable.
91 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
92 return GVToDIEEntryMap[GV];
95 /// AddDie - Adds or interns the DIE to the compile unit.
97 DIE *AddDie(DIE &Buffer) {
101 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
104 Die = new DIE(Buffer);
105 DiesSet.InsertNode(Die, Where);
106 this->Die->AddChild(Die);
114 //===----------------------------------------------------------------------===//
115 /// DbgVariable - This class is used to track local variable information.
117 class VISIBILITY_HIDDEN DbgVariable {
118 DIVariable Var; // Variable Descriptor.
119 unsigned FrameIndex; // Variable frame index.
120 bool InlinedFnVar; // Variable for an inlined function.
122 DbgVariable(DIVariable V, unsigned I, bool IFV)
123 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
126 DIVariable getVariable() const { return Var; }
127 unsigned getFrameIndex() const { return FrameIndex; }
128 bool isInlinedFnVar() const { return InlinedFnVar; }
131 //===----------------------------------------------------------------------===//
132 /// DbgScope - This class is used to track scope information.
134 class DbgConcreteScope;
135 class VISIBILITY_HIDDEN DbgScope {
136 DbgScope *Parent; // Parent to this scope.
137 DIDescriptor Desc; // Debug info descriptor for scope.
138 // Either subprogram or block.
139 unsigned StartLabelID; // Label ID of the beginning of scope.
140 unsigned EndLabelID; // Label ID of the end of scope.
141 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
142 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
143 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
145 DbgScope(DbgScope *P, DIDescriptor D)
146 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
150 DbgScope *getParent() const { return Parent; }
151 DIDescriptor getDesc() const { return Desc; }
152 unsigned getStartLabelID() const { return StartLabelID; }
153 unsigned getEndLabelID() const { return EndLabelID; }
154 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
155 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
156 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
157 void setStartLabelID(unsigned S) { StartLabelID = S; }
158 void setEndLabelID(unsigned E) { EndLabelID = E; }
160 /// AddScope - Add a scope to the scope.
162 void AddScope(DbgScope *S) { Scopes.push_back(S); }
164 /// AddVariable - Add a variable to the scope.
166 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
168 /// AddConcreteInst - Add a concrete instance to the scope.
170 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
178 void DbgScope::dump() const {
179 static unsigned IndentLevel = 0;
180 std::string Indent(IndentLevel, ' ');
182 cerr << Indent; Desc.dump();
183 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
187 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
188 if (Scopes[i] != this)
195 //===----------------------------------------------------------------------===//
196 /// DbgConcreteScope - This class is used to track a scope that holds concrete
197 /// instance information.
199 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
201 DIE *Die; // Debug info for this concrete scope.
203 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
206 DIE *getDie() const { return Die; }
207 void setDie(DIE *D) { Die = D; }
210 DbgScope::~DbgScope() {
211 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
213 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
215 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
216 delete ConcreteInsts[k];
219 } // end llvm namespace
221 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
222 : Dwarf(OS, A, T, "dbg"), MainCU(0),
223 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
224 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
225 SectionSourceLines(), didInitial(false), shouldEmit(false),
226 FunctionDbgScope(0), DebugTimer(0) {
227 if (TimePassesIsEnabled)
228 DebugTimer = new Timer("Dwarf Debug Writer",
229 getDwarfTimerGroup());
231 DwarfDebug::~DwarfDebug() {
232 for (unsigned j = 0, M = Values.size(); j < M; ++j)
235 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
236 I = AbstractInstanceRootMap.begin(),
237 E = AbstractInstanceRootMap.end(); I != E;++I)
243 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
245 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
246 // Profile the node so that we can make it unique.
250 // Check the set for priors.
251 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
253 // If it's newly added.
254 if (InSet == &Abbrev) {
255 // Add to abbreviation list.
256 Abbreviations.push_back(&Abbrev);
258 // Assign the vector position + 1 as its number.
259 Abbrev.setNumber(Abbreviations.size());
261 // Assign existing abbreviation number.
262 Abbrev.setNumber(InSet->getNumber());
266 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
267 /// information entry.
268 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
273 DIEEntry::Profile(ID, Entry);
275 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
277 if (Value) return Value;
279 Value = new DIEEntry(Entry);
280 ValuesSet.InsertNode(Value, Where);
282 Value = new DIEEntry(Entry);
285 Values.push_back(Value);
289 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
291 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
292 Value->setEntry(Entry);
294 // Add to values set if not already there. If it is, we merely have a
295 // duplicate in the values list (no harm.)
296 ValuesSet.GetOrInsertNode(Value);
299 /// AddUInt - Add an unsigned integer attribute data and value.
301 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
302 unsigned Form, uint64_t Integer) {
303 if (!Form) Form = DIEInteger::BestForm(false, Integer);
306 DIEInteger::Profile(ID, Integer);
308 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
311 Value = new DIEInteger(Integer);
312 ValuesSet.InsertNode(Value, Where);
313 Values.push_back(Value);
316 Die->AddValue(Attribute, Form, Value);
319 /// AddSInt - Add an signed integer attribute data and value.
321 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
322 unsigned Form, int64_t Integer) {
323 if (!Form) Form = DIEInteger::BestForm(true, Integer);
326 DIEInteger::Profile(ID, (uint64_t)Integer);
328 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
331 Value = new DIEInteger(Integer);
332 ValuesSet.InsertNode(Value, Where);
333 Values.push_back(Value);
336 Die->AddValue(Attribute, Form, Value);
339 /// AddString - Add a string attribute data and value.
341 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
342 const std::string &String) {
344 DIEString::Profile(ID, String);
346 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
349 Value = new DIEString(String);
350 ValuesSet.InsertNode(Value, Where);
351 Values.push_back(Value);
354 Die->AddValue(Attribute, Form, Value);
357 /// AddLabel - Add a Dwarf label attribute data and value.
359 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
360 const DWLabel &Label) {
362 DIEDwarfLabel::Profile(ID, Label);
364 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
367 Value = new DIEDwarfLabel(Label);
368 ValuesSet.InsertNode(Value, Where);
369 Values.push_back(Value);
372 Die->AddValue(Attribute, Form, Value);
375 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
377 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
378 const std::string &Label) {
380 DIEObjectLabel::Profile(ID, Label);
382 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
385 Value = new DIEObjectLabel(Label);
386 ValuesSet.InsertNode(Value, Where);
387 Values.push_back(Value);
390 Die->AddValue(Attribute, Form, Value);
393 /// AddSectionOffset - Add a section offset label attribute data and value.
395 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
396 const DWLabel &Label, const DWLabel &Section,
397 bool isEH, bool useSet) {
399 DIESectionOffset::Profile(ID, Label, Section);
401 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
404 Value = new DIESectionOffset(Label, Section, isEH, useSet);
405 ValuesSet.InsertNode(Value, Where);
406 Values.push_back(Value);
409 Die->AddValue(Attribute, Form, Value);
412 /// AddDelta - Add a label delta attribute data and value.
414 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
415 const DWLabel &Hi, const DWLabel &Lo) {
417 DIEDelta::Profile(ID, Hi, Lo);
419 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
422 Value = new DIEDelta(Hi, Lo);
423 ValuesSet.InsertNode(Value, Where);
424 Values.push_back(Value);
427 Die->AddValue(Attribute, Form, Value);
430 /// AddBlock - Add block data.
432 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
434 Block->ComputeSize(TD);
438 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
442 ValuesSet.InsertNode(Value, Where);
443 Values.push_back(Value);
445 // Already exists, reuse the previous one.
447 Block = cast<DIEBlock>(Value);
450 Die->AddValue(Attribute, Block->BestForm(), Value);
453 /// AddSourceLine - Add location information to specified debug information
455 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
456 // If there is no compile unit specified, don't add a line #.
457 if (V->getCompileUnit().isNull())
460 unsigned Line = V->getLineNumber();
461 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
462 assert(FileID && "Invalid file id");
463 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
464 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
467 /// AddSourceLine - Add location information to specified debug information
469 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
470 // If there is no compile unit specified, don't add a line #.
471 if (G->getCompileUnit().isNull())
474 unsigned Line = G->getLineNumber();
475 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
476 assert(FileID && "Invalid file id");
477 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
478 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
480 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
481 // If there is no compile unit specified, don't add a line #.
482 DICompileUnit CU = Ty->getCompileUnit();
486 unsigned Line = Ty->getLineNumber();
487 unsigned FileID = FindCompileUnit(CU).getID();
488 assert(FileID && "Invalid file id");
489 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
490 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
493 /// AddAddress - Add an address attribute to a die based on the location
495 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
496 const MachineLocation &Location) {
497 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
498 DIEBlock *Block = new DIEBlock();
500 if (Location.isReg()) {
502 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
504 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
505 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
509 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
511 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
512 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
515 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
518 AddBlock(Die, Attribute, 0, Block);
521 /// AddType - Add a new type attribute to the specified entity.
522 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
526 // Check for pre-existence.
527 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
529 // If it exists then use the existing value.
531 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
536 Slot = CreateDIEEntry();
539 DIE Buffer(dwarf::DW_TAG_base_type);
540 if (Ty.isBasicType(Ty.getTag()))
541 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
542 else if (Ty.isDerivedType(Ty.getTag()))
543 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
545 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
546 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
549 // Add debug information entry to entity and appropriate context.
551 DIDescriptor Context = Ty.getContext();
552 if (!Context.isNull())
553 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
556 DIE *Child = new DIE(Buffer);
557 Die->AddChild(Child);
559 SetDIEEntry(Slot, Child);
561 Die = DW_Unit->AddDie(Buffer);
562 SetDIEEntry(Slot, Die);
565 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
568 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
569 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
571 // Get core information.
574 Buffer.setTag(dwarf::DW_TAG_base_type);
575 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
578 // Add name if not anonymous or intermediate type.
580 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
581 uint64_t Size = BTy.getSizeInBits() >> 3;
582 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
585 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
586 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
588 // Get core information.
591 uint64_t Size = DTy.getSizeInBits() >> 3;
592 unsigned Tag = DTy.getTag();
594 // FIXME - Workaround for templates.
595 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
599 // Map to main type, void will not have a type.
600 DIType FromTy = DTy.getTypeDerivedFrom();
601 AddType(DW_Unit, &Buffer, FromTy);
603 // Add name if not anonymous or intermediate type.
605 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
607 // Add size if non-zero (derived types might be zero-sized.)
609 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
611 // Add source line info if available and TyDesc is not a forward declaration.
612 if (!DTy.isForwardDecl())
613 AddSourceLine(&Buffer, &DTy);
616 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
617 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
618 DICompositeType CTy) {
619 // Get core information.
623 uint64_t Size = CTy.getSizeInBits() >> 3;
624 unsigned Tag = CTy.getTag();
628 case dwarf::DW_TAG_vector_type:
629 case dwarf::DW_TAG_array_type:
630 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
632 case dwarf::DW_TAG_enumeration_type: {
633 DIArray Elements = CTy.getTypeArray();
635 // Add enumerators to enumeration type.
636 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
638 DIEnumerator Enum(Elements.getElement(i).getGV());
639 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
640 Buffer.AddChild(ElemDie);
644 case dwarf::DW_TAG_subroutine_type: {
646 DIArray Elements = CTy.getTypeArray();
647 DIDescriptor RTy = Elements.getElement(0);
648 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
650 // Add prototype flag.
651 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
654 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
655 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
656 DIDescriptor Ty = Elements.getElement(i);
657 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
658 Buffer.AddChild(Arg);
662 case dwarf::DW_TAG_structure_type:
663 case dwarf::DW_TAG_union_type:
664 case dwarf::DW_TAG_class_type: {
665 // Add elements to structure type.
666 DIArray Elements = CTy.getTypeArray();
668 // A forward struct declared type may not have elements available.
669 if (Elements.isNull())
672 // Add elements to structure type.
673 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
674 DIDescriptor Element = Elements.getElement(i);
676 if (Element.getTag() == dwarf::DW_TAG_subprogram)
677 ElemDie = CreateSubprogramDIE(DW_Unit,
678 DISubprogram(Element.getGV()));
679 else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
680 ElemDie = CreateGlobalVariableDIE(DW_Unit,
681 DIGlobalVariable(Element.getGV()));
683 ElemDie = CreateMemberDIE(DW_Unit,
684 DIDerivedType(Element.getGV()));
685 Buffer.AddChild(ElemDie);
688 // FIXME: We'd like an API to register additional attributes for the
689 // frontend to use while synthesizing, and then we'd use that api in clang
691 if (Name == "__block_literal_generic")
692 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
694 unsigned RLang = CTy.getRunTimeLang();
696 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
697 dwarf::DW_FORM_data1, RLang);
704 // Add name if not anonymous or intermediate type.
706 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
708 if (Tag == dwarf::DW_TAG_enumeration_type ||
709 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
710 // Add size if non-zero (derived types might be zero-sized.)
712 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
714 // Add zero size if it is not a forward declaration.
715 if (CTy.isForwardDecl())
716 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
718 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
721 // Add source line info if available.
722 if (!CTy.isForwardDecl())
723 AddSourceLine(&Buffer, &CTy);
727 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
728 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
729 int64_t L = SR.getLo();
730 int64_t H = SR.getHi();
731 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
734 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
736 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
737 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
740 Buffer.AddChild(DW_Subrange);
743 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
744 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
745 DICompositeType *CTy) {
746 Buffer.setTag(dwarf::DW_TAG_array_type);
747 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
748 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
750 // Emit derived type.
751 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
752 DIArray Elements = CTy->getTypeArray();
754 // Construct an anonymous type for index type.
755 DIE IdxBuffer(dwarf::DW_TAG_base_type);
756 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
757 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
758 dwarf::DW_ATE_signed);
759 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
761 // Add subranges to array type.
762 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
763 DIDescriptor Element = Elements.getElement(i);
764 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
765 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
769 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
770 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
771 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
774 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
775 int64_t Value = ETy->getEnumValue();
776 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
780 /// CreateGlobalVariableDIE - Create new DIE using GV.
781 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
782 const DIGlobalVariable &GV) {
783 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
785 GV.getDisplayName(Name);
786 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
787 std::string LinkageName;
788 GV.getLinkageName(LinkageName);
789 if (!LinkageName.empty())
790 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
792 AddType(DW_Unit, GVDie, GV.getType());
793 if (!GV.isLocalToUnit())
794 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
795 AddSourceLine(GVDie, &GV);
799 /// CreateMemberDIE - Create new member DIE.
800 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
801 DIE *MemberDie = new DIE(DT.getTag());
805 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
807 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
809 AddSourceLine(MemberDie, &DT);
811 uint64_t Size = DT.getSizeInBits();
812 uint64_t FieldSize = DT.getOriginalTypeSize();
814 if (Size != FieldSize) {
816 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
817 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
819 uint64_t Offset = DT.getOffsetInBits();
820 uint64_t FieldOffset = Offset;
821 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
822 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
823 FieldOffset = (HiMark - FieldSize);
824 Offset -= FieldOffset;
826 // Maybe we need to work from the other end.
827 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
828 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
831 DIEBlock *Block = new DIEBlock();
832 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
833 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
834 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
836 if (DT.isProtected())
837 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
838 dwarf::DW_ACCESS_protected);
839 else if (DT.isPrivate())
840 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
841 dwarf::DW_ACCESS_private);
846 /// CreateSubprogramDIE - Create new DIE using SP.
847 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
848 const DISubprogram &SP,
851 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
855 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
857 std::string LinkageName;
858 SP.getLinkageName(LinkageName);
860 if (!LinkageName.empty())
861 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
864 AddSourceLine(SPDie, &SP);
866 DICompositeType SPTy = SP.getType();
867 DIArray Args = SPTy.getTypeArray();
869 // Add prototyped tag, if C or ObjC.
870 unsigned Lang = SP.getCompileUnit().getLanguage();
871 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
872 Lang == dwarf::DW_LANG_ObjC)
873 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
876 unsigned SPTag = SPTy.getTag();
877 if (!IsConstructor) {
878 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
879 AddType(DW_Unit, SPDie, SPTy);
881 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
884 if (!SP.isDefinition()) {
885 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
887 // Add arguments. Do not add arguments for subprogram definition. They will
888 // be handled through RecordVariable.
889 if (SPTag == dwarf::DW_TAG_subroutine_type)
890 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
891 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
892 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
893 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
894 SPDie->AddChild(Arg);
898 if (!SP.isLocalToUnit() && !IsInlined)
899 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
901 // DW_TAG_inlined_subroutine may refer to this DIE.
902 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
907 /// FindCompileUnit - Get the compile unit for the given descriptor.
909 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
910 DenseMap<Value *, CompileUnit *>::const_iterator I =
911 CompileUnitMap.find(Unit.getGV());
912 assert(I != CompileUnitMap.end() && "Missing compile unit.");
916 /// CreateDbgScopeVariable - Create a new scope variable.
918 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
919 // Get the descriptor.
920 const DIVariable &VD = DV->getVariable();
922 // Translate tag to proper Dwarf tag. The result variable is dropped for
925 switch (VD.getTag()) {
926 case dwarf::DW_TAG_return_variable:
928 case dwarf::DW_TAG_arg_variable:
929 Tag = dwarf::DW_TAG_formal_parameter;
931 case dwarf::DW_TAG_auto_variable: // fall thru
933 Tag = dwarf::DW_TAG_variable;
937 // Define variable debug information entry.
938 DIE *VariableDie = new DIE(Tag);
941 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
943 // Add source line info if available.
944 AddSourceLine(VariableDie, &VD);
946 // Add variable type.
947 AddType(Unit, VariableDie, VD.getType());
949 // Add variable address.
950 if (!DV->isInlinedFnVar()) {
951 // Variables for abstract instances of inlined functions don't get a
953 MachineLocation Location;
954 Location.set(RI->getFrameRegister(*MF),
955 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
956 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
962 /// getOrCreateScope - Returns the scope associated with the given descriptor.
964 DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
965 DbgScope *&Slot = DbgScopeMap[V];
966 if (Slot) return Slot;
968 DbgScope *Parent = NULL;
971 // Don't create a new scope if we already created one for an inlined function.
972 DenseMap<const GlobalVariable *, DbgScope *>::iterator
973 II = AbstractInstanceRootMap.find(V);
974 if (II != AbstractInstanceRootMap.end())
975 return LexicalScopeStack.back();
977 if (!Block.isNull()) {
978 DIDescriptor ParentDesc = Block.getContext();
980 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
983 Slot = new DbgScope(Parent, DIDescriptor(V));
986 Parent->AddScope(Slot);
988 // First function is top level function.
989 FunctionDbgScope = Slot;
994 /// ConstructDbgScope - Construct the components of a scope.
996 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
997 unsigned ParentStartID,
998 unsigned ParentEndID,
999 DIE *ParentDie, CompileUnit *Unit) {
1000 // Add variables to scope.
1001 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1002 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1003 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
1004 if (VariableDie) ParentDie->AddChild(VariableDie);
1007 // Add concrete instances to scope.
1008 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1009 ParentScope->getConcreteInsts();
1010 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1011 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1012 DIE *Die = ConcreteInst->getDie();
1014 unsigned StartID = ConcreteInst->getStartLabelID();
1015 unsigned EndID = ConcreteInst->getEndLabelID();
1017 // Add the scope bounds.
1019 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1020 DWLabel("label", StartID));
1022 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1023 DWLabel("func_begin", SubprogramCount));
1026 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1027 DWLabel("label", EndID));
1029 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1030 DWLabel("func_end", SubprogramCount));
1032 ParentDie->AddChild(Die);
1035 // Add nested scopes.
1036 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1037 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1038 // Define the Scope debug information entry.
1039 DbgScope *Scope = Scopes[j];
1041 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1042 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1044 // Ignore empty scopes.
1045 if (StartID == EndID && StartID != 0) continue;
1047 // Do not ignore inlined scopes even if they don't have any variables or
1049 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1050 Scope->getConcreteInsts().empty())
1053 if (StartID == ParentStartID && EndID == ParentEndID) {
1054 // Just add stuff to the parent scope.
1055 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1057 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1059 // Add the scope bounds.
1061 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1062 DWLabel("label", StartID));
1064 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1065 DWLabel("func_begin", SubprogramCount));
1068 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1069 DWLabel("label", EndID));
1071 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1072 DWLabel("func_end", SubprogramCount));
1074 // Add the scope's contents.
1075 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1076 ParentDie->AddChild(ScopeDie);
1081 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1083 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1084 bool AbstractScope) {
1085 // Exit if there is no root scope.
1086 if (!RootScope) return;
1087 DIDescriptor Desc = RootScope->getDesc();
1091 // Get the subprogram debug information entry.
1092 DISubprogram SPD(Desc.getGV());
1094 // Get the compile unit context.
1095 CompileUnit *Unit = MainCU;
1097 Unit = &FindCompileUnit(SPD.getCompileUnit());
1099 // Get the subprogram die.
1100 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1101 assert(SPDie && "Missing subprogram descriptor");
1103 if (!AbstractScope) {
1104 // Add the function bounds.
1105 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1106 DWLabel("func_begin", SubprogramCount));
1107 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1108 DWLabel("func_end", SubprogramCount));
1109 MachineLocation Location(RI->getFrameRegister(*MF));
1110 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1113 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1116 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1118 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1119 const char *FnName = MF->getFunction()->getNameStart();
1121 StringMap<DIE*> &Globals = MainCU->getGlobals();
1122 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1123 if (GI != Globals.end()) {
1124 DIE *SPDie = GI->second;
1126 // Add the function bounds.
1127 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1128 DWLabel("func_begin", SubprogramCount));
1129 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1130 DWLabel("func_end", SubprogramCount));
1132 MachineLocation Location(RI->getFrameRegister(*MF));
1133 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1137 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1138 CompileUnit *Unit = CompileUnits[i];
1139 StringMap<DIE*> &Globals = Unit->getGlobals();
1140 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1141 if (GI != Globals.end()) {
1142 DIE *SPDie = GI->second;
1144 // Add the function bounds.
1145 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1146 DWLabel("func_begin", SubprogramCount));
1147 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1148 DWLabel("func_end", SubprogramCount));
1150 MachineLocation Location(RI->getFrameRegister(*MF));
1151 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1158 // FIXME: This is causing an abort because C++ mangled names are compared with
1159 // their unmangled counterparts. See PR2885. Don't do this assert.
1160 assert(0 && "Couldn't find DIE for machine function!");
1164 /// GetOrCreateSourceID - Look up the source id with the given directory and
1165 /// source file names. If none currently exists, create a new id and insert it
1166 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1168 unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1169 const std::string &FileName) {
1171 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1172 if (DI != DirectoryIdMap.end()) {
1173 DId = DI->getValue();
1175 DId = DirectoryNames.size() + 1;
1176 DirectoryIdMap[DirName] = DId;
1177 DirectoryNames.push_back(DirName);
1181 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1182 if (FI != SourceFileIdMap.end()) {
1183 FId = FI->getValue();
1185 FId = SourceFileNames.size() + 1;
1186 SourceFileIdMap[FileName] = FId;
1187 SourceFileNames.push_back(FileName);
1190 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1191 SourceIdMap.find(std::make_pair(DId, FId));
1192 if (SI != SourceIdMap.end())
1195 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1196 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1197 SourceIds.push_back(std::make_pair(DId, FId));
1202 void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1203 DICompileUnit DIUnit(GV);
1204 std::string Dir, FN, Prod;
1205 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1206 DIUnit.getFilename(FN));
1208 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1209 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1210 DWLabel("section_line", 0), DWLabel("section_line", 0),
1212 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1213 DIUnit.getProducer(Prod));
1214 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1215 DIUnit.getLanguage());
1216 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1219 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1220 if (DIUnit.isOptimized())
1221 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1224 DIUnit.getFlags(Flags);
1226 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1228 unsigned RVer = DIUnit.getRunTimeVersion();
1230 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1231 dwarf::DW_FORM_data1, RVer);
1233 CompileUnit *Unit = new CompileUnit(ID, Die);
1234 if (DIUnit.isMain()) {
1235 assert(!MainCU && "Multiple main compile units are found!");
1239 CompileUnitMap[DIUnit.getGV()] = Unit;
1240 CompileUnits.push_back(Unit);
1243 /// ConstructCompileUnits - Create a compile unit DIEs.
1244 void DwarfDebug::ConstructCompileUnits() {
1245 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
1248 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1249 "Malformed compile unit descriptor anchor type");
1250 Constant *RootC = cast<Constant>(*Root->use_begin());
1251 assert(RootC->hasNUsesOrMore(1) &&
1252 "Malformed compile unit descriptor anchor type");
1254 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1256 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1257 UUI != UUE; ++UUI) {
1258 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
1259 ConstructCompileUnit(GV);
1263 bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
1264 DIGlobalVariable DI_GV(GV);
1265 CompileUnit *DW_Unit = MainCU;
1267 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
1269 // Check for pre-existence.
1270 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
1274 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
1277 DIEBlock *Block = new DIEBlock();
1278 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1280 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1281 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
1282 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1287 // Add to context owner.
1288 DW_Unit->getDie()->AddChild(VariableDie);
1290 // Expose as global. FIXME - need to check external flag.
1292 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
1296 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
1297 /// global variables. Return true if at least one global DIE is created.
1298 bool DwarfDebug::ConstructGlobalVariableDIEs() {
1299 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
1303 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1304 "Malformed global variable descriptor anchor type");
1305 Constant *RootC = cast<Constant>(*Root->use_begin());
1306 assert(RootC->hasNUsesOrMore(1) &&
1307 "Malformed global variable descriptor anchor type");
1309 bool Result = false;
1310 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1312 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1314 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
1319 bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
1320 DISubprogram SP(GV);
1321 CompileUnit *Unit = MainCU;
1323 Unit = &FindCompileUnit(SP.getCompileUnit());
1325 // Check for pre-existence.
1326 DIE *&Slot = Unit->getDieMapSlotFor(GV);
1330 if (!SP.isDefinition())
1331 // This is a method declaration which will be handled while constructing
1335 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
1338 Slot = SubprogramDie;
1340 // Add to context owner.
1341 Unit->getDie()->AddChild(SubprogramDie);
1343 // Expose as global.
1345 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
1349 /// ConstructSubprograms - Create DIEs for each of the externally visible
1350 /// subprograms. Return true if at least one subprogram DIE is created.
1351 bool DwarfDebug::ConstructSubprograms() {
1352 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
1356 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1357 "Malformed subprogram descriptor anchor type");
1358 Constant *RootC = cast<Constant>(*Root->use_begin());
1359 assert(RootC->hasNUsesOrMore(1) &&
1360 "Malformed subprogram descriptor anchor type");
1362 bool Result = false;
1363 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1365 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1367 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
1372 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
1373 /// This is inovked by the target AsmPrinter.
1374 void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
1375 if (TimePassesIsEnabled)
1376 DebugTimer->startTimer();
1378 // Create all the compile unit DIEs.
1379 ConstructCompileUnits();
1381 if (CompileUnits.empty()) {
1382 if (TimePassesIsEnabled)
1383 DebugTimer->stopTimer();
1388 // Create DIEs for each of the externally visible global variables.
1389 bool globalDIEs = ConstructGlobalVariableDIEs();
1391 // Create DIEs for each of the externally visible subprograms.
1392 bool subprogramDIEs = ConstructSubprograms();
1394 // If there is not any debug info available for any global variables and any
1395 // subprograms then there is not any debug info to emit.
1396 if (!globalDIEs && !subprogramDIEs) {
1397 if (TimePassesIsEnabled)
1398 DebugTimer->stopTimer();
1405 MMI->setDebugInfoAvailability(true);
1407 // Prime section data.
1408 SectionMap.insert(TAI->getTextSection());
1410 // Print out .file directives to specify files for .loc directives. These are
1411 // printed out early so that they precede any .loc directives.
1412 if (TAI->hasDotLocAndDotFile()) {
1413 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1414 // Remember source id starts at 1.
1415 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1416 sys::Path FullPath(getSourceDirectoryName(Id.first));
1418 FullPath.appendComponent(getSourceFileName(Id.second));
1419 assert(AppendOk && "Could not append filename to directory!");
1421 Asm->EmitFile(i, FullPath.toString());
1426 // Emit initial sections
1429 if (TimePassesIsEnabled)
1430 DebugTimer->stopTimer();
1433 /// EndModule - Emit all Dwarf sections that should come after the content.
1435 void DwarfDebug::EndModule() {
1436 if (!ShouldEmitDwarfDebug())
1439 if (TimePassesIsEnabled)
1440 DebugTimer->startTimer();
1442 // Standard sections final addresses.
1443 Asm->SwitchToSection(TAI->getTextSection());
1444 EmitLabel("text_end", 0);
1445 Asm->SwitchToSection(TAI->getDataSection());
1446 EmitLabel("data_end", 0);
1448 // End text sections.
1449 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1450 Asm->SwitchToSection(SectionMap[i]);
1451 EmitLabel("section_end", i);
1454 // Emit common frame information.
1455 EmitCommonDebugFrame();
1457 // Emit function debug frame information
1458 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1459 E = DebugFrames.end(); I != E; ++I)
1460 EmitFunctionDebugFrame(*I);
1462 // Compute DIE offsets and sizes.
1465 // Emit all the DIEs into a debug info section
1468 // Corresponding abbreviations into a abbrev section.
1469 EmitAbbreviations();
1471 // Emit source line correspondence into a debug line section.
1474 // Emit info into a debug pubnames section.
1475 EmitDebugPubNames();
1477 // Emit info into a debug str section.
1480 // Emit info into a debug loc section.
1483 // Emit info into a debug aranges section.
1486 // Emit info into a debug ranges section.
1489 // Emit info into a debug macinfo section.
1492 // Emit inline info.
1493 EmitDebugInlineInfo();
1495 if (TimePassesIsEnabled)
1496 DebugTimer->stopTimer();
1499 /// BeginFunction - Gather pre-function debug information. Assumes being
1500 /// emitted immediately after the function entry point.
1501 void DwarfDebug::BeginFunction(MachineFunction *MF) {
1504 if (!ShouldEmitDwarfDebug()) return;
1506 if (TimePassesIsEnabled)
1507 DebugTimer->startTimer();
1509 // Begin accumulating function debug information.
1510 MMI->BeginFunction(MF);
1512 // Assumes in correct section after the entry point.
1513 EmitLabel("func_begin", ++SubprogramCount);
1515 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1517 DebugLoc FDL = MF->getDefaultDebugLoc();
1518 if (!FDL.isUnknown()) {
1519 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1520 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
1521 DICompileUnit(DLT.CompileUnit));
1522 Asm->printLabel(LabelID);
1525 if (TimePassesIsEnabled)
1526 DebugTimer->stopTimer();
1529 /// EndFunction - Gather and emit post-function debug information.
1531 void DwarfDebug::EndFunction(MachineFunction *MF) {
1532 if (!ShouldEmitDwarfDebug()) return;
1534 if (TimePassesIsEnabled)
1535 DebugTimer->startTimer();
1537 // Define end label for subprogram.
1538 EmitLabel("func_end", SubprogramCount);
1540 // Get function line info.
1541 if (!Lines.empty()) {
1542 // Get section line info.
1543 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
1544 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1545 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1546 // Append the function info to section info.
1547 SectionLineInfos.insert(SectionLineInfos.end(),
1548 Lines.begin(), Lines.end());
1551 // Construct the DbgScope for abstract instances.
1552 for (SmallVector<DbgScope *, 32>::iterator
1553 I = AbstractInstanceRootList.begin(),
1554 E = AbstractInstanceRootList.end(); I != E; ++I)
1555 ConstructFunctionDbgScope(*I);
1557 // Construct scopes for subprogram.
1558 if (FunctionDbgScope)
1559 ConstructFunctionDbgScope(FunctionDbgScope);
1561 // FIXME: This is wrong. We are essentially getting past a problem with
1562 // debug information not being able to handle unreachable blocks that have
1563 // debug information in them. In particular, those unreachable blocks that
1564 // have "region end" info in them. That situation results in the "root
1565 // scope" not being created. If that's the case, then emit a "default"
1566 // scope, i.e., one that encompasses the whole function. This isn't
1567 // desirable. And a better way of handling this (and all of the debugging
1568 // information) needs to be explored.
1569 ConstructDefaultDbgScope(MF);
1571 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1572 MMI->getFrameMoves()));
1575 if (FunctionDbgScope) {
1576 delete FunctionDbgScope;
1577 DbgScopeMap.clear();
1578 DbgAbstractScopeMap.clear();
1579 DbgConcreteScopeMap.clear();
1580 InlinedVariableScopes.clear();
1581 FunctionDbgScope = NULL;
1582 LexicalScopeStack.clear();
1583 AbstractInstanceRootList.clear();
1584 AbstractInstanceRootMap.clear();
1589 if (TimePassesIsEnabled)
1590 DebugTimer->stopTimer();
1593 /// RecordSourceLine - Records location information and associates it with a
1594 /// label. Returns a unique label ID used to generate a label and provide
1595 /// correspondence to the source line list.
1596 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1597 if (TimePassesIsEnabled)
1598 DebugTimer->startTimer();
1600 CompileUnit *Unit = CompileUnitMap[V];
1601 assert(Unit && "Unable to find CompileUnit");
1602 unsigned ID = MMI->NextLabelID();
1603 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1605 if (TimePassesIsEnabled)
1606 DebugTimer->stopTimer();
1611 /// RecordSourceLine - Records location information and associates it with a
1612 /// label. Returns a unique label ID used to generate a label and provide
1613 /// correspondence to the source line list.
1614 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1616 if (TimePassesIsEnabled)
1617 DebugTimer->startTimer();
1619 std::string Dir, Fn;
1620 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
1621 CU.getFilename(Fn));
1622 unsigned ID = MMI->NextLabelID();
1623 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1625 if (TimePassesIsEnabled)
1626 DebugTimer->stopTimer();
1631 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1632 /// timed. Look up the source id with the given directory and source file
1633 /// names. If none currently exists, create a new id and insert it in the
1634 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1636 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1637 const std::string &FileName) {
1638 if (TimePassesIsEnabled)
1639 DebugTimer->startTimer();
1641 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
1643 if (TimePassesIsEnabled)
1644 DebugTimer->stopTimer();
1649 /// RecordRegionStart - Indicate the start of a region.
1650 unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
1651 if (TimePassesIsEnabled)
1652 DebugTimer->startTimer();
1654 DbgScope *Scope = getOrCreateScope(V);
1655 unsigned ID = MMI->NextLabelID();
1656 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1657 LexicalScopeStack.push_back(Scope);
1659 if (TimePassesIsEnabled)
1660 DebugTimer->stopTimer();
1665 /// RecordRegionEnd - Indicate the end of a region.
1666 unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
1667 if (TimePassesIsEnabled)
1668 DebugTimer->startTimer();
1670 DbgScope *Scope = getOrCreateScope(V);
1671 unsigned ID = MMI->NextLabelID();
1672 Scope->setEndLabelID(ID);
1673 // FIXME : region.end() may not be in the last basic block.
1674 // For now, do not pop last lexical scope because next basic
1675 // block may start new inlined function's body.
1676 unsigned LSSize = LexicalScopeStack.size();
1677 if (LSSize != 0 && LSSize != 1)
1678 LexicalScopeStack.pop_back();
1680 if (TimePassesIsEnabled)
1681 DebugTimer->stopTimer();
1686 /// RecordVariable - Indicate the declaration of a local variable.
1687 void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
1688 const MachineInstr *MI) {
1689 if (TimePassesIsEnabled)
1690 DebugTimer->startTimer();
1692 DIDescriptor Desc(GV);
1693 DbgScope *Scope = NULL;
1694 bool InlinedFnVar = false;
1696 if (Desc.getTag() == dwarf::DW_TAG_variable) {
1697 // GV is a global variable.
1698 DIGlobalVariable DG(GV);
1699 Scope = getOrCreateScope(DG.getContext().getGV());
1701 DenseMap<const MachineInstr *, DbgScope *>::iterator
1702 SI = InlinedVariableScopes.find(MI);
1704 if (SI != InlinedVariableScopes.end()) {
1705 // or GV is an inlined local variable.
1709 GlobalVariable *V = DV.getContext().getGV();
1711 // FIXME: The code that checks for the inlined local variable is a hack!
1712 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1713 AI = AbstractInstanceRootMap.find(V);
1715 if (AI != AbstractInstanceRootMap.end()) {
1716 // This method is called each time a DECLARE node is encountered. For an
1717 // inlined function, this could be many, many times. We don't want to
1718 // re-add variables to that DIE for each time. We just want to add them
1719 // once. Check to make sure that we haven't added them already.
1720 DenseMap<const GlobalVariable *,
1721 SmallSet<const GlobalVariable *, 32> >::iterator
1722 IP = InlinedParamMap.find(V);
1724 if (IP != InlinedParamMap.end() && IP->second.count(GV) > 0) {
1725 if (TimePassesIsEnabled)
1726 DebugTimer->stopTimer();
1730 // or GV is an inlined local variable.
1732 InlinedParamMap[V].insert(GV);
1733 InlinedFnVar = true;
1735 // or GV is a local variable.
1736 Scope = getOrCreateScope(V);
1741 assert(Scope && "Unable to find the variable's scope");
1742 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
1743 Scope->AddVariable(DV);
1745 if (TimePassesIsEnabled)
1746 DebugTimer->stopTimer();
1749 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1750 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1751 unsigned Line, unsigned Col) {
1752 unsigned LabelID = MMI->NextLabelID();
1754 if (!TAI->doesDwarfUsesInlineInfoSection())
1757 if (TimePassesIsEnabled)
1758 DebugTimer->startTimer();
1760 CompileUnit *Unit = MainCU;
1762 Unit = &FindCompileUnit(SP.getCompileUnit());
1763 GlobalVariable *GV = SP.getGV();
1764 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1765 II = AbstractInstanceRootMap.find(GV);
1767 if (II == AbstractInstanceRootMap.end()) {
1768 // Create an abstract instance entry for this inlined function if it doesn't
1770 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
1772 // Get the compile unit context.
1773 DIE *SPDie = Unit->getDieMapSlotFor(GV);
1775 SPDie = CreateSubprogramDIE(Unit, SP, false, true);
1777 // Mark as being inlined. This makes this subprogram entry an abstract
1779 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1780 // that it's defined. That probably won't change in the future. However,
1781 // this could be more elegant.
1782 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1784 // Keep track of the abstract scope for this function.
1785 DbgAbstractScopeMap[GV] = Scope;
1787 AbstractInstanceRootMap[GV] = Scope;
1788 AbstractInstanceRootList.push_back(Scope);
1791 // Create a concrete inlined instance for this inlined function.
1792 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
1793 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
1794 ScopeDie->setAbstractCompileUnit(Unit);
1796 DIE *Origin = Unit->getDieMapSlotFor(GV);
1797 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1798 dwarf::DW_FORM_ref4, Origin);
1799 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
1800 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1801 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1803 ConcreteScope->setDie(ScopeDie);
1804 ConcreteScope->setStartLabelID(LabelID);
1805 MMI->RecordUsedDbgLabel(LabelID);
1807 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
1809 // Keep track of the concrete scope that's inlined into this function.
1810 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1811 SI = DbgConcreteScopeMap.find(GV);
1813 if (SI == DbgConcreteScopeMap.end())
1814 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
1816 SI->second.push_back(ConcreteScope);
1818 // Track the start label for this inlined function.
1819 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1820 I = InlineInfo.find(GV);
1822 if (I == InlineInfo.end())
1823 InlineInfo[GV].push_back(LabelID);
1825 I->second.push_back(LabelID);
1827 if (TimePassesIsEnabled)
1828 DebugTimer->stopTimer();
1833 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
1834 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
1835 if (!TAI->doesDwarfUsesInlineInfoSection())
1838 if (TimePassesIsEnabled)
1839 DebugTimer->startTimer();
1841 GlobalVariable *GV = SP.getGV();
1842 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1843 I = DbgConcreteScopeMap.find(GV);
1845 if (I == DbgConcreteScopeMap.end()) {
1846 // FIXME: Can this situation actually happen? And if so, should it?
1847 if (TimePassesIsEnabled)
1848 DebugTimer->stopTimer();
1853 SmallVector<DbgScope *, 8> &Scopes = I->second;
1854 if (Scopes.empty()) {
1855 // Returned ID is 0 if this is unbalanced "end of inlined
1856 // scope". This could happen if optimizer eats dbg intrinsics
1857 // or "beginning of inlined scope" is not recoginized due to
1858 // missing location info. In such cases, ignore this region.end.
1862 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
1863 unsigned ID = MMI->NextLabelID();
1864 MMI->RecordUsedDbgLabel(ID);
1865 Scope->setEndLabelID(ID);
1867 if (TimePassesIsEnabled)
1868 DebugTimer->stopTimer();
1873 /// RecordVariableScope - Record scope for the variable declared by
1874 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
1875 /// for only inlined subroutine variables. Other variables's scopes are
1876 /// determined during RecordVariable().
1877 void DwarfDebug::RecordVariableScope(DIVariable &DV,
1878 const MachineInstr *DeclareMI) {
1879 if (TimePassesIsEnabled)
1880 DebugTimer->startTimer();
1882 DISubprogram SP(DV.getContext().getGV());
1885 if (TimePassesIsEnabled)
1886 DebugTimer->stopTimer();
1891 DenseMap<GlobalVariable *, DbgScope *>::iterator
1892 I = DbgAbstractScopeMap.find(SP.getGV());
1893 if (I != DbgAbstractScopeMap.end())
1894 InlinedVariableScopes[DeclareMI] = I->second;
1896 if (TimePassesIsEnabled)
1897 DebugTimer->stopTimer();
1900 //===----------------------------------------------------------------------===//
1902 //===----------------------------------------------------------------------===//
1904 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1906 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1907 // Get the children.
1908 const std::vector<DIE *> &Children = Die->getChildren();
1910 // If not last sibling and has children then add sibling offset attribute.
1911 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1913 // Record the abbreviation.
1914 AssignAbbrevNumber(Die->getAbbrev());
1916 // Get the abbreviation for this DIE.
1917 unsigned AbbrevNumber = Die->getAbbrevNumber();
1918 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1921 Die->setOffset(Offset);
1923 // Start the size with the size of abbreviation code.
1924 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1926 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1927 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1929 // Size the DIE attribute values.
1930 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1931 // Size attribute value.
1932 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1934 // Size the DIE children if any.
1935 if (!Children.empty()) {
1936 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1937 "Children flag not set");
1939 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1940 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1942 // End of children marker.
1943 Offset += sizeof(int8_t);
1946 Die->setSize(Offset - Die->getOffset());
1950 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1952 void DwarfDebug::SizeAndOffsets() {
1953 // Compute size of compile unit header.
1954 static unsigned Offset =
1955 sizeof(int32_t) + // Length of Compilation Unit Info
1956 sizeof(int16_t) + // DWARF version number
1957 sizeof(int32_t) + // Offset Into Abbrev. Section
1958 sizeof(int8_t); // Pointer Size (in bytes)
1960 // Process base compile unit.
1962 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1963 CompileUnitOffsets[MainCU] = 0;
1967 // Process all compile units.
1968 unsigned PrevOffset = 0;
1970 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1971 CompileUnit *Unit = CompileUnits[i];
1972 CompileUnitOffsets[Unit] = PrevOffset;
1973 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1974 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1978 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1979 /// tools to recognize the object file contains Dwarf information.
1980 void DwarfDebug::EmitInitial() {
1981 // Check to see if we already emitted intial headers.
1982 if (didInitial) return;
1985 // Dwarf sections base addresses.
1986 if (TAI->doesDwarfRequireFrameSection()) {
1987 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1988 EmitLabel("section_debug_frame", 0);
1991 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1992 EmitLabel("section_info", 0);
1993 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1994 EmitLabel("section_abbrev", 0);
1995 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1996 EmitLabel("section_aranges", 0);
1998 if (TAI->doesSupportMacInfoSection()) {
1999 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2000 EmitLabel("section_macinfo", 0);
2003 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2004 EmitLabel("section_line", 0);
2005 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2006 EmitLabel("section_loc", 0);
2007 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2008 EmitLabel("section_pubnames", 0);
2009 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2010 EmitLabel("section_str", 0);
2011 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2012 EmitLabel("section_ranges", 0);
2014 Asm->SwitchToSection(TAI->getTextSection());
2015 EmitLabel("text_begin", 0);
2016 Asm->SwitchToSection(TAI->getDataSection());
2017 EmitLabel("data_begin", 0);
2020 /// EmitDIE - Recusively Emits a debug information entry.
2022 void DwarfDebug::EmitDIE(DIE *Die) {
2023 // Get the abbreviation for this DIE.
2024 unsigned AbbrevNumber = Die->getAbbrevNumber();
2025 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2029 // Emit the code (index) for the abbreviation.
2030 Asm->EmitULEB128Bytes(AbbrevNumber);
2032 if (Asm->isVerbose())
2033 Asm->EOL(std::string("Abbrev [" +
2034 utostr(AbbrevNumber) +
2035 "] 0x" + utohexstr(Die->getOffset()) +
2036 ":0x" + utohexstr(Die->getSize()) + " " +
2037 dwarf::TagString(Abbrev->getTag())));
2041 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2042 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2044 // Emit the DIE attribute values.
2045 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2046 unsigned Attr = AbbrevData[i].getAttribute();
2047 unsigned Form = AbbrevData[i].getForm();
2048 assert(Form && "Too many attributes for DIE (check abbreviation)");
2051 case dwarf::DW_AT_sibling:
2052 Asm->EmitInt32(Die->SiblingOffset());
2054 case dwarf::DW_AT_abstract_origin: {
2055 DIEEntry *E = cast<DIEEntry>(Values[i]);
2056 DIE *Origin = E->getEntry();
2058 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
2059 Origin->getOffset();
2061 Asm->EmitInt32(Addr);
2065 // Emit an attribute using the defined form.
2066 Values[i]->EmitValue(this, Form);
2070 Asm->EOL(dwarf::AttributeString(Attr));
2073 // Emit the DIE children if any.
2074 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2075 const std::vector<DIE *> &Children = Die->getChildren();
2077 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2078 EmitDIE(Children[j]);
2080 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2084 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2086 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2087 DIE *Die = Unit->getDie();
2089 // Emit the compile units header.
2090 EmitLabel("info_begin", Unit->getID());
2092 // Emit size of content not including length itself
2093 unsigned ContentSize = Die->getSize() +
2094 sizeof(int16_t) + // DWARF version number
2095 sizeof(int32_t) + // Offset Into Abbrev. Section
2096 sizeof(int8_t) + // Pointer Size (in bytes)
2097 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2099 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2100 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2101 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2102 Asm->EOL("Offset Into Abbrev. Section");
2103 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2106 // FIXME - extra padding for gdb bug.
2107 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2108 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2109 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2110 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2111 EmitLabel("info_end", Unit->getID());
2116 void DwarfDebug::EmitDebugInfo() {
2117 // Start debug info section.
2118 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2121 EmitDebugInfoPerCU(MainCU);
2125 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2126 EmitDebugInfoPerCU(CompileUnits[i]);
2129 /// EmitAbbreviations - Emit the abbreviation section.
2131 void DwarfDebug::EmitAbbreviations() const {
2132 // Check to see if it is worth the effort.
2133 if (!Abbreviations.empty()) {
2134 // Start the debug abbrev section.
2135 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2137 EmitLabel("abbrev_begin", 0);
2139 // For each abbrevation.
2140 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2141 // Get abbreviation data
2142 const DIEAbbrev *Abbrev = Abbreviations[i];
2144 // Emit the abbrevations code (base 1 index.)
2145 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2146 Asm->EOL("Abbreviation Code");
2148 // Emit the abbreviations data.
2154 // Mark end of abbreviations.
2155 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2157 EmitLabel("abbrev_end", 0);
2162 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2163 /// the line matrix.
2165 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2166 // Define last address of section.
2167 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2168 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2169 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2170 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2172 // Mark end of matrix.
2173 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2174 Asm->EmitULEB128Bytes(1); Asm->EOL();
2175 Asm->EmitInt8(1); Asm->EOL();
2178 /// EmitDebugLines - Emit source line information.
2180 void DwarfDebug::EmitDebugLines() {
2181 // If the target is using .loc/.file, the assembler will be emitting the
2182 // .debug_line table automatically.
2183 if (TAI->hasDotLocAndDotFile())
2186 // Minimum line delta, thus ranging from -10..(255-10).
2187 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2188 // Maximum line delta, thus ranging from -10..(255-10).
2189 const int MaxLineDelta = 255 + MinLineDelta;
2191 // Start the dwarf line section.
2192 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2194 // Construct the section header.
2195 EmitDifference("line_end", 0, "line_begin", 0, true);
2196 Asm->EOL("Length of Source Line Info");
2197 EmitLabel("line_begin", 0);
2199 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2201 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2202 Asm->EOL("Prolog Length");
2203 EmitLabel("line_prolog_begin", 0);
2205 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2207 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2209 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2211 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2213 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2215 // Line number standard opcode encodings argument count
2216 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2217 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2218 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2219 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2220 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2221 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2222 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2223 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2224 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2226 // Emit directories.
2227 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2228 Asm->EmitString(getSourceDirectoryName(DI));
2229 Asm->EOL("Directory");
2232 Asm->EmitInt8(0); Asm->EOL("End of directories");
2235 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2236 // Remember source id starts at 1.
2237 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2238 Asm->EmitString(getSourceFileName(Id.second));
2240 Asm->EmitULEB128Bytes(Id.first);
2241 Asm->EOL("Directory #");
2242 Asm->EmitULEB128Bytes(0);
2243 Asm->EOL("Mod date");
2244 Asm->EmitULEB128Bytes(0);
2245 Asm->EOL("File size");
2248 Asm->EmitInt8(0); Asm->EOL("End of files");
2250 EmitLabel("line_prolog_end", 0);
2252 // A sequence for each text section.
2253 unsigned SecSrcLinesSize = SectionSourceLines.size();
2255 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2256 // Isolate current sections line info.
2257 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2259 if (Asm->isVerbose()) {
2260 const Section* S = SectionMap[j + 1];
2261 O << '\t' << TAI->getCommentString() << " Section"
2262 << S->getName() << '\n';
2267 // Dwarf assumes we start with first line of first source file.
2268 unsigned Source = 1;
2271 // Construct rows of the address, source, line, column matrix.
2272 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2273 const SrcLineInfo &LineInfo = LineInfos[i];
2274 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2275 if (!LabelID) continue;
2277 if (!Asm->isVerbose())
2280 std::pair<unsigned, unsigned> SourceID =
2281 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2282 O << '\t' << TAI->getCommentString() << ' '
2283 << getSourceDirectoryName(SourceID.first) << ' '
2284 << getSourceFileName(SourceID.second)
2285 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2288 // Define the line address.
2289 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2290 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2291 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2292 EmitReference("label", LabelID); Asm->EOL("Location label");
2294 // If change of source, then switch to the new source.
2295 if (Source != LineInfo.getSourceID()) {
2296 Source = LineInfo.getSourceID();
2297 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2298 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2301 // If change of line.
2302 if (Line != LineInfo.getLine()) {
2303 // Determine offset.
2304 int Offset = LineInfo.getLine() - Line;
2305 int Delta = Offset - MinLineDelta;
2308 Line = LineInfo.getLine();
2310 // If delta is small enough and in range...
2311 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2312 // ... then use fast opcode.
2313 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2315 // ... otherwise use long hand.
2316 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2317 Asm->EOL("DW_LNS_advance_line");
2318 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2319 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2322 // Copy the previous row (different address or source)
2323 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2327 EmitEndOfLineMatrix(j + 1);
2330 if (SecSrcLinesSize == 0)
2331 // Because we're emitting a debug_line section, we still need a line
2332 // table. The linker and friends expect it to exist. If there's nothing to
2333 // put into it, emit an empty table.
2334 EmitEndOfLineMatrix(1);
2336 EmitLabel("line_end", 0);
2340 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2342 void DwarfDebug::EmitCommonDebugFrame() {
2343 if (!TAI->doesDwarfRequireFrameSection())
2347 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2348 TargetFrameInfo::StackGrowsUp ?
2349 TD->getPointerSize() : -TD->getPointerSize();
2351 // Start the dwarf frame section.
2352 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2354 EmitLabel("debug_frame_common", 0);
2355 EmitDifference("debug_frame_common_end", 0,
2356 "debug_frame_common_begin", 0, true);
2357 Asm->EOL("Length of Common Information Entry");
2359 EmitLabel("debug_frame_common_begin", 0);
2360 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2361 Asm->EOL("CIE Identifier Tag");
2362 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2363 Asm->EOL("CIE Version");
2364 Asm->EmitString("");
2365 Asm->EOL("CIE Augmentation");
2366 Asm->EmitULEB128Bytes(1);
2367 Asm->EOL("CIE Code Alignment Factor");
2368 Asm->EmitSLEB128Bytes(stackGrowth);
2369 Asm->EOL("CIE Data Alignment Factor");
2370 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2371 Asm->EOL("CIE RA Column");
2373 std::vector<MachineMove> Moves;
2374 RI->getInitialFrameState(Moves);
2376 EmitFrameMoves(NULL, 0, Moves, false);
2378 Asm->EmitAlignment(2, 0, 0, false);
2379 EmitLabel("debug_frame_common_end", 0);
2384 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2387 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2388 if (!TAI->doesDwarfRequireFrameSection())
2391 // Start the dwarf frame section.
2392 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2394 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2395 "debug_frame_begin", DebugFrameInfo.Number, true);
2396 Asm->EOL("Length of Frame Information Entry");
2398 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2400 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2402 Asm->EOL("FDE CIE offset");
2404 EmitReference("func_begin", DebugFrameInfo.Number);
2405 Asm->EOL("FDE initial location");
2406 EmitDifference("func_end", DebugFrameInfo.Number,
2407 "func_begin", DebugFrameInfo.Number);
2408 Asm->EOL("FDE address range");
2410 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2413 Asm->EmitAlignment(2, 0, 0, false);
2414 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2419 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2420 EmitDifference("pubnames_end", Unit->getID(),
2421 "pubnames_begin", Unit->getID(), true);
2422 Asm->EOL("Length of Public Names Info");
2424 EmitLabel("pubnames_begin", Unit->getID());
2426 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2428 EmitSectionOffset("info_begin", "section_info",
2429 Unit->getID(), 0, true, false);
2430 Asm->EOL("Offset of Compilation Unit Info");
2432 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2434 Asm->EOL("Compilation Unit Length");
2436 StringMap<DIE*> &Globals = Unit->getGlobals();
2437 for (StringMap<DIE*>::const_iterator
2438 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2439 const char *Name = GI->getKeyData();
2440 DIE * Entity = GI->second;
2442 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2443 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2446 Asm->EmitInt32(0); Asm->EOL("End Mark");
2447 EmitLabel("pubnames_end", Unit->getID());
2452 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2454 void DwarfDebug::EmitDebugPubNames() {
2455 // Start the dwarf pubnames section.
2456 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2459 EmitDebugPubNamesPerCU(MainCU);
2463 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2464 EmitDebugPubNamesPerCU(CompileUnits[i]);
2467 /// EmitDebugStr - Emit visible names into a debug str section.
2469 void DwarfDebug::EmitDebugStr() {
2470 // Check to see if it is worth the effort.
2471 if (!StringPool.empty()) {
2472 // Start the dwarf str section.
2473 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2475 // For each of strings in the string pool.
2476 for (unsigned StringID = 1, N = StringPool.size();
2477 StringID <= N; ++StringID) {
2478 // Emit a label for reference from debug information entries.
2479 EmitLabel("string", StringID);
2481 // Emit the string itself.
2482 const std::string &String = StringPool[StringID];
2483 Asm->EmitString(String); Asm->EOL();
2490 /// EmitDebugLoc - Emit visible names into a debug loc section.
2492 void DwarfDebug::EmitDebugLoc() {
2493 // Start the dwarf loc section.
2494 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2498 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2500 void DwarfDebug::EmitDebugARanges() {
2501 // Start the dwarf aranges section.
2502 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2506 CompileUnit *Unit = GetBaseCompileUnit();
2508 // Don't include size of length
2509 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2511 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2513 EmitReference("info_begin", Unit->getID());
2514 Asm->EOL("Offset of Compilation Unit Info");
2516 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2518 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2520 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2521 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2524 EmitReference("text_begin", 0); Asm->EOL("Address");
2525 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2527 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2528 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2534 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2536 void DwarfDebug::EmitDebugRanges() {
2537 // Start the dwarf ranges section.
2538 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2542 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2544 void DwarfDebug::EmitDebugMacInfo() {
2545 if (TAI->doesSupportMacInfoSection()) {
2546 // Start the dwarf macinfo section.
2547 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2552 /// EmitDebugInlineInfo - Emit inline info using following format.
2554 /// 1. length of section
2555 /// 2. Dwarf version number
2556 /// 3. address size.
2558 /// Entries (one "entry" for each function that was inlined):
2560 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2561 /// otherwise offset into __debug_str for regular function name.
2562 /// 2. offset into __debug_str section for regular function name.
2563 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2564 /// instances for the function.
2566 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2567 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2568 /// __debug_info section, and the low_pc is the starting address for the
2569 /// inlining instance.
2570 void DwarfDebug::EmitDebugInlineInfo() {
2571 if (!TAI->doesDwarfUsesInlineInfoSection())
2577 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2579 EmitDifference("debug_inlined_end", 1,
2580 "debug_inlined_begin", 1, true);
2581 Asm->EOL("Length of Debug Inlined Information Entry");
2583 EmitLabel("debug_inlined_begin", 1);
2585 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2586 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2588 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2589 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2590 GlobalVariable *GV = I->first;
2591 SmallVector<unsigned, 4> &Labels = I->second;
2592 DISubprogram SP(GV);
2596 SP.getLinkageName(LName);
2599 Asm->EmitString(LName.empty() ? Name : LName);
2600 Asm->EOL("MIPS linkage name");
2602 Asm->EmitString(Name); Asm->EOL("Function name");
2604 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2606 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2607 LE = Labels.end(); LI != LE; ++LI) {
2608 DIE *SP = MainCU->getDieMapSlotFor(GV);
2609 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2611 if (TD->getPointerSize() == sizeof(int32_t))
2612 O << TAI->getData32bitsDirective();
2614 O << TAI->getData64bitsDirective();
2616 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2620 EmitLabel("debug_inlined_end", 1);