Change allowsUnalignedMemoryAccesses to take type argument since some targets
[llvm/avr.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
blobbe92fbd485f55b325e014b5f9d6c621298cb54f9
1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/MC/MCSection.h"
18 #include "llvm/Target/TargetAsmInfo.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetLoweringObjectFile.h"
22 #include "llvm/Target/TargetRegisterInfo.h"
23 #include "llvm/Support/Timer.h"
24 #include "llvm/System/Path.h"
25 using namespace llvm;
27 static TimerGroup &getDwarfTimerGroup() {
28 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
29 return DwarfTimerGroup;
32 //===----------------------------------------------------------------------===//
34 /// Configuration values for initial hash set sizes (log2).
35 ///
36 static const unsigned InitDiesSetSize = 9; // log2(512)
37 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
38 static const unsigned InitValuesSetSize = 9; // log2(512)
40 namespace llvm {
42 //===----------------------------------------------------------------------===//
43 /// CompileUnit - This dwarf writer support class manages information associate
44 /// with a source file.
45 class VISIBILITY_HIDDEN CompileUnit {
46 /// ID - File identifier for source.
47 ///
48 unsigned ID;
50 /// Die - Compile unit debug information entry.
51 ///
52 DIE *Die;
54 /// GVToDieMap - Tracks the mapping of unit level debug informaton
55 /// variables to debug information entries.
56 std::map<GlobalVariable *, DIE *> GVToDieMap;
58 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
59 /// descriptors to debug information entries using a DIEEntry proxy.
60 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
62 /// Globals - A map of globally visible named entities for this unit.
63 ///
64 StringMap<DIE*> Globals;
66 /// DiesSet - Used to uniquely define dies within the compile unit.
67 ///
68 FoldingSet<DIE> DiesSet;
69 public:
70 CompileUnit(unsigned I, DIE *D)
71 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
72 ~CompileUnit() { delete Die; }
74 // Accessors.
75 unsigned getID() const { return ID; }
76 DIE* getDie() const { return Die; }
77 StringMap<DIE*> &getGlobals() { return Globals; }
79 /// hasContent - Return true if this compile unit has something to write out.
80 ///
81 bool hasContent() const { return !Die->getChildren().empty(); }
83 /// AddGlobal - Add a new global entity to the compile unit.
84 ///
85 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
87 /// getDieMapSlotFor - Returns the debug information entry map slot for the
88 /// specified debug variable.
89 DIE *&getDieMapSlotFor(GlobalVariable *GV) { return GVToDieMap[GV]; }
91 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
92 /// the specified debug variable.
93 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
94 return GVToDIEEntryMap[GV];
97 /// AddDie - Adds or interns the DIE to the compile unit.
98 ///
99 DIE *AddDie(DIE &Buffer) {
100 FoldingSetNodeID ID;
101 Buffer.Profile(ID);
102 void *Where;
103 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
105 if (!Die) {
106 Die = new DIE(Buffer);
107 DiesSet.InsertNode(Die, Where);
108 this->Die->AddChild(Die);
109 Buffer.Detach();
112 return Die;
116 //===----------------------------------------------------------------------===//
117 /// DbgVariable - This class is used to track local variable information.
119 class VISIBILITY_HIDDEN DbgVariable {
120 DIVariable Var; // Variable Descriptor.
121 unsigned FrameIndex; // Variable frame index.
122 bool InlinedFnVar; // Variable for an inlined function.
123 public:
124 DbgVariable(DIVariable V, unsigned I, bool IFV)
125 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
127 // Accessors.
128 DIVariable getVariable() const { return Var; }
129 unsigned getFrameIndex() const { return FrameIndex; }
130 bool isInlinedFnVar() const { return InlinedFnVar; }
133 //===----------------------------------------------------------------------===//
134 /// DbgScope - This class is used to track scope information.
136 class DbgConcreteScope;
137 class VISIBILITY_HIDDEN DbgScope {
138 DbgScope *Parent; // Parent to this scope.
139 DIDescriptor Desc; // Debug info descriptor for scope.
140 // Either subprogram or block.
141 unsigned StartLabelID; // Label ID of the beginning of scope.
142 unsigned EndLabelID; // Label ID of the end of scope.
143 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
144 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
145 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
147 // Private state for dump()
148 mutable unsigned IndentLevel;
149 public:
150 DbgScope(DbgScope *P, DIDescriptor D)
151 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), IndentLevel(0) {}
152 virtual ~DbgScope();
154 // Accessors.
155 DbgScope *getParent() const { return Parent; }
156 DIDescriptor getDesc() const { return Desc; }
157 unsigned getStartLabelID() const { return StartLabelID; }
158 unsigned getEndLabelID() const { return EndLabelID; }
159 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
160 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
161 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
162 void setStartLabelID(unsigned S) { StartLabelID = S; }
163 void setEndLabelID(unsigned E) { EndLabelID = E; }
165 /// AddScope - Add a scope to the scope.
167 void AddScope(DbgScope *S) { Scopes.push_back(S); }
169 /// AddVariable - Add a variable to the scope.
171 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
173 /// AddConcreteInst - Add a concrete instance to the scope.
175 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
177 #ifndef NDEBUG
178 void dump() const;
179 #endif
182 #ifndef NDEBUG
183 void DbgScope::dump() const {
184 std::string Indent(IndentLevel, ' ');
186 cerr << Indent; Desc.dump();
187 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
189 IndentLevel += 2;
191 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
192 if (Scopes[i] != this)
193 Scopes[i]->dump();
195 IndentLevel -= 2;
197 #endif
199 //===----------------------------------------------------------------------===//
200 /// DbgConcreteScope - This class is used to track a scope that holds concrete
201 /// instance information.
203 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
204 CompileUnit *Unit;
205 DIE *Die; // Debug info for this concrete scope.
206 public:
207 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
209 // Accessors.
210 DIE *getDie() const { return Die; }
211 void setDie(DIE *D) { Die = D; }
214 DbgScope::~DbgScope() {
215 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
216 delete Scopes[i];
217 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
218 delete Variables[j];
219 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
220 delete ConcreteInsts[k];
223 } // end llvm namespace
225 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
226 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
227 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
228 ValuesSet(InitValuesSetSize), Values(), StringPool(),
229 SectionSourceLines(), didInitial(false), shouldEmit(false),
230 FunctionDbgScope(0), DebugTimer(0) {
231 if (TimePassesIsEnabled)
232 DebugTimer = new Timer("Dwarf Debug Writer",
233 getDwarfTimerGroup());
235 DwarfDebug::~DwarfDebug() {
236 for (unsigned j = 0, M = Values.size(); j < M; ++j)
237 delete Values[j];
239 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
240 I = AbstractInstanceRootMap.begin(),
241 E = AbstractInstanceRootMap.end(); I != E;++I)
242 delete I->second;
244 delete DebugTimer;
247 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
249 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
250 // Profile the node so that we can make it unique.
251 FoldingSetNodeID ID;
252 Abbrev.Profile(ID);
254 // Check the set for priors.
255 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
257 // If it's newly added.
258 if (InSet == &Abbrev) {
259 // Add to abbreviation list.
260 Abbreviations.push_back(&Abbrev);
262 // Assign the vector position + 1 as its number.
263 Abbrev.setNumber(Abbreviations.size());
264 } else {
265 // Assign existing abbreviation number.
266 Abbrev.setNumber(InSet->getNumber());
270 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
271 /// information entry.
272 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
273 DIEEntry *Value;
275 if (Entry) {
276 FoldingSetNodeID ID;
277 DIEEntry::Profile(ID, Entry);
278 void *Where;
279 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
281 if (Value) return Value;
283 Value = new DIEEntry(Entry);
284 ValuesSet.InsertNode(Value, Where);
285 } else {
286 Value = new DIEEntry(Entry);
289 Values.push_back(Value);
290 return Value;
293 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
295 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
296 Value->setEntry(Entry);
298 // Add to values set if not already there. If it is, we merely have a
299 // duplicate in the values list (no harm.)
300 ValuesSet.GetOrInsertNode(Value);
303 /// AddUInt - Add an unsigned integer attribute data and value.
305 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
306 unsigned Form, uint64_t Integer) {
307 if (!Form) Form = DIEInteger::BestForm(false, Integer);
309 FoldingSetNodeID ID;
310 DIEInteger::Profile(ID, Integer);
311 void *Where;
312 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
314 if (!Value) {
315 Value = new DIEInteger(Integer);
316 ValuesSet.InsertNode(Value, Where);
317 Values.push_back(Value);
320 Die->AddValue(Attribute, Form, Value);
323 /// AddSInt - Add an signed integer attribute data and value.
325 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
326 unsigned Form, int64_t Integer) {
327 if (!Form) Form = DIEInteger::BestForm(true, Integer);
329 FoldingSetNodeID ID;
330 DIEInteger::Profile(ID, (uint64_t)Integer);
331 void *Where;
332 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
334 if (!Value) {
335 Value = new DIEInteger(Integer);
336 ValuesSet.InsertNode(Value, Where);
337 Values.push_back(Value);
340 Die->AddValue(Attribute, Form, Value);
343 /// AddString - Add a string attribute data and value.
345 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
346 const std::string &String) {
347 FoldingSetNodeID ID;
348 DIEString::Profile(ID, String);
349 void *Where;
350 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
352 if (!Value) {
353 Value = new DIEString(String);
354 ValuesSet.InsertNode(Value, Where);
355 Values.push_back(Value);
358 Die->AddValue(Attribute, Form, Value);
361 /// AddLabel - Add a Dwarf label attribute data and value.
363 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
364 const DWLabel &Label) {
365 FoldingSetNodeID ID;
366 DIEDwarfLabel::Profile(ID, Label);
367 void *Where;
368 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
370 if (!Value) {
371 Value = new DIEDwarfLabel(Label);
372 ValuesSet.InsertNode(Value, Where);
373 Values.push_back(Value);
376 Die->AddValue(Attribute, Form, Value);
379 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
381 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
382 const std::string &Label) {
383 FoldingSetNodeID ID;
384 DIEObjectLabel::Profile(ID, Label);
385 void *Where;
386 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
388 if (!Value) {
389 Value = new DIEObjectLabel(Label);
390 ValuesSet.InsertNode(Value, Where);
391 Values.push_back(Value);
394 Die->AddValue(Attribute, Form, Value);
397 /// AddSectionOffset - Add a section offset label attribute data and value.
399 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
400 const DWLabel &Label, const DWLabel &Section,
401 bool isEH, bool useSet) {
402 FoldingSetNodeID ID;
403 DIESectionOffset::Profile(ID, Label, Section);
404 void *Where;
405 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
407 if (!Value) {
408 Value = new DIESectionOffset(Label, Section, isEH, useSet);
409 ValuesSet.InsertNode(Value, Where);
410 Values.push_back(Value);
413 Die->AddValue(Attribute, Form, Value);
416 /// AddDelta - Add a label delta attribute data and value.
418 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
419 const DWLabel &Hi, const DWLabel &Lo) {
420 FoldingSetNodeID ID;
421 DIEDelta::Profile(ID, Hi, Lo);
422 void *Where;
423 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
425 if (!Value) {
426 Value = new DIEDelta(Hi, Lo);
427 ValuesSet.InsertNode(Value, Where);
428 Values.push_back(Value);
431 Die->AddValue(Attribute, Form, Value);
434 /// AddBlock - Add block data.
436 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
437 DIEBlock *Block) {
438 Block->ComputeSize(TD);
439 FoldingSetNodeID ID;
440 Block->Profile(ID);
441 void *Where;
442 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
444 if (!Value) {
445 Value = Block;
446 ValuesSet.InsertNode(Value, Where);
447 Values.push_back(Value);
448 } else {
449 // Already exists, reuse the previous one.
450 delete Block;
451 Block = cast<DIEBlock>(Value);
454 Die->AddValue(Attribute, Block->BestForm(), Value);
457 /// AddSourceLine - Add location information to specified debug information
458 /// entry.
459 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
460 // If there is no compile unit specified, don't add a line #.
461 if (V->getCompileUnit().isNull())
462 return;
464 unsigned Line = V->getLineNumber();
465 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
466 assert(FileID && "Invalid file id");
467 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
468 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
471 /// AddSourceLine - Add location information to specified debug information
472 /// entry.
473 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
474 // If there is no compile unit specified, don't add a line #.
475 if (G->getCompileUnit().isNull())
476 return;
478 unsigned Line = G->getLineNumber();
479 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
480 assert(FileID && "Invalid file id");
481 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
482 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
484 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
485 // If there is no compile unit specified, don't add a line #.
486 DICompileUnit CU = Ty->getCompileUnit();
487 if (CU.isNull())
488 return;
490 unsigned Line = Ty->getLineNumber();
491 unsigned FileID = FindCompileUnit(CU).getID();
492 assert(FileID && "Invalid file id");
493 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
494 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
497 /// AddAddress - Add an address attribute to a die based on the location
498 /// provided.
499 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
500 const MachineLocation &Location) {
501 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
502 DIEBlock *Block = new DIEBlock();
504 if (Location.isReg()) {
505 if (Reg < 32) {
506 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
507 } else {
508 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
509 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
511 } else {
512 if (Reg < 32) {
513 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
514 } else {
515 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
516 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
519 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
522 AddBlock(Die, Attribute, 0, Block);
525 /// AddType - Add a new type attribute to the specified entity.
526 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
527 if (Ty.isNull())
528 return;
530 // Check for pre-existence.
531 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
533 // If it exists then use the existing value.
534 if (Slot) {
535 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
536 return;
539 // Set up proxy.
540 Slot = CreateDIEEntry();
542 // Construct type.
543 DIE Buffer(dwarf::DW_TAG_base_type);
544 if (Ty.isBasicType(Ty.getTag()))
545 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
546 else if (Ty.isDerivedType(Ty.getTag()))
547 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
548 else {
549 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
550 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
553 // Add debug information entry to entity and appropriate context.
554 DIE *Die = NULL;
555 DIDescriptor Context = Ty.getContext();
556 if (!Context.isNull())
557 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
559 if (Die) {
560 DIE *Child = new DIE(Buffer);
561 Die->AddChild(Child);
562 Buffer.Detach();
563 SetDIEEntry(Slot, Child);
564 } else {
565 Die = DW_Unit->AddDie(Buffer);
566 SetDIEEntry(Slot, Die);
569 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
572 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
573 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
574 DIBasicType BTy) {
575 // Get core information.
576 std::string Name;
577 BTy.getName(Name);
578 Buffer.setTag(dwarf::DW_TAG_base_type);
579 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
580 BTy.getEncoding());
582 // Add name if not anonymous or intermediate type.
583 if (!Name.empty())
584 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
585 uint64_t Size = BTy.getSizeInBits() >> 3;
586 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
589 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
590 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
591 DIDerivedType DTy) {
592 // Get core information.
593 std::string Name;
594 DTy.getName(Name);
595 uint64_t Size = DTy.getSizeInBits() >> 3;
596 unsigned Tag = DTy.getTag();
598 // FIXME - Workaround for templates.
599 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
601 Buffer.setTag(Tag);
603 // Map to main type, void will not have a type.
604 DIType FromTy = DTy.getTypeDerivedFrom();
605 AddType(DW_Unit, &Buffer, FromTy);
607 // Add name if not anonymous or intermediate type.
608 if (!Name.empty())
609 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
611 // Add size if non-zero (derived types might be zero-sized.)
612 if (Size)
613 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
615 // Add source line info if available and TyDesc is not a forward declaration.
616 if (!DTy.isForwardDecl())
617 AddSourceLine(&Buffer, &DTy);
620 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
621 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
622 DICompositeType CTy) {
623 // Get core information.
624 std::string Name;
625 CTy.getName(Name);
627 uint64_t Size = CTy.getSizeInBits() >> 3;
628 unsigned Tag = CTy.getTag();
629 Buffer.setTag(Tag);
631 switch (Tag) {
632 case dwarf::DW_TAG_vector_type:
633 case dwarf::DW_TAG_array_type:
634 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
635 break;
636 case dwarf::DW_TAG_enumeration_type: {
637 DIArray Elements = CTy.getTypeArray();
639 // Add enumerators to enumeration type.
640 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
641 DIE *ElemDie = NULL;
642 DIEnumerator Enum(Elements.getElement(i).getGV());
643 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
644 Buffer.AddChild(ElemDie);
647 break;
648 case dwarf::DW_TAG_subroutine_type: {
649 // Add return type.
650 DIArray Elements = CTy.getTypeArray();
651 DIDescriptor RTy = Elements.getElement(0);
652 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
654 // Add prototype flag.
655 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
657 // Add arguments.
658 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
659 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
660 DIDescriptor Ty = Elements.getElement(i);
661 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
662 Buffer.AddChild(Arg);
665 break;
666 case dwarf::DW_TAG_structure_type:
667 case dwarf::DW_TAG_union_type:
668 case dwarf::DW_TAG_class_type: {
669 // Add elements to structure type.
670 DIArray Elements = CTy.getTypeArray();
672 // A forward struct declared type may not have elements available.
673 if (Elements.isNull())
674 break;
676 // Add elements to structure type.
677 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
678 DIDescriptor Element = Elements.getElement(i);
679 DIE *ElemDie = NULL;
680 if (Element.getTag() == dwarf::DW_TAG_subprogram)
681 ElemDie = CreateSubprogramDIE(DW_Unit,
682 DISubprogram(Element.getGV()));
683 else
684 ElemDie = CreateMemberDIE(DW_Unit,
685 DIDerivedType(Element.getGV()));
686 Buffer.AddChild(ElemDie);
689 // FIXME: We'd like an API to register additional attributes for the
690 // frontend to use while synthesizing, and then we'd use that api in clang
691 // instead of this.
692 if (Name == "__block_literal_generic")
693 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
695 unsigned RLang = CTy.getRunTimeLang();
696 if (RLang)
697 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
698 dwarf::DW_FORM_data1, RLang);
699 break;
701 default:
702 break;
705 // Add name if not anonymous or intermediate type.
706 if (!Name.empty())
707 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
709 if (Tag == dwarf::DW_TAG_enumeration_type ||
710 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
711 // Add size if non-zero (derived types might be zero-sized.)
712 if (Size)
713 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
714 else {
715 // Add zero size if it is not a forward declaration.
716 if (CTy.isForwardDecl())
717 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
718 else
719 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
722 // Add source line info if available.
723 if (!CTy.isForwardDecl())
724 AddSourceLine(&Buffer, &CTy);
728 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
729 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
730 int64_t L = SR.getLo();
731 int64_t H = SR.getHi();
732 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
734 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
735 if (L)
736 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
737 if (H)
738 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);
772 std::string Name;
773 ETy->getName(Name);
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);
777 return Enumerator;
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);
784 std::string Name;
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 // Skip special LLVM prefix that is used to inform the asm printer to not emit
791 // usual symbol prefix before the symbol name. This happens for Objective-C
792 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
793 if (LinkageName[0] == 1)
794 LinkageName = &LinkageName[1];
795 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
796 LinkageName);
798 AddType(DW_Unit, GVDie, GV.getType());
799 if (!GV.isLocalToUnit())
800 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
801 AddSourceLine(GVDie, &GV);
802 return GVDie;
805 /// CreateMemberDIE - Create new member DIE.
806 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
807 DIE *MemberDie = new DIE(DT.getTag());
808 std::string Name;
809 DT.getName(Name);
810 if (!Name.empty())
811 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
813 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
815 AddSourceLine(MemberDie, &DT);
817 uint64_t Size = DT.getSizeInBits();
818 uint64_t FieldSize = DT.getOriginalTypeSize();
820 if (Size != FieldSize) {
821 // Handle bitfield.
822 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
823 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
825 uint64_t Offset = DT.getOffsetInBits();
826 uint64_t FieldOffset = Offset;
827 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
828 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
829 FieldOffset = (HiMark - FieldSize);
830 Offset -= FieldOffset;
832 // Maybe we need to work from the other end.
833 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
834 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
837 DIEBlock *Block = new DIEBlock();
838 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
839 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
840 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
842 if (DT.isProtected())
843 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
844 dwarf::DW_ACCESS_protected);
845 else if (DT.isPrivate())
846 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
847 dwarf::DW_ACCESS_private);
849 return MemberDie;
852 /// CreateSubprogramDIE - Create new DIE using SP.
853 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
854 const DISubprogram &SP,
855 bool IsConstructor,
856 bool IsInlined) {
857 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
859 std::string Name;
860 SP.getName(Name);
861 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
863 std::string LinkageName;
864 SP.getLinkageName(LinkageName);
865 if (!LinkageName.empty()) {
866 // Skip special LLVM prefix that is used to inform the asm printer to not emit
867 // usual symbol prefix before the symbol name. This happens for Objective-C
868 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
869 if (LinkageName[0] == 1)
870 LinkageName = &LinkageName[1];
871 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
872 LinkageName);
874 AddSourceLine(SPDie, &SP);
876 DICompositeType SPTy = SP.getType();
877 DIArray Args = SPTy.getTypeArray();
879 // Add prototyped tag, if C or ObjC.
880 unsigned Lang = SP.getCompileUnit().getLanguage();
881 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
882 Lang == dwarf::DW_LANG_ObjC)
883 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
885 // Add Return Type.
886 unsigned SPTag = SPTy.getTag();
887 if (!IsConstructor) {
888 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
889 AddType(DW_Unit, SPDie, SPTy);
890 else
891 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
894 if (!SP.isDefinition()) {
895 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
897 // Add arguments. Do not add arguments for subprogram definition. They will
898 // be handled through RecordVariable.
899 if (SPTag == dwarf::DW_TAG_subroutine_type)
900 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
901 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
902 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
903 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
904 SPDie->AddChild(Arg);
908 if (!SP.isLocalToUnit() && !IsInlined)
909 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
911 // DW_TAG_inlined_subroutine may refer to this DIE.
912 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
913 Slot = SPDie;
914 return SPDie;
917 /// FindCompileUnit - Get the compile unit for the given descriptor.
919 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
920 DenseMap<Value *, CompileUnit *>::const_iterator I =
921 CompileUnitMap.find(Unit.getGV());
922 assert(I != CompileUnitMap.end() && "Missing compile unit.");
923 return *I->second;
926 /// CreateDbgScopeVariable - Create a new scope variable.
928 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
929 // Get the descriptor.
930 const DIVariable &VD = DV->getVariable();
932 // Translate tag to proper Dwarf tag. The result variable is dropped for
933 // now.
934 unsigned Tag;
935 switch (VD.getTag()) {
936 case dwarf::DW_TAG_return_variable:
937 return NULL;
938 case dwarf::DW_TAG_arg_variable:
939 Tag = dwarf::DW_TAG_formal_parameter;
940 break;
941 case dwarf::DW_TAG_auto_variable: // fall thru
942 default:
943 Tag = dwarf::DW_TAG_variable;
944 break;
947 // Define variable debug information entry.
948 DIE *VariableDie = new DIE(Tag);
949 std::string Name;
950 VD.getName(Name);
951 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
953 // Add source line info if available.
954 AddSourceLine(VariableDie, &VD);
956 // Add variable type.
957 AddType(Unit, VariableDie, VD.getType());
959 // Add variable address.
960 if (!DV->isInlinedFnVar()) {
961 // Variables for abstract instances of inlined functions don't get a
962 // location.
963 MachineLocation Location;
964 Location.set(RI->getFrameRegister(*MF),
965 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
966 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
969 return VariableDie;
972 /// getOrCreateScope - Returns the scope associated with the given descriptor.
974 DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
975 DbgScope *&Slot = DbgScopeMap[V];
976 if (Slot) return Slot;
978 DbgScope *Parent = NULL;
979 DIBlock Block(V);
981 // Don't create a new scope if we already created one for an inlined function.
982 DenseMap<const GlobalVariable *, DbgScope *>::iterator
983 II = AbstractInstanceRootMap.find(V);
984 if (II != AbstractInstanceRootMap.end())
985 return LexicalScopeStack.back();
987 if (!Block.isNull()) {
988 DIDescriptor ParentDesc = Block.getContext();
989 Parent =
990 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
993 Slot = new DbgScope(Parent, DIDescriptor(V));
995 if (Parent)
996 Parent->AddScope(Slot);
997 else
998 // First function is top level function.
999 FunctionDbgScope = Slot;
1001 return Slot;
1004 /// ConstructDbgScope - Construct the components of a scope.
1006 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1007 unsigned ParentStartID,
1008 unsigned ParentEndID,
1009 DIE *ParentDie, CompileUnit *Unit) {
1010 // Add variables to scope.
1011 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1012 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1013 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
1014 if (VariableDie) ParentDie->AddChild(VariableDie);
1017 // Add concrete instances to scope.
1018 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1019 ParentScope->getConcreteInsts();
1020 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1021 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1022 DIE *Die = ConcreteInst->getDie();
1024 unsigned StartID = ConcreteInst->getStartLabelID();
1025 unsigned EndID = ConcreteInst->getEndLabelID();
1027 // Add the scope bounds.
1028 if (StartID)
1029 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1030 DWLabel("label", StartID));
1031 else
1032 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1033 DWLabel("func_begin", SubprogramCount));
1035 if (EndID)
1036 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1037 DWLabel("label", EndID));
1038 else
1039 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1040 DWLabel("func_end", SubprogramCount));
1042 ParentDie->AddChild(Die);
1045 // Add nested scopes.
1046 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1047 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1048 // Define the Scope debug information entry.
1049 DbgScope *Scope = Scopes[j];
1051 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1052 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1054 // Ignore empty scopes.
1055 if (StartID == EndID && StartID != 0) continue;
1057 // Do not ignore inlined scopes even if they don't have any variables or
1058 // scopes.
1059 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1060 Scope->getConcreteInsts().empty())
1061 continue;
1063 if (StartID == ParentStartID && EndID == ParentEndID) {
1064 // Just add stuff to the parent scope.
1065 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1066 } else {
1067 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1069 // Add the scope bounds.
1070 if (StartID)
1071 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1072 DWLabel("label", StartID));
1073 else
1074 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1075 DWLabel("func_begin", SubprogramCount));
1077 if (EndID)
1078 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1079 DWLabel("label", EndID));
1080 else
1081 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1082 DWLabel("func_end", SubprogramCount));
1084 // Add the scope's contents.
1085 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1086 ParentDie->AddChild(ScopeDie);
1091 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1093 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1094 bool AbstractScope) {
1095 // Exit if there is no root scope.
1096 if (!RootScope) return;
1097 DIDescriptor Desc = RootScope->getDesc();
1098 if (Desc.isNull())
1099 return;
1101 // Get the subprogram debug information entry.
1102 DISubprogram SPD(Desc.getGV());
1104 // Get the subprogram die.
1105 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getGV());
1106 assert(SPDie && "Missing subprogram descriptor");
1108 if (!AbstractScope) {
1109 // Add the function bounds.
1110 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1111 DWLabel("func_begin", SubprogramCount));
1112 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1113 DWLabel("func_end", SubprogramCount));
1114 MachineLocation Location(RI->getFrameRegister(*MF));
1115 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1118 ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
1121 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1123 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1124 StringMap<DIE*> &Globals = ModuleCU->getGlobals();
1125 StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
1126 if (GI != Globals.end()) {
1127 DIE *SPDie = GI->second;
1129 // Add the function bounds.
1130 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1131 DWLabel("func_begin", SubprogramCount));
1132 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1133 DWLabel("func_end", SubprogramCount));
1135 MachineLocation Location(RI->getFrameRegister(*MF));
1136 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1140 /// GetOrCreateSourceID - Look up the source id with the given directory and
1141 /// source file names. If none currently exists, create a new id and insert it
1142 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1143 /// maps as well.
1144 unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1145 const std::string &FileName) {
1146 unsigned DId;
1147 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1148 if (DI != DirectoryIdMap.end()) {
1149 DId = DI->getValue();
1150 } else {
1151 DId = DirectoryNames.size() + 1;
1152 DirectoryIdMap[DirName] = DId;
1153 DirectoryNames.push_back(DirName);
1156 unsigned FId;
1157 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1158 if (FI != SourceFileIdMap.end()) {
1159 FId = FI->getValue();
1160 } else {
1161 FId = SourceFileNames.size() + 1;
1162 SourceFileIdMap[FileName] = FId;
1163 SourceFileNames.push_back(FileName);
1166 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1167 SourceIdMap.find(std::make_pair(DId, FId));
1168 if (SI != SourceIdMap.end())
1169 return SI->second;
1171 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1172 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1173 SourceIds.push_back(std::make_pair(DId, FId));
1175 return SrcId;
1178 void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1179 DICompileUnit DIUnit(GV);
1180 std::string Dir, FN, Prod;
1181 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1182 DIUnit.getFilename(FN));
1184 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1185 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1186 DWLabel("section_line", 0), DWLabel("section_line", 0),
1187 false);
1188 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1189 DIUnit.getProducer(Prod));
1190 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1191 DIUnit.getLanguage());
1192 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1194 if (!Dir.empty())
1195 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1196 if (DIUnit.isOptimized())
1197 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1199 std::string Flags;
1200 DIUnit.getFlags(Flags);
1201 if (!Flags.empty())
1202 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1204 unsigned RVer = DIUnit.getRunTimeVersion();
1205 if (RVer)
1206 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1207 dwarf::DW_FORM_data1, RVer);
1209 CompileUnit *Unit = new CompileUnit(ID, Die);
1210 if (!ModuleCU && DIUnit.isMain()) {
1211 // Use first compile unit marked as isMain as the compile unit
1212 // for this module.
1213 ModuleCU = Unit;
1216 CompileUnitMap[DIUnit.getGV()] = Unit;
1217 CompileUnits.push_back(Unit);
1220 void DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
1221 DIGlobalVariable DI_GV(GV);
1223 // Check for pre-existence.
1224 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getGV());
1225 if (Slot)
1226 return;
1228 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1230 // Add address.
1231 DIEBlock *Block = new DIEBlock();
1232 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1233 std::string GLN;
1234 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1235 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
1236 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1238 // Add to map.
1239 Slot = VariableDie;
1241 // Add to context owner.
1242 ModuleCU->getDie()->AddChild(VariableDie);
1244 // Expose as global. FIXME - need to check external flag.
1245 std::string Name;
1246 ModuleCU->AddGlobal(DI_GV.getName(Name), VariableDie);
1247 return;
1250 void DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
1251 DISubprogram SP(GV);
1253 // Check for pre-existence.
1254 DIE *&Slot = ModuleCU->getDieMapSlotFor(GV);
1255 if (Slot)
1256 return;
1258 if (!SP.isDefinition())
1259 // This is a method declaration which will be handled while constructing
1260 // class type.
1261 return;
1263 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1265 // Add to map.
1266 Slot = SubprogramDie;
1268 // Add to context owner.
1269 ModuleCU->getDie()->AddChild(SubprogramDie);
1271 // Expose as global.
1272 std::string Name;
1273 ModuleCU->AddGlobal(SP.getName(Name), SubprogramDie);
1274 return;
1277 /// BeginModule - Emit all Dwarf sections that should come prior to the
1278 /// content. Create global DIEs and emit initial debug info sections.
1279 /// This is inovked by the target AsmPrinter.
1280 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1281 this->M = M;
1283 if (TimePassesIsEnabled)
1284 DebugTimer->startTimer();
1286 DebugInfoFinder DbgFinder;
1287 DbgFinder.processModule(*M);
1289 // Create all the compile unit DIEs.
1290 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1291 E = DbgFinder.compile_unit_end(); I != E; ++I)
1292 ConstructCompileUnit(*I);
1294 if (CompileUnits.empty()) {
1295 if (TimePassesIsEnabled)
1296 DebugTimer->stopTimer();
1298 return;
1301 // If main compile unit for this module is not seen than randomly
1302 // select first compile unit.
1303 if (!ModuleCU)
1304 ModuleCU = CompileUnits[0];
1306 // If there is not any debug info available for any global variables and any
1307 // subprograms then there is not any debug info to emit.
1308 if (DbgFinder.global_variable_count() == 0
1309 && DbgFinder.subprogram_count() == 0) {
1310 if (TimePassesIsEnabled)
1311 DebugTimer->stopTimer();
1312 return;
1315 // Create DIEs for each of the externally visible global variables.
1316 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1317 E = DbgFinder.global_variable_end(); I != E; ++I)
1318 ConstructGlobalVariableDIE(*I);
1320 // Create DIEs for each of the externally visible subprograms.
1321 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1322 E = DbgFinder.subprogram_end(); I != E; ++I)
1323 ConstructSubprogram(*I);
1325 MMI = mmi;
1326 shouldEmit = true;
1327 MMI->setDebugInfoAvailability(true);
1329 // Prime section data.
1330 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1332 // Print out .file directives to specify files for .loc directives. These are
1333 // printed out early so that they precede any .loc directives.
1334 if (TAI->hasDotLocAndDotFile()) {
1335 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1336 // Remember source id starts at 1.
1337 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1338 sys::Path FullPath(getSourceDirectoryName(Id.first));
1339 bool AppendOk =
1340 FullPath.appendComponent(getSourceFileName(Id.second));
1341 assert(AppendOk && "Could not append filename to directory!");
1342 AppendOk = false;
1343 Asm->EmitFile(i, FullPath.toString());
1344 Asm->EOL();
1348 // Emit initial sections
1349 EmitInitial();
1351 if (TimePassesIsEnabled)
1352 DebugTimer->stopTimer();
1355 /// EndModule - Emit all Dwarf sections that should come after the content.
1357 void DwarfDebug::EndModule() {
1358 if (!ShouldEmitDwarfDebug())
1359 return;
1361 if (TimePassesIsEnabled)
1362 DebugTimer->startTimer();
1364 // Standard sections final addresses.
1365 Asm->SwitchToSection(Asm->getObjFileLowering().getTextSection());
1366 EmitLabel("text_end", 0);
1367 Asm->SwitchToSection(Asm->getObjFileLowering().getDataSection());
1368 EmitLabel("data_end", 0);
1370 // End text sections.
1371 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1372 Asm->SwitchToSection(SectionMap[i]);
1373 EmitLabel("section_end", i);
1376 // Emit common frame information.
1377 EmitCommonDebugFrame();
1379 // Emit function debug frame information
1380 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1381 E = DebugFrames.end(); I != E; ++I)
1382 EmitFunctionDebugFrame(*I);
1384 // Compute DIE offsets and sizes.
1385 SizeAndOffsets();
1387 // Emit all the DIEs into a debug info section
1388 EmitDebugInfo();
1390 // Corresponding abbreviations into a abbrev section.
1391 EmitAbbreviations();
1393 // Emit source line correspondence into a debug line section.
1394 EmitDebugLines();
1396 // Emit info into a debug pubnames section.
1397 EmitDebugPubNames();
1399 // Emit info into a debug str section.
1400 EmitDebugStr();
1402 // Emit info into a debug loc section.
1403 EmitDebugLoc();
1405 // Emit info into a debug aranges section.
1406 EmitDebugARanges();
1408 // Emit info into a debug ranges section.
1409 EmitDebugRanges();
1411 // Emit info into a debug macinfo section.
1412 EmitDebugMacInfo();
1414 // Emit inline info.
1415 EmitDebugInlineInfo();
1417 if (TimePassesIsEnabled)
1418 DebugTimer->stopTimer();
1421 /// BeginFunction - Gather pre-function debug information. Assumes being
1422 /// emitted immediately after the function entry point.
1423 void DwarfDebug::BeginFunction(MachineFunction *MF) {
1424 this->MF = MF;
1426 if (!ShouldEmitDwarfDebug()) return;
1428 if (TimePassesIsEnabled)
1429 DebugTimer->startTimer();
1431 // Begin accumulating function debug information.
1432 MMI->BeginFunction(MF);
1434 // Assumes in correct section after the entry point.
1435 EmitLabel("func_begin", ++SubprogramCount);
1437 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1438 // function.
1439 DebugLoc FDL = MF->getDefaultDebugLoc();
1440 if (!FDL.isUnknown()) {
1441 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1442 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
1443 DICompileUnit(DLT.CompileUnit));
1444 Asm->printLabel(LabelID);
1447 if (TimePassesIsEnabled)
1448 DebugTimer->stopTimer();
1451 /// EndFunction - Gather and emit post-function debug information.
1453 void DwarfDebug::EndFunction(MachineFunction *MF) {
1454 if (!ShouldEmitDwarfDebug()) return;
1456 if (TimePassesIsEnabled)
1457 DebugTimer->startTimer();
1459 // Define end label for subprogram.
1460 EmitLabel("func_end", SubprogramCount);
1462 // Get function line info.
1463 if (!Lines.empty()) {
1464 // Get section line info.
1465 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
1466 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1467 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1468 // Append the function info to section info.
1469 SectionLineInfos.insert(SectionLineInfos.end(),
1470 Lines.begin(), Lines.end());
1473 // Construct the DbgScope for abstract instances.
1474 for (SmallVector<DbgScope *, 32>::iterator
1475 I = AbstractInstanceRootList.begin(),
1476 E = AbstractInstanceRootList.end(); I != E; ++I)
1477 ConstructFunctionDbgScope(*I);
1479 // Construct scopes for subprogram.
1480 if (FunctionDbgScope)
1481 ConstructFunctionDbgScope(FunctionDbgScope);
1482 else
1483 // FIXME: This is wrong. We are essentially getting past a problem with
1484 // debug information not being able to handle unreachable blocks that have
1485 // debug information in them. In particular, those unreachable blocks that
1486 // have "region end" info in them. That situation results in the "root
1487 // scope" not being created. If that's the case, then emit a "default"
1488 // scope, i.e., one that encompasses the whole function. This isn't
1489 // desirable. And a better way of handling this (and all of the debugging
1490 // information) needs to be explored.
1491 ConstructDefaultDbgScope(MF);
1493 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1494 MMI->getFrameMoves()));
1496 // Clear debug info
1497 if (FunctionDbgScope) {
1498 delete FunctionDbgScope;
1499 DbgScopeMap.clear();
1500 DbgAbstractScopeMap.clear();
1501 DbgConcreteScopeMap.clear();
1502 InlinedVariableScopes.clear();
1503 FunctionDbgScope = NULL;
1504 LexicalScopeStack.clear();
1505 AbstractInstanceRootList.clear();
1506 AbstractInstanceRootMap.clear();
1509 Lines.clear();
1511 if (TimePassesIsEnabled)
1512 DebugTimer->stopTimer();
1515 /// RecordSourceLine - Records location information and associates it with a
1516 /// label. Returns a unique label ID used to generate a label and provide
1517 /// correspondence to the source line list.
1518 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1519 if (TimePassesIsEnabled)
1520 DebugTimer->startTimer();
1522 CompileUnit *Unit = CompileUnitMap[V];
1523 assert(Unit && "Unable to find CompileUnit");
1524 unsigned ID = MMI->NextLabelID();
1525 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1527 if (TimePassesIsEnabled)
1528 DebugTimer->stopTimer();
1530 return ID;
1533 /// RecordSourceLine - Records location information and associates it with a
1534 /// label. Returns a unique label ID used to generate a label and provide
1535 /// correspondence to the source line list.
1536 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1537 DICompileUnit CU) {
1538 if (TimePassesIsEnabled)
1539 DebugTimer->startTimer();
1541 std::string Dir, Fn;
1542 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
1543 CU.getFilename(Fn));
1544 unsigned ID = MMI->NextLabelID();
1545 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1547 if (TimePassesIsEnabled)
1548 DebugTimer->stopTimer();
1550 return ID;
1553 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1554 /// timed. Look up the source id with the given directory and source file
1555 /// names. If none currently exists, create a new id and insert it in the
1556 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1557 /// well.
1558 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1559 const std::string &FileName) {
1560 if (TimePassesIsEnabled)
1561 DebugTimer->startTimer();
1563 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
1565 if (TimePassesIsEnabled)
1566 DebugTimer->stopTimer();
1568 return SrcId;
1571 /// RecordRegionStart - Indicate the start of a region.
1572 unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
1573 if (TimePassesIsEnabled)
1574 DebugTimer->startTimer();
1576 DbgScope *Scope = getOrCreateScope(V);
1577 unsigned ID = MMI->NextLabelID();
1578 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1579 LexicalScopeStack.push_back(Scope);
1581 if (TimePassesIsEnabled)
1582 DebugTimer->stopTimer();
1584 return ID;
1587 /// RecordRegionEnd - Indicate the end of a region.
1588 unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
1589 if (TimePassesIsEnabled)
1590 DebugTimer->startTimer();
1592 DbgScope *Scope = getOrCreateScope(V);
1593 unsigned ID = MMI->NextLabelID();
1594 Scope->setEndLabelID(ID);
1595 // FIXME : region.end() may not be in the last basic block.
1596 // For now, do not pop last lexical scope because next basic
1597 // block may start new inlined function's body.
1598 unsigned LSSize = LexicalScopeStack.size();
1599 if (LSSize != 0 && LSSize != 1)
1600 LexicalScopeStack.pop_back();
1602 if (TimePassesIsEnabled)
1603 DebugTimer->stopTimer();
1605 return ID;
1608 /// RecordVariable - Indicate the declaration of a local variable.
1609 void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
1610 const MachineInstr *MI) {
1611 if (TimePassesIsEnabled)
1612 DebugTimer->startTimer();
1614 DIDescriptor Desc(GV);
1615 DbgScope *Scope = NULL;
1616 bool InlinedFnVar = false;
1618 if (Desc.getTag() == dwarf::DW_TAG_variable) {
1619 // GV is a global variable.
1620 DIGlobalVariable DG(GV);
1621 Scope = getOrCreateScope(DG.getContext().getGV());
1622 } else {
1623 DenseMap<const MachineInstr *, DbgScope *>::iterator
1624 SI = InlinedVariableScopes.find(MI);
1626 if (SI != InlinedVariableScopes.end()) {
1627 // or GV is an inlined local variable.
1628 Scope = SI->second;
1629 InlinedFnVar = true;
1630 } else {
1631 DIVariable DV(GV);
1632 GlobalVariable *V = DV.getContext().getGV();
1634 // or GV is a local variable.
1635 Scope = getOrCreateScope(V);
1639 assert(Scope && "Unable to find the variable's scope");
1640 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
1641 Scope->AddVariable(DV);
1643 if (TimePassesIsEnabled)
1644 DebugTimer->stopTimer();
1647 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1648 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1649 unsigned Line, unsigned Col) {
1650 unsigned LabelID = MMI->NextLabelID();
1652 if (!TAI->doesDwarfUsesInlineInfoSection())
1653 return LabelID;
1655 if (TimePassesIsEnabled)
1656 DebugTimer->startTimer();
1658 GlobalVariable *GV = SP.getGV();
1659 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1660 II = AbstractInstanceRootMap.find(GV);
1662 if (II == AbstractInstanceRootMap.end()) {
1663 // Create an abstract instance entry for this inlined function if it doesn't
1664 // already exist.
1665 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
1667 // Get the compile unit context.
1668 DIE *SPDie = ModuleCU->getDieMapSlotFor(GV);
1669 if (!SPDie)
1670 SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
1672 // Mark as being inlined. This makes this subprogram entry an abstract
1673 // instance root.
1674 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1675 // that it's defined. That probably won't change in the future. However,
1676 // this could be more elegant.
1677 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1679 // Keep track of the abstract scope for this function.
1680 DbgAbstractScopeMap[GV] = Scope;
1682 AbstractInstanceRootMap[GV] = Scope;
1683 AbstractInstanceRootList.push_back(Scope);
1686 // Create a concrete inlined instance for this inlined function.
1687 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
1688 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
1689 ScopeDie->setAbstractCompileUnit(ModuleCU);
1691 DIE *Origin = ModuleCU->getDieMapSlotFor(GV);
1692 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1693 dwarf::DW_FORM_ref4, Origin);
1694 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1695 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1696 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1698 ConcreteScope->setDie(ScopeDie);
1699 ConcreteScope->setStartLabelID(LabelID);
1700 MMI->RecordUsedDbgLabel(LabelID);
1702 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
1704 // Keep track of the concrete scope that's inlined into this function.
1705 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1706 SI = DbgConcreteScopeMap.find(GV);
1708 if (SI == DbgConcreteScopeMap.end())
1709 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
1710 else
1711 SI->second.push_back(ConcreteScope);
1713 // Track the start label for this inlined function.
1714 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1715 I = InlineInfo.find(GV);
1717 if (I == InlineInfo.end())
1718 InlineInfo[GV].push_back(LabelID);
1719 else
1720 I->second.push_back(LabelID);
1722 if (TimePassesIsEnabled)
1723 DebugTimer->stopTimer();
1725 return LabelID;
1728 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
1729 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
1730 if (!TAI->doesDwarfUsesInlineInfoSection())
1731 return 0;
1733 if (TimePassesIsEnabled)
1734 DebugTimer->startTimer();
1736 GlobalVariable *GV = SP.getGV();
1737 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1738 I = DbgConcreteScopeMap.find(GV);
1740 if (I == DbgConcreteScopeMap.end()) {
1741 // FIXME: Can this situation actually happen? And if so, should it?
1742 if (TimePassesIsEnabled)
1743 DebugTimer->stopTimer();
1745 return 0;
1748 SmallVector<DbgScope *, 8> &Scopes = I->second;
1749 if (Scopes.empty()) {
1750 // Returned ID is 0 if this is unbalanced "end of inlined
1751 // scope". This could happen if optimizer eats dbg intrinsics
1752 // or "beginning of inlined scope" is not recoginized due to
1753 // missing location info. In such cases, ignore this region.end.
1754 return 0;
1757 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
1758 unsigned ID = MMI->NextLabelID();
1759 MMI->RecordUsedDbgLabel(ID);
1760 Scope->setEndLabelID(ID);
1762 if (TimePassesIsEnabled)
1763 DebugTimer->stopTimer();
1765 return ID;
1768 /// RecordVariableScope - Record scope for the variable declared by
1769 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
1770 /// for only inlined subroutine variables. Other variables's scopes are
1771 /// determined during RecordVariable().
1772 void DwarfDebug::RecordVariableScope(DIVariable &DV,
1773 const MachineInstr *DeclareMI) {
1774 if (TimePassesIsEnabled)
1775 DebugTimer->startTimer();
1777 DISubprogram SP(DV.getContext().getGV());
1779 if (SP.isNull()) {
1780 if (TimePassesIsEnabled)
1781 DebugTimer->stopTimer();
1783 return;
1786 DenseMap<GlobalVariable *, DbgScope *>::iterator
1787 I = DbgAbstractScopeMap.find(SP.getGV());
1788 if (I != DbgAbstractScopeMap.end())
1789 InlinedVariableScopes[DeclareMI] = I->second;
1791 if (TimePassesIsEnabled)
1792 DebugTimer->stopTimer();
1795 //===----------------------------------------------------------------------===//
1796 // Emit Methods
1797 //===----------------------------------------------------------------------===//
1799 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1801 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1802 // Get the children.
1803 const std::vector<DIE *> &Children = Die->getChildren();
1805 // If not last sibling and has children then add sibling offset attribute.
1806 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1808 // Record the abbreviation.
1809 AssignAbbrevNumber(Die->getAbbrev());
1811 // Get the abbreviation for this DIE.
1812 unsigned AbbrevNumber = Die->getAbbrevNumber();
1813 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1815 // Set DIE offset
1816 Die->setOffset(Offset);
1818 // Start the size with the size of abbreviation code.
1819 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1821 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1822 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1824 // Size the DIE attribute values.
1825 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1826 // Size attribute value.
1827 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1829 // Size the DIE children if any.
1830 if (!Children.empty()) {
1831 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1832 "Children flag not set");
1834 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1835 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1837 // End of children marker.
1838 Offset += sizeof(int8_t);
1841 Die->setSize(Offset - Die->getOffset());
1842 return Offset;
1845 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1847 void DwarfDebug::SizeAndOffsets() {
1848 // Compute size of compile unit header.
1849 static unsigned Offset =
1850 sizeof(int32_t) + // Length of Compilation Unit Info
1851 sizeof(int16_t) + // DWARF version number
1852 sizeof(int32_t) + // Offset Into Abbrev. Section
1853 sizeof(int8_t); // Pointer Size (in bytes)
1855 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
1856 CompileUnitOffsets[ModuleCU] = 0;
1859 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1860 /// tools to recognize the object file contains Dwarf information.
1861 void DwarfDebug::EmitInitial() {
1862 // Check to see if we already emitted intial headers.
1863 if (didInitial) return;
1864 didInitial = true;
1866 // Dwarf sections base addresses.
1867 if (TAI->doesDwarfRequireFrameSection()) {
1868 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfFrameSection());
1869 EmitLabel("section_debug_frame", 0);
1872 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfInfoSection());
1873 EmitLabel("section_info", 0);
1874 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfAbbrevSection());
1875 EmitLabel("section_abbrev", 0);
1876 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfARangesSection());
1877 EmitLabel("section_aranges", 0);
1879 if (const MCSection *LineInfoDirective =
1880 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1881 Asm->SwitchToSection(LineInfoDirective);
1882 EmitLabel("section_macinfo", 0);
1885 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfLineSection());
1886 EmitLabel("section_line", 0);
1887 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfLocSection());
1888 EmitLabel("section_loc", 0);
1889 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
1890 EmitLabel("section_pubnames", 0);
1891 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfStrSection());
1892 EmitLabel("section_str", 0);
1893 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfRangesSection());
1894 EmitLabel("section_ranges", 0);
1896 Asm->SwitchToSection(Asm->getObjFileLowering().getTextSection());
1897 EmitLabel("text_begin", 0);
1898 Asm->SwitchToSection(Asm->getObjFileLowering().getDataSection());
1899 EmitLabel("data_begin", 0);
1902 /// EmitDIE - Recusively Emits a debug information entry.
1904 void DwarfDebug::EmitDIE(DIE *Die) {
1905 // Get the abbreviation for this DIE.
1906 unsigned AbbrevNumber = Die->getAbbrevNumber();
1907 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1909 Asm->EOL();
1911 // Emit the code (index) for the abbreviation.
1912 Asm->EmitULEB128Bytes(AbbrevNumber);
1914 if (Asm->isVerbose())
1915 Asm->EOL(std::string("Abbrev [" +
1916 utostr(AbbrevNumber) +
1917 "] 0x" + utohexstr(Die->getOffset()) +
1918 ":0x" + utohexstr(Die->getSize()) + " " +
1919 dwarf::TagString(Abbrev->getTag())));
1920 else
1921 Asm->EOL();
1923 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1924 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1926 // Emit the DIE attribute values.
1927 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1928 unsigned Attr = AbbrevData[i].getAttribute();
1929 unsigned Form = AbbrevData[i].getForm();
1930 assert(Form && "Too many attributes for DIE (check abbreviation)");
1932 switch (Attr) {
1933 case dwarf::DW_AT_sibling:
1934 Asm->EmitInt32(Die->SiblingOffset());
1935 break;
1936 case dwarf::DW_AT_abstract_origin: {
1937 DIEEntry *E = cast<DIEEntry>(Values[i]);
1938 DIE *Origin = E->getEntry();
1939 unsigned Addr =
1940 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1941 Origin->getOffset();
1943 Asm->EmitInt32(Addr);
1944 break;
1946 default:
1947 // Emit an attribute using the defined form.
1948 Values[i]->EmitValue(this, Form);
1949 break;
1952 Asm->EOL(dwarf::AttributeString(Attr));
1955 // Emit the DIE children if any.
1956 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1957 const std::vector<DIE *> &Children = Die->getChildren();
1959 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1960 EmitDIE(Children[j]);
1962 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1966 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1968 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1969 DIE *Die = Unit->getDie();
1971 // Emit the compile units header.
1972 EmitLabel("info_begin", Unit->getID());
1974 // Emit size of content not including length itself
1975 unsigned ContentSize = Die->getSize() +
1976 sizeof(int16_t) + // DWARF version number
1977 sizeof(int32_t) + // Offset Into Abbrev. Section
1978 sizeof(int8_t) + // Pointer Size (in bytes)
1979 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1981 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1982 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1983 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1984 Asm->EOL("Offset Into Abbrev. Section");
1985 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1987 EmitDIE(Die);
1988 // FIXME - extra padding for gdb bug.
1989 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1990 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1991 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1992 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1993 EmitLabel("info_end", Unit->getID());
1995 Asm->EOL();
1998 void DwarfDebug::EmitDebugInfo() {
1999 // Start debug info section.
2000 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfInfoSection());
2002 EmitDebugInfoPerCU(ModuleCU);
2005 /// EmitAbbreviations - Emit the abbreviation section.
2007 void DwarfDebug::EmitAbbreviations() const {
2008 // Check to see if it is worth the effort.
2009 if (!Abbreviations.empty()) {
2010 // Start the debug abbrev section.
2011 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfAbbrevSection());
2013 EmitLabel("abbrev_begin", 0);
2015 // For each abbrevation.
2016 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2017 // Get abbreviation data
2018 const DIEAbbrev *Abbrev = Abbreviations[i];
2020 // Emit the abbrevations code (base 1 index.)
2021 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2022 Asm->EOL("Abbreviation Code");
2024 // Emit the abbreviations data.
2025 Abbrev->Emit(Asm);
2027 Asm->EOL();
2030 // Mark end of abbreviations.
2031 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2033 EmitLabel("abbrev_end", 0);
2034 Asm->EOL();
2038 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2039 /// the line matrix.
2041 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2042 // Define last address of section.
2043 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2044 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2045 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2046 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2048 // Mark end of matrix.
2049 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2050 Asm->EmitULEB128Bytes(1); Asm->EOL();
2051 Asm->EmitInt8(1); Asm->EOL();
2054 /// EmitDebugLines - Emit source line information.
2056 void DwarfDebug::EmitDebugLines() {
2057 // If the target is using .loc/.file, the assembler will be emitting the
2058 // .debug_line table automatically.
2059 if (TAI->hasDotLocAndDotFile())
2060 return;
2062 // Minimum line delta, thus ranging from -10..(255-10).
2063 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2064 // Maximum line delta, thus ranging from -10..(255-10).
2065 const int MaxLineDelta = 255 + MinLineDelta;
2067 // Start the dwarf line section.
2068 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfLineSection());
2070 // Construct the section header.
2071 EmitDifference("line_end", 0, "line_begin", 0, true);
2072 Asm->EOL("Length of Source Line Info");
2073 EmitLabel("line_begin", 0);
2075 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2077 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2078 Asm->EOL("Prolog Length");
2079 EmitLabel("line_prolog_begin", 0);
2081 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2083 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2085 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2087 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2089 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2091 // Line number standard opcode encodings argument count
2092 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2093 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2094 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2095 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2096 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2097 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2098 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2099 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2100 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2102 // Emit directories.
2103 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2104 Asm->EmitString(getSourceDirectoryName(DI));
2105 Asm->EOL("Directory");
2108 Asm->EmitInt8(0); Asm->EOL("End of directories");
2110 // Emit files.
2111 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2112 // Remember source id starts at 1.
2113 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2114 Asm->EmitString(getSourceFileName(Id.second));
2115 Asm->EOL("Source");
2116 Asm->EmitULEB128Bytes(Id.first);
2117 Asm->EOL("Directory #");
2118 Asm->EmitULEB128Bytes(0);
2119 Asm->EOL("Mod date");
2120 Asm->EmitULEB128Bytes(0);
2121 Asm->EOL("File size");
2124 Asm->EmitInt8(0); Asm->EOL("End of files");
2126 EmitLabel("line_prolog_end", 0);
2128 // A sequence for each text section.
2129 unsigned SecSrcLinesSize = SectionSourceLines.size();
2131 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2132 // Isolate current sections line info.
2133 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2135 /*if (Asm->isVerbose()) {
2136 const MCSection *S = SectionMap[j + 1];
2137 O << '\t' << TAI->getCommentString() << " Section"
2138 << S->getName() << '\n';
2140 Asm->EOL();
2142 // Dwarf assumes we start with first line of first source file.
2143 unsigned Source = 1;
2144 unsigned Line = 1;
2146 // Construct rows of the address, source, line, column matrix.
2147 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2148 const SrcLineInfo &LineInfo = LineInfos[i];
2149 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2150 if (!LabelID) continue;
2152 if (!Asm->isVerbose())
2153 Asm->EOL();
2154 else {
2155 std::pair<unsigned, unsigned> SourceID =
2156 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2157 O << '\t' << TAI->getCommentString() << ' '
2158 << getSourceDirectoryName(SourceID.first) << ' '
2159 << getSourceFileName(SourceID.second)
2160 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2163 // Define the line address.
2164 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2165 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2166 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2167 EmitReference("label", LabelID); Asm->EOL("Location label");
2169 // If change of source, then switch to the new source.
2170 if (Source != LineInfo.getSourceID()) {
2171 Source = LineInfo.getSourceID();
2172 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2173 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2176 // If change of line.
2177 if (Line != LineInfo.getLine()) {
2178 // Determine offset.
2179 int Offset = LineInfo.getLine() - Line;
2180 int Delta = Offset - MinLineDelta;
2182 // Update line.
2183 Line = LineInfo.getLine();
2185 // If delta is small enough and in range...
2186 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2187 // ... then use fast opcode.
2188 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2189 } else {
2190 // ... otherwise use long hand.
2191 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2192 Asm->EOL("DW_LNS_advance_line");
2193 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2194 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2196 } else {
2197 // Copy the previous row (different address or source)
2198 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2202 EmitEndOfLineMatrix(j + 1);
2205 if (SecSrcLinesSize == 0)
2206 // Because we're emitting a debug_line section, we still need a line
2207 // table. The linker and friends expect it to exist. If there's nothing to
2208 // put into it, emit an empty table.
2209 EmitEndOfLineMatrix(1);
2211 EmitLabel("line_end", 0);
2212 Asm->EOL();
2215 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2217 void DwarfDebug::EmitCommonDebugFrame() {
2218 if (!TAI->doesDwarfRequireFrameSection())
2219 return;
2221 int stackGrowth =
2222 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2223 TargetFrameInfo::StackGrowsUp ?
2224 TD->getPointerSize() : -TD->getPointerSize();
2226 // Start the dwarf frame section.
2227 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfFrameSection());
2229 EmitLabel("debug_frame_common", 0);
2230 EmitDifference("debug_frame_common_end", 0,
2231 "debug_frame_common_begin", 0, true);
2232 Asm->EOL("Length of Common Information Entry");
2234 EmitLabel("debug_frame_common_begin", 0);
2235 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2236 Asm->EOL("CIE Identifier Tag");
2237 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2238 Asm->EOL("CIE Version");
2239 Asm->EmitString("");
2240 Asm->EOL("CIE Augmentation");
2241 Asm->EmitULEB128Bytes(1);
2242 Asm->EOL("CIE Code Alignment Factor");
2243 Asm->EmitSLEB128Bytes(stackGrowth);
2244 Asm->EOL("CIE Data Alignment Factor");
2245 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2246 Asm->EOL("CIE RA Column");
2248 std::vector<MachineMove> Moves;
2249 RI->getInitialFrameState(Moves);
2251 EmitFrameMoves(NULL, 0, Moves, false);
2253 Asm->EmitAlignment(2, 0, 0, false);
2254 EmitLabel("debug_frame_common_end", 0);
2256 Asm->EOL();
2259 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2260 /// section.
2261 void
2262 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2263 if (!TAI->doesDwarfRequireFrameSection())
2264 return;
2266 // Start the dwarf frame section.
2267 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfFrameSection());
2269 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2270 "debug_frame_begin", DebugFrameInfo.Number, true);
2271 Asm->EOL("Length of Frame Information Entry");
2273 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2275 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2276 0, 0, true, false);
2277 Asm->EOL("FDE CIE offset");
2279 EmitReference("func_begin", DebugFrameInfo.Number);
2280 Asm->EOL("FDE initial location");
2281 EmitDifference("func_end", DebugFrameInfo.Number,
2282 "func_begin", DebugFrameInfo.Number);
2283 Asm->EOL("FDE address range");
2285 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2286 false);
2288 Asm->EmitAlignment(2, 0, 0, false);
2289 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2291 Asm->EOL();
2294 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2295 EmitDifference("pubnames_end", Unit->getID(),
2296 "pubnames_begin", Unit->getID(), true);
2297 Asm->EOL("Length of Public Names Info");
2299 EmitLabel("pubnames_begin", Unit->getID());
2301 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2303 EmitSectionOffset("info_begin", "section_info",
2304 Unit->getID(), 0, true, false);
2305 Asm->EOL("Offset of Compilation Unit Info");
2307 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2308 true);
2309 Asm->EOL("Compilation Unit Length");
2311 StringMap<DIE*> &Globals = Unit->getGlobals();
2312 for (StringMap<DIE*>::const_iterator
2313 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2314 const char *Name = GI->getKeyData();
2315 DIE * Entity = GI->second;
2317 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2318 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2321 Asm->EmitInt32(0); Asm->EOL("End Mark");
2322 EmitLabel("pubnames_end", Unit->getID());
2324 Asm->EOL();
2327 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2329 void DwarfDebug::EmitDebugPubNames() {
2330 // Start the dwarf pubnames section.
2331 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
2333 EmitDebugPubNamesPerCU(ModuleCU);
2336 /// EmitDebugStr - Emit visible names into a debug str section.
2338 void DwarfDebug::EmitDebugStr() {
2339 // Check to see if it is worth the effort.
2340 if (!StringPool.empty()) {
2341 // Start the dwarf str section.
2342 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfStrSection());
2344 // For each of strings in the string pool.
2345 for (unsigned StringID = 1, N = StringPool.size();
2346 StringID <= N; ++StringID) {
2347 // Emit a label for reference from debug information entries.
2348 EmitLabel("string", StringID);
2350 // Emit the string itself.
2351 const std::string &String = StringPool[StringID];
2352 Asm->EmitString(String); Asm->EOL();
2355 Asm->EOL();
2359 /// EmitDebugLoc - Emit visible names into a debug loc section.
2361 void DwarfDebug::EmitDebugLoc() {
2362 // Start the dwarf loc section.
2363 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfLocSection());
2364 Asm->EOL();
2367 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2369 void DwarfDebug::EmitDebugARanges() {
2370 // Start the dwarf aranges section.
2371 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfARangesSection());
2373 // FIXME - Mock up
2374 #if 0
2375 CompileUnit *Unit = GetBaseCompileUnit();
2377 // Don't include size of length
2378 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2380 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2382 EmitReference("info_begin", Unit->getID());
2383 Asm->EOL("Offset of Compilation Unit Info");
2385 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2387 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2389 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2390 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2392 // Range 1
2393 EmitReference("text_begin", 0); Asm->EOL("Address");
2394 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2396 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2397 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2398 #endif
2400 Asm->EOL();
2403 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2405 void DwarfDebug::EmitDebugRanges() {
2406 // Start the dwarf ranges section.
2407 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfRangesSection());
2408 Asm->EOL();
2411 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2413 void DwarfDebug::EmitDebugMacInfo() {
2414 if (const MCSection *LineInfo =
2415 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2416 // Start the dwarf macinfo section.
2417 Asm->SwitchToSection(LineInfo);
2418 Asm->EOL();
2422 /// EmitDebugInlineInfo - Emit inline info using following format.
2423 /// Section Header:
2424 /// 1. length of section
2425 /// 2. Dwarf version number
2426 /// 3. address size.
2428 /// Entries (one "entry" for each function that was inlined):
2430 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2431 /// otherwise offset into __debug_str for regular function name.
2432 /// 2. offset into __debug_str section for regular function name.
2433 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2434 /// instances for the function.
2436 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2437 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2438 /// __debug_info section, and the low_pc is the starting address for the
2439 /// inlining instance.
2440 void DwarfDebug::EmitDebugInlineInfo() {
2441 if (!TAI->doesDwarfUsesInlineInfoSection())
2442 return;
2444 if (!ModuleCU)
2445 return;
2447 Asm->SwitchToSection(Asm->getObjFileLowering().getDwarfDebugInlineSection());
2448 Asm->EOL();
2449 EmitDifference("debug_inlined_end", 1,
2450 "debug_inlined_begin", 1, true);
2451 Asm->EOL("Length of Debug Inlined Information Entry");
2453 EmitLabel("debug_inlined_begin", 1);
2455 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2456 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2458 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2459 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2460 GlobalVariable *GV = I->first;
2461 SmallVector<unsigned, 4> &Labels = I->second;
2462 DISubprogram SP(GV);
2463 std::string Name;
2464 std::string LName;
2466 SP.getLinkageName(LName);
2467 SP.getName(Name);
2469 if (LName.empty())
2470 Asm->EmitString(Name);
2471 else {
2472 // Skip special LLVM prefix that is used to inform the asm printer to not emit
2473 // usual symbol prefix before the symbol name. This happens for Objective-C
2474 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
2475 if (LName[0] == 1)
2476 LName = &LName[1];
2477 Asm->EmitString(LName);
2479 Asm->EOL("MIPS linkage name");
2481 Asm->EmitString(Name); Asm->EOL("Function name");
2483 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2485 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2486 LE = Labels.end(); LI != LE; ++LI) {
2487 DIE *SP = ModuleCU->getDieMapSlotFor(GV);
2488 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2490 if (TD->getPointerSize() == sizeof(int32_t))
2491 O << TAI->getData32bitsDirective();
2492 else
2493 O << TAI->getData64bitsDirective();
2495 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2499 EmitLabel("debug_inlined_end", 1);
2500 Asm->EOL();