blob: 7f9894d39eaf1bbfa19b6d018e44b57cdc27583f [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)
224 : Dwarf(OS, A, T, "dbg"), MainCU(0),
225 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()));
681 else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
682 ElemDie = CreateGlobalVariableDIE(DW_Unit,
683 DIGlobalVariable(Element.getGV()));
684 else
685 ElemDie = CreateMemberDIE(DW_Unit,
686 DIDerivedType(Element.getGV()));
687 Buffer.AddChild(ElemDie);
688 }
689
690 // FIXME: We'd like an API to register additional attributes for the
691 // frontend to use while synthesizing, and then we'd use that api in clang
692 // instead of this.
693 if (Name == "__block_literal_generic")
694 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
695
696 unsigned RLang = CTy.getRunTimeLang();
697 if (RLang)
698 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
699 dwarf::DW_FORM_data1, RLang);
700 break;
701 }
702 default:
703 break;
704 }
705
706 // Add name if not anonymous or intermediate type.
707 if (!Name.empty())
708 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
709
710 if (Tag == dwarf::DW_TAG_enumeration_type ||
711 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
712 // Add size if non-zero (derived types might be zero-sized.)
713 if (Size)
714 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
715 else {
716 // Add zero size if it is not a forward declaration.
717 if (CTy.isForwardDecl())
718 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
719 else
720 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
721 }
722
723 // Add source line info if available.
724 if (!CTy.isForwardDecl())
725 AddSourceLine(&Buffer, &CTy);
726 }
727}
728
729/// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
730void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
731 int64_t L = SR.getLo();
732 int64_t H = SR.getHi();
733 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
734
735 if (L != H) {
736 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
737 if (L)
738 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
739 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
740 }
741
742 Buffer.AddChild(DW_Subrange);
743}
744
745/// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
746void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
747 DICompositeType *CTy) {
748 Buffer.setTag(dwarf::DW_TAG_array_type);
749 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
750 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
751
752 // Emit derived type.
753 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
754 DIArray Elements = CTy->getTypeArray();
755
756 // Construct an anonymous type for index type.
757 DIE IdxBuffer(dwarf::DW_TAG_base_type);
758 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
759 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
760 dwarf::DW_ATE_signed);
761 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
762
763 // Add subranges to array type.
764 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
765 DIDescriptor Element = Elements.getElement(i);
766 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
767 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
768 }
769}
770
771/// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
772DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
773 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
774 std::string Name;
775 ETy->getName(Name);
776 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
777 int64_t Value = ETy->getEnumValue();
778 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
779 return Enumerator;
780}
781
782/// CreateGlobalVariableDIE - Create new DIE using GV.
783DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
784 const DIGlobalVariable &GV) {
785 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
786 std::string Name;
787 GV.getDisplayName(Name);
788 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
789 std::string LinkageName;
790 GV.getLinkageName(LinkageName);
791 if (!LinkageName.empty())
792 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
793 LinkageName);
794 AddType(DW_Unit, GVDie, GV.getType());
795 if (!GV.isLocalToUnit())
796 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
797 AddSourceLine(GVDie, &GV);
798 return GVDie;
799}
800
801/// CreateMemberDIE - Create new member DIE.
802DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
803 DIE *MemberDie = new DIE(DT.getTag());
804 std::string Name;
805 DT.getName(Name);
806 if (!Name.empty())
807 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
808
809 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
810
811 AddSourceLine(MemberDie, &DT);
812
813 uint64_t Size = DT.getSizeInBits();
814 uint64_t FieldSize = DT.getOriginalTypeSize();
815
816 if (Size != FieldSize) {
817 // Handle bitfield.
818 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
819 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
820
821 uint64_t Offset = DT.getOffsetInBits();
822 uint64_t FieldOffset = Offset;
823 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
824 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
825 FieldOffset = (HiMark - FieldSize);
826 Offset -= FieldOffset;
827
828 // Maybe we need to work from the other end.
829 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
830 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
831 }
832
833 DIEBlock *Block = new DIEBlock();
834 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
835 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
836 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
837
838 if (DT.isProtected())
839 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
840 dwarf::DW_ACCESS_protected);
841 else if (DT.isPrivate())
842 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
843 dwarf::DW_ACCESS_private);
844
845 return MemberDie;
846}
847
848/// CreateSubprogramDIE - Create new DIE using SP.
849DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
850 const DISubprogram &SP,
Bill Wendling6679ee42009-05-18 22:02:36 +0000851 bool IsConstructor,
852 bool IsInlined) {
Bill Wendling0310d762009-05-15 09:23:25 +0000853 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
854
855 std::string Name;
856 SP.getName(Name);
857 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
858
859 std::string LinkageName;
860 SP.getLinkageName(LinkageName);
861
862 if (!LinkageName.empty())
863 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
864 LinkageName);
865
866 AddSourceLine(SPDie, &SP);
867
868 DICompositeType SPTy = SP.getType();
869 DIArray Args = SPTy.getTypeArray();
870
871 // Add prototyped tag, if C or ObjC.
872 unsigned Lang = SP.getCompileUnit().getLanguage();
873 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
874 Lang == dwarf::DW_LANG_ObjC)
875 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
876
877 // Add Return Type.
878 unsigned SPTag = SPTy.getTag();
879 if (!IsConstructor) {
880 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
881 AddType(DW_Unit, SPDie, SPTy);
882 else
883 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
884 }
885
886 if (!SP.isDefinition()) {
887 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
888
889 // Add arguments. Do not add arguments for subprogram definition. They will
890 // be handled through RecordVariable.
891 if (SPTag == dwarf::DW_TAG_subroutine_type)
892 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
893 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
894 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
895 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
896 SPDie->AddChild(Arg);
897 }
898 }
899
Bill Wendling6679ee42009-05-18 22:02:36 +0000900 if (!SP.isLocalToUnit() && !IsInlined)
Bill Wendling0310d762009-05-15 09:23:25 +0000901 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
902
903 // DW_TAG_inlined_subroutine may refer to this DIE.
904 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
905 Slot = SPDie;
906 return SPDie;
907}
908
909/// FindCompileUnit - Get the compile unit for the given descriptor.
910///
911CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
912 DenseMap<Value *, CompileUnit *>::const_iterator I =
913 CompileUnitMap.find(Unit.getGV());
914 assert(I != CompileUnitMap.end() && "Missing compile unit.");
915 return *I->second;
916}
917
Bill Wendling995f80a2009-05-20 23:24:48 +0000918/// CreateDbgScopeVariable - Create a new scope variable.
Bill Wendling0310d762009-05-15 09:23:25 +0000919///
Bill Wendling995f80a2009-05-20 23:24:48 +0000920DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
Bill Wendling0310d762009-05-15 09:23:25 +0000921 // Get the descriptor.
922 const DIVariable &VD = DV->getVariable();
923
924 // Translate tag to proper Dwarf tag. The result variable is dropped for
925 // now.
926 unsigned Tag;
927 switch (VD.getTag()) {
928 case dwarf::DW_TAG_return_variable:
929 return NULL;
930 case dwarf::DW_TAG_arg_variable:
931 Tag = dwarf::DW_TAG_formal_parameter;
932 break;
933 case dwarf::DW_TAG_auto_variable: // fall thru
934 default:
935 Tag = dwarf::DW_TAG_variable;
936 break;
937 }
938
939 // Define variable debug information entry.
940 DIE *VariableDie = new DIE(Tag);
941 std::string Name;
942 VD.getName(Name);
943 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
944
945 // Add source line info if available.
946 AddSourceLine(VariableDie, &VD);
947
948 // Add variable type.
949 AddType(Unit, VariableDie, VD.getType());
950
951 // Add variable address.
Bill Wendling1180c782009-05-18 23:08:55 +0000952 if (!DV->isInlinedFnVar()) {
953 // Variables for abstract instances of inlined functions don't get a
954 // location.
955 MachineLocation Location;
956 Location.set(RI->getFrameRegister(*MF),
957 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
958 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
959 }
Bill Wendling0310d762009-05-15 09:23:25 +0000960
961 return VariableDie;
962}
963
964/// getOrCreateScope - Returns the scope associated with the given descriptor.
965///
966DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
967 DbgScope *&Slot = DbgScopeMap[V];
968 if (Slot) return Slot;
969
970 DbgScope *Parent = NULL;
971 DIBlock Block(V);
972
Bill Wendling8fff19b2009-06-01 20:18:46 +0000973 // Don't create a new scope if we already created one for an inlined function.
974 DenseMap<const GlobalVariable *, DbgScope *>::iterator
975 II = AbstractInstanceRootMap.find(V);
976 if (II != AbstractInstanceRootMap.end())
977 return LexicalScopeStack.back();
978
Bill Wendling0310d762009-05-15 09:23:25 +0000979 if (!Block.isNull()) {
980 DIDescriptor ParentDesc = Block.getContext();
981 Parent =
982 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
983 }
984
985 Slot = new DbgScope(Parent, DIDescriptor(V));
986
987 if (Parent)
988 Parent->AddScope(Slot);
989 else
990 // First function is top level function.
991 FunctionDbgScope = Slot;
992
993 return Slot;
994}
995
996/// ConstructDbgScope - Construct the components of a scope.
997///
998void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
999 unsigned ParentStartID,
1000 unsigned ParentEndID,
1001 DIE *ParentDie, CompileUnit *Unit) {
1002 // Add variables to scope.
1003 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1004 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
Bill Wendling995f80a2009-05-20 23:24:48 +00001005 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
Bill Wendling0310d762009-05-15 09:23:25 +00001006 if (VariableDie) ParentDie->AddChild(VariableDie);
1007 }
1008
1009 // Add concrete instances to scope.
1010 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1011 ParentScope->getConcreteInsts();
1012 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1013 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1014 DIE *Die = ConcreteInst->getDie();
1015
1016 unsigned StartID = ConcreteInst->getStartLabelID();
1017 unsigned EndID = ConcreteInst->getEndLabelID();
1018
1019 // Add the scope bounds.
1020 if (StartID)
1021 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1022 DWLabel("label", StartID));
1023 else
1024 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1025 DWLabel("func_begin", SubprogramCount));
1026
1027 if (EndID)
1028 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1029 DWLabel("label", EndID));
1030 else
1031 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1032 DWLabel("func_end", SubprogramCount));
1033
1034 ParentDie->AddChild(Die);
1035 }
1036
1037 // Add nested scopes.
1038 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1039 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1040 // Define the Scope debug information entry.
1041 DbgScope *Scope = Scopes[j];
1042
1043 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1044 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1045
1046 // Ignore empty scopes.
1047 if (StartID == EndID && StartID != 0) continue;
1048
1049 // Do not ignore inlined scopes even if they don't have any variables or
1050 // scopes.
1051 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1052 Scope->getConcreteInsts().empty())
1053 continue;
1054
1055 if (StartID == ParentStartID && EndID == ParentEndID) {
1056 // Just add stuff to the parent scope.
1057 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1058 } else {
1059 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1060
1061 // Add the scope bounds.
1062 if (StartID)
1063 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1064 DWLabel("label", StartID));
1065 else
1066 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1067 DWLabel("func_begin", SubprogramCount));
1068
1069 if (EndID)
1070 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1071 DWLabel("label", EndID));
1072 else
1073 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1074 DWLabel("func_end", SubprogramCount));
1075
1076 // Add the scope's contents.
1077 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1078 ParentDie->AddChild(ScopeDie);
1079 }
1080 }
1081}
1082
1083/// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1084///
Bill Wendling17956162009-05-20 23:28:48 +00001085void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1086 bool AbstractScope) {
Bill Wendling0310d762009-05-15 09:23:25 +00001087 // Exit if there is no root scope.
1088 if (!RootScope) return;
1089 DIDescriptor Desc = RootScope->getDesc();
1090 if (Desc.isNull())
1091 return;
1092
1093 // Get the subprogram debug information entry.
1094 DISubprogram SPD(Desc.getGV());
1095
1096 // Get the compile unit context.
1097 CompileUnit *Unit = MainCU;
1098 if (!Unit)
1099 Unit = &FindCompileUnit(SPD.getCompileUnit());
1100
1101 // Get the subprogram die.
1102 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1103 assert(SPDie && "Missing subprogram descriptor");
1104
Bill Wendling17956162009-05-20 23:28:48 +00001105 if (!AbstractScope) {
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 }
Bill Wendling0310d762009-05-15 09:23:25 +00001114
1115 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1116}
1117
Bill Wendling0310d762009-05-15 09:23:25 +00001118/// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1119///
1120void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1121 const char *FnName = MF->getFunction()->getNameStart();
1122 if (MainCU) {
1123 StringMap<DIE*> &Globals = MainCU->getGlobals();
1124 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1125 if (GI != Globals.end()) {
1126 DIE *SPDie = GI->second;
1127
1128 // Add the function bounds.
1129 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1130 DWLabel("func_begin", SubprogramCount));
1131 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1132 DWLabel("func_end", SubprogramCount));
1133
1134 MachineLocation Location(RI->getFrameRegister(*MF));
1135 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1136 return;
1137 }
1138 } else {
1139 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1140 CompileUnit *Unit = CompileUnits[i];
1141 StringMap<DIE*> &Globals = Unit->getGlobals();
1142 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1143 if (GI != Globals.end()) {
1144 DIE *SPDie = GI->second;
1145
1146 // Add the function bounds.
1147 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1148 DWLabel("func_begin", SubprogramCount));
1149 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1150 DWLabel("func_end", SubprogramCount));
1151
1152 MachineLocation Location(RI->getFrameRegister(*MF));
1153 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1154 return;
1155 }
1156 }
1157 }
1158
1159#if 0
1160 // FIXME: This is causing an abort because C++ mangled names are compared with
1161 // their unmangled counterparts. See PR2885. Don't do this assert.
1162 assert(0 && "Couldn't find DIE for machine function!");
1163#endif
1164}
1165
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001166/// GetOrCreateSourceID - Look up the source id with the given directory and
1167/// source file names. If none currently exists, create a new id and insert it
1168/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1169/// maps as well.
1170unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1171 const std::string &FileName) {
1172 unsigned DId;
1173 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1174 if (DI != DirectoryIdMap.end()) {
1175 DId = DI->getValue();
1176 } else {
1177 DId = DirectoryNames.size() + 1;
1178 DirectoryIdMap[DirName] = DId;
1179 DirectoryNames.push_back(DirName);
1180 }
1181
1182 unsigned FId;
1183 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1184 if (FI != SourceFileIdMap.end()) {
1185 FId = FI->getValue();
1186 } else {
1187 FId = SourceFileNames.size() + 1;
1188 SourceFileIdMap[FileName] = FId;
1189 SourceFileNames.push_back(FileName);
1190 }
1191
1192 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1193 SourceIdMap.find(std::make_pair(DId, FId));
1194 if (SI != SourceIdMap.end())
1195 return SI->second;
1196
1197 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1198 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1199 SourceIds.push_back(std::make_pair(DId, FId));
1200
1201 return SrcId;
1202}
1203
1204void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1205 DICompileUnit DIUnit(GV);
1206 std::string Dir, FN, Prod;
1207 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1208 DIUnit.getFilename(FN));
1209
1210 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1211 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1212 DWLabel("section_line", 0), DWLabel("section_line", 0),
1213 false);
1214 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1215 DIUnit.getProducer(Prod));
1216 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1217 DIUnit.getLanguage());
1218 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1219
1220 if (!Dir.empty())
1221 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1222 if (DIUnit.isOptimized())
1223 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1224
1225 std::string Flags;
1226 DIUnit.getFlags(Flags);
1227 if (!Flags.empty())
1228 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1229
1230 unsigned RVer = DIUnit.getRunTimeVersion();
1231 if (RVer)
1232 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1233 dwarf::DW_FORM_data1, RVer);
1234
1235 CompileUnit *Unit = new CompileUnit(ID, Die);
1236 if (DIUnit.isMain()) {
1237 assert(!MainCU && "Multiple main compile units are found!");
1238 MainCU = Unit;
1239 }
1240
1241 CompileUnitMap[DIUnit.getGV()] = Unit;
1242 CompileUnits.push_back(Unit);
1243}
1244
1245/// ConstructCompileUnits - Create a compile unit DIEs.
1246void DwarfDebug::ConstructCompileUnits() {
1247 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
1248 if (!Root)
1249 return;
1250 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1251 "Malformed compile unit descriptor anchor type");
1252 Constant *RootC = cast<Constant>(*Root->use_begin());
1253 assert(RootC->hasNUsesOrMore(1) &&
1254 "Malformed compile unit descriptor anchor type");
1255
1256 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1257 UI != UE; ++UI)
1258 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1259 UUI != UUE; ++UUI) {
1260 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
1261 ConstructCompileUnit(GV);
1262 }
1263}
1264
1265bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
1266 DIGlobalVariable DI_GV(GV);
1267 CompileUnit *DW_Unit = MainCU;
1268 if (!DW_Unit)
1269 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
1270
1271 // Check for pre-existence.
1272 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
1273 if (Slot)
1274 return false;
1275
1276 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
1277
1278 // Add address.
1279 DIEBlock *Block = new DIEBlock();
1280 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1281 std::string GLN;
1282 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1283 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
1284 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1285
1286 // Add to map.
1287 Slot = VariableDie;
1288
1289 // Add to context owner.
1290 DW_Unit->getDie()->AddChild(VariableDie);
1291
1292 // Expose as global. FIXME - need to check external flag.
1293 std::string Name;
1294 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
1295 return true;
1296}
1297
1298/// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
1299/// global variables. Return true if at least one global DIE is created.
1300bool DwarfDebug::ConstructGlobalVariableDIEs() {
1301 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
1302 if (!Root)
1303 return false;
1304
1305 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1306 "Malformed global variable descriptor anchor type");
1307 Constant *RootC = cast<Constant>(*Root->use_begin());
1308 assert(RootC->hasNUsesOrMore(1) &&
1309 "Malformed global variable descriptor anchor type");
1310
1311 bool Result = false;
1312 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1313 UI != UE; ++UI)
1314 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1315 UUI != UUE; ++UUI)
1316 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
1317
1318 return Result;
1319}
1320
1321bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
1322 DISubprogram SP(GV);
1323 CompileUnit *Unit = MainCU;
1324 if (!Unit)
1325 Unit = &FindCompileUnit(SP.getCompileUnit());
1326
1327 // Check for pre-existence.
1328 DIE *&Slot = Unit->getDieMapSlotFor(GV);
1329 if (Slot)
1330 return false;
1331
1332 if (!SP.isDefinition())
1333 // This is a method declaration which will be handled while constructing
1334 // class type.
1335 return false;
1336
1337 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
1338
1339 // Add to map.
1340 Slot = SubprogramDie;
1341
1342 // Add to context owner.
1343 Unit->getDie()->AddChild(SubprogramDie);
1344
1345 // Expose as global.
1346 std::string Name;
1347 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
1348 return true;
1349}
1350
1351/// ConstructSubprograms - Create DIEs for each of the externally visible
1352/// subprograms. Return true if at least one subprogram DIE is created.
1353bool DwarfDebug::ConstructSubprograms() {
1354 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
1355 if (!Root)
1356 return false;
1357
1358 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1359 "Malformed subprogram descriptor anchor type");
1360 Constant *RootC = cast<Constant>(*Root->use_begin());
1361 assert(RootC->hasNUsesOrMore(1) &&
1362 "Malformed subprogram descriptor anchor type");
1363
1364 bool Result = false;
1365 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1366 UI != UE; ++UI)
1367 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1368 UUI != UUE; ++UUI)
1369 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
1370
1371 return Result;
1372}
1373
1374/// SetDebugInfo - Create global DIEs and emit initial debug info sections.
1375/// This is inovked by the target AsmPrinter.
1376void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
1377 if (TimePassesIsEnabled)
1378 DebugTimer->startTimer();
1379
1380 // Create all the compile unit DIEs.
1381 ConstructCompileUnits();
1382
1383 if (CompileUnits.empty()) {
1384 if (TimePassesIsEnabled)
1385 DebugTimer->stopTimer();
1386
1387 return;
1388 }
1389
1390 // Create DIEs for each of the externally visible global variables.
1391 bool globalDIEs = ConstructGlobalVariableDIEs();
1392
1393 // Create DIEs for each of the externally visible subprograms.
1394 bool subprogramDIEs = ConstructSubprograms();
1395
1396 // If there is not any debug info available for any global variables and any
1397 // subprograms then there is not any debug info to emit.
1398 if (!globalDIEs && !subprogramDIEs) {
1399 if (TimePassesIsEnabled)
1400 DebugTimer->stopTimer();
1401
1402 return;
1403 }
1404
1405 MMI = mmi;
1406 shouldEmit = true;
1407 MMI->setDebugInfoAvailability(true);
1408
1409 // Prime section data.
1410 SectionMap.insert(TAI->getTextSection());
1411
1412 // Print out .file directives to specify files for .loc directives. These are
1413 // printed out early so that they precede any .loc directives.
1414 if (TAI->hasDotLocAndDotFile()) {
1415 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1416 // Remember source id starts at 1.
1417 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1418 sys::Path FullPath(getSourceDirectoryName(Id.first));
1419 bool AppendOk =
1420 FullPath.appendComponent(getSourceFileName(Id.second));
1421 assert(AppendOk && "Could not append filename to directory!");
1422 AppendOk = false;
1423 Asm->EmitFile(i, FullPath.toString());
1424 Asm->EOL();
1425 }
1426 }
1427
1428 // Emit initial sections
1429 EmitInitial();
1430
1431 if (TimePassesIsEnabled)
1432 DebugTimer->stopTimer();
1433}
1434
1435/// EndModule - Emit all Dwarf sections that should come after the content.
1436///
1437void DwarfDebug::EndModule() {
1438 if (!ShouldEmitDwarfDebug())
1439 return;
1440
1441 if (TimePassesIsEnabled)
1442 DebugTimer->startTimer();
1443
1444 // Standard sections final addresses.
1445 Asm->SwitchToSection(TAI->getTextSection());
1446 EmitLabel("text_end", 0);
1447 Asm->SwitchToSection(TAI->getDataSection());
1448 EmitLabel("data_end", 0);
1449
1450 // End text sections.
1451 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1452 Asm->SwitchToSection(SectionMap[i]);
1453 EmitLabel("section_end", i);
1454 }
1455
1456 // Emit common frame information.
1457 EmitCommonDebugFrame();
1458
1459 // Emit function debug frame information
1460 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1461 E = DebugFrames.end(); I != E; ++I)
1462 EmitFunctionDebugFrame(*I);
1463
1464 // Compute DIE offsets and sizes.
1465 SizeAndOffsets();
1466
1467 // Emit all the DIEs into a debug info section
1468 EmitDebugInfo();
1469
1470 // Corresponding abbreviations into a abbrev section.
1471 EmitAbbreviations();
1472
1473 // Emit source line correspondence into a debug line section.
1474 EmitDebugLines();
1475
1476 // Emit info into a debug pubnames section.
1477 EmitDebugPubNames();
1478
1479 // Emit info into a debug str section.
1480 EmitDebugStr();
1481
1482 // Emit info into a debug loc section.
1483 EmitDebugLoc();
1484
1485 // Emit info into a debug aranges section.
1486 EmitDebugARanges();
1487
1488 // Emit info into a debug ranges section.
1489 EmitDebugRanges();
1490
1491 // Emit info into a debug macinfo section.
1492 EmitDebugMacInfo();
1493
1494 // Emit inline info.
1495 EmitDebugInlineInfo();
1496
1497 if (TimePassesIsEnabled)
1498 DebugTimer->stopTimer();
1499}
1500
1501/// BeginFunction - Gather pre-function debug information. Assumes being
1502/// emitted immediately after the function entry point.
1503void DwarfDebug::BeginFunction(MachineFunction *MF) {
1504 this->MF = MF;
1505
1506 if (!ShouldEmitDwarfDebug()) return;
1507
1508 if (TimePassesIsEnabled)
1509 DebugTimer->startTimer();
1510
1511 // Begin accumulating function debug information.
1512 MMI->BeginFunction(MF);
1513
1514 // Assumes in correct section after the entry point.
1515 EmitLabel("func_begin", ++SubprogramCount);
1516
1517 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1518 // function.
1519 DebugLoc FDL = MF->getDefaultDebugLoc();
1520 if (!FDL.isUnknown()) {
1521 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1522 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
1523 DICompileUnit(DLT.CompileUnit));
1524 Asm->printLabel(LabelID);
1525 }
1526
1527 if (TimePassesIsEnabled)
1528 DebugTimer->stopTimer();
1529}
1530
1531/// EndFunction - Gather and emit post-function debug information.
1532///
1533void DwarfDebug::EndFunction(MachineFunction *MF) {
1534 if (!ShouldEmitDwarfDebug()) return;
1535
1536 if (TimePassesIsEnabled)
1537 DebugTimer->startTimer();
1538
1539 // Define end label for subprogram.
1540 EmitLabel("func_end", SubprogramCount);
1541
1542 // Get function line info.
1543 if (!Lines.empty()) {
1544 // Get section line info.
1545 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
1546 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1547 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1548 // Append the function info to section info.
1549 SectionLineInfos.insert(SectionLineInfos.end(),
1550 Lines.begin(), Lines.end());
1551 }
1552
1553 // Construct the DbgScope for abstract instances.
1554 for (SmallVector<DbgScope *, 32>::iterator
1555 I = AbstractInstanceRootList.begin(),
1556 E = AbstractInstanceRootList.end(); I != E; ++I)
Bill Wendling17956162009-05-20 23:28:48 +00001557 ConstructFunctionDbgScope(*I);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001558
1559 // Construct scopes for subprogram.
1560 if (FunctionDbgScope)
1561 ConstructFunctionDbgScope(FunctionDbgScope);
1562 else
1563 // FIXME: This is wrong. We are essentially getting past a problem with
1564 // debug information not being able to handle unreachable blocks that have
1565 // debug information in them. In particular, those unreachable blocks that
1566 // have "region end" info in them. That situation results in the "root
1567 // scope" not being created. If that's the case, then emit a "default"
1568 // scope, i.e., one that encompasses the whole function. This isn't
1569 // desirable. And a better way of handling this (and all of the debugging
1570 // information) needs to be explored.
1571 ConstructDefaultDbgScope(MF);
1572
1573 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1574 MMI->getFrameMoves()));
1575
1576 // Clear debug info
1577 if (FunctionDbgScope) {
1578 delete FunctionDbgScope;
1579 DbgScopeMap.clear();
1580 DbgAbstractScopeMap.clear();
1581 DbgConcreteScopeMap.clear();
1582 InlinedVariableScopes.clear();
1583 FunctionDbgScope = NULL;
1584 LexicalScopeStack.clear();
1585 AbstractInstanceRootList.clear();
Devang Patel9217f792009-06-12 19:24:05 +00001586 AbstractInstanceRootMap.clear();
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001587 }
1588
1589 Lines.clear();
1590
1591 if (TimePassesIsEnabled)
1592 DebugTimer->stopTimer();
1593}
1594
1595/// RecordSourceLine - Records location information and associates it with a
1596/// label. Returns a unique label ID used to generate a label and provide
1597/// correspondence to the source line list.
1598unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1599 if (TimePassesIsEnabled)
1600 DebugTimer->startTimer();
1601
1602 CompileUnit *Unit = CompileUnitMap[V];
1603 assert(Unit && "Unable to find CompileUnit");
1604 unsigned ID = MMI->NextLabelID();
1605 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1606
1607 if (TimePassesIsEnabled)
1608 DebugTimer->stopTimer();
1609
1610 return ID;
1611}
1612
1613/// RecordSourceLine - Records location information and associates it with a
1614/// label. Returns a unique label ID used to generate a label and provide
1615/// correspondence to the source line list.
1616unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1617 DICompileUnit CU) {
1618 if (TimePassesIsEnabled)
1619 DebugTimer->startTimer();
1620
1621 std::string Dir, Fn;
1622 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
1623 CU.getFilename(Fn));
1624 unsigned ID = MMI->NextLabelID();
1625 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1626
1627 if (TimePassesIsEnabled)
1628 DebugTimer->stopTimer();
1629
1630 return ID;
1631}
1632
1633/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1634/// timed. Look up the source id with the given directory and source file
1635/// names. If none currently exists, create a new id and insert it in the
1636/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1637/// well.
1638unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1639 const std::string &FileName) {
1640 if (TimePassesIsEnabled)
1641 DebugTimer->startTimer();
1642
1643 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
1644
1645 if (TimePassesIsEnabled)
1646 DebugTimer->stopTimer();
1647
1648 return SrcId;
1649}
1650
1651/// RecordRegionStart - Indicate the start of a region.
1652unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
1653 if (TimePassesIsEnabled)
1654 DebugTimer->startTimer();
1655
1656 DbgScope *Scope = getOrCreateScope(V);
1657 unsigned ID = MMI->NextLabelID();
1658 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1659 LexicalScopeStack.push_back(Scope);
1660
1661 if (TimePassesIsEnabled)
1662 DebugTimer->stopTimer();
1663
1664 return ID;
1665}
1666
1667/// RecordRegionEnd - Indicate the end of a region.
1668unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
1669 if (TimePassesIsEnabled)
1670 DebugTimer->startTimer();
1671
1672 DbgScope *Scope = getOrCreateScope(V);
1673 unsigned ID = MMI->NextLabelID();
1674 Scope->setEndLabelID(ID);
Devang Pateldaf9e022009-06-13 02:16:18 +00001675 // FIXME : region.end() may not be in the last basic block.
1676 // For now, do not pop last lexical scope because next basic
1677 // block may start new inlined function's body.
1678 unsigned LSSize = LexicalScopeStack.size();
1679 if (LSSize != 0 && LSSize != 1)
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001680 LexicalScopeStack.pop_back();
1681
1682 if (TimePassesIsEnabled)
1683 DebugTimer->stopTimer();
1684
1685 return ID;
1686}
1687
1688/// RecordVariable - Indicate the declaration of a local variable.
1689void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
1690 const MachineInstr *MI) {
1691 if (TimePassesIsEnabled)
1692 DebugTimer->startTimer();
1693
1694 DIDescriptor Desc(GV);
1695 DbgScope *Scope = NULL;
1696 bool InlinedFnVar = false;
1697
1698 if (Desc.getTag() == dwarf::DW_TAG_variable) {
1699 // GV is a global variable.
1700 DIGlobalVariable DG(GV);
1701 Scope = getOrCreateScope(DG.getContext().getGV());
1702 } else {
1703 DenseMap<const MachineInstr *, DbgScope *>::iterator
1704 SI = InlinedVariableScopes.find(MI);
1705
1706 if (SI != InlinedVariableScopes.end()) {
1707 // or GV is an inlined local variable.
1708 Scope = SI->second;
1709 } else {
1710 DIVariable DV(GV);
1711 GlobalVariable *V = DV.getContext().getGV();
1712
1713 // FIXME: The code that checks for the inlined local variable is a hack!
1714 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1715 AI = AbstractInstanceRootMap.find(V);
1716
1717 if (AI != AbstractInstanceRootMap.end()) {
1718 // This method is called each time a DECLARE node is encountered. For an
1719 // inlined function, this could be many, many times. We don't want to
1720 // re-add variables to that DIE for each time. We just want to add them
1721 // once. Check to make sure that we haven't added them already.
1722 DenseMap<const GlobalVariable *,
1723 SmallSet<const GlobalVariable *, 32> >::iterator
1724 IP = InlinedParamMap.find(V);
1725
1726 if (IP != InlinedParamMap.end() && IP->second.count(GV) > 0) {
1727 if (TimePassesIsEnabled)
1728 DebugTimer->stopTimer();
1729 return;
1730 }
1731
1732 // or GV is an inlined local variable.
1733 Scope = AI->second;
1734 InlinedParamMap[V].insert(GV);
1735 InlinedFnVar = true;
1736 } else {
1737 // or GV is a local variable.
1738 Scope = getOrCreateScope(V);
1739 }
1740 }
1741 }
1742
1743 assert(Scope && "Unable to find the variable's scope");
1744 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
1745 Scope->AddVariable(DV);
1746
1747 if (TimePassesIsEnabled)
1748 DebugTimer->stopTimer();
1749}
1750
1751//// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1752unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1753 unsigned Line, unsigned Col) {
1754 unsigned LabelID = MMI->NextLabelID();
1755
1756 if (!TAI->doesDwarfUsesInlineInfoSection())
1757 return LabelID;
1758
1759 if (TimePassesIsEnabled)
1760 DebugTimer->startTimer();
1761
Devang Patelc2230822009-06-16 02:09:30 +00001762 CompileUnit *Unit = MainCU;
1763 if (!Unit)
1764 Unit = &FindCompileUnit(SP.getCompileUnit());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001765 GlobalVariable *GV = SP.getGV();
1766 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1767 II = AbstractInstanceRootMap.find(GV);
1768
1769 if (II == AbstractInstanceRootMap.end()) {
1770 // Create an abstract instance entry for this inlined function if it doesn't
1771 // already exist.
1772 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
1773
1774 // Get the compile unit context.
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001775 DIE *SPDie = Unit->getDieMapSlotFor(GV);
1776 if (!SPDie)
1777 SPDie = CreateSubprogramDIE(Unit, SP, false, true);
1778
1779 // Mark as being inlined. This makes this subprogram entry an abstract
1780 // instance root.
1781 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1782 // that it's defined. That probably won't change in the future. However,
1783 // this could be more elegant.
1784 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1785
1786 // Keep track of the abstract scope for this function.
1787 DbgAbstractScopeMap[GV] = Scope;
1788
1789 AbstractInstanceRootMap[GV] = Scope;
1790 AbstractInstanceRootList.push_back(Scope);
1791 }
1792
1793 // Create a concrete inlined instance for this inlined function.
1794 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
1795 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001796 ScopeDie->setAbstractCompileUnit(Unit);
1797
1798 DIE *Origin = Unit->getDieMapSlotFor(GV);
1799 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1800 dwarf::DW_FORM_ref4, Origin);
1801 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
1802 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1803 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1804
1805 ConcreteScope->setDie(ScopeDie);
1806 ConcreteScope->setStartLabelID(LabelID);
1807 MMI->RecordUsedDbgLabel(LabelID);
1808
1809 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
1810
1811 // Keep track of the concrete scope that's inlined into this function.
1812 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1813 SI = DbgConcreteScopeMap.find(GV);
1814
1815 if (SI == DbgConcreteScopeMap.end())
1816 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
1817 else
1818 SI->second.push_back(ConcreteScope);
1819
1820 // Track the start label for this inlined function.
1821 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1822 I = InlineInfo.find(GV);
1823
1824 if (I == InlineInfo.end())
1825 InlineInfo[GV].push_back(LabelID);
1826 else
1827 I->second.push_back(LabelID);
1828
1829 if (TimePassesIsEnabled)
1830 DebugTimer->stopTimer();
1831
1832 return LabelID;
1833}
1834
1835/// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
1836unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
1837 if (!TAI->doesDwarfUsesInlineInfoSection())
1838 return 0;
1839
1840 if (TimePassesIsEnabled)
1841 DebugTimer->startTimer();
1842
1843 GlobalVariable *GV = SP.getGV();
1844 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1845 I = DbgConcreteScopeMap.find(GV);
1846
1847 if (I == DbgConcreteScopeMap.end()) {
1848 // FIXME: Can this situation actually happen? And if so, should it?
1849 if (TimePassesIsEnabled)
1850 DebugTimer->stopTimer();
1851
1852 return 0;
1853 }
1854
1855 SmallVector<DbgScope *, 8> &Scopes = I->second;
Devang Patel11a407f2009-06-15 21:45:50 +00001856 if (Scopes.empty()) {
1857 // Returned ID is 0 if this is unbalanced "end of inlined
1858 // scope". This could happen if optimizer eats dbg intrinsics
1859 // or "beginning of inlined scope" is not recoginized due to
1860 // missing location info. In such cases, ignore this region.end.
1861 return 0;
1862 }
1863
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001864 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
1865 unsigned ID = MMI->NextLabelID();
1866 MMI->RecordUsedDbgLabel(ID);
1867 Scope->setEndLabelID(ID);
1868
1869 if (TimePassesIsEnabled)
1870 DebugTimer->stopTimer();
1871
1872 return ID;
1873}
1874
1875/// RecordVariableScope - Record scope for the variable declared by
1876/// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
1877/// for only inlined subroutine variables. Other variables's scopes are
1878/// determined during RecordVariable().
1879void DwarfDebug::RecordVariableScope(DIVariable &DV,
1880 const MachineInstr *DeclareMI) {
1881 if (TimePassesIsEnabled)
1882 DebugTimer->startTimer();
1883
1884 DISubprogram SP(DV.getContext().getGV());
1885
1886 if (SP.isNull()) {
1887 if (TimePassesIsEnabled)
1888 DebugTimer->stopTimer();
1889
1890 return;
1891 }
1892
1893 DenseMap<GlobalVariable *, DbgScope *>::iterator
1894 I = DbgAbstractScopeMap.find(SP.getGV());
1895 if (I != DbgAbstractScopeMap.end())
1896 InlinedVariableScopes[DeclareMI] = I->second;
1897
1898 if (TimePassesIsEnabled)
1899 DebugTimer->stopTimer();
1900}
Bill Wendling94d04b82009-05-20 23:21:38 +00001901
Bill Wendling829e67b2009-05-20 23:22:40 +00001902//===----------------------------------------------------------------------===//
1903// Emit Methods
1904//===----------------------------------------------------------------------===//
1905
Bill Wendling94d04b82009-05-20 23:21:38 +00001906/// SizeAndOffsetDie - Compute the size and offset of a DIE.
1907///
1908unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1909 // Get the children.
1910 const std::vector<DIE *> &Children = Die->getChildren();
1911
1912 // If not last sibling and has children then add sibling offset attribute.
1913 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1914
1915 // Record the abbreviation.
1916 AssignAbbrevNumber(Die->getAbbrev());
1917
1918 // Get the abbreviation for this DIE.
1919 unsigned AbbrevNumber = Die->getAbbrevNumber();
1920 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1921
1922 // Set DIE offset
1923 Die->setOffset(Offset);
1924
1925 // Start the size with the size of abbreviation code.
1926 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1927
1928 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1929 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1930
1931 // Size the DIE attribute values.
1932 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1933 // Size attribute value.
1934 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1935
1936 // Size the DIE children if any.
1937 if (!Children.empty()) {
1938 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1939 "Children flag not set");
1940
1941 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1942 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1943
1944 // End of children marker.
1945 Offset += sizeof(int8_t);
1946 }
1947
1948 Die->setSize(Offset - Die->getOffset());
1949 return Offset;
1950}
1951
1952/// SizeAndOffsets - Compute the size and offset of all the DIEs.
1953///
1954void DwarfDebug::SizeAndOffsets() {
1955 // Compute size of compile unit header.
1956 static unsigned Offset =
1957 sizeof(int32_t) + // Length of Compilation Unit Info
1958 sizeof(int16_t) + // DWARF version number
1959 sizeof(int32_t) + // Offset Into Abbrev. Section
1960 sizeof(int8_t); // Pointer Size (in bytes)
1961
1962 // Process base compile unit.
1963 if (MainCU) {
1964 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1965 CompileUnitOffsets[MainCU] = 0;
1966 return;
1967 }
1968
1969 // Process all compile units.
1970 unsigned PrevOffset = 0;
1971
1972 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1973 CompileUnit *Unit = CompileUnits[i];
1974 CompileUnitOffsets[Unit] = PrevOffset;
1975 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1976 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1977 }
1978}
1979
1980/// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1981/// tools to recognize the object file contains Dwarf information.
1982void DwarfDebug::EmitInitial() {
1983 // Check to see if we already emitted intial headers.
1984 if (didInitial) return;
1985 didInitial = true;
1986
1987 // Dwarf sections base addresses.
1988 if (TAI->doesDwarfRequireFrameSection()) {
1989 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1990 EmitLabel("section_debug_frame", 0);
1991 }
1992
1993 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1994 EmitLabel("section_info", 0);
1995 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1996 EmitLabel("section_abbrev", 0);
1997 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1998 EmitLabel("section_aranges", 0);
1999
Chris Lattnerb839c3f2009-06-18 23:31:37 +00002000 if (const char *LineInfoDirective = TAI->getDwarfMacroInfoSection()) {
2001 Asm->SwitchToDataSection(LineInfoDirective);
Bill Wendling94d04b82009-05-20 23:21:38 +00002002 EmitLabel("section_macinfo", 0);
2003 }
2004
2005 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2006 EmitLabel("section_line", 0);
2007 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2008 EmitLabel("section_loc", 0);
2009 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2010 EmitLabel("section_pubnames", 0);
2011 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2012 EmitLabel("section_str", 0);
2013 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2014 EmitLabel("section_ranges", 0);
2015
2016 Asm->SwitchToSection(TAI->getTextSection());
2017 EmitLabel("text_begin", 0);
2018 Asm->SwitchToSection(TAI->getDataSection());
2019 EmitLabel("data_begin", 0);
2020}
2021
2022/// EmitDIE - Recusively Emits a debug information entry.
2023///
2024void DwarfDebug::EmitDIE(DIE *Die) {
2025 // Get the abbreviation for this DIE.
2026 unsigned AbbrevNumber = Die->getAbbrevNumber();
2027 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2028
2029 Asm->EOL();
2030
2031 // Emit the code (index) for the abbreviation.
2032 Asm->EmitULEB128Bytes(AbbrevNumber);
2033
2034 if (Asm->isVerbose())
2035 Asm->EOL(std::string("Abbrev [" +
2036 utostr(AbbrevNumber) +
2037 "] 0x" + utohexstr(Die->getOffset()) +
2038 ":0x" + utohexstr(Die->getSize()) + " " +
2039 dwarf::TagString(Abbrev->getTag())));
2040 else
2041 Asm->EOL();
2042
2043 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2044 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2045
2046 // Emit the DIE attribute values.
2047 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2048 unsigned Attr = AbbrevData[i].getAttribute();
2049 unsigned Form = AbbrevData[i].getForm();
2050 assert(Form && "Too many attributes for DIE (check abbreviation)");
2051
2052 switch (Attr) {
2053 case dwarf::DW_AT_sibling:
2054 Asm->EmitInt32(Die->SiblingOffset());
2055 break;
2056 case dwarf::DW_AT_abstract_origin: {
2057 DIEEntry *E = cast<DIEEntry>(Values[i]);
2058 DIE *Origin = E->getEntry();
2059 unsigned Addr =
2060 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
2061 Origin->getOffset();
2062
2063 Asm->EmitInt32(Addr);
2064 break;
2065 }
2066 default:
2067 // Emit an attribute using the defined form.
2068 Values[i]->EmitValue(this, Form);
2069 break;
2070 }
2071
2072 Asm->EOL(dwarf::AttributeString(Attr));
2073 }
2074
2075 // Emit the DIE children if any.
2076 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2077 const std::vector<DIE *> &Children = Die->getChildren();
2078
2079 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2080 EmitDIE(Children[j]);
2081
2082 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2083 }
2084}
2085
2086/// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2087///
2088void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2089 DIE *Die = Unit->getDie();
2090
2091 // Emit the compile units header.
2092 EmitLabel("info_begin", Unit->getID());
2093
2094 // Emit size of content not including length itself
2095 unsigned ContentSize = Die->getSize() +
2096 sizeof(int16_t) + // DWARF version number
2097 sizeof(int32_t) + // Offset Into Abbrev. Section
2098 sizeof(int8_t) + // Pointer Size (in bytes)
2099 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2100
2101 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2102 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2103 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2104 Asm->EOL("Offset Into Abbrev. Section");
2105 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2106
2107 EmitDIE(Die);
2108 // FIXME - extra padding for gdb bug.
2109 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2110 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2111 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2112 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2113 EmitLabel("info_end", Unit->getID());
2114
2115 Asm->EOL();
2116}
2117
2118void DwarfDebug::EmitDebugInfo() {
2119 // Start debug info section.
2120 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2121
2122 if (MainCU) {
2123 EmitDebugInfoPerCU(MainCU);
2124 return;
2125 }
2126
2127 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2128 EmitDebugInfoPerCU(CompileUnits[i]);
2129}
2130
2131/// EmitAbbreviations - Emit the abbreviation section.
2132///
2133void DwarfDebug::EmitAbbreviations() const {
2134 // Check to see if it is worth the effort.
2135 if (!Abbreviations.empty()) {
2136 // Start the debug abbrev section.
2137 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2138
2139 EmitLabel("abbrev_begin", 0);
2140
2141 // For each abbrevation.
2142 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2143 // Get abbreviation data
2144 const DIEAbbrev *Abbrev = Abbreviations[i];
2145
2146 // Emit the abbrevations code (base 1 index.)
2147 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2148 Asm->EOL("Abbreviation Code");
2149
2150 // Emit the abbreviations data.
2151 Abbrev->Emit(Asm);
2152
2153 Asm->EOL();
2154 }
2155
2156 // Mark end of abbreviations.
2157 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2158
2159 EmitLabel("abbrev_end", 0);
2160 Asm->EOL();
2161 }
2162}
2163
2164/// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2165/// the line matrix.
2166///
2167void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2168 // Define last address of section.
2169 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2170 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2171 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2172 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2173
2174 // Mark end of matrix.
2175 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2176 Asm->EmitULEB128Bytes(1); Asm->EOL();
2177 Asm->EmitInt8(1); Asm->EOL();
2178}
2179
2180/// EmitDebugLines - Emit source line information.
2181///
2182void DwarfDebug::EmitDebugLines() {
2183 // If the target is using .loc/.file, the assembler will be emitting the
2184 // .debug_line table automatically.
2185 if (TAI->hasDotLocAndDotFile())
2186 return;
2187
2188 // Minimum line delta, thus ranging from -10..(255-10).
2189 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2190 // Maximum line delta, thus ranging from -10..(255-10).
2191 const int MaxLineDelta = 255 + MinLineDelta;
2192
2193 // Start the dwarf line section.
2194 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2195
2196 // Construct the section header.
2197 EmitDifference("line_end", 0, "line_begin", 0, true);
2198 Asm->EOL("Length of Source Line Info");
2199 EmitLabel("line_begin", 0);
2200
2201 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2202
2203 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2204 Asm->EOL("Prolog Length");
2205 EmitLabel("line_prolog_begin", 0);
2206
2207 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2208
2209 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2210
2211 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2212
2213 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2214
2215 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2216
2217 // Line number standard opcode encodings argument count
2218 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2219 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2220 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2221 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2222 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2223 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2224 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2225 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2226 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2227
2228 // Emit directories.
2229 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2230 Asm->EmitString(getSourceDirectoryName(DI));
2231 Asm->EOL("Directory");
2232 }
2233
2234 Asm->EmitInt8(0); Asm->EOL("End of directories");
2235
2236 // Emit files.
2237 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2238 // Remember source id starts at 1.
2239 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2240 Asm->EmitString(getSourceFileName(Id.second));
2241 Asm->EOL("Source");
2242 Asm->EmitULEB128Bytes(Id.first);
2243 Asm->EOL("Directory #");
2244 Asm->EmitULEB128Bytes(0);
2245 Asm->EOL("Mod date");
2246 Asm->EmitULEB128Bytes(0);
2247 Asm->EOL("File size");
2248 }
2249
2250 Asm->EmitInt8(0); Asm->EOL("End of files");
2251
2252 EmitLabel("line_prolog_end", 0);
2253
2254 // A sequence for each text section.
2255 unsigned SecSrcLinesSize = SectionSourceLines.size();
2256
2257 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2258 // Isolate current sections line info.
2259 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2260
2261 if (Asm->isVerbose()) {
2262 const Section* S = SectionMap[j + 1];
2263 O << '\t' << TAI->getCommentString() << " Section"
2264 << S->getName() << '\n';
2265 } else {
2266 Asm->EOL();
2267 }
2268
2269 // Dwarf assumes we start with first line of first source file.
2270 unsigned Source = 1;
2271 unsigned Line = 1;
2272
2273 // Construct rows of the address, source, line, column matrix.
2274 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2275 const SrcLineInfo &LineInfo = LineInfos[i];
2276 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2277 if (!LabelID) continue;
2278
2279 if (!Asm->isVerbose())
2280 Asm->EOL();
2281 else {
2282 std::pair<unsigned, unsigned> SourceID =
2283 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2284 O << '\t' << TAI->getCommentString() << ' '
2285 << getSourceDirectoryName(SourceID.first) << ' '
2286 << getSourceFileName(SourceID.second)
2287 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2288 }
2289
2290 // Define the line address.
2291 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2292 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2293 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2294 EmitReference("label", LabelID); Asm->EOL("Location label");
2295
2296 // If change of source, then switch to the new source.
2297 if (Source != LineInfo.getSourceID()) {
2298 Source = LineInfo.getSourceID();
2299 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2300 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2301 }
2302
2303 // If change of line.
2304 if (Line != LineInfo.getLine()) {
2305 // Determine offset.
2306 int Offset = LineInfo.getLine() - Line;
2307 int Delta = Offset - MinLineDelta;
2308
2309 // Update line.
2310 Line = LineInfo.getLine();
2311
2312 // If delta is small enough and in range...
2313 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2314 // ... then use fast opcode.
2315 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2316 } else {
2317 // ... otherwise use long hand.
2318 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2319 Asm->EOL("DW_LNS_advance_line");
2320 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2321 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2322 }
2323 } else {
2324 // Copy the previous row (different address or source)
2325 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2326 }
2327 }
2328
2329 EmitEndOfLineMatrix(j + 1);
2330 }
2331
2332 if (SecSrcLinesSize == 0)
2333 // Because we're emitting a debug_line section, we still need a line
2334 // table. The linker and friends expect it to exist. If there's nothing to
2335 // put into it, emit an empty table.
2336 EmitEndOfLineMatrix(1);
2337
2338 EmitLabel("line_end", 0);
2339 Asm->EOL();
2340}
2341
2342/// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2343///
2344void DwarfDebug::EmitCommonDebugFrame() {
2345 if (!TAI->doesDwarfRequireFrameSection())
2346 return;
2347
2348 int stackGrowth =
2349 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2350 TargetFrameInfo::StackGrowsUp ?
2351 TD->getPointerSize() : -TD->getPointerSize();
2352
2353 // Start the dwarf frame section.
2354 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2355
2356 EmitLabel("debug_frame_common", 0);
2357 EmitDifference("debug_frame_common_end", 0,
2358 "debug_frame_common_begin", 0, true);
2359 Asm->EOL("Length of Common Information Entry");
2360
2361 EmitLabel("debug_frame_common_begin", 0);
2362 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2363 Asm->EOL("CIE Identifier Tag");
2364 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2365 Asm->EOL("CIE Version");
2366 Asm->EmitString("");
2367 Asm->EOL("CIE Augmentation");
2368 Asm->EmitULEB128Bytes(1);
2369 Asm->EOL("CIE Code Alignment Factor");
2370 Asm->EmitSLEB128Bytes(stackGrowth);
2371 Asm->EOL("CIE Data Alignment Factor");
2372 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2373 Asm->EOL("CIE RA Column");
2374
2375 std::vector<MachineMove> Moves;
2376 RI->getInitialFrameState(Moves);
2377
2378 EmitFrameMoves(NULL, 0, Moves, false);
2379
2380 Asm->EmitAlignment(2, 0, 0, false);
2381 EmitLabel("debug_frame_common_end", 0);
2382
2383 Asm->EOL();
2384}
2385
2386/// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2387/// section.
2388void
2389DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2390 if (!TAI->doesDwarfRequireFrameSection())
2391 return;
2392
2393 // Start the dwarf frame section.
2394 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2395
2396 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2397 "debug_frame_begin", DebugFrameInfo.Number, true);
2398 Asm->EOL("Length of Frame Information Entry");
2399
2400 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2401
2402 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2403 0, 0, true, false);
2404 Asm->EOL("FDE CIE offset");
2405
2406 EmitReference("func_begin", DebugFrameInfo.Number);
2407 Asm->EOL("FDE initial location");
2408 EmitDifference("func_end", DebugFrameInfo.Number,
2409 "func_begin", DebugFrameInfo.Number);
2410 Asm->EOL("FDE address range");
2411
2412 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2413 false);
2414
2415 Asm->EmitAlignment(2, 0, 0, false);
2416 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2417
2418 Asm->EOL();
2419}
2420
2421void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2422 EmitDifference("pubnames_end", Unit->getID(),
2423 "pubnames_begin", Unit->getID(), true);
2424 Asm->EOL("Length of Public Names Info");
2425
2426 EmitLabel("pubnames_begin", Unit->getID());
2427
2428 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2429
2430 EmitSectionOffset("info_begin", "section_info",
2431 Unit->getID(), 0, true, false);
2432 Asm->EOL("Offset of Compilation Unit Info");
2433
2434 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2435 true);
2436 Asm->EOL("Compilation Unit Length");
2437
2438 StringMap<DIE*> &Globals = Unit->getGlobals();
2439 for (StringMap<DIE*>::const_iterator
2440 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2441 const char *Name = GI->getKeyData();
2442 DIE * Entity = GI->second;
2443
2444 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2445 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2446 }
2447
2448 Asm->EmitInt32(0); Asm->EOL("End Mark");
2449 EmitLabel("pubnames_end", Unit->getID());
2450
2451 Asm->EOL();
2452}
2453
2454/// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2455///
2456void DwarfDebug::EmitDebugPubNames() {
2457 // Start the dwarf pubnames section.
2458 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2459
2460 if (MainCU) {
2461 EmitDebugPubNamesPerCU(MainCU);
2462 return;
2463 }
2464
2465 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2466 EmitDebugPubNamesPerCU(CompileUnits[i]);
2467}
2468
2469/// EmitDebugStr - Emit visible names into a debug str section.
2470///
2471void DwarfDebug::EmitDebugStr() {
2472 // Check to see if it is worth the effort.
2473 if (!StringPool.empty()) {
2474 // Start the dwarf str section.
2475 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2476
2477 // For each of strings in the string pool.
2478 for (unsigned StringID = 1, N = StringPool.size();
2479 StringID <= N; ++StringID) {
2480 // Emit a label for reference from debug information entries.
2481 EmitLabel("string", StringID);
2482
2483 // Emit the string itself.
2484 const std::string &String = StringPool[StringID];
2485 Asm->EmitString(String); Asm->EOL();
2486 }
2487
2488 Asm->EOL();
2489 }
2490}
2491
2492/// EmitDebugLoc - Emit visible names into a debug loc section.
2493///
2494void DwarfDebug::EmitDebugLoc() {
2495 // Start the dwarf loc section.
2496 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2497 Asm->EOL();
2498}
2499
2500/// EmitDebugARanges - Emit visible names into a debug aranges section.
2501///
2502void DwarfDebug::EmitDebugARanges() {
2503 // Start the dwarf aranges section.
2504 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2505
2506 // FIXME - Mock up
2507#if 0
2508 CompileUnit *Unit = GetBaseCompileUnit();
2509
2510 // Don't include size of length
2511 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2512
2513 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2514
2515 EmitReference("info_begin", Unit->getID());
2516 Asm->EOL("Offset of Compilation Unit Info");
2517
2518 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2519
2520 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2521
2522 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2523 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2524
2525 // Range 1
2526 EmitReference("text_begin", 0); Asm->EOL("Address");
2527 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2528
2529 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2530 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2531#endif
2532
2533 Asm->EOL();
2534}
2535
2536/// EmitDebugRanges - Emit visible names into a debug ranges section.
2537///
2538void DwarfDebug::EmitDebugRanges() {
2539 // Start the dwarf ranges section.
2540 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2541 Asm->EOL();
2542}
2543
2544/// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2545///
2546void DwarfDebug::EmitDebugMacInfo() {
Chris Lattnerb839c3f2009-06-18 23:31:37 +00002547 if (const char *LineInfoDirective = TAI->getDwarfMacroInfoSection()) {
Bill Wendling94d04b82009-05-20 23:21:38 +00002548 // Start the dwarf macinfo section.
Chris Lattnerb839c3f2009-06-18 23:31:37 +00002549 Asm->SwitchToDataSection(LineInfoDirective);
Bill Wendling94d04b82009-05-20 23:21:38 +00002550 Asm->EOL();
2551 }
2552}
2553
2554/// EmitDebugInlineInfo - Emit inline info using following format.
2555/// Section Header:
2556/// 1. length of section
2557/// 2. Dwarf version number
2558/// 3. address size.
2559///
2560/// Entries (one "entry" for each function that was inlined):
2561///
2562/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2563/// otherwise offset into __debug_str for regular function name.
2564/// 2. offset into __debug_str section for regular function name.
2565/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2566/// instances for the function.
2567///
2568/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2569/// inlined instance; the die_offset points to the inlined_subroutine die in the
2570/// __debug_info section, and the low_pc is the starting address for the
2571/// inlining instance.
2572void DwarfDebug::EmitDebugInlineInfo() {
2573 if (!TAI->doesDwarfUsesInlineInfoSection())
2574 return;
2575
2576 if (!MainCU)
2577 return;
2578
2579 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2580 Asm->EOL();
2581 EmitDifference("debug_inlined_end", 1,
2582 "debug_inlined_begin", 1, true);
2583 Asm->EOL("Length of Debug Inlined Information Entry");
2584
2585 EmitLabel("debug_inlined_begin", 1);
2586
2587 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2588 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2589
2590 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2591 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2592 GlobalVariable *GV = I->first;
2593 SmallVector<unsigned, 4> &Labels = I->second;
2594 DISubprogram SP(GV);
2595 std::string Name;
2596 std::string LName;
2597
2598 SP.getLinkageName(LName);
2599 SP.getName(Name);
2600
2601 Asm->EmitString(LName.empty() ? Name : LName);
2602 Asm->EOL("MIPS linkage name");
2603
2604 Asm->EmitString(Name); Asm->EOL("Function name");
2605
2606 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2607
2608 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2609 LE = Labels.end(); LI != LE; ++LI) {
2610 DIE *SP = MainCU->getDieMapSlotFor(GV);
2611 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2612
2613 if (TD->getPointerSize() == sizeof(int32_t))
2614 O << TAI->getData32bitsDirective();
2615 else
2616 O << TAI->getData64bitsDirective();
2617
2618 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2619 }
2620 }
2621
2622 EmitLabel("debug_inlined_end", 1);
2623 Asm->EOL();
2624}