blob: 0122d87a9f3a8c05f9cb5f1f46bc3c6a491767ba [file] [log] [blame]
Bill Wendling0310d762009-05-15 09:23:25 +00001//===-- 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.
11//
12//===----------------------------------------------------------------------===//
13
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"
23#include <ostream>
24using namespace llvm;
25
26static TimerGroup &getDwarfTimerGroup() {
27 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
28 return DwarfTimerGroup;
29}
30
31//===----------------------------------------------------------------------===//
32
33/// Configuration values for initial hash set sizes (log2).
34///
35static const unsigned InitDiesSetSize = 9; // log2(512)
36static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
37static const unsigned InitValuesSetSize = 9; // log2(512)
38
39namespace llvm {
40
41//===----------------------------------------------------------------------===//
42/// CompileUnit - This dwarf writer support class manages information associate
43/// with a source file.
44class VISIBILITY_HIDDEN CompileUnit {
45 /// ID - File identifier for source.
46 ///
47 unsigned ID;
48
49 /// Die - Compile unit debug information entry.
50 ///
51 DIE *Die;
52
53 /// GVToDieMap - Tracks the mapping of unit level debug informaton
54 /// variables to debug information entries.
55 std::map<GlobalVariable *, DIE *> GVToDieMap;
56
57 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
58 /// descriptors to debug information entries using a DIEEntry proxy.
59 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
60
61 /// Globals - A map of globally visible named entities for this unit.
62 ///
63 StringMap<DIE*> Globals;
64
65 /// DiesSet - Used to uniquely define dies within the compile unit.
66 ///
67 FoldingSet<DIE> DiesSet;
68public:
69 CompileUnit(unsigned I, DIE *D)
70 : ID(I), Die(D), GVToDieMap(),
71 GVToDIEEntryMap(), Globals(), DiesSet(InitDiesSetSize)
72 {}
73
74 ~CompileUnit() {
75 delete Die;
76 }
77
78 // Accessors.
79 unsigned getID() const { return ID; }
80 DIE* getDie() const { return Die; }
81 StringMap<DIE*> &getGlobals() { return Globals; }
82
83 /// hasContent - Return true if this compile unit has something to write out.
84 ///
85 bool hasContent() const {
86 return !Die->getChildren().empty();
87 }
88
89 /// AddGlobal - Add a new global entity to the compile unit.
90 ///
91 void AddGlobal(const std::string &Name, DIE *Die) {
92 Globals[Name] = Die;
93 }
94
95 /// getDieMapSlotFor - Returns the debug information entry map slot for the
96 /// specified debug variable.
97 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
98 return GVToDieMap[GV];
99 }
100
101 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
102 /// specified debug variable.
103 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
104 return GVToDIEEntryMap[GV];
105 }
106
107 /// AddDie - Adds or interns the DIE to the compile unit.
108 ///
109 DIE *AddDie(DIE &Buffer) {
110 FoldingSetNodeID ID;
111 Buffer.Profile(ID);
112 void *Where;
113 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
114
115 if (!Die) {
116 Die = new DIE(Buffer);
117 DiesSet.InsertNode(Die, Where);
118 this->Die->AddChild(Die);
119 Buffer.Detach();
120 }
121
122 return Die;
123 }
124};
125
126//===----------------------------------------------------------------------===//
127/// DbgVariable - This class is used to track local variable information.
128///
129class VISIBILITY_HIDDEN DbgVariable {
130 DIVariable Var; // Variable Descriptor.
131 unsigned FrameIndex; // Variable frame index.
132public:
133 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
134
135 // Accessors.
136 DIVariable getVariable() const { return Var; }
137 unsigned getFrameIndex() const { return FrameIndex; }
138};
139
140//===----------------------------------------------------------------------===//
141/// DbgScope - This class is used to track scope information.
142///
143class DbgConcreteScope;
144class VISIBILITY_HIDDEN DbgScope {
145 DbgScope *Parent; // Parent to this scope.
146 DIDescriptor Desc; // Debug info descriptor for scope.
147 // Either subprogram or block.
148 unsigned StartLabelID; // Label ID of the beginning of scope.
149 unsigned EndLabelID; // Label ID of the end of scope.
150 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
151 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
152 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
153public:
154 DbgScope(DbgScope *P, DIDescriptor D)
155 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
156 virtual ~DbgScope();
157
158 // Accessors.
159 DbgScope *getParent() const { return Parent; }
160 DIDescriptor getDesc() const { return Desc; }
161 unsigned getStartLabelID() const { return StartLabelID; }
162 unsigned getEndLabelID() const { return EndLabelID; }
163 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
164 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
165 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
166 void setStartLabelID(unsigned S) { StartLabelID = S; }
167 void setEndLabelID(unsigned E) { EndLabelID = E; }
168
169 /// AddScope - Add a scope to the scope.
170 ///
171 void AddScope(DbgScope *S) { Scopes.push_back(S); }
172
173 /// AddVariable - Add a variable to the scope.
174 ///
175 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
176
177 /// AddConcreteInst - Add a concrete instance to the scope.
178 ///
179 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
180
181#ifndef NDEBUG
182 void dump() const;
183#endif
184};
185
186#ifndef NDEBUG
187void DbgScope::dump() const {
188 static unsigned IndentLevel = 0;
189 std::string Indent(IndentLevel, ' ');
190
191 cerr << Indent; Desc.dump();
192 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
193
194 IndentLevel += 2;
195
196 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
197 if (Scopes[i] != this)
198 Scopes[i]->dump();
199
200 IndentLevel -= 2;
201}
202#endif
203
204//===----------------------------------------------------------------------===//
205/// DbgConcreteScope - This class is used to track a scope that holds concrete
206/// instance information.
207///
208class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
209 CompileUnit *Unit;
210 DIE *Die; // Debug info for this concrete scope.
211public:
212 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
213
214 // Accessors.
215 DIE *getDie() const { return Die; }
216 void setDie(DIE *D) { Die = D; }
217};
218
219DbgScope::~DbgScope() {
220 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
221 delete Scopes[i];
222 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
223 delete Variables[j];
224 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
225 delete ConcreteInsts[k];
226}
227
228} // end llvm namespace
229
230DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
231 : Dwarf(OS, A, T, "dbg"), MainCU(0),
232 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
233 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
234 SectionSourceLines(), didInitial(false), shouldEmit(false),
235 FunctionDbgScope(0), DebugTimer(0) {
236 if (TimePassesIsEnabled)
237 DebugTimer = new Timer("Dwarf Debug Writer",
238 getDwarfTimerGroup());
239}
240DwarfDebug::~DwarfDebug() {
241 for (unsigned j = 0, M = Values.size(); j < M; ++j)
242 delete Values[j];
243
244 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
245 I = AbstractInstanceRootMap.begin(),
246 E = AbstractInstanceRootMap.end(); I != E;++I)
247 delete I->second;
248
249 delete DebugTimer;
250}
251
252/// AssignAbbrevNumber - Define a unique number for the abbreviation.
253///
254void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
255 // Profile the node so that we can make it unique.
256 FoldingSetNodeID ID;
257 Abbrev.Profile(ID);
258
259 // Check the set for priors.
260 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
261
262 // If it's newly added.
263 if (InSet == &Abbrev) {
264 // Add to abbreviation list.
265 Abbreviations.push_back(&Abbrev);
266
267 // Assign the vector position + 1 as its number.
268 Abbrev.setNumber(Abbreviations.size());
269 } else {
270 // Assign existing abbreviation number.
271 Abbrev.setNumber(InSet->getNumber());
272 }
273}
274
275/// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
276/// entry.
277DIEEntry *DwarfDebug::NewDIEEntry(DIE *Entry) {
278 DIEEntry *Value;
279
280 if (Entry) {
281 FoldingSetNodeID ID;
282 DIEEntry::Profile(ID, Entry);
283 void *Where;
284 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
285
286 if (Value) return Value;
287
288 Value = new DIEEntry(Entry);
289 ValuesSet.InsertNode(Value, Where);
290 } else {
291 Value = new DIEEntry(Entry);
292 }
293
294 Values.push_back(Value);
295 return Value;
296}
297
298/// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
299///
300void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
301 Value->setEntry(Entry);
302
303 // Add to values set if not already there. If it is, we merely have a
304 // duplicate in the values list (no harm.)
305 ValuesSet.GetOrInsertNode(Value);
306}
307
308/// AddUInt - Add an unsigned integer attribute data and value.
309///
310void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
311 unsigned Form, uint64_t Integer) {
312 if (!Form) Form = DIEInteger::BestForm(false, Integer);
313
314 FoldingSetNodeID ID;
315 DIEInteger::Profile(ID, Integer);
316 void *Where;
317 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
318
319 if (!Value) {
320 Value = new DIEInteger(Integer);
321 ValuesSet.InsertNode(Value, Where);
322 Values.push_back(Value);
323 }
324
325 Die->AddValue(Attribute, Form, Value);
326}
327
328/// AddSInt - Add an signed integer attribute data and value.
329///
330void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
331 unsigned Form, int64_t Integer) {
332 if (!Form) Form = DIEInteger::BestForm(true, Integer);
333
334 FoldingSetNodeID ID;
335 DIEInteger::Profile(ID, (uint64_t)Integer);
336 void *Where;
337 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
338
339 if (!Value) {
340 Value = new DIEInteger(Integer);
341 ValuesSet.InsertNode(Value, Where);
342 Values.push_back(Value);
343 }
344
345 Die->AddValue(Attribute, Form, Value);
346}
347
348/// AddString - Add a string attribute data and value.
349///
350void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
351 const std::string &String) {
352 FoldingSetNodeID ID;
353 DIEString::Profile(ID, String);
354 void *Where;
355 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
356
357 if (!Value) {
358 Value = new DIEString(String);
359 ValuesSet.InsertNode(Value, Where);
360 Values.push_back(Value);
361 }
362
363 Die->AddValue(Attribute, Form, Value);
364}
365
366/// AddLabel - Add a Dwarf label attribute data and value.
367///
368void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
369 const DWLabel &Label) {
370 FoldingSetNodeID ID;
371 DIEDwarfLabel::Profile(ID, Label);
372 void *Where;
373 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
374
375 if (!Value) {
376 Value = new DIEDwarfLabel(Label);
377 ValuesSet.InsertNode(Value, Where);
378 Values.push_back(Value);
379 }
380
381 Die->AddValue(Attribute, Form, Value);
382}
383
384/// AddObjectLabel - Add an non-Dwarf label attribute data and value.
385///
386void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
387 const std::string &Label) {
388 FoldingSetNodeID ID;
389 DIEObjectLabel::Profile(ID, Label);
390 void *Where;
391 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
392
393 if (!Value) {
394 Value = new DIEObjectLabel(Label);
395 ValuesSet.InsertNode(Value, Where);
396 Values.push_back(Value);
397 }
398
399 Die->AddValue(Attribute, Form, Value);
400}
401
402/// AddSectionOffset - Add a section offset label attribute data and value.
403///
404void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
405 const DWLabel &Label, const DWLabel &Section,
406 bool isEH, bool useSet) {
407 FoldingSetNodeID ID;
408 DIESectionOffset::Profile(ID, Label, Section);
409 void *Where;
410 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
411
412 if (!Value) {
413 Value = new DIESectionOffset(Label, Section, isEH, useSet);
414 ValuesSet.InsertNode(Value, Where);
415 Values.push_back(Value);
416 }
417
418 Die->AddValue(Attribute, Form, Value);
419}
420
421/// AddDelta - Add a label delta attribute data and value.
422///
423void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
424 const DWLabel &Hi, const DWLabel &Lo) {
425 FoldingSetNodeID ID;
426 DIEDelta::Profile(ID, Hi, Lo);
427 void *Where;
428 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
429
430 if (!Value) {
431 Value = new DIEDelta(Hi, Lo);
432 ValuesSet.InsertNode(Value, Where);
433 Values.push_back(Value);
434 }
435
436 Die->AddValue(Attribute, Form, Value);
437}
438
439/// AddBlock - Add block data.
440///
441void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
442 DIEBlock *Block) {
443 Block->ComputeSize(TD);
444 FoldingSetNodeID ID;
445 Block->Profile(ID);
446 void *Where;
447 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
448
449 if (!Value) {
450 Value = Block;
451 ValuesSet.InsertNode(Value, Where);
452 Values.push_back(Value);
453 } else {
454 // Already exists, reuse the previous one.
455 delete Block;
456 Block = cast<DIEBlock>(Value);
457 }
458
459 Die->AddValue(Attribute, Block->BestForm(), Value);
460}
461
462/// AddSourceLine - Add location information to specified debug information
463/// entry.
464void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
465 // If there is no compile unit specified, don't add a line #.
466 if (V->getCompileUnit().isNull())
467 return;
468
469 unsigned Line = V->getLineNumber();
470 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
471 assert(FileID && "Invalid file id");
472 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
473 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
474}
475
476/// AddSourceLine - Add location information to specified debug information
477/// entry.
478void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
479 // If there is no compile unit specified, don't add a line #.
480 if (G->getCompileUnit().isNull())
481 return;
482
483 unsigned Line = G->getLineNumber();
484 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
485 assert(FileID && "Invalid file id");
486 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
487 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
488}
489void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
490 // If there is no compile unit specified, don't add a line #.
491 DICompileUnit CU = Ty->getCompileUnit();
492 if (CU.isNull())
493 return;
494
495 unsigned Line = Ty->getLineNumber();
496 unsigned FileID = FindCompileUnit(CU).getID();
497 assert(FileID && "Invalid file id");
498 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
499 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
500}
501
502/// AddAddress - Add an address attribute to a die based on the location
503/// provided.
504void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
505 const MachineLocation &Location) {
506 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
507 DIEBlock *Block = new DIEBlock();
508
509 if (Location.isReg()) {
510 if (Reg < 32) {
511 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
512 } else {
513 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
514 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
515 }
516 } else {
517 if (Reg < 32) {
518 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
519 } else {
520 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
521 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
522 }
523
524 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
525 }
526
527 AddBlock(Die, Attribute, 0, Block);
528}
529
530/// AddType - Add a new type attribute to the specified entity.
531void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
532 if (Ty.isNull())
533 return;
534
535 // Check for pre-existence.
536 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
537
538 // If it exists then use the existing value.
539 if (Slot) {
540 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
541 return;
542 }
543
544 // Set up proxy.
545 Slot = NewDIEEntry();
546
547 // Construct type.
548 DIE Buffer(dwarf::DW_TAG_base_type);
549 if (Ty.isBasicType(Ty.getTag()))
550 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
551 else if (Ty.isDerivedType(Ty.getTag()))
552 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
553 else {
554 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
555 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
556 }
557
558 // Add debug information entry to entity and appropriate context.
559 DIE *Die = NULL;
560 DIDescriptor Context = Ty.getContext();
561 if (!Context.isNull())
562 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
563
564 if (Die) {
565 DIE *Child = new DIE(Buffer);
566 Die->AddChild(Child);
567 Buffer.Detach();
568 SetDIEEntry(Slot, Child);
569 } else {
570 Die = DW_Unit->AddDie(Buffer);
571 SetDIEEntry(Slot, Die);
572 }
573
574 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
575}
576
577/// ConstructTypeDIE - Construct basic type die from DIBasicType.
578void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
579 DIBasicType BTy) {
580 // Get core information.
581 std::string Name;
582 BTy.getName(Name);
583 Buffer.setTag(dwarf::DW_TAG_base_type);
584 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
585 BTy.getEncoding());
586
587 // Add name if not anonymous or intermediate type.
588 if (!Name.empty())
589 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
590 uint64_t Size = BTy.getSizeInBits() >> 3;
591 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
592}
593
594/// ConstructTypeDIE - Construct derived type die from DIDerivedType.
595void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
596 DIDerivedType DTy) {
597 // Get core information.
598 std::string Name;
599 DTy.getName(Name);
600 uint64_t Size = DTy.getSizeInBits() >> 3;
601 unsigned Tag = DTy.getTag();
602
603 // FIXME - Workaround for templates.
604 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
605
606 Buffer.setTag(Tag);
607
608 // Map to main type, void will not have a type.
609 DIType FromTy = DTy.getTypeDerivedFrom();
610 AddType(DW_Unit, &Buffer, FromTy);
611
612 // Add name if not anonymous or intermediate type.
613 if (!Name.empty())
614 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
615
616 // Add size if non-zero (derived types might be zero-sized.)
617 if (Size)
618 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
619
620 // Add source line info if available and TyDesc is not a forward declaration.
621 if (!DTy.isForwardDecl())
622 AddSourceLine(&Buffer, &DTy);
623}
624
625/// ConstructTypeDIE - Construct type DIE from DICompositeType.
626void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
627 DICompositeType CTy) {
628 // Get core information.
629 std::string Name;
630 CTy.getName(Name);
631
632 uint64_t Size = CTy.getSizeInBits() >> 3;
633 unsigned Tag = CTy.getTag();
634 Buffer.setTag(Tag);
635
636 switch (Tag) {
637 case dwarf::DW_TAG_vector_type:
638 case dwarf::DW_TAG_array_type:
639 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
640 break;
641 case dwarf::DW_TAG_enumeration_type: {
642 DIArray Elements = CTy.getTypeArray();
643
644 // Add enumerators to enumeration type.
645 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
646 DIE *ElemDie = NULL;
647 DIEnumerator Enum(Elements.getElement(i).getGV());
648 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
649 Buffer.AddChild(ElemDie);
650 }
651 }
652 break;
653 case dwarf::DW_TAG_subroutine_type: {
654 // Add return type.
655 DIArray Elements = CTy.getTypeArray();
656 DIDescriptor RTy = Elements.getElement(0);
657 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
658
659 // Add prototype flag.
660 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
661
662 // Add arguments.
663 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
664 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
665 DIDescriptor Ty = Elements.getElement(i);
666 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
667 Buffer.AddChild(Arg);
668 }
669 }
670 break;
671 case dwarf::DW_TAG_structure_type:
672 case dwarf::DW_TAG_union_type:
673 case dwarf::DW_TAG_class_type: {
674 // Add elements to structure type.
675 DIArray Elements = CTy.getTypeArray();
676
677 // A forward struct declared type may not have elements available.
678 if (Elements.isNull())
679 break;
680
681 // Add elements to structure type.
682 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
683 DIDescriptor Element = Elements.getElement(i);
684 DIE *ElemDie = NULL;
685 if (Element.getTag() == dwarf::DW_TAG_subprogram)
686 ElemDie = CreateSubprogramDIE(DW_Unit,
687 DISubprogram(Element.getGV()));
688 else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
689 ElemDie = CreateGlobalVariableDIE(DW_Unit,
690 DIGlobalVariable(Element.getGV()));
691 else
692 ElemDie = CreateMemberDIE(DW_Unit,
693 DIDerivedType(Element.getGV()));
694 Buffer.AddChild(ElemDie);
695 }
696
697 // FIXME: We'd like an API to register additional attributes for the
698 // frontend to use while synthesizing, and then we'd use that api in clang
699 // instead of this.
700 if (Name == "__block_literal_generic")
701 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
702
703 unsigned RLang = CTy.getRunTimeLang();
704 if (RLang)
705 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
706 dwarf::DW_FORM_data1, RLang);
707 break;
708 }
709 default:
710 break;
711 }
712
713 // Add name if not anonymous or intermediate type.
714 if (!Name.empty())
715 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
716
717 if (Tag == dwarf::DW_TAG_enumeration_type ||
718 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
719 // Add size if non-zero (derived types might be zero-sized.)
720 if (Size)
721 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
722 else {
723 // Add zero size if it is not a forward declaration.
724 if (CTy.isForwardDecl())
725 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
726 else
727 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
728 }
729
730 // Add source line info if available.
731 if (!CTy.isForwardDecl())
732 AddSourceLine(&Buffer, &CTy);
733 }
734}
735
736/// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
737void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
738 int64_t L = SR.getLo();
739 int64_t H = SR.getHi();
740 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
741
742 if (L != H) {
743 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
744 if (L)
745 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
746 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
747 }
748
749 Buffer.AddChild(DW_Subrange);
750}
751
752/// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
753void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
754 DICompositeType *CTy) {
755 Buffer.setTag(dwarf::DW_TAG_array_type);
756 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
757 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
758
759 // Emit derived type.
760 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
761 DIArray Elements = CTy->getTypeArray();
762
763 // Construct an anonymous type for index type.
764 DIE IdxBuffer(dwarf::DW_TAG_base_type);
765 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
766 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
767 dwarf::DW_ATE_signed);
768 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
769
770 // Add subranges to array type.
771 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
772 DIDescriptor Element = Elements.getElement(i);
773 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
774 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
775 }
776}
777
778/// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
779DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
780 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
781 std::string Name;
782 ETy->getName(Name);
783 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
784 int64_t Value = ETy->getEnumValue();
785 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
786 return Enumerator;
787}
788
789/// CreateGlobalVariableDIE - Create new DIE using GV.
790DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
791 const DIGlobalVariable &GV) {
792 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
793 std::string Name;
794 GV.getDisplayName(Name);
795 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
796 std::string LinkageName;
797 GV.getLinkageName(LinkageName);
798 if (!LinkageName.empty())
799 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
800 LinkageName);
801 AddType(DW_Unit, GVDie, GV.getType());
802 if (!GV.isLocalToUnit())
803 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
804 AddSourceLine(GVDie, &GV);
805 return GVDie;
806}
807
808/// CreateMemberDIE - Create new member DIE.
809DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
810 DIE *MemberDie = new DIE(DT.getTag());
811 std::string Name;
812 DT.getName(Name);
813 if (!Name.empty())
814 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
815
816 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
817
818 AddSourceLine(MemberDie, &DT);
819
820 uint64_t Size = DT.getSizeInBits();
821 uint64_t FieldSize = DT.getOriginalTypeSize();
822
823 if (Size != FieldSize) {
824 // Handle bitfield.
825 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
826 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
827
828 uint64_t Offset = DT.getOffsetInBits();
829 uint64_t FieldOffset = Offset;
830 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
831 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
832 FieldOffset = (HiMark - FieldSize);
833 Offset -= FieldOffset;
834
835 // Maybe we need to work from the other end.
836 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
837 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
838 }
839
840 DIEBlock *Block = new DIEBlock();
841 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
842 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
843 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
844
845 if (DT.isProtected())
846 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
847 dwarf::DW_ACCESS_protected);
848 else if (DT.isPrivate())
849 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
850 dwarf::DW_ACCESS_private);
851
852 return MemberDie;
853}
854
855/// CreateSubprogramDIE - Create new DIE using SP.
856DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
857 const DISubprogram &SP,
858 bool IsConstructor) {
859 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
860
861 std::string Name;
862 SP.getName(Name);
863 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
864
865 std::string LinkageName;
866 SP.getLinkageName(LinkageName);
867
868 if (!LinkageName.empty())
869 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
870 LinkageName);
871
872 AddSourceLine(SPDie, &SP);
873
874 DICompositeType SPTy = SP.getType();
875 DIArray Args = SPTy.getTypeArray();
876
877 // Add prototyped tag, if C or ObjC.
878 unsigned Lang = SP.getCompileUnit().getLanguage();
879 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
880 Lang == dwarf::DW_LANG_ObjC)
881 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
882
883 // Add Return Type.
884 unsigned SPTag = SPTy.getTag();
885 if (!IsConstructor) {
886 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
887 AddType(DW_Unit, SPDie, SPTy);
888 else
889 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
890 }
891
892 if (!SP.isDefinition()) {
893 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
894
895 // Add arguments. Do not add arguments for subprogram definition. They will
896 // be handled through RecordVariable.
897 if (SPTag == dwarf::DW_TAG_subroutine_type)
898 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
899 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
900 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
901 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
902 SPDie->AddChild(Arg);
903 }
904 }
905
906 if (!SP.isLocalToUnit())
907 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
908
909 // DW_TAG_inlined_subroutine may refer to this DIE.
910 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
911 Slot = SPDie;
912 return SPDie;
913}
914
915/// FindCompileUnit - Get the compile unit for the given descriptor.
916///
917CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
918 DenseMap<Value *, CompileUnit *>::const_iterator I =
919 CompileUnitMap.find(Unit.getGV());
920 assert(I != CompileUnitMap.end() && "Missing compile unit.");
921 return *I->second;
922}
923
924/// NewDbgScopeVariable - Create a new scope variable.
925///
926DIE *DwarfDebug::NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
927 // Get the descriptor.
928 const DIVariable &VD = DV->getVariable();
929
930 // Translate tag to proper Dwarf tag. The result variable is dropped for
931 // now.
932 unsigned Tag;
933 switch (VD.getTag()) {
934 case dwarf::DW_TAG_return_variable:
935 return NULL;
936 case dwarf::DW_TAG_arg_variable:
937 Tag = dwarf::DW_TAG_formal_parameter;
938 break;
939 case dwarf::DW_TAG_auto_variable: // fall thru
940 default:
941 Tag = dwarf::DW_TAG_variable;
942 break;
943 }
944
945 // Define variable debug information entry.
946 DIE *VariableDie = new DIE(Tag);
947 std::string Name;
948 VD.getName(Name);
949 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
950
951 // Add source line info if available.
952 AddSourceLine(VariableDie, &VD);
953
954 // Add variable type.
955 AddType(Unit, VariableDie, VD.getType());
956
957 // Add variable address.
958 MachineLocation Location;
959 Location.set(RI->getFrameRegister(*MF),
960 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
961 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
962
963 return VariableDie;
964}
965
966/// getOrCreateScope - Returns the scope associated with the given descriptor.
967///
968DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
969 DbgScope *&Slot = DbgScopeMap[V];
970 if (Slot) return Slot;
971
972 DbgScope *Parent = NULL;
973 DIBlock Block(V);
974
975 // Don't create a new scope if we already created one for an inlined function.
976 DenseMap<const GlobalVariable *, DbgScope *>::iterator
977 II = AbstractInstanceRootMap.find(V);
978 if (II != AbstractInstanceRootMap.end())
979 return LexicalScopeStack.back();
980
981 if (!Block.isNull()) {
982 DIDescriptor ParentDesc = Block.getContext();
983 Parent =
984 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
985 }
986
987 Slot = new DbgScope(Parent, DIDescriptor(V));
988
989 if (Parent)
990 Parent->AddScope(Slot);
991 else
992 // First function is top level function.
993 FunctionDbgScope = Slot;
994
995 return Slot;
996}
997
998/// ConstructDbgScope - Construct the components of a scope.
999///
1000void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1001 unsigned ParentStartID,
1002 unsigned ParentEndID,
1003 DIE *ParentDie, CompileUnit *Unit) {
1004 // Add variables to scope.
1005 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1006 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1007 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
1008 if (VariableDie) ParentDie->AddChild(VariableDie);
1009 }
1010
1011 // Add concrete instances to scope.
1012 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1013 ParentScope->getConcreteInsts();
1014 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1015 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1016 DIE *Die = ConcreteInst->getDie();
1017
1018 unsigned StartID = ConcreteInst->getStartLabelID();
1019 unsigned EndID = ConcreteInst->getEndLabelID();
1020
1021 // Add the scope bounds.
1022 if (StartID)
1023 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1024 DWLabel("label", StartID));
1025 else
1026 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1027 DWLabel("func_begin", SubprogramCount));
1028
1029 if (EndID)
1030 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1031 DWLabel("label", EndID));
1032 else
1033 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1034 DWLabel("func_end", SubprogramCount));
1035
1036 ParentDie->AddChild(Die);
1037 }
1038
1039 // Add nested scopes.
1040 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1041 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1042 // Define the Scope debug information entry.
1043 DbgScope *Scope = Scopes[j];
1044
1045 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1046 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1047
1048 // Ignore empty scopes.
1049 if (StartID == EndID && StartID != 0) continue;
1050
1051 // Do not ignore inlined scopes even if they don't have any variables or
1052 // scopes.
1053 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1054 Scope->getConcreteInsts().empty())
1055 continue;
1056
1057 if (StartID == ParentStartID && EndID == ParentEndID) {
1058 // Just add stuff to the parent scope.
1059 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1060 } else {
1061 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1062
1063 // Add the scope bounds.
1064 if (StartID)
1065 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1066 DWLabel("label", StartID));
1067 else
1068 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1069 DWLabel("func_begin", SubprogramCount));
1070
1071 if (EndID)
1072 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1073 DWLabel("label", EndID));
1074 else
1075 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1076 DWLabel("func_end", SubprogramCount));
1077
1078 // Add the scope's contents.
1079 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1080 ParentDie->AddChild(ScopeDie);
1081 }
1082 }
1083}
1084
1085/// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1086///
1087void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope) {
1088 // Exit if there is no root scope.
1089 if (!RootScope) return;
1090 DIDescriptor Desc = RootScope->getDesc();
1091 if (Desc.isNull())
1092 return;
1093
1094 // Get the subprogram debug information entry.
1095 DISubprogram SPD(Desc.getGV());
1096
1097 // Get the compile unit context.
1098 CompileUnit *Unit = MainCU;
1099 if (!Unit)
1100 Unit = &FindCompileUnit(SPD.getCompileUnit());
1101
1102 // Get the subprogram die.
1103 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1104 assert(SPDie && "Missing subprogram descriptor");
1105
1106 // Add the function bounds.
1107 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1108 DWLabel("func_begin", SubprogramCount));
1109 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1110 DWLabel("func_end", SubprogramCount));
1111 MachineLocation Location(RI->getFrameRegister(*MF));
1112 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1113
1114 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1115}
1116
1117/// ConstructFunctionDbgScope - Construct the scope for the abstract debug
1118/// scope.
1119///
1120void DwarfDebug::ConstructAbstractDbgScope(DbgScope *AbsScope) {
1121 // Exit if there is no root scope.
1122 if (!AbsScope) return;
1123
1124 DIDescriptor Desc = AbsScope->getDesc();
1125 if (Desc.isNull())
1126 return;
1127
1128 // Get the subprogram debug information entry.
1129 DISubprogram SPD(Desc.getGV());
1130
1131 // Get the compile unit context.
1132 CompileUnit *Unit = MainCU;
1133 if (!Unit)
1134 Unit = &FindCompileUnit(SPD.getCompileUnit());
1135
1136 // Get the subprogram die.
1137 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1138 assert(SPDie && "Missing subprogram descriptor");
1139
1140 ConstructDbgScope(AbsScope, 0, 0, SPDie, Unit);
1141}
1142
1143/// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1144///
1145void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1146 const char *FnName = MF->getFunction()->getNameStart();
1147 if (MainCU) {
1148 StringMap<DIE*> &Globals = MainCU->getGlobals();
1149 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1150 if (GI != Globals.end()) {
1151 DIE *SPDie = GI->second;
1152
1153 // Add the function bounds.
1154 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1155 DWLabel("func_begin", SubprogramCount));
1156 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1157 DWLabel("func_end", SubprogramCount));
1158
1159 MachineLocation Location(RI->getFrameRegister(*MF));
1160 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1161 return;
1162 }
1163 } else {
1164 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1165 CompileUnit *Unit = CompileUnits[i];
1166 StringMap<DIE*> &Globals = Unit->getGlobals();
1167 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1168 if (GI != Globals.end()) {
1169 DIE *SPDie = GI->second;
1170
1171 // Add the function bounds.
1172 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1173 DWLabel("func_begin", SubprogramCount));
1174 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1175 DWLabel("func_end", SubprogramCount));
1176
1177 MachineLocation Location(RI->getFrameRegister(*MF));
1178 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1179 return;
1180 }
1181 }
1182 }
1183
1184#if 0
1185 // FIXME: This is causing an abort because C++ mangled names are compared with
1186 // their unmangled counterparts. See PR2885. Don't do this assert.
1187 assert(0 && "Couldn't find DIE for machine function!");
1188#endif
1189}
1190
1191/// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1192/// tools to recognize the object file contains Dwarf information.
1193void DwarfDebug::EmitInitial() {
1194 // Check to see if we already emitted intial headers.
1195 if (didInitial) return;
1196 didInitial = true;
1197
1198 // Dwarf sections base addresses.
1199 if (TAI->doesDwarfRequireFrameSection()) {
1200 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1201 EmitLabel("section_debug_frame", 0);
1202 }
1203
1204 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1205 EmitLabel("section_info", 0);
1206 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1207 EmitLabel("section_abbrev", 0);
1208 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1209 EmitLabel("section_aranges", 0);
1210
1211 if (TAI->doesSupportMacInfoSection()) {
1212 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1213 EmitLabel("section_macinfo", 0);
1214 }
1215
1216 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1217 EmitLabel("section_line", 0);
1218 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1219 EmitLabel("section_loc", 0);
1220 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1221 EmitLabel("section_pubnames", 0);
1222 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1223 EmitLabel("section_str", 0);
1224 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1225 EmitLabel("section_ranges", 0);
1226
1227 Asm->SwitchToSection(TAI->getTextSection());
1228 EmitLabel("text_begin", 0);
1229 Asm->SwitchToSection(TAI->getDataSection());
1230 EmitLabel("data_begin", 0);
1231}
1232
1233/// EmitDIE - Recusively Emits a debug information entry.
1234///
1235void DwarfDebug::EmitDIE(DIE *Die) {
1236 // Get the abbreviation for this DIE.
1237 unsigned AbbrevNumber = Die->getAbbrevNumber();
1238 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1239
1240 Asm->EOL();
1241
1242 // Emit the code (index) for the abbreviation.
1243 Asm->EmitULEB128Bytes(AbbrevNumber);
1244
1245 if (Asm->isVerbose())
1246 Asm->EOL(std::string("Abbrev [" +
1247 utostr(AbbrevNumber) +
1248 "] 0x" + utohexstr(Die->getOffset()) +
1249 ":0x" + utohexstr(Die->getSize()) + " " +
1250 dwarf::TagString(Abbrev->getTag())));
1251 else
1252 Asm->EOL();
1253
1254 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1255 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1256
1257 // Emit the DIE attribute values.
1258 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1259 unsigned Attr = AbbrevData[i].getAttribute();
1260 unsigned Form = AbbrevData[i].getForm();
1261 assert(Form && "Too many attributes for DIE (check abbreviation)");
1262
1263 switch (Attr) {
1264 case dwarf::DW_AT_sibling:
1265 Asm->EmitInt32(Die->SiblingOffset());
1266 break;
1267 case dwarf::DW_AT_abstract_origin: {
1268 DIEEntry *E = cast<DIEEntry>(Values[i]);
1269 DIE *Origin = E->getEntry();
1270 unsigned Addr =
1271 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1272 Origin->getOffset();
1273
1274 Asm->EmitInt32(Addr);
1275 break;
1276 }
1277 default:
1278 // Emit an attribute using the defined form.
1279 Values[i]->EmitValue(this, Form);
1280 break;
1281 }
1282
1283 Asm->EOL(dwarf::AttributeString(Attr));
1284 }
1285
1286 // Emit the DIE children if any.
1287 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1288 const std::vector<DIE *> &Children = Die->getChildren();
1289
1290 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1291 EmitDIE(Children[j]);
1292
1293 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1294 }
1295}
1296
1297/// SizeAndOffsetDie - Compute the size and offset of a DIE.
1298///
1299unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1300 // Get the children.
1301 const std::vector<DIE *> &Children = Die->getChildren();
1302
1303 // If not last sibling and has children then add sibling offset attribute.
1304 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1305
1306 // Record the abbreviation.
1307 AssignAbbrevNumber(Die->getAbbrev());
1308
1309 // Get the abbreviation for this DIE.
1310 unsigned AbbrevNumber = Die->getAbbrevNumber();
1311 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1312
1313 // Set DIE offset
1314 Die->setOffset(Offset);
1315
1316 // Start the size with the size of abbreviation code.
1317 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1318
1319 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1320 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1321
1322 // Size the DIE attribute values.
1323 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1324 // Size attribute value.
1325 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1326
1327 // Size the DIE children if any.
1328 if (!Children.empty()) {
1329 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1330 "Children flag not set");
1331
1332 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1333 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1334
1335 // End of children marker.
1336 Offset += sizeof(int8_t);
1337 }
1338
1339 Die->setSize(Offset - Die->getOffset());
1340 return Offset;
1341}
1342
1343/// SizeAndOffsets - Compute the size and offset of all the DIEs.
1344///
1345void DwarfDebug::SizeAndOffsets() {
1346 // Compute size of compile unit header.
1347 static unsigned Offset =
1348 sizeof(int32_t) + // Length of Compilation Unit Info
1349 sizeof(int16_t) + // DWARF version number
1350 sizeof(int32_t) + // Offset Into Abbrev. Section
1351 sizeof(int8_t); // Pointer Size (in bytes)
1352
1353 // Process base compile unit.
1354 if (MainCU) {
1355 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1356 CompileUnitOffsets[MainCU] = 0;
1357 return;
1358 }
1359
1360 // Process all compile units.
1361 unsigned PrevOffset = 0;
1362
1363 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1364 CompileUnit *Unit = CompileUnits[i];
1365 CompileUnitOffsets[Unit] = PrevOffset;
1366 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1367 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1368 }
1369}
1370
1371/// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1372///
1373void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1374 DIE *Die = Unit->getDie();
1375
1376 // Emit the compile units header.
1377 EmitLabel("info_begin", Unit->getID());
1378
1379 // Emit size of content not including length itself
1380 unsigned ContentSize = Die->getSize() +
1381 sizeof(int16_t) + // DWARF version number
1382 sizeof(int32_t) + // Offset Into Abbrev. Section
1383 sizeof(int8_t) + // Pointer Size (in bytes)
1384 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1385
1386 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1387 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1388 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1389 Asm->EOL("Offset Into Abbrev. Section");
1390 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1391
1392 EmitDIE(Die);
1393 // FIXME - extra padding for gdb bug.
1394 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1395 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1396 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1397 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1398 EmitLabel("info_end", Unit->getID());
1399
1400 Asm->EOL();
1401}
1402
1403void DwarfDebug::EmitDebugInfo() {
1404 // Start debug info section.
1405 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1406
1407 if (MainCU) {
1408 EmitDebugInfoPerCU(MainCU);
1409 return;
1410 }
1411
1412 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1413 EmitDebugInfoPerCU(CompileUnits[i]);
1414}
1415
1416/// EmitAbbreviations - Emit the abbreviation section.
1417///
1418void DwarfDebug::EmitAbbreviations() const {
1419 // Check to see if it is worth the effort.
1420 if (!Abbreviations.empty()) {
1421 // Start the debug abbrev section.
1422 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1423
1424 EmitLabel("abbrev_begin", 0);
1425
1426 // For each abbrevation.
1427 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1428 // Get abbreviation data
1429 const DIEAbbrev *Abbrev = Abbreviations[i];
1430
1431 // Emit the abbrevations code (base 1 index.)
1432 Asm->EmitULEB128Bytes(Abbrev->getNumber());
1433 Asm->EOL("Abbreviation Code");
1434
1435 // Emit the abbreviations data.
1436 Abbrev->Emit(Asm);
1437
1438 Asm->EOL();
1439 }
1440
1441 // Mark end of abbreviations.
1442 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
1443
1444 EmitLabel("abbrev_end", 0);
1445 Asm->EOL();
1446 }
1447}
1448
1449/// EmitEndOfLineMatrix - Emit the last address of the section and the end of
1450/// the line matrix.
1451///
1452void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
1453 // Define last address of section.
1454 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1455 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1456 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1457 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
1458
1459 // Mark end of matrix.
1460 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
1461 Asm->EmitULEB128Bytes(1); Asm->EOL();
1462 Asm->EmitInt8(1); Asm->EOL();
1463}
1464
1465/// EmitDebugLines - Emit source line information.
1466///
1467void DwarfDebug::EmitDebugLines() {
1468 // If the target is using .loc/.file, the assembler will be emitting the
1469 // .debug_line table automatically.
1470 if (TAI->hasDotLocAndDotFile())
1471 return;
1472
1473 // Minimum line delta, thus ranging from -10..(255-10).
1474 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
1475 // Maximum line delta, thus ranging from -10..(255-10).
1476 const int MaxLineDelta = 255 + MinLineDelta;
1477
1478 // Start the dwarf line section.
1479 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1480
1481 // Construct the section header.
1482 EmitDifference("line_end", 0, "line_begin", 0, true);
1483 Asm->EOL("Length of Source Line Info");
1484 EmitLabel("line_begin", 0);
1485
1486 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1487
1488 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
1489 Asm->EOL("Prolog Length");
1490 EmitLabel("line_prolog_begin", 0);
1491
1492 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
1493
1494 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
1495
1496 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
1497
1498 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
1499
1500 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
1501
1502 // Line number standard opcode encodings argument count
1503 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
1504 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
1505 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
1506 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
1507 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
1508 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
1509 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
1510 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
1511 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
1512
1513 // Emit directories.
1514 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
1515 Asm->EmitString(getSourceDirectoryName(DI));
1516 Asm->EOL("Directory");
1517 }
1518
1519 Asm->EmitInt8(0); Asm->EOL("End of directories");
1520
1521 // Emit files.
1522 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
1523 // Remember source id starts at 1.
1524 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
1525 Asm->EmitString(getSourceFileName(Id.second));
1526 Asm->EOL("Source");
1527 Asm->EmitULEB128Bytes(Id.first);
1528 Asm->EOL("Directory #");
1529 Asm->EmitULEB128Bytes(0);
1530 Asm->EOL("Mod date");
1531 Asm->EmitULEB128Bytes(0);
1532 Asm->EOL("File size");
1533 }
1534
1535 Asm->EmitInt8(0); Asm->EOL("End of files");
1536
1537 EmitLabel("line_prolog_end", 0);
1538
1539 // A sequence for each text section.
1540 unsigned SecSrcLinesSize = SectionSourceLines.size();
1541
1542 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
1543 // Isolate current sections line info.
1544 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
1545
1546 if (Asm->isVerbose()) {
1547 const Section* S = SectionMap[j + 1];
1548 O << '\t' << TAI->getCommentString() << " Section"
1549 << S->getName() << '\n';
1550 } else {
1551 Asm->EOL();
1552 }
1553
1554 // Dwarf assumes we start with first line of first source file.
1555 unsigned Source = 1;
1556 unsigned Line = 1;
1557
1558 // Construct rows of the address, source, line, column matrix.
1559 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1560 const SrcLineInfo &LineInfo = LineInfos[i];
1561 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
1562 if (!LabelID) continue;
1563
1564 if (!Asm->isVerbose())
1565 Asm->EOL();
1566 else {
1567 std::pair<unsigned, unsigned> SourceID =
1568 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
1569 O << '\t' << TAI->getCommentString() << ' '
1570 << getSourceDirectoryName(SourceID.first) << ' '
1571 << getSourceFileName(SourceID.second)
1572 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
1573 }
1574
1575 // Define the line address.
1576 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1577 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1578 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1579 EmitReference("label", LabelID); Asm->EOL("Location label");
1580
1581 // If change of source, then switch to the new source.
1582 if (Source != LineInfo.getSourceID()) {
1583 Source = LineInfo.getSourceID();
1584 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
1585 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
1586 }
1587
1588 // If change of line.
1589 if (Line != LineInfo.getLine()) {
1590 // Determine offset.
1591 int Offset = LineInfo.getLine() - Line;
1592 int Delta = Offset - MinLineDelta;
1593
1594 // Update line.
1595 Line = LineInfo.getLine();
1596
1597 // If delta is small enough and in range...
1598 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1599 // ... then use fast opcode.
1600 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
1601 } else {
1602 // ... otherwise use long hand.
1603 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
1604 Asm->EOL("DW_LNS_advance_line");
1605 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
1606 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1607 }
1608 } else {
1609 // Copy the previous row (different address or source)
1610 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1611 }
1612 }
1613
1614 EmitEndOfLineMatrix(j + 1);
1615 }
1616
1617 if (SecSrcLinesSize == 0)
1618 // Because we're emitting a debug_line section, we still need a line
1619 // table. The linker and friends expect it to exist. If there's nothing to
1620 // put into it, emit an empty table.
1621 EmitEndOfLineMatrix(1);
1622
1623 EmitLabel("line_end", 0);
1624 Asm->EOL();
1625}
1626
1627/// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
1628///
1629void DwarfDebug::EmitCommonDebugFrame() {
1630 if (!TAI->doesDwarfRequireFrameSection())
1631 return;
1632
1633 int stackGrowth =
1634 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1635 TargetFrameInfo::StackGrowsUp ?
1636 TD->getPointerSize() : -TD->getPointerSize();
1637
1638 // Start the dwarf frame section.
1639 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1640
1641 EmitLabel("debug_frame_common", 0);
1642 EmitDifference("debug_frame_common_end", 0,
1643 "debug_frame_common_begin", 0, true);
1644 Asm->EOL("Length of Common Information Entry");
1645
1646 EmitLabel("debug_frame_common_begin", 0);
1647 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
1648 Asm->EOL("CIE Identifier Tag");
1649 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
1650 Asm->EOL("CIE Version");
1651 Asm->EmitString("");
1652 Asm->EOL("CIE Augmentation");
1653 Asm->EmitULEB128Bytes(1);
1654 Asm->EOL("CIE Code Alignment Factor");
1655 Asm->EmitSLEB128Bytes(stackGrowth);
1656 Asm->EOL("CIE Data Alignment Factor");
1657 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
1658 Asm->EOL("CIE RA Column");
1659
1660 std::vector<MachineMove> Moves;
1661 RI->getInitialFrameState(Moves);
1662
1663 EmitFrameMoves(NULL, 0, Moves, false);
1664
1665 Asm->EmitAlignment(2, 0, 0, false);
1666 EmitLabel("debug_frame_common_end", 0);
1667
1668 Asm->EOL();
1669}
1670
1671/// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
1672/// section.
1673void
1674DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
1675 if (!TAI->doesDwarfRequireFrameSection())
1676 return;
1677
1678 // Start the dwarf frame section.
1679 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1680
1681 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
1682 "debug_frame_begin", DebugFrameInfo.Number, true);
1683 Asm->EOL("Length of Frame Information Entry");
1684
1685 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
1686
1687 EmitSectionOffset("debug_frame_common", "section_debug_frame",
1688 0, 0, true, false);
1689 Asm->EOL("FDE CIE offset");
1690
1691 EmitReference("func_begin", DebugFrameInfo.Number);
1692 Asm->EOL("FDE initial location");
1693 EmitDifference("func_end", DebugFrameInfo.Number,
1694 "func_begin", DebugFrameInfo.Number);
1695 Asm->EOL("FDE address range");
1696
1697 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
1698 false);
1699
1700 Asm->EmitAlignment(2, 0, 0, false);
1701 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
1702
1703 Asm->EOL();
1704}
1705
1706void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
1707 EmitDifference("pubnames_end", Unit->getID(),
1708 "pubnames_begin", Unit->getID(), true);
1709 Asm->EOL("Length of Public Names Info");
1710
1711 EmitLabel("pubnames_begin", Unit->getID());
1712
1713 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
1714
1715 EmitSectionOffset("info_begin", "section_info",
1716 Unit->getID(), 0, true, false);
1717 Asm->EOL("Offset of Compilation Unit Info");
1718
1719 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
1720 true);
1721 Asm->EOL("Compilation Unit Length");
1722
1723 StringMap<DIE*> &Globals = Unit->getGlobals();
1724 for (StringMap<DIE*>::const_iterator
1725 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1726 const char *Name = GI->getKeyData();
1727 DIE * Entity = GI->second;
1728
1729 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
1730 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
1731 }
1732
1733 Asm->EmitInt32(0); Asm->EOL("End Mark");
1734 EmitLabel("pubnames_end", Unit->getID());
1735
1736 Asm->EOL();
1737}
1738
1739/// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1740///
1741void DwarfDebug::EmitDebugPubNames() {
1742 // Start the dwarf pubnames section.
1743 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1744
1745 if (MainCU) {
1746 EmitDebugPubNamesPerCU(MainCU);
1747 return;
1748 }
1749
1750 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1751 EmitDebugPubNamesPerCU(CompileUnits[i]);
1752}
1753
1754/// EmitDebugStr - Emit visible names into a debug str section.
1755///
1756void DwarfDebug::EmitDebugStr() {
1757 // Check to see if it is worth the effort.
1758 if (!StringPool.empty()) {
1759 // Start the dwarf str section.
1760 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1761
1762 // For each of strings in the string pool.
1763 for (unsigned StringID = 1, N = StringPool.size();
1764 StringID <= N; ++StringID) {
1765 // Emit a label for reference from debug information entries.
1766 EmitLabel("string", StringID);
1767
1768 // Emit the string itself.
1769 const std::string &String = StringPool[StringID];
1770 Asm->EmitString(String); Asm->EOL();
1771 }
1772
1773 Asm->EOL();
1774 }
1775}
1776
1777/// EmitDebugLoc - Emit visible names into a debug loc section.
1778///
1779void DwarfDebug::EmitDebugLoc() {
1780 // Start the dwarf loc section.
1781 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1782 Asm->EOL();
1783}
1784
1785/// EmitDebugARanges - Emit visible names into a debug aranges section.
1786///
1787void DwarfDebug::EmitDebugARanges() {
1788 // Start the dwarf aranges section.
1789 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1790
1791 // FIXME - Mock up
1792#if 0
1793 CompileUnit *Unit = GetBaseCompileUnit();
1794
1795 // Don't include size of length
1796 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
1797
1798 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1799
1800 EmitReference("info_begin", Unit->getID());
1801 Asm->EOL("Offset of Compilation Unit Info");
1802
1803 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
1804
1805 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
1806
1807 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
1808 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
1809
1810 // Range 1
1811 EmitReference("text_begin", 0); Asm->EOL("Address");
1812 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
1813
1814 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
1815 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
1816#endif
1817
1818 Asm->EOL();
1819}
1820
1821/// EmitDebugRanges - Emit visible names into a debug ranges section.
1822///
1823void DwarfDebug::EmitDebugRanges() {
1824 // Start the dwarf ranges section.
1825 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1826 Asm->EOL();
1827}
1828
1829/// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
1830///
1831void DwarfDebug::EmitDebugMacInfo() {
1832 if (TAI->doesSupportMacInfoSection()) {
1833 // Start the dwarf macinfo section.
1834 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1835 Asm->EOL();
1836 }
1837}
1838
1839/// EmitDebugInlineInfo - Emit inline info using following format.
1840/// Section Header:
1841/// 1. length of section
1842/// 2. Dwarf version number
1843/// 3. address size.
1844///
1845/// Entries (one "entry" for each function that was inlined):
1846///
1847/// 1. offset into __debug_str section for MIPS linkage name, if exists;
1848/// otherwise offset into __debug_str for regular function name.
1849/// 2. offset into __debug_str section for regular function name.
1850/// 3. an unsigned LEB128 number indicating the number of distinct inlining
1851/// instances for the function.
1852///
1853/// The rest of the entry consists of a {die_offset, low_pc} pair for each
1854/// inlined instance; the die_offset points to the inlined_subroutine die in the
1855/// __debug_info section, and the low_pc is the starting address for the
1856/// inlining instance.
1857void DwarfDebug::EmitDebugInlineInfo() {
1858 if (!TAI->doesDwarfUsesInlineInfoSection())
1859 return;
1860
1861 if (!MainCU)
1862 return;
1863
1864 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
1865 Asm->EOL();
1866 EmitDifference("debug_inlined_end", 1,
1867 "debug_inlined_begin", 1, true);
1868 Asm->EOL("Length of Debug Inlined Information Entry");
1869
1870 EmitLabel("debug_inlined_begin", 1);
1871
1872 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1873 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1874
1875 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1876 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
1877 GlobalVariable *GV = I->first;
1878 SmallVector<unsigned, 4> &Labels = I->second;
1879 DISubprogram SP(GV);
1880 std::string Name;
1881 std::string LName;
1882
1883 SP.getLinkageName(LName);
1884 SP.getName(Name);
1885
1886 Asm->EmitString(LName.empty() ? Name : LName);
1887 Asm->EOL("MIPS linkage name");
1888
1889 Asm->EmitString(Name); Asm->EOL("Function name");
1890
1891 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
1892
1893 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
1894 LE = Labels.end(); LI != LE; ++LI) {
1895 DIE *SP = MainCU->getDieMapSlotFor(GV);
1896 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
1897
1898 if (TD->getPointerSize() == sizeof(int32_t))
1899 O << TAI->getData32bitsDirective();
1900 else
1901 O << TAI->getData64bitsDirective();
1902
1903 PrintLabelName("label", *LI); Asm->EOL("low_pc");
1904 }
1905 }
1906
1907 EmitLabel("debug_inlined_end", 1);
1908 Asm->EOL();
1909}
1910
1911/// GetOrCreateSourceID - Look up the source id with the given directory and
1912/// source file names. If none currently exists, create a new id and insert it
1913/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1914/// maps as well.
1915unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1916 const std::string &FileName) {
1917 unsigned DId;
1918 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1919 if (DI != DirectoryIdMap.end()) {
1920 DId = DI->getValue();
1921 } else {
1922 DId = DirectoryNames.size() + 1;
1923 DirectoryIdMap[DirName] = DId;
1924 DirectoryNames.push_back(DirName);
1925 }
1926
1927 unsigned FId;
1928 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1929 if (FI != SourceFileIdMap.end()) {
1930 FId = FI->getValue();
1931 } else {
1932 FId = SourceFileNames.size() + 1;
1933 SourceFileIdMap[FileName] = FId;
1934 SourceFileNames.push_back(FileName);
1935 }
1936
1937 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1938 SourceIdMap.find(std::make_pair(DId, FId));
1939 if (SI != SourceIdMap.end())
1940 return SI->second;
1941
1942 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1943 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1944 SourceIds.push_back(std::make_pair(DId, FId));
1945
1946 return SrcId;
1947}
1948
1949void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1950 DICompileUnit DIUnit(GV);
1951 std::string Dir, FN, Prod;
1952 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1953 DIUnit.getFilename(FN));
1954
1955 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1956 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1957 DWLabel("section_line", 0), DWLabel("section_line", 0),
1958 false);
1959 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1960 DIUnit.getProducer(Prod));
1961 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1962 DIUnit.getLanguage());
1963 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1964
1965 if (!Dir.empty())
1966 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1967 if (DIUnit.isOptimized())
1968 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1969
1970 std::string Flags;
1971 DIUnit.getFlags(Flags);
1972 if (!Flags.empty())
1973 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1974
1975 unsigned RVer = DIUnit.getRunTimeVersion();
1976 if (RVer)
1977 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1978 dwarf::DW_FORM_data1, RVer);
1979
1980 CompileUnit *Unit = new CompileUnit(ID, Die);
1981 if (DIUnit.isMain()) {
1982 assert(!MainCU && "Multiple main compile units are found!");
1983 MainCU = Unit;
1984 }
1985
1986 CompileUnitMap[DIUnit.getGV()] = Unit;
1987 CompileUnits.push_back(Unit);
1988}
1989
1990/// ConstructCompileUnits - Create a compile unit DIEs.
1991void DwarfDebug::ConstructCompileUnits() {
1992 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
1993 if (!Root)
1994 return;
1995 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1996 "Malformed compile unit descriptor anchor type");
1997 Constant *RootC = cast<Constant>(*Root->use_begin());
1998 assert(RootC->hasNUsesOrMore(1) &&
1999 "Malformed compile unit descriptor anchor type");
2000
2001 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2002 UI != UE; ++UI)
2003 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2004 UUI != UUE; ++UUI) {
2005 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2006 ConstructCompileUnit(GV);
2007 }
2008}
2009
2010bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
2011 DIGlobalVariable DI_GV(GV);
2012 CompileUnit *DW_Unit = MainCU;
2013 if (!DW_Unit)
2014 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
2015
2016 // Check for pre-existence.
2017 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2018 if (Slot)
2019 return false;
2020
2021 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2022
2023 // Add address.
2024 DIEBlock *Block = new DIEBlock();
2025 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
2026 std::string GLN;
2027 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
2028 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
2029 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
2030
2031 // Add to map.
2032 Slot = VariableDie;
2033
2034 // Add to context owner.
2035 DW_Unit->getDie()->AddChild(VariableDie);
2036
2037 // Expose as global. FIXME - need to check external flag.
2038 std::string Name;
2039 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2040 return true;
2041}
2042
2043/// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
2044/// global variables. Return true if at least one global DIE is created.
2045bool DwarfDebug::ConstructGlobalVariableDIEs() {
2046 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2047 if (!Root)
2048 return false;
2049
2050 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2051 "Malformed global variable descriptor anchor type");
2052 Constant *RootC = cast<Constant>(*Root->use_begin());
2053 assert(RootC->hasNUsesOrMore(1) &&
2054 "Malformed global variable descriptor anchor type");
2055
2056 bool Result = false;
2057 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2058 UI != UE; ++UI)
2059 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2060 UUI != UUE; ++UUI)
2061 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
2062
2063 return Result;
2064}
2065
2066bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
2067 DISubprogram SP(GV);
2068 CompileUnit *Unit = MainCU;
2069 if (!Unit)
2070 Unit = &FindCompileUnit(SP.getCompileUnit());
2071
2072 // Check for pre-existence.
2073 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2074 if (Slot)
2075 return false;
2076
2077 if (!SP.isDefinition())
2078 // This is a method declaration which will be handled while constructing
2079 // class type.
2080 return false;
2081
2082 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2083
2084 // Add to map.
2085 Slot = SubprogramDie;
2086
2087 // Add to context owner.
2088 Unit->getDie()->AddChild(SubprogramDie);
2089
2090 // Expose as global.
2091 std::string Name;
2092 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2093 return true;
2094}
2095
2096/// ConstructSubprograms - Create DIEs for each of the externally visible
2097/// subprograms. Return true if at least one subprogram DIE is created.
2098bool DwarfDebug::ConstructSubprograms() {
2099 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2100 if (!Root)
2101 return false;
2102
2103 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2104 "Malformed subprogram descriptor anchor type");
2105 Constant *RootC = cast<Constant>(*Root->use_begin());
2106 assert(RootC->hasNUsesOrMore(1) &&
2107 "Malformed subprogram descriptor anchor type");
2108
2109 bool Result = false;
2110 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2111 UI != UE; ++UI)
2112 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2113 UUI != UUE; ++UUI)
2114 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
2115
2116 return Result;
2117}
2118
2119/// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2120/// This is inovked by the target AsmPrinter.
2121void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
2122 if (TimePassesIsEnabled)
2123 DebugTimer->startTimer();
2124
2125 // Create all the compile unit DIEs.
2126 ConstructCompileUnits();
2127
2128 if (CompileUnits.empty()) {
2129 if (TimePassesIsEnabled)
2130 DebugTimer->stopTimer();
2131
2132 return;
2133 }
2134
2135 // Create DIEs for each of the externally visible global variables.
2136 bool globalDIEs = ConstructGlobalVariableDIEs();
2137
2138 // Create DIEs for each of the externally visible subprograms.
2139 bool subprogramDIEs = ConstructSubprograms();
2140
2141 // If there is not any debug info available for any global variables and any
2142 // subprograms then there is not any debug info to emit.
2143 if (!globalDIEs && !subprogramDIEs) {
2144 if (TimePassesIsEnabled)
2145 DebugTimer->stopTimer();
2146
2147 return;
2148 }
2149
2150 MMI = mmi;
2151 shouldEmit = true;
2152 MMI->setDebugInfoAvailability(true);
2153
2154 // Prime section data.
2155 SectionMap.insert(TAI->getTextSection());
2156
2157 // Print out .file directives to specify files for .loc directives. These are
2158 // printed out early so that they precede any .loc directives.
2159 if (TAI->hasDotLocAndDotFile()) {
2160 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2161 // Remember source id starts at 1.
2162 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2163 sys::Path FullPath(getSourceDirectoryName(Id.first));
2164 bool AppendOk =
2165 FullPath.appendComponent(getSourceFileName(Id.second));
2166 assert(AppendOk && "Could not append filename to directory!");
2167 AppendOk = false;
2168 Asm->EmitFile(i, FullPath.toString());
2169 Asm->EOL();
2170 }
2171 }
2172
2173 // Emit initial sections
2174 EmitInitial();
2175
2176 if (TimePassesIsEnabled)
2177 DebugTimer->stopTimer();
2178}
2179
2180/// EndModule - Emit all Dwarf sections that should come after the content.
2181///
2182void DwarfDebug::EndModule() {
2183 if (!ShouldEmitDwarfDebug())
2184 return;
2185
2186 if (TimePassesIsEnabled)
2187 DebugTimer->startTimer();
2188
2189 // Standard sections final addresses.
2190 Asm->SwitchToSection(TAI->getTextSection());
2191 EmitLabel("text_end", 0);
2192 Asm->SwitchToSection(TAI->getDataSection());
2193 EmitLabel("data_end", 0);
2194
2195 // End text sections.
2196 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2197 Asm->SwitchToSection(SectionMap[i]);
2198 EmitLabel("section_end", i);
2199 }
2200
2201 // Emit common frame information.
2202 EmitCommonDebugFrame();
2203
2204 // Emit function debug frame information
2205 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2206 E = DebugFrames.end(); I != E; ++I)
2207 EmitFunctionDebugFrame(*I);
2208
2209 // Compute DIE offsets and sizes.
2210 SizeAndOffsets();
2211
2212 // Emit all the DIEs into a debug info section
2213 EmitDebugInfo();
2214
2215 // Corresponding abbreviations into a abbrev section.
2216 EmitAbbreviations();
2217
2218 // Emit source line correspondence into a debug line section.
2219 EmitDebugLines();
2220
2221 // Emit info into a debug pubnames section.
2222 EmitDebugPubNames();
2223
2224 // Emit info into a debug str section.
2225 EmitDebugStr();
2226
2227 // Emit info into a debug loc section.
2228 EmitDebugLoc();
2229
2230 // Emit info into a debug aranges section.
2231 EmitDebugARanges();
2232
2233 // Emit info into a debug ranges section.
2234 EmitDebugRanges();
2235
2236 // Emit info into a debug macinfo section.
2237 EmitDebugMacInfo();
2238
2239 // Emit inline info.
2240 EmitDebugInlineInfo();
2241
2242 if (TimePassesIsEnabled)
2243 DebugTimer->stopTimer();
2244}
2245
2246/// BeginFunction - Gather pre-function debug information. Assumes being
2247/// emitted immediately after the function entry point.
2248void DwarfDebug::BeginFunction(MachineFunction *MF) {
2249 this->MF = MF;
2250
2251 if (!ShouldEmitDwarfDebug()) return;
2252
2253 if (TimePassesIsEnabled)
2254 DebugTimer->startTimer();
2255
2256 // Begin accumulating function debug information.
2257 MMI->BeginFunction(MF);
2258
2259 // Assumes in correct section after the entry point.
2260 EmitLabel("func_begin", ++SubprogramCount);
2261
2262 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2263 // function.
2264 DebugLoc FDL = MF->getDefaultDebugLoc();
2265 if (!FDL.isUnknown()) {
2266 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2267 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
2268 DICompileUnit(DLT.CompileUnit));
2269 Asm->printLabel(LabelID);
2270 }
2271
2272 if (TimePassesIsEnabled)
2273 DebugTimer->stopTimer();
2274}
2275
2276/// EndFunction - Gather and emit post-function debug information.
2277///
2278void DwarfDebug::EndFunction(MachineFunction *MF) {
2279 if (!ShouldEmitDwarfDebug()) return;
2280
2281 if (TimePassesIsEnabled)
2282 DebugTimer->startTimer();
2283
2284 // Define end label for subprogram.
2285 EmitLabel("func_end", SubprogramCount);
2286
2287 // Get function line info.
2288 if (!Lines.empty()) {
2289 // Get section line info.
2290 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2291 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2292 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2293 // Append the function info to section info.
2294 SectionLineInfos.insert(SectionLineInfos.end(),
2295 Lines.begin(), Lines.end());
2296 }
2297
2298 // Construct the DbgScope for abstract instances.
2299 for (SmallVector<DbgScope *, 32>::iterator
2300 I = AbstractInstanceRootList.begin(),
2301 E = AbstractInstanceRootList.end(); I != E; ++I)
2302 ConstructAbstractDbgScope(*I);
2303
2304 // Construct scopes for subprogram.
2305 if (FunctionDbgScope)
2306 ConstructFunctionDbgScope(FunctionDbgScope);
2307 else
2308 // FIXME: This is wrong. We are essentially getting past a problem with
2309 // debug information not being able to handle unreachable blocks that have
2310 // debug information in them. In particular, those unreachable blocks that
2311 // have "region end" info in them. That situation results in the "root
2312 // scope" not being created. If that's the case, then emit a "default"
2313 // scope, i.e., one that encompasses the whole function. This isn't
2314 // desirable. And a better way of handling this (and all of the debugging
2315 // information) needs to be explored.
2316 ConstructDefaultDbgScope(MF);
2317
2318 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2319 MMI->getFrameMoves()));
2320
2321 // Clear debug info
2322 if (FunctionDbgScope) {
2323 delete FunctionDbgScope;
2324 DbgScopeMap.clear();
2325 DbgAbstractScopeMap.clear();
2326 DbgConcreteScopeMap.clear();
2327 InlinedVariableScopes.clear();
2328 FunctionDbgScope = NULL;
2329 LexicalScopeStack.clear();
2330 AbstractInstanceRootList.clear();
2331 }
2332
2333 Lines.clear();
2334
2335 if (TimePassesIsEnabled)
2336 DebugTimer->stopTimer();
2337}
2338
2339/// RecordSourceLine - Records location information and associates it with a
2340/// label. Returns a unique label ID used to generate a label and provide
2341/// correspondence to the source line list.
2342unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2343 if (TimePassesIsEnabled)
2344 DebugTimer->startTimer();
2345
2346 CompileUnit *Unit = CompileUnitMap[V];
2347 assert(Unit && "Unable to find CompileUnit");
2348 unsigned ID = MMI->NextLabelID();
2349 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2350
2351 if (TimePassesIsEnabled)
2352 DebugTimer->stopTimer();
2353
2354 return ID;
2355}
2356
2357/// RecordSourceLine - Records location information and associates it with a
2358/// label. Returns a unique label ID used to generate a label and provide
2359/// correspondence to the source line list.
2360unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2361 DICompileUnit CU) {
2362 if (TimePassesIsEnabled)
2363 DebugTimer->startTimer();
2364
2365 std::string Dir, Fn;
2366 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
2367 CU.getFilename(Fn));
2368 unsigned ID = MMI->NextLabelID();
2369 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2370
2371 if (TimePassesIsEnabled)
2372 DebugTimer->stopTimer();
2373
2374 return ID;
2375}
2376
2377/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2378/// timed. Look up the source id with the given directory and source file
2379/// names. If none currently exists, create a new id and insert it in the
2380/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2381/// well.
2382unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2383 const std::string &FileName) {
2384 if (TimePassesIsEnabled)
2385 DebugTimer->startTimer();
2386
2387 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
2388
2389 if (TimePassesIsEnabled)
2390 DebugTimer->stopTimer();
2391
2392 return SrcId;
2393}
2394
2395/// RecordRegionStart - Indicate the start of a region.
2396unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
2397 if (TimePassesIsEnabled)
2398 DebugTimer->startTimer();
2399
2400 DbgScope *Scope = getOrCreateScope(V);
2401 unsigned ID = MMI->NextLabelID();
2402 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2403 LexicalScopeStack.push_back(Scope);
2404
2405 if (TimePassesIsEnabled)
2406 DebugTimer->stopTimer();
2407
2408 return ID;
2409}
2410
2411/// RecordRegionEnd - Indicate the end of a region.
2412unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
2413 if (TimePassesIsEnabled)
2414 DebugTimer->startTimer();
2415
2416 DbgScope *Scope = getOrCreateScope(V);
2417 unsigned ID = MMI->NextLabelID();
2418 Scope->setEndLabelID(ID);
2419 if (LexicalScopeStack.size() != 0)
2420 LexicalScopeStack.pop_back();
2421
2422 if (TimePassesIsEnabled)
2423 DebugTimer->stopTimer();
2424
2425 return ID;
2426}
2427
2428/// RecordVariable - Indicate the declaration of a local variable.
2429void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2430 const MachineInstr *MI) {
2431 if (TimePassesIsEnabled)
2432 DebugTimer->startTimer();
2433
2434 DIDescriptor Desc(GV);
2435 DbgScope *Scope = NULL;
2436
2437 if (Desc.getTag() == dwarf::DW_TAG_variable) {
2438 // GV is a global variable.
2439 DIGlobalVariable DG(GV);
2440 Scope = getOrCreateScope(DG.getContext().getGV());
2441 } else {
2442 DenseMap<const MachineInstr *, DbgScope *>::iterator
2443 SI = InlinedVariableScopes.find(MI);
2444
2445 if (SI != InlinedVariableScopes.end()) {
2446 // or GV is an inlined local variable.
2447 Scope = SI->second;
2448 } else {
2449 DIVariable DV(GV);
2450 GlobalVariable *V = DV.getContext().getGV();
2451
2452 // FIXME: The code that checks for the inlined local variable is a hack!
2453 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2454 AI = AbstractInstanceRootMap.find(V);
2455
2456 if (AI != AbstractInstanceRootMap.end())
2457 // or GV is an inlined local variable.
2458 Scope = AI->second;
2459 else
2460 // or GV is a local variable.
2461 Scope = getOrCreateScope(V);
2462 }
2463 }
2464
2465 assert(Scope && "Unable to find the variable's scope");
2466 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
2467 Scope->AddVariable(DV);
2468
2469 if (TimePassesIsEnabled)
2470 DebugTimer->stopTimer();
2471}
2472
2473//// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2474unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2475 unsigned Line, unsigned Col) {
2476 unsigned LabelID = MMI->NextLabelID();
2477
2478 if (!TAI->doesDwarfUsesInlineInfoSection())
2479 return LabelID;
2480
2481 if (TimePassesIsEnabled)
2482 DebugTimer->startTimer();
2483
2484 GlobalVariable *GV = SP.getGV();
2485 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2486 II = AbstractInstanceRootMap.find(GV);
2487
2488 if (II == AbstractInstanceRootMap.end()) {
2489 // Create an abstract instance entry for this inlined function if it doesn't
2490 // already exist.
2491 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
2492
2493 // Get the compile unit context.
2494 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2495 DIE *SPDie = Unit->getDieMapSlotFor(GV);
2496 if (!SPDie)
2497 SPDie = CreateSubprogramDIE(Unit, SP);
2498
2499 // Mark as being inlined. This makes this subprogram entry an abstract
2500 // instance root.
2501 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2502 // that it's defined. It probably won't change in the future, but this
2503 // could be more elegant.
2504 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
2505
2506 // Keep track of the abstract scope for this function.
2507 DbgAbstractScopeMap[GV] = Scope;
2508
2509 AbstractInstanceRootMap[GV] = Scope;
2510 AbstractInstanceRootList.push_back(Scope);
2511 }
2512
2513 // Create a concrete inlined instance for this inlined function.
2514 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
2515 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
2516 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2517 ScopeDie->setAbstractCompileUnit(Unit);
2518
2519 DIE *Origin = Unit->getDieMapSlotFor(GV);
2520 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
2521 dwarf::DW_FORM_ref4, Origin);
2522 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
2523 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
2524 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
2525
2526 ConcreteScope->setDie(ScopeDie);
2527 ConcreteScope->setStartLabelID(LabelID);
2528 MMI->RecordUsedDbgLabel(LabelID);
2529
2530 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2531
2532 // Keep track of the concrete scope that's inlined into this function.
2533 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2534 SI = DbgConcreteScopeMap.find(GV);
2535
2536 if (SI == DbgConcreteScopeMap.end())
2537 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
2538 else
2539 SI->second.push_back(ConcreteScope);
2540
2541 // Track the start label for this inlined function.
2542 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2543 I = InlineInfo.find(GV);
2544
2545 if (I == InlineInfo.end())
2546 InlineInfo[GV].push_back(LabelID);
2547 else
2548 I->second.push_back(LabelID);
2549
2550 if (TimePassesIsEnabled)
2551 DebugTimer->stopTimer();
2552
2553 return LabelID;
2554}
2555
2556/// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2557unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2558 if (!TAI->doesDwarfUsesInlineInfoSection())
2559 return 0;
2560
2561 if (TimePassesIsEnabled)
2562 DebugTimer->startTimer();
2563
2564 GlobalVariable *GV = SP.getGV();
2565 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2566 I = DbgConcreteScopeMap.find(GV);
2567
2568 if (I == DbgConcreteScopeMap.end()) {
2569 if (TimePassesIsEnabled)
2570 DebugTimer->stopTimer();
2571
2572 return 0;
2573 }
2574
2575 SmallVector<DbgScope *, 8> &Scopes = I->second;
2576 assert(!Scopes.empty() && "We should have at least one debug scope!");
2577 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2578 unsigned ID = MMI->NextLabelID();
2579 MMI->RecordUsedDbgLabel(ID);
2580 Scope->setEndLabelID(ID);
2581
2582 if (TimePassesIsEnabled)
2583 DebugTimer->stopTimer();
2584
2585 return ID;
2586}
2587
2588/// RecordVariableScope - Record scope for the variable declared by
2589/// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
2590/// for only inlined subroutine variables. Other variables's scopes are
2591/// determined during RecordVariable().
2592void DwarfDebug::RecordVariableScope(DIVariable &DV,
2593 const MachineInstr *DeclareMI) {
2594 if (TimePassesIsEnabled)
2595 DebugTimer->startTimer();
2596
2597 DISubprogram SP(DV.getContext().getGV());
2598
2599 if (SP.isNull()) {
2600 if (TimePassesIsEnabled)
2601 DebugTimer->stopTimer();
2602
2603 return;
2604 }
2605
2606 DenseMap<GlobalVariable *, DbgScope *>::iterator
2607 I = DbgAbstractScopeMap.find(SP.getGV());
2608 if (I != DbgAbstractScopeMap.end())
2609 InlinedVariableScopes[DeclareMI] = I->second;
2610
2611 if (TimePassesIsEnabled)
2612 DebugTimer->stopTimer();
2613}