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