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