Split out the Dwarf writer stuff into separate files. This is a much more
[llvm/msp430.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
blob83275fb92eb01c91ea4a487d7e5c5a8a3b71851a
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf 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 info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
15 #include "DIE.h"
16 #include "DwarfPrinter.h"
17 #include "llvm/Module.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineLocation.h"
24 #include "llvm/Analysis/DebugInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/DataTypes.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Support/Timer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/System/Path.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetFrameInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/FoldingSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/StringMap.h"
44 #include <ostream>
45 #include <string>
46 using namespace llvm;
47 using namespace llvm::dwarf;
49 static RegisterPass<DwarfWriter>
50 X("dwarfwriter", "DWARF Information Writer");
51 char DwarfWriter::ID = 0;
53 static TimerGroup &getDwarfTimerGroup() {
54 static TimerGroup DwarfTimerGroup("Dwarf Exception and Debugging");
55 return DwarfTimerGroup;
58 namespace llvm {
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
63 ///
64 static const unsigned InitDiesSetSize = 9; // log2(512)
65 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
66 static const unsigned InitValuesSetSize = 9; // log2(512)
68 //===----------------------------------------------------------------------===//
69 /// CompileUnit - This dwarf writer support class manages information associate
70 /// with a source file.
71 class CompileUnit {
72 /// ID - File identifier for source.
73 ///
74 unsigned ID;
76 /// Die - Compile unit debug information entry.
77 ///
78 DIE *Die;
80 /// GVToDieMap - Tracks the mapping of unit level debug informaton
81 /// variables to debug information entries.
82 std::map<GlobalVariable *, DIE *> GVToDieMap;
84 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
85 /// descriptors to debug information entries using a DIEEntry proxy.
86 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
88 /// Globals - A map of globally visible named entities for this unit.
89 ///
90 StringMap<DIE*> Globals;
92 /// DiesSet - Used to uniquely define dies within the compile unit.
93 ///
94 FoldingSet<DIE> DiesSet;
95 public:
96 CompileUnit(unsigned I, DIE *D)
97 : ID(I), Die(D), GVToDieMap(),
98 GVToDIEEntryMap(), Globals(), DiesSet(InitDiesSetSize)
101 ~CompileUnit() {
102 delete Die;
105 // Accessors.
106 unsigned getID() const { return ID; }
107 DIE* getDie() const { return Die; }
108 StringMap<DIE*> &getGlobals() { return Globals; }
110 /// hasContent - Return true if this compile unit has something to write out.
112 bool hasContent() const {
113 return !Die->getChildren().empty();
116 /// AddGlobal - Add a new global entity to the compile unit.
118 void AddGlobal(const std::string &Name, DIE *Die) {
119 Globals[Name] = Die;
122 /// getDieMapSlotFor - Returns the debug information entry map slot for the
123 /// specified debug variable.
124 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
125 return GVToDieMap[GV];
128 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
129 /// specified debug variable.
130 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
131 return GVToDIEEntryMap[GV];
134 /// AddDie - Adds or interns the DIE to the compile unit.
136 DIE *AddDie(DIE &Buffer) {
137 FoldingSetNodeID ID;
138 Buffer.Profile(ID);
139 void *Where;
140 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
142 if (!Die) {
143 Die = new DIE(Buffer);
144 DiesSet.InsertNode(Die, Where);
145 this->Die->AddChild(Die);
146 Buffer.Detach();
149 return Die;
153 //===----------------------------------------------------------------------===//
154 /// SrcLineInfo - This class is used to record source line correspondence.
156 class SrcLineInfo {
157 unsigned Line; // Source line number.
158 unsigned Column; // Source column.
159 unsigned SourceID; // Source ID number.
160 unsigned LabelID; // Label in code ID number.
161 public:
162 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
163 : Line(L), Column(C), SourceID(S), LabelID(I) {}
165 // Accessors
166 unsigned getLine() const { return Line; }
167 unsigned getColumn() const { return Column; }
168 unsigned getSourceID() const { return SourceID; }
169 unsigned getLabelID() const { return LabelID; }
172 //===----------------------------------------------------------------------===//
173 /// DbgVariable - This class is used to track local variable information.
175 class DbgVariable {
176 DIVariable Var; // Variable Descriptor.
177 unsigned FrameIndex; // Variable frame index.
178 public:
179 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
181 // Accessors.
182 DIVariable getVariable() const { return Var; }
183 unsigned getFrameIndex() const { return FrameIndex; }
186 //===----------------------------------------------------------------------===//
187 /// DbgScope - This class is used to track scope information.
189 class DbgConcreteScope;
190 class DbgScope {
191 DbgScope *Parent; // Parent to this scope.
192 DIDescriptor Desc; // Debug info descriptor for scope.
193 // Either subprogram or block.
194 unsigned StartLabelID; // Label ID of the beginning of scope.
195 unsigned EndLabelID; // Label ID of the end of scope.
196 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
197 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
198 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
199 public:
200 DbgScope(DbgScope *P, DIDescriptor D)
201 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
202 virtual ~DbgScope();
204 // Accessors.
205 DbgScope *getParent() const { return Parent; }
206 DIDescriptor getDesc() const { return Desc; }
207 unsigned getStartLabelID() const { return StartLabelID; }
208 unsigned getEndLabelID() const { return EndLabelID; }
209 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
210 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
211 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
212 void setStartLabelID(unsigned S) { StartLabelID = S; }
213 void setEndLabelID(unsigned E) { EndLabelID = E; }
215 /// AddScope - Add a scope to the scope.
217 void AddScope(DbgScope *S) { Scopes.push_back(S); }
219 /// AddVariable - Add a variable to the scope.
221 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
223 /// AddConcreteInst - Add a concrete instance to the scope.
225 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
227 #ifndef NDEBUG
228 void dump() const;
229 #endif
232 #ifndef NDEBUG
233 void DbgScope::dump() const {
234 static unsigned IndentLevel = 0;
235 std::string Indent(IndentLevel, ' ');
237 cerr << Indent; Desc.dump();
238 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
240 IndentLevel += 2;
242 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
243 if (Scopes[i] != this)
244 Scopes[i]->dump();
246 IndentLevel -= 2;
248 #endif
250 //===----------------------------------------------------------------------===//
251 /// DbgConcreteScope - This class is used to track a scope that holds concrete
252 /// instance information.
253 ///
254 class DbgConcreteScope : public DbgScope {
255 CompileUnit *Unit;
256 DIE *Die; // Debug info for this concrete scope.
257 public:
258 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
260 // Accessors.
261 DIE *getDie() const { return Die; }
262 void setDie(DIE *D) { Die = D; }
265 DbgScope::~DbgScope() {
266 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
267 delete Scopes[i];
268 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
269 delete Variables[j];
270 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
271 delete ConcreteInsts[k];
274 //===----------------------------------------------------------------------===//
275 /// DwarfDebug - Emits Dwarf debug directives.
277 class DwarfDebug : public Dwarf {
278 //===--------------------------------------------------------------------===//
279 // Attributes used to construct specific Dwarf sections.
282 /// CompileUnitMap - A map of global variables representing compile units to
283 /// compile units.
284 DenseMap<Value *, CompileUnit *> CompileUnitMap;
286 /// CompileUnits - All the compile units in this module.
288 SmallVector<CompileUnit *, 8> CompileUnits;
290 /// MainCU - Some platform prefers one compile unit per .o file. In such
291 /// cases, all dies are inserted in MainCU.
292 CompileUnit *MainCU;
294 /// AbbreviationsSet - Used to uniquely define abbreviations.
296 FoldingSet<DIEAbbrev> AbbreviationsSet;
298 /// Abbreviations - A list of all the unique abbreviations in use.
300 std::vector<DIEAbbrev *> Abbreviations;
302 /// DirectoryIdMap - Directory name to directory id map.
304 StringMap<unsigned> DirectoryIdMap;
306 /// DirectoryNames - A list of directory names.
307 SmallVector<std::string, 8> DirectoryNames;
309 /// SourceFileIdMap - Source file name to source file id map.
311 StringMap<unsigned> SourceFileIdMap;
313 /// SourceFileNames - A list of source file names.
314 SmallVector<std::string, 8> SourceFileNames;
316 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
317 /// id mapped to a unique id.
318 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
320 /// SourceIds - Reverse map from source id to directory id + file id pair.
322 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
324 /// Lines - List of of source line correspondence.
325 std::vector<SrcLineInfo> Lines;
327 /// ValuesSet - Used to uniquely define values.
329 FoldingSet<DIEValue> ValuesSet;
331 /// Values - A list of all the unique values in use.
333 std::vector<DIEValue *> Values;
335 /// StringPool - A UniqueVector of strings used by indirect references.
337 UniqueVector<std::string> StringPool;
339 /// SectionMap - Provides a unique id per text section.
341 UniqueVector<const Section*> SectionMap;
343 /// SectionSourceLines - Tracks line numbers per text section.
345 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
347 /// didInitial - Flag to indicate if initial emission has been done.
349 bool didInitial;
351 /// shouldEmit - Flag to indicate if debug information should be emitted.
353 bool shouldEmit;
355 // FunctionDbgScope - Top level scope for the current function.
357 DbgScope *FunctionDbgScope;
359 /// DbgScopeMap - Tracks the scopes in the current function.
360 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
362 /// DbgAbstractScopeMap - Tracks abstract instance scopes in the current
363 /// function.
364 DenseMap<GlobalVariable *, DbgScope *> DbgAbstractScopeMap;
366 /// DbgConcreteScopeMap - Tracks concrete instance scopes in the current
367 /// function.
368 DenseMap<GlobalVariable *,
369 SmallVector<DbgScope *, 8> > DbgConcreteScopeMap;
371 /// InlineInfo - Keep track of inlined functions and their location. This
372 /// information is used to populate debug_inlined section.
373 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> > InlineInfo;
375 /// InlinedVariableScopes - Scopes information for the inlined subroutine
376 /// variables.
377 DenseMap<const MachineInstr *, DbgScope *> InlinedVariableScopes;
379 /// AbstractInstanceRootMap - Map of abstract instance roots of inlined
380 /// functions. These are subroutine entries that contain a DW_AT_inline
381 /// attribute.
382 DenseMap<const GlobalVariable *, DbgScope *> AbstractInstanceRootMap;
384 /// AbstractInstanceRootList - List of abstract instance roots of inlined
385 /// functions. These are subroutine entries that contain a DW_AT_inline
386 /// attribute.
387 SmallVector<DbgScope *, 32> AbstractInstanceRootList;
389 /// LexicalScopeStack - A stack of lexical scopes. The top one is the current
390 /// scope.
391 SmallVector<DbgScope *, 16> LexicalScopeStack;
393 /// CompileUnitOffsets - A vector of the offsets of the compile units. This is
394 /// used when calculating the "origin" of a concrete instance of an inlined
395 /// function.
396 DenseMap<CompileUnit *, unsigned> CompileUnitOffsets;
398 /// DebugTimer - Timer for the Dwarf debug writer.
399 Timer *DebugTimer;
401 struct FunctionDebugFrameInfo {
402 unsigned Number;
403 std::vector<MachineMove> Moves;
405 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
406 Number(Num), Moves(M) { }
409 std::vector<FunctionDebugFrameInfo> DebugFrames;
411 private:
412 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
413 /// maps to the source id. Source id starts at 1.
414 std::pair<unsigned, unsigned>
415 getSourceDirectoryAndFileIds(unsigned SId) const {
416 return SourceIds[SId-1];
419 /// getNumSourceDirectories - Return the number of source directories in the
420 /// debug info.
421 unsigned getNumSourceDirectories() const {
422 return DirectoryNames.size();
425 /// getSourceDirectoryName - Return the name of the directory corresponding
426 /// to the id.
427 const std::string &getSourceDirectoryName(unsigned Id) const {
428 return DirectoryNames[Id - 1];
431 /// getSourceFileName - Return the name of the source file corresponding
432 /// to the id.
433 const std::string &getSourceFileName(unsigned Id) const {
434 return SourceFileNames[Id - 1];
437 /// getNumSourceIds - Return the number of unique source ids.
438 unsigned getNumSourceIds() const {
439 return SourceIds.size();
442 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
444 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
445 // Profile the node so that we can make it unique.
446 FoldingSetNodeID ID;
447 Abbrev.Profile(ID);
449 // Check the set for priors.
450 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
452 // If it's newly added.
453 if (InSet == &Abbrev) {
454 // Add to abbreviation list.
455 Abbreviations.push_back(&Abbrev);
456 // Assign the vector position + 1 as its number.
457 Abbrev.setNumber(Abbreviations.size());
458 } else {
459 // Assign existing abbreviation number.
460 Abbrev.setNumber(InSet->getNumber());
464 /// NewString - Add a string to the constant pool and returns a label.
466 DWLabel NewString(const std::string &String) {
467 unsigned StringID = StringPool.insert(String);
468 return DWLabel("string", StringID);
471 /// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
472 /// entry.
473 DIEEntry *NewDIEEntry(DIE *Entry = NULL) {
474 DIEEntry *Value;
476 if (Entry) {
477 FoldingSetNodeID ID;
478 DIEEntry::Profile(ID, Entry);
479 void *Where;
480 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
482 if (Value) return Value;
484 Value = new DIEEntry(Entry);
485 ValuesSet.InsertNode(Value, Where);
486 } else {
487 Value = new DIEEntry(Entry);
490 Values.push_back(Value);
491 return Value;
494 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
496 void SetDIEEntry(DIEEntry *Value, DIE *Entry) {
497 Value->setEntry(Entry);
498 // Add to values set if not already there. If it is, we merely have a
499 // duplicate in the values list (no harm.)
500 ValuesSet.GetOrInsertNode(Value);
503 /// AddUInt - Add an unsigned integer attribute data and value.
505 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
506 if (!Form) Form = DIEInteger::BestForm(false, Integer);
508 FoldingSetNodeID ID;
509 DIEInteger::Profile(ID, Integer);
510 void *Where;
511 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
512 if (!Value) {
513 Value = new DIEInteger(Integer);
514 ValuesSet.InsertNode(Value, Where);
515 Values.push_back(Value);
518 Die->AddValue(Attribute, Form, Value);
521 /// AddSInt - Add an signed integer attribute data and value.
523 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
524 if (!Form) Form = DIEInteger::BestForm(true, Integer);
526 FoldingSetNodeID ID;
527 DIEInteger::Profile(ID, (uint64_t)Integer);
528 void *Where;
529 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
530 if (!Value) {
531 Value = new DIEInteger(Integer);
532 ValuesSet.InsertNode(Value, Where);
533 Values.push_back(Value);
536 Die->AddValue(Attribute, Form, Value);
539 /// AddString - Add a string attribute data and value.
541 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
542 const std::string &String) {
543 FoldingSetNodeID ID;
544 DIEString::Profile(ID, String);
545 void *Where;
546 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
547 if (!Value) {
548 Value = new DIEString(String);
549 ValuesSet.InsertNode(Value, Where);
550 Values.push_back(Value);
553 Die->AddValue(Attribute, Form, Value);
556 /// AddLabel - Add a Dwarf label attribute data and value.
558 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
559 const DWLabel &Label) {
560 FoldingSetNodeID ID;
561 DIEDwarfLabel::Profile(ID, Label);
562 void *Where;
563 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
564 if (!Value) {
565 Value = new DIEDwarfLabel(Label);
566 ValuesSet.InsertNode(Value, Where);
567 Values.push_back(Value);
570 Die->AddValue(Attribute, Form, Value);
573 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
575 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
576 const std::string &Label) {
577 FoldingSetNodeID ID;
578 DIEObjectLabel::Profile(ID, Label);
579 void *Where;
580 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
581 if (!Value) {
582 Value = new DIEObjectLabel(Label);
583 ValuesSet.InsertNode(Value, Where);
584 Values.push_back(Value);
587 Die->AddValue(Attribute, Form, Value);
590 /// AddSectionOffset - Add a section offset label attribute data and value.
592 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
593 const DWLabel &Label, const DWLabel &Section,
594 bool isEH = false, bool useSet = true) {
595 FoldingSetNodeID ID;
596 DIESectionOffset::Profile(ID, Label, Section);
597 void *Where;
598 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
599 if (!Value) {
600 Value = new DIESectionOffset(Label, Section, isEH, useSet);
601 ValuesSet.InsertNode(Value, Where);
602 Values.push_back(Value);
605 Die->AddValue(Attribute, Form, Value);
608 /// AddDelta - Add a label delta attribute data and value.
610 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
611 const DWLabel &Hi, const DWLabel &Lo) {
612 FoldingSetNodeID ID;
613 DIEDelta::Profile(ID, Hi, Lo);
614 void *Where;
615 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
616 if (!Value) {
617 Value = new DIEDelta(Hi, Lo);
618 ValuesSet.InsertNode(Value, Where);
619 Values.push_back(Value);
622 Die->AddValue(Attribute, Form, Value);
625 /// AddDIEEntry - Add a DIE attribute data and value.
627 void AddDIEEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
628 Die->AddValue(Attribute, Form, NewDIEEntry(Entry));
631 /// AddBlock - Add block data.
633 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
634 Block->ComputeSize(TD);
635 FoldingSetNodeID ID;
636 Block->Profile(ID);
637 void *Where;
638 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
639 if (!Value) {
640 Value = Block;
641 ValuesSet.InsertNode(Value, Where);
642 Values.push_back(Value);
643 } else {
644 // Already exists, reuse the previous one.
645 delete Block;
646 Block = cast<DIEBlock>(Value);
649 Die->AddValue(Attribute, Block->BestForm(), Value);
652 /// AddSourceLine - Add location information to specified debug information
653 /// entry.
654 void AddSourceLine(DIE *Die, const DIVariable *V) {
655 // If there is no compile unit specified, don't add a line #.
656 if (V->getCompileUnit().isNull())
657 return;
659 unsigned Line = V->getLineNumber();
660 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
661 assert(FileID && "Invalid file id");
662 AddUInt(Die, DW_AT_decl_file, 0, FileID);
663 AddUInt(Die, DW_AT_decl_line, 0, Line);
666 /// AddSourceLine - Add location information to specified debug information
667 /// entry.
668 void AddSourceLine(DIE *Die, const DIGlobal *G) {
669 // If there is no compile unit specified, don't add a line #.
670 if (G->getCompileUnit().isNull())
671 return;
672 unsigned Line = G->getLineNumber();
673 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
674 assert(FileID && "Invalid file id");
675 AddUInt(Die, DW_AT_decl_file, 0, FileID);
676 AddUInt(Die, DW_AT_decl_line, 0, Line);
679 void AddSourceLine(DIE *Die, const DIType *Ty) {
680 // If there is no compile unit specified, don't add a line #.
681 DICompileUnit CU = Ty->getCompileUnit();
682 if (CU.isNull())
683 return;
685 unsigned Line = Ty->getLineNumber();
686 unsigned FileID = FindCompileUnit(CU).getID();
687 assert(FileID && "Invalid file id");
688 AddUInt(Die, DW_AT_decl_file, 0, FileID);
689 AddUInt(Die, DW_AT_decl_line, 0, Line);
692 /// AddAddress - Add an address attribute to a die based on the location
693 /// provided.
694 void AddAddress(DIE *Die, unsigned Attribute,
695 const MachineLocation &Location) {
696 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
697 DIEBlock *Block = new DIEBlock();
699 if (Location.isReg()) {
700 if (Reg < 32) {
701 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
702 } else {
703 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
704 AddUInt(Block, 0, DW_FORM_udata, Reg);
706 } else {
707 if (Reg < 32) {
708 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
709 } else {
710 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
711 AddUInt(Block, 0, DW_FORM_udata, Reg);
713 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
716 AddBlock(Die, Attribute, 0, Block);
719 /// AddType - Add a new type attribute to the specified entity.
720 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
721 if (Ty.isNull())
722 return;
724 // Check for pre-existence.
725 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
726 // If it exists then use the existing value.
727 if (Slot) {
728 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
729 return;
732 // Set up proxy.
733 Slot = NewDIEEntry();
735 // Construct type.
736 DIE Buffer(DW_TAG_base_type);
737 if (Ty.isBasicType(Ty.getTag()))
738 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
739 else if (Ty.isDerivedType(Ty.getTag()))
740 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
741 else {
742 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
743 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
746 // Add debug information entry to entity and appropriate context.
747 DIE *Die = NULL;
748 DIDescriptor Context = Ty.getContext();
749 if (!Context.isNull())
750 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
752 if (Die) {
753 DIE *Child = new DIE(Buffer);
754 Die->AddChild(Child);
755 Buffer.Detach();
756 SetDIEEntry(Slot, Child);
757 } else {
758 Die = DW_Unit->AddDie(Buffer);
759 SetDIEEntry(Slot, Die);
762 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
765 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
766 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
767 DIBasicType BTy) {
769 // Get core information.
770 std::string Name;
771 BTy.getName(Name);
772 Buffer.setTag(DW_TAG_base_type);
773 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
774 // Add name if not anonymous or intermediate type.
775 if (!Name.empty())
776 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
777 uint64_t Size = BTy.getSizeInBits() >> 3;
778 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
781 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
782 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
783 DIDerivedType DTy) {
785 // Get core information.
786 std::string Name;
787 DTy.getName(Name);
788 uint64_t Size = DTy.getSizeInBits() >> 3;
789 unsigned Tag = DTy.getTag();
791 // FIXME - Workaround for templates.
792 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
794 Buffer.setTag(Tag);
796 // Map to main type, void will not have a type.
797 DIType FromTy = DTy.getTypeDerivedFrom();
798 AddType(DW_Unit, &Buffer, FromTy);
800 // Add name if not anonymous or intermediate type.
801 if (!Name.empty())
802 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
804 // Add size if non-zero (derived types might be zero-sized.)
805 if (Size)
806 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
808 // Add source line info if available and TyDesc is not a forward
809 // declaration.
810 if (!DTy.isForwardDecl())
811 AddSourceLine(&Buffer, &DTy);
814 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
815 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
816 DICompositeType CTy) {
817 // Get core information.
818 std::string Name;
819 CTy.getName(Name);
821 uint64_t Size = CTy.getSizeInBits() >> 3;
822 unsigned Tag = CTy.getTag();
823 Buffer.setTag(Tag);
825 switch (Tag) {
826 case DW_TAG_vector_type:
827 case DW_TAG_array_type:
828 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
829 break;
830 case DW_TAG_enumeration_type:
832 DIArray Elements = CTy.getTypeArray();
833 // Add enumerators to enumeration type.
834 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
835 DIE *ElemDie = NULL;
836 DIEnumerator Enum(Elements.getElement(i).getGV());
837 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
838 Buffer.AddChild(ElemDie);
841 break;
842 case DW_TAG_subroutine_type:
844 // Add return type.
845 DIArray Elements = CTy.getTypeArray();
846 DIDescriptor RTy = Elements.getElement(0);
847 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
849 // Add prototype flag.
850 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
852 // Add arguments.
853 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
854 DIE *Arg = new DIE(DW_TAG_formal_parameter);
855 DIDescriptor Ty = Elements.getElement(i);
856 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
857 Buffer.AddChild(Arg);
860 break;
861 case DW_TAG_structure_type:
862 case DW_TAG_union_type:
863 case DW_TAG_class_type:
865 // Add elements to structure type.
866 DIArray Elements = CTy.getTypeArray();
868 // A forward struct declared type may not have elements available.
869 if (Elements.isNull())
870 break;
872 // Add elements to structure type.
873 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
874 DIDescriptor Element = Elements.getElement(i);
875 DIE *ElemDie = NULL;
876 if (Element.getTag() == dwarf::DW_TAG_subprogram)
877 ElemDie = CreateSubprogramDIE(DW_Unit,
878 DISubprogram(Element.getGV()));
879 else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
880 ElemDie = CreateGlobalVariableDIE(DW_Unit,
881 DIGlobalVariable(Element.getGV()));
882 else
883 ElemDie = CreateMemberDIE(DW_Unit,
884 DIDerivedType(Element.getGV()));
885 Buffer.AddChild(ElemDie);
888 // FIXME: We'd like an API to register additional attributes for the
889 // frontend to use while synthesizing, and then we'd use that api in
890 // clang instead of this.
891 if (Name == "__block_literal_generic")
892 AddUInt(&Buffer, DW_AT_APPLE_block, DW_FORM_flag, 1);
894 unsigned RLang = CTy.getRunTimeLang();
895 if (RLang)
896 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
898 break;
899 default:
900 break;
903 // Add name if not anonymous or intermediate type.
904 if (!Name.empty())
905 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
907 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
908 || Tag == DW_TAG_union_type) {
909 // Add size if non-zero (derived types might be zero-sized.)
910 if (Size)
911 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
912 else {
913 // Add zero size if it is not a forward declaration.
914 if (CTy.isForwardDecl())
915 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
916 else
917 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
920 // Add source line info if available.
921 if (!CTy.isForwardDecl())
922 AddSourceLine(&Buffer, &CTy);
926 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
927 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
928 int64_t L = SR.getLo();
929 int64_t H = SR.getHi();
930 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
931 if (L != H) {
932 AddDIEEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
933 if (L)
934 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
935 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
937 Buffer.AddChild(DW_Subrange);
940 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
941 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
942 DICompositeType *CTy) {
943 Buffer.setTag(DW_TAG_array_type);
944 if (CTy->getTag() == DW_TAG_vector_type)
945 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
947 // Emit derived type.
948 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
949 DIArray Elements = CTy->getTypeArray();
951 // Construct an anonymous type for index type.
952 DIE IdxBuffer(DW_TAG_base_type);
953 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
954 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
955 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
957 // Add subranges to array type.
958 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
959 DIDescriptor Element = Elements.getElement(i);
960 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
961 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
965 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
966 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
968 DIE *Enumerator = new DIE(DW_TAG_enumerator);
969 std::string Name;
970 ETy->getName(Name);
971 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
972 int64_t Value = ETy->getEnumValue();
973 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
974 return Enumerator;
977 /// CreateGlobalVariableDIE - Create new DIE using GV.
978 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
980 DIE *GVDie = new DIE(DW_TAG_variable);
981 std::string Name;
982 GV.getDisplayName(Name);
983 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
984 std::string LinkageName;
985 GV.getLinkageName(LinkageName);
986 if (!LinkageName.empty())
987 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
988 AddType(DW_Unit, GVDie, GV.getType());
989 if (!GV.isLocalToUnit())
990 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
991 AddSourceLine(GVDie, &GV);
992 return GVDie;
995 /// CreateMemberDIE - Create new member DIE.
996 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
997 DIE *MemberDie = new DIE(DT.getTag());
998 std::string Name;
999 DT.getName(Name);
1000 if (!Name.empty())
1001 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1003 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1005 AddSourceLine(MemberDie, &DT);
1007 uint64_t Size = DT.getSizeInBits();
1008 uint64_t FieldSize = DT.getOriginalTypeSize();
1010 if (Size != FieldSize) {
1011 // Handle bitfield.
1012 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1013 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1015 uint64_t Offset = DT.getOffsetInBits();
1016 uint64_t FieldOffset = Offset;
1017 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1018 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1019 FieldOffset = (HiMark - FieldSize);
1020 Offset -= FieldOffset;
1021 // Maybe we need to work from the other end.
1022 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1023 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1025 DIEBlock *Block = new DIEBlock();
1026 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1027 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1028 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1030 if (DT.isProtected())
1031 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1032 else if (DT.isPrivate())
1033 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1035 return MemberDie;
1038 /// CreateSubprogramDIE - Create new DIE using SP.
1039 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1040 const DISubprogram &SP,
1041 bool IsConstructor = false) {
1042 DIE *SPDie = new DIE(DW_TAG_subprogram);
1044 std::string Name;
1045 SP.getName(Name);
1046 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1048 std::string LinkageName;
1049 SP.getLinkageName(LinkageName);
1051 if (!LinkageName.empty())
1052 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1054 AddSourceLine(SPDie, &SP);
1056 DICompositeType SPTy = SP.getType();
1057 DIArray Args = SPTy.getTypeArray();
1059 // Add prototyped tag, if C or ObjC.
1060 unsigned Lang = SP.getCompileUnit().getLanguage();
1061 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89 || Lang == DW_LANG_ObjC)
1062 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1064 // Add Return Type.
1065 unsigned SPTag = SPTy.getTag();
1066 if (!IsConstructor) {
1067 if (Args.isNull() || SPTag != DW_TAG_subroutine_type)
1068 AddType(DW_Unit, SPDie, SPTy);
1069 else
1070 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1073 if (!SP.isDefinition()) {
1074 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1075 // Add arguments. Do not add arguments for subprogram definition. They
1076 // will be handled through RecordVariable.
1077 if (SPTag == DW_TAG_subroutine_type)
1078 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1079 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1080 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1081 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ??
1082 SPDie->AddChild(Arg);
1086 if (!SP.isLocalToUnit())
1087 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1089 // DW_TAG_inlined_subroutine may refer to this DIE.
1090 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
1091 Slot = SPDie;
1092 return SPDie;
1095 /// FindCompileUnit - Get the compile unit for the given descriptor.
1097 CompileUnit &FindCompileUnit(DICompileUnit Unit) const {
1098 DenseMap<Value *, CompileUnit *>::const_iterator I =
1099 CompileUnitMap.find(Unit.getGV());
1100 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1101 return *I->second;
1104 /// NewDbgScopeVariable - Create a new scope variable.
1106 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1107 // Get the descriptor.
1108 const DIVariable &VD = DV->getVariable();
1110 // Translate tag to proper Dwarf tag. The result variable is dropped for
1111 // now.
1112 unsigned Tag;
1113 switch (VD.getTag()) {
1114 case DW_TAG_return_variable: return NULL;
1115 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1116 case DW_TAG_auto_variable: // fall thru
1117 default: Tag = DW_TAG_variable; break;
1120 // Define variable debug information entry.
1121 DIE *VariableDie = new DIE(Tag);
1122 std::string Name;
1123 VD.getName(Name);
1124 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1126 // Add source line info if available.
1127 AddSourceLine(VariableDie, &VD);
1129 // Add variable type.
1130 AddType(Unit, VariableDie, VD.getType());
1132 // Add variable address.
1133 MachineLocation Location;
1134 Location.set(RI->getFrameRegister(*MF),
1135 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1136 AddAddress(VariableDie, DW_AT_location, Location);
1138 return VariableDie;
1141 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1143 DbgScope *getOrCreateScope(GlobalVariable *V) {
1144 DbgScope *&Slot = DbgScopeMap[V];
1145 if (Slot) return Slot;
1147 DbgScope *Parent = NULL;
1148 DIBlock Block(V);
1150 // Don't create a new scope if we already created one for an inlined
1151 // function.
1152 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1153 II = AbstractInstanceRootMap.find(V);
1154 if (II != AbstractInstanceRootMap.end())
1155 return LexicalScopeStack.back();
1157 if (!Block.isNull()) {
1158 DIDescriptor ParentDesc = Block.getContext();
1159 Parent =
1160 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
1163 Slot = new DbgScope(Parent, DIDescriptor(V));
1165 if (Parent)
1166 Parent->AddScope(Slot);
1167 else
1168 // First function is top level function.
1169 FunctionDbgScope = Slot;
1171 return Slot;
1174 /// ConstructDbgScope - Construct the components of a scope.
1176 void ConstructDbgScope(DbgScope *ParentScope,
1177 unsigned ParentStartID, unsigned ParentEndID,
1178 DIE *ParentDie, CompileUnit *Unit) {
1179 // Add variables to scope.
1180 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1181 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1182 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
1183 if (VariableDie) ParentDie->AddChild(VariableDie);
1186 // Add concrete instances to scope.
1187 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts = ParentScope->getConcreteInsts();
1188 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1189 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1190 DIE *Die = ConcreteInst->getDie();
1192 unsigned StartID = ConcreteInst->getStartLabelID();
1193 unsigned EndID = ConcreteInst->getEndLabelID();
1195 // Add the scope bounds.
1196 if (StartID)
1197 AddLabel(Die, DW_AT_low_pc, DW_FORM_addr,
1198 DWLabel("label", StartID));
1199 else
1200 AddLabel(Die, DW_AT_low_pc, DW_FORM_addr,
1201 DWLabel("func_begin", SubprogramCount));
1203 if (EndID)
1204 AddLabel(Die, DW_AT_high_pc, DW_FORM_addr,
1205 DWLabel("label", EndID));
1206 else
1207 AddLabel(Die, DW_AT_high_pc, DW_FORM_addr,
1208 DWLabel("func_end", SubprogramCount));
1210 ParentDie->AddChild(Die);
1213 // Add nested scopes.
1214 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1215 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1216 // Define the Scope debug information entry.
1217 DbgScope *Scope = Scopes[j];
1219 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1220 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1222 // Ignore empty scopes.
1223 if (StartID == EndID && StartID != 0) continue;
1225 // Do not ignore inlined scopes even if they don't have any variables or
1226 // scopes.
1227 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1228 Scope->getConcreteInsts().empty())
1229 continue;
1231 if (StartID == ParentStartID && EndID == ParentEndID) {
1232 // Just add stuff to the parent scope.
1233 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1234 } else {
1235 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1237 // Add the scope bounds.
1238 if (StartID)
1239 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1240 DWLabel("label", StartID));
1241 else
1242 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1243 DWLabel("func_begin", SubprogramCount));
1245 if (EndID)
1246 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1247 DWLabel("label", EndID));
1248 else
1249 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1250 DWLabel("func_end", SubprogramCount));
1252 // Add the scope's contents.
1253 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1254 ParentDie->AddChild(ScopeDie);
1259 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1261 void ConstructFunctionDbgScope(DbgScope *RootScope) {
1262 // Exit if there is no root scope.
1263 if (!RootScope) return;
1264 DIDescriptor Desc = RootScope->getDesc();
1265 if (Desc.isNull())
1266 return;
1268 // Get the subprogram debug information entry.
1269 DISubprogram SPD(Desc.getGV());
1271 // Get the compile unit context.
1272 CompileUnit *Unit = MainCU;
1273 if (!Unit)
1274 Unit = &FindCompileUnit(SPD.getCompileUnit());
1276 // Get the subprogram die.
1277 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1278 assert(SPDie && "Missing subprogram descriptor");
1280 // Add the function bounds.
1281 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1282 DWLabel("func_begin", SubprogramCount));
1283 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1284 DWLabel("func_end", SubprogramCount));
1285 MachineLocation Location(RI->getFrameRegister(*MF));
1286 AddAddress(SPDie, DW_AT_frame_base, Location);
1288 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1291 /// ConstructFunctionDbgScope - Construct the scope for the abstract debug
1292 /// scope.
1294 void ConstructAbstractDbgScope(DbgScope *AbsScope) {
1295 // Exit if there is no root scope.
1296 if (!AbsScope) return;
1298 DIDescriptor Desc = AbsScope->getDesc();
1299 if (Desc.isNull())
1300 return;
1302 // Get the subprogram debug information entry.
1303 DISubprogram SPD(Desc.getGV());
1305 // Get the compile unit context.
1306 CompileUnit *Unit = MainCU;
1307 if (!Unit)
1308 Unit = &FindCompileUnit(SPD.getCompileUnit());
1310 // Get the subprogram die.
1311 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1312 assert(SPDie && "Missing subprogram descriptor");
1314 ConstructDbgScope(AbsScope, 0, 0, SPDie, Unit);
1317 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1319 void ConstructDefaultDbgScope(MachineFunction *MF) {
1320 const char *FnName = MF->getFunction()->getNameStart();
1321 if (MainCU) {
1322 StringMap<DIE*> &Globals = MainCU->getGlobals();
1323 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1324 if (GI != Globals.end()) {
1325 DIE *SPDie = GI->second;
1327 // Add the function bounds.
1328 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1329 DWLabel("func_begin", SubprogramCount));
1330 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1331 DWLabel("func_end", SubprogramCount));
1333 MachineLocation Location(RI->getFrameRegister(*MF));
1334 AddAddress(SPDie, DW_AT_frame_base, Location);
1335 return;
1337 } else {
1338 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1339 CompileUnit *Unit = CompileUnits[i];
1340 StringMap<DIE*> &Globals = Unit->getGlobals();
1341 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1342 if (GI != Globals.end()) {
1343 DIE *SPDie = GI->second;
1345 // Add the function bounds.
1346 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1347 DWLabel("func_begin", SubprogramCount));
1348 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1349 DWLabel("func_end", SubprogramCount));
1351 MachineLocation Location(RI->getFrameRegister(*MF));
1352 AddAddress(SPDie, DW_AT_frame_base, Location);
1353 return;
1358 #if 0
1359 // FIXME: This is causing an abort because C++ mangled names are compared
1360 // with their unmangled counterparts. See PR2885. Don't do this assert.
1361 assert(0 && "Couldn't find DIE for machine function!");
1362 #endif
1365 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1366 /// tools to recognize the object file contains Dwarf information.
1367 void EmitInitial() {
1368 // Check to see if we already emitted intial headers.
1369 if (didInitial) return;
1370 didInitial = true;
1372 // Dwarf sections base addresses.
1373 if (TAI->doesDwarfRequireFrameSection()) {
1374 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1375 EmitLabel("section_debug_frame", 0);
1377 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1378 EmitLabel("section_info", 0);
1379 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1380 EmitLabel("section_abbrev", 0);
1381 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1382 EmitLabel("section_aranges", 0);
1383 if (TAI->doesSupportMacInfoSection()) {
1384 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1385 EmitLabel("section_macinfo", 0);
1387 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1388 EmitLabel("section_line", 0);
1389 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1390 EmitLabel("section_loc", 0);
1391 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1392 EmitLabel("section_pubnames", 0);
1393 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1394 EmitLabel("section_str", 0);
1395 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1396 EmitLabel("section_ranges", 0);
1398 Asm->SwitchToSection(TAI->getTextSection());
1399 EmitLabel("text_begin", 0);
1400 Asm->SwitchToSection(TAI->getDataSection());
1401 EmitLabel("data_begin", 0);
1404 /// EmitDIE - Recusively Emits a debug information entry.
1406 void EmitDIE(DIE *Die) {
1407 // Get the abbreviation for this DIE.
1408 unsigned AbbrevNumber = Die->getAbbrevNumber();
1409 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1411 Asm->EOL();
1413 // Emit the code (index) for the abbreviation.
1414 Asm->EmitULEB128Bytes(AbbrevNumber);
1416 if (Asm->isVerbose())
1417 Asm->EOL(std::string("Abbrev [" +
1418 utostr(AbbrevNumber) +
1419 "] 0x" + utohexstr(Die->getOffset()) +
1420 ":0x" + utohexstr(Die->getSize()) + " " +
1421 TagString(Abbrev->getTag())));
1422 else
1423 Asm->EOL();
1425 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1426 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1428 // Emit the DIE attribute values.
1429 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1430 unsigned Attr = AbbrevData[i].getAttribute();
1431 unsigned Form = AbbrevData[i].getForm();
1432 assert(Form && "Too many attributes for DIE (check abbreviation)");
1434 switch (Attr) {
1435 case DW_AT_sibling:
1436 Asm->EmitInt32(Die->SiblingOffset());
1437 break;
1438 case DW_AT_abstract_origin: {
1439 DIEEntry *E = cast<DIEEntry>(Values[i]);
1440 DIE *Origin = E->getEntry();
1441 unsigned Addr =
1442 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1443 Origin->getOffset();
1445 Asm->EmitInt32(Addr);
1446 break;
1448 default:
1449 // Emit an attribute using the defined form.
1450 Values[i]->EmitValue(this, Form);
1451 break;
1454 Asm->EOL(AttributeString(Attr));
1457 // Emit the DIE children if any.
1458 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
1459 const std::vector<DIE *> &Children = Die->getChildren();
1461 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1462 EmitDIE(Children[j]);
1464 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1468 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1470 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1471 // Get the children.
1472 const std::vector<DIE *> &Children = Die->getChildren();
1474 // If not last sibling and has children then add sibling offset attribute.
1475 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1477 // Record the abbreviation.
1478 AssignAbbrevNumber(Die->getAbbrev());
1480 // Get the abbreviation for this DIE.
1481 unsigned AbbrevNumber = Die->getAbbrevNumber();
1482 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1484 // Set DIE offset
1485 Die->setOffset(Offset);
1487 // Start the size with the size of abbreviation code.
1488 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1490 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1491 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1493 // Size the DIE attribute values.
1494 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1495 // Size attribute value.
1496 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1499 // Size the DIE children if any.
1500 if (!Children.empty()) {
1501 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
1502 "Children flag not set");
1504 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1505 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1508 // End of children marker.
1509 Offset += sizeof(int8_t);
1512 Die->setSize(Offset - Die->getOffset());
1513 return Offset;
1516 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1518 void SizeAndOffsets() {
1519 // Compute size of compile unit header.
1520 static unsigned Offset =
1521 sizeof(int32_t) + // Length of Compilation Unit Info
1522 sizeof(int16_t) + // DWARF version number
1523 sizeof(int32_t) + // Offset Into Abbrev. Section
1524 sizeof(int8_t); // Pointer Size (in bytes)
1526 // Process base compile unit.
1527 if (MainCU) {
1528 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1529 CompileUnitOffsets[MainCU] = 0;
1530 return;
1533 // Process all compile units.
1534 unsigned PrevOffset = 0;
1536 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1537 CompileUnit *Unit = CompileUnits[i];
1538 CompileUnitOffsets[Unit] = PrevOffset;
1539 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1540 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1544 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1546 void EmitDebugInfoPerCU(CompileUnit *Unit) {
1547 DIE *Die = Unit->getDie();
1548 // Emit the compile units header.
1549 EmitLabel("info_begin", Unit->getID());
1550 // Emit size of content not including length itself
1551 unsigned ContentSize = Die->getSize() +
1552 sizeof(int16_t) + // DWARF version number
1553 sizeof(int32_t) + // Offset Into Abbrev. Section
1554 sizeof(int8_t) + // Pointer Size (in bytes)
1555 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1557 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1558 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
1559 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1560 Asm->EOL("Offset Into Abbrev. Section");
1561 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1563 EmitDIE(Die);
1564 // FIXME - extra padding for gdb bug.
1565 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1566 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1567 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1568 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1569 EmitLabel("info_end", Unit->getID());
1571 Asm->EOL();
1574 void EmitDebugInfo() {
1575 // Start debug info section.
1576 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1578 if (MainCU) {
1579 EmitDebugInfoPerCU(MainCU);
1580 return;
1583 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1584 EmitDebugInfoPerCU(CompileUnits[i]);
1587 /// EmitAbbreviations - Emit the abbreviation section.
1589 void EmitAbbreviations() const {
1590 // Check to see if it is worth the effort.
1591 if (!Abbreviations.empty()) {
1592 // Start the debug abbrev section.
1593 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1595 EmitLabel("abbrev_begin", 0);
1597 // For each abbrevation.
1598 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1599 // Get abbreviation data
1600 const DIEAbbrev *Abbrev = Abbreviations[i];
1602 // Emit the abbrevations code (base 1 index.)
1603 Asm->EmitULEB128Bytes(Abbrev->getNumber());
1604 Asm->EOL("Abbreviation Code");
1606 // Emit the abbreviations data.
1607 Abbrev->Emit(Asm);
1609 Asm->EOL();
1612 // Mark end of abbreviations.
1613 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
1615 EmitLabel("abbrev_end", 0);
1617 Asm->EOL();
1621 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
1622 /// the line matrix.
1624 void EmitEndOfLineMatrix(unsigned SectionEnd) {
1625 // Define last address of section.
1626 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1627 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1628 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1629 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
1631 // Mark end of matrix.
1632 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
1633 Asm->EmitULEB128Bytes(1); Asm->EOL();
1634 Asm->EmitInt8(1); Asm->EOL();
1637 /// EmitDebugLines - Emit source line information.
1639 void EmitDebugLines() {
1640 // If the target is using .loc/.file, the assembler will be emitting the
1641 // .debug_line table automatically.
1642 if (TAI->hasDotLocAndDotFile())
1643 return;
1645 // Minimum line delta, thus ranging from -10..(255-10).
1646 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
1647 // Maximum line delta, thus ranging from -10..(255-10).
1648 const int MaxLineDelta = 255 + MinLineDelta;
1650 // Start the dwarf line section.
1651 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1653 // Construct the section header.
1655 EmitDifference("line_end", 0, "line_begin", 0, true);
1656 Asm->EOL("Length of Source Line Info");
1657 EmitLabel("line_begin", 0);
1659 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
1661 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
1662 Asm->EOL("Prolog Length");
1663 EmitLabel("line_prolog_begin", 0);
1665 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
1667 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
1669 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
1671 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
1673 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
1675 // Line number standard opcode encodings argument count
1676 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
1677 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
1678 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
1679 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
1680 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
1681 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
1682 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
1683 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
1684 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
1686 // Emit directories.
1687 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
1688 Asm->EmitString(getSourceDirectoryName(DI));
1689 Asm->EOL("Directory");
1691 Asm->EmitInt8(0); Asm->EOL("End of directories");
1693 // Emit files.
1694 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
1695 // Remember source id starts at 1.
1696 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
1697 Asm->EmitString(getSourceFileName(Id.second));
1698 Asm->EOL("Source");
1699 Asm->EmitULEB128Bytes(Id.first);
1700 Asm->EOL("Directory #");
1701 Asm->EmitULEB128Bytes(0);
1702 Asm->EOL("Mod date");
1703 Asm->EmitULEB128Bytes(0);
1704 Asm->EOL("File size");
1706 Asm->EmitInt8(0); Asm->EOL("End of files");
1708 EmitLabel("line_prolog_end", 0);
1710 // A sequence for each text section.
1711 unsigned SecSrcLinesSize = SectionSourceLines.size();
1713 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
1714 // Isolate current sections line info.
1715 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
1717 if (Asm->isVerbose()) {
1718 const Section* S = SectionMap[j + 1];
1719 O << '\t' << TAI->getCommentString() << " Section"
1720 << S->getName() << '\n';
1721 } else
1722 Asm->EOL();
1724 // Dwarf assumes we start with first line of first source file.
1725 unsigned Source = 1;
1726 unsigned Line = 1;
1728 // Construct rows of the address, source, line, column matrix.
1729 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1730 const SrcLineInfo &LineInfo = LineInfos[i];
1731 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
1732 if (!LabelID) continue;
1734 if (!Asm->isVerbose())
1735 Asm->EOL();
1736 else {
1737 std::pair<unsigned, unsigned> SourceID =
1738 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
1739 O << '\t' << TAI->getCommentString() << ' '
1740 << getSourceDirectoryName(SourceID.first) << ' '
1741 << getSourceFileName(SourceID.second)
1742 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
1745 // Define the line address.
1746 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1747 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1748 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1749 EmitReference("label", LabelID); Asm->EOL("Location label");
1751 // If change of source, then switch to the new source.
1752 if (Source != LineInfo.getSourceID()) {
1753 Source = LineInfo.getSourceID();
1754 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
1755 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
1758 // If change of line.
1759 if (Line != LineInfo.getLine()) {
1760 // Determine offset.
1761 int Offset = LineInfo.getLine() - Line;
1762 int Delta = Offset - MinLineDelta;
1764 // Update line.
1765 Line = LineInfo.getLine();
1767 // If delta is small enough and in range...
1768 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1769 // ... then use fast opcode.
1770 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
1771 } else {
1772 // ... otherwise use long hand.
1773 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
1774 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
1775 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1777 } else {
1778 // Copy the previous row (different address or source)
1779 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1783 EmitEndOfLineMatrix(j + 1);
1786 if (SecSrcLinesSize == 0)
1787 // Because we're emitting a debug_line section, we still need a line
1788 // table. The linker and friends expect it to exist. If there's nothing to
1789 // put into it, emit an empty table.
1790 EmitEndOfLineMatrix(1);
1792 EmitLabel("line_end", 0);
1794 Asm->EOL();
1797 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
1799 void EmitCommonDebugFrame() {
1800 if (!TAI->doesDwarfRequireFrameSection())
1801 return;
1803 int stackGrowth =
1804 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1805 TargetFrameInfo::StackGrowsUp ?
1806 TD->getPointerSize() : -TD->getPointerSize();
1808 // Start the dwarf frame section.
1809 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1811 EmitLabel("debug_frame_common", 0);
1812 EmitDifference("debug_frame_common_end", 0,
1813 "debug_frame_common_begin", 0, true);
1814 Asm->EOL("Length of Common Information Entry");
1816 EmitLabel("debug_frame_common_begin", 0);
1817 Asm->EmitInt32((int)DW_CIE_ID);
1818 Asm->EOL("CIE Identifier Tag");
1819 Asm->EmitInt8(DW_CIE_VERSION);
1820 Asm->EOL("CIE Version");
1821 Asm->EmitString("");
1822 Asm->EOL("CIE Augmentation");
1823 Asm->EmitULEB128Bytes(1);
1824 Asm->EOL("CIE Code Alignment Factor");
1825 Asm->EmitSLEB128Bytes(stackGrowth);
1826 Asm->EOL("CIE Data Alignment Factor");
1827 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
1828 Asm->EOL("CIE RA Column");
1830 std::vector<MachineMove> Moves;
1831 RI->getInitialFrameState(Moves);
1833 EmitFrameMoves(NULL, 0, Moves, false);
1835 Asm->EmitAlignment(2, 0, 0, false);
1836 EmitLabel("debug_frame_common_end", 0);
1838 Asm->EOL();
1841 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
1842 /// section.
1843 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
1844 if (!TAI->doesDwarfRequireFrameSection())
1845 return;
1847 // Start the dwarf frame section.
1848 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1850 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
1851 "debug_frame_begin", DebugFrameInfo.Number, true);
1852 Asm->EOL("Length of Frame Information Entry");
1854 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
1856 EmitSectionOffset("debug_frame_common", "section_debug_frame",
1857 0, 0, true, false);
1858 Asm->EOL("FDE CIE offset");
1860 EmitReference("func_begin", DebugFrameInfo.Number);
1861 Asm->EOL("FDE initial location");
1862 EmitDifference("func_end", DebugFrameInfo.Number,
1863 "func_begin", DebugFrameInfo.Number);
1864 Asm->EOL("FDE address range");
1866 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
1867 false);
1869 Asm->EmitAlignment(2, 0, 0, false);
1870 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
1872 Asm->EOL();
1875 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
1876 EmitDifference("pubnames_end", Unit->getID(),
1877 "pubnames_begin", Unit->getID(), true);
1878 Asm->EOL("Length of Public Names Info");
1880 EmitLabel("pubnames_begin", Unit->getID());
1882 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
1884 EmitSectionOffset("info_begin", "section_info",
1885 Unit->getID(), 0, true, false);
1886 Asm->EOL("Offset of Compilation Unit Info");
1888 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
1889 true);
1890 Asm->EOL("Compilation Unit Length");
1892 StringMap<DIE*> &Globals = Unit->getGlobals();
1893 for (StringMap<DIE*>::const_iterator
1894 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1895 const char *Name = GI->getKeyData();
1896 DIE * Entity = GI->second;
1898 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
1899 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
1902 Asm->EmitInt32(0); Asm->EOL("End Mark");
1903 EmitLabel("pubnames_end", Unit->getID());
1905 Asm->EOL();
1908 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1910 void EmitDebugPubNames() {
1911 // Start the dwarf pubnames section.
1912 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1914 if (MainCU) {
1915 EmitDebugPubNamesPerCU(MainCU);
1916 return;
1919 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1920 EmitDebugPubNamesPerCU(CompileUnits[i]);
1923 /// EmitDebugStr - Emit visible names into a debug str section.
1925 void EmitDebugStr() {
1926 // Check to see if it is worth the effort.
1927 if (!StringPool.empty()) {
1928 // Start the dwarf str section.
1929 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1931 // For each of strings in the string pool.
1932 for (unsigned StringID = 1, N = StringPool.size();
1933 StringID <= N; ++StringID) {
1934 // Emit a label for reference from debug information entries.
1935 EmitLabel("string", StringID);
1936 // Emit the string itself.
1937 const std::string &String = StringPool[StringID];
1938 Asm->EmitString(String); Asm->EOL();
1941 Asm->EOL();
1945 /// EmitDebugLoc - Emit visible names into a debug loc section.
1947 void EmitDebugLoc() {
1948 // Start the dwarf loc section.
1949 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1951 Asm->EOL();
1954 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1956 void EmitDebugARanges() {
1957 // Start the dwarf aranges section.
1958 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1960 // FIXME - Mock up
1961 #if 0
1962 CompileUnit *Unit = GetBaseCompileUnit();
1964 // Don't include size of length
1965 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
1967 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
1969 EmitReference("info_begin", Unit->getID());
1970 Asm->EOL("Offset of Compilation Unit Info");
1972 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
1974 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
1976 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
1977 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
1979 // Range 1
1980 EmitReference("text_begin", 0); Asm->EOL("Address");
1981 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
1983 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
1984 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
1985 #endif
1987 Asm->EOL();
1990 /// EmitDebugRanges - Emit visible names into a debug ranges section.
1992 void EmitDebugRanges() {
1993 // Start the dwarf ranges section.
1994 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1996 Asm->EOL();
1999 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2001 void EmitDebugMacInfo() {
2002 if (TAI->doesSupportMacInfoSection()) {
2003 // Start the dwarf macinfo section.
2004 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2006 Asm->EOL();
2010 /// EmitDebugInlineInfo - Emit inline info using following format.
2011 /// Section Header:
2012 /// 1. length of section
2013 /// 2. Dwarf version number
2014 /// 3. address size.
2016 /// Entries (one "entry" for each function that was inlined):
2018 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2019 /// otherwise offset into __debug_str for regular function name.
2020 /// 2. offset into __debug_str section for regular function name.
2021 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2022 /// instances for the function.
2023 ///
2024 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2025 /// inlined instance; the die_offset points to the inlined_subroutine die in
2026 /// the __debug_info section, and the low_pc is the starting address for the
2027 /// inlining instance.
2028 void EmitDebugInlineInfo() {
2029 if (!TAI->doesDwarfUsesInlineInfoSection())
2030 return;
2032 if (!MainCU)
2033 return;
2035 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2036 Asm->EOL();
2037 EmitDifference("debug_inlined_end", 1,
2038 "debug_inlined_begin", 1, true);
2039 Asm->EOL("Length of Debug Inlined Information Entry");
2041 EmitLabel("debug_inlined_begin", 1);
2043 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2044 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2046 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2047 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2048 GlobalVariable *GV = I->first;
2049 SmallVector<unsigned, 4> &Labels = I->second;
2050 DISubprogram SP(GV);
2051 std::string Name;
2052 std::string LName;
2054 SP.getLinkageName(LName);
2055 SP.getName(Name);
2057 Asm->EmitString(LName.empty() ? Name : LName);
2058 Asm->EOL("MIPS linkage name");
2060 Asm->EmitString(Name); Asm->EOL("Function name");
2062 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2064 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2065 LE = Labels.end(); LI != LE; ++LI) {
2066 DIE *SP = MainCU->getDieMapSlotFor(GV);
2067 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2069 if (TD->getPointerSize() == sizeof(int32_t))
2070 O << TAI->getData32bitsDirective();
2071 else
2072 O << TAI->getData64bitsDirective();
2073 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2077 EmitLabel("debug_inlined_end", 1);
2078 Asm->EOL();
2081 /// GetOrCreateSourceID - Look up the source id with the given directory and
2082 /// source file names. If none currently exists, create a new id and insert it
2083 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2084 /// as well.
2085 unsigned GetOrCreateSourceID(const std::string &DirName,
2086 const std::string &FileName) {
2087 unsigned DId;
2088 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2089 if (DI != DirectoryIdMap.end()) {
2090 DId = DI->getValue();
2091 } else {
2092 DId = DirectoryNames.size() + 1;
2093 DirectoryIdMap[DirName] = DId;
2094 DirectoryNames.push_back(DirName);
2097 unsigned FId;
2098 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2099 if (FI != SourceFileIdMap.end()) {
2100 FId = FI->getValue();
2101 } else {
2102 FId = SourceFileNames.size() + 1;
2103 SourceFileIdMap[FileName] = FId;
2104 SourceFileNames.push_back(FileName);
2107 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2108 SourceIdMap.find(std::make_pair(DId, FId));
2109 if (SI != SourceIdMap.end())
2110 return SI->second;
2112 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2113 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2114 SourceIds.push_back(std::make_pair(DId, FId));
2116 return SrcId;
2119 void ConstructCompileUnit(GlobalVariable *GV) {
2120 DICompileUnit DIUnit(GV);
2121 std::string Dir, FN, Prod;
2122 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2123 DIUnit.getFilename(FN));
2125 DIE *Die = new DIE(DW_TAG_compile_unit);
2126 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2127 DWLabel("section_line", 0), DWLabel("section_line", 0),
2128 false);
2129 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2130 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2131 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2132 if (!Dir.empty())
2133 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2134 if (DIUnit.isOptimized())
2135 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2136 std::string Flags;
2137 DIUnit.getFlags(Flags);
2138 if (!Flags.empty())
2139 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2140 unsigned RVer = DIUnit.getRunTimeVersion();
2141 if (RVer)
2142 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2144 CompileUnit *Unit = new CompileUnit(ID, Die);
2145 if (DIUnit.isMain()) {
2146 assert(!MainCU && "Multiple main compile units are found!");
2147 MainCU = Unit;
2149 CompileUnitMap[DIUnit.getGV()] = Unit;
2150 CompileUnits.push_back(Unit);
2153 /// ConstructCompileUnits - Create a compile unit DIEs.
2154 void ConstructCompileUnits() {
2155 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2156 if (!Root)
2157 return;
2158 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2159 "Malformed compile unit descriptor anchor type");
2160 Constant *RootC = cast<Constant>(*Root->use_begin());
2161 assert(RootC->hasNUsesOrMore(1) &&
2162 "Malformed compile unit descriptor anchor type");
2163 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2164 UI != UE; ++UI)
2165 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2166 UUI != UUE; ++UUI) {
2167 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2168 ConstructCompileUnit(GV);
2172 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2173 DIGlobalVariable DI_GV(GV);
2174 CompileUnit *DW_Unit = MainCU;
2175 if (!DW_Unit)
2176 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
2178 // Check for pre-existence.
2179 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2180 if (Slot)
2181 return false;
2183 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2185 // Add address.
2186 DIEBlock *Block = new DIEBlock();
2187 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2188 std::string GLN;
2189 AddObjectLabel(Block, 0, DW_FORM_udata,
2190 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
2191 AddBlock(VariableDie, DW_AT_location, 0, Block);
2193 // Add to map.
2194 Slot = VariableDie;
2196 // Add to context owner.
2197 DW_Unit->getDie()->AddChild(VariableDie);
2199 // Expose as global. FIXME - need to check external flag.
2200 std::string Name;
2201 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2202 return true;
2205 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2206 /// visible global variables. Return true if at least one global DIE is
2207 /// created.
2208 bool ConstructGlobalVariableDIEs() {
2209 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2210 if (!Root)
2211 return false;
2213 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2214 "Malformed global variable descriptor anchor type");
2215 Constant *RootC = cast<Constant>(*Root->use_begin());
2216 assert(RootC->hasNUsesOrMore(1) &&
2217 "Malformed global variable descriptor anchor type");
2219 bool Result = false;
2220 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2221 UI != UE; ++UI)
2222 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2223 UUI != UUE; ++UUI)
2224 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
2226 return Result;
2229 bool ConstructSubprogram(GlobalVariable *GV) {
2230 DISubprogram SP(GV);
2231 CompileUnit *Unit = MainCU;
2232 if (!Unit)
2233 Unit = &FindCompileUnit(SP.getCompileUnit());
2235 // Check for pre-existence.
2236 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2237 if (Slot)
2238 return false;
2240 if (!SP.isDefinition())
2241 // This is a method declaration which will be handled while
2242 // constructing class type.
2243 return false;
2245 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2247 // Add to map.
2248 Slot = SubprogramDie;
2249 // Add to context owner.
2250 Unit->getDie()->AddChild(SubprogramDie);
2251 // Expose as global.
2252 std::string Name;
2253 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2254 return true;
2257 /// ConstructSubprograms - Create DIEs for each of the externally visible
2258 /// subprograms. Return true if at least one subprogram DIE is created.
2259 bool ConstructSubprograms() {
2260 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2261 if (!Root)
2262 return false;
2264 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2265 "Malformed subprogram descriptor anchor type");
2266 Constant *RootC = cast<Constant>(*Root->use_begin());
2267 assert(RootC->hasNUsesOrMore(1) &&
2268 "Malformed subprogram descriptor anchor type");
2270 bool Result = false;
2271 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2272 UI != UE; ++UI)
2273 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2274 UUI != UUE; ++UUI)
2275 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
2277 return Result;
2280 public:
2281 //===--------------------------------------------------------------------===//
2282 // Main entry points.
2284 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2285 : Dwarf(OS, A, T, "dbg"), MainCU(0),
2286 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
2287 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
2288 SectionSourceLines(), didInitial(false), shouldEmit(false),
2289 FunctionDbgScope(0), DebugTimer(0) {
2290 if (TimePassesIsEnabled)
2291 DebugTimer = new Timer("Dwarf Debug Writer",
2292 getDwarfTimerGroup());
2294 virtual ~DwarfDebug() {
2295 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2296 delete Values[j];
2298 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
2299 I = AbstractInstanceRootMap.begin(),
2300 E = AbstractInstanceRootMap.end(); I != E;++I)
2301 delete I->second;
2303 delete DebugTimer;
2306 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
2307 /// be emitted.
2308 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
2310 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2311 /// This is inovked by the target AsmPrinter.
2312 void SetDebugInfo(MachineModuleInfo *mmi) {
2313 if (TimePassesIsEnabled)
2314 DebugTimer->startTimer();
2316 // Create all the compile unit DIEs.
2317 ConstructCompileUnits();
2319 if (CompileUnits.empty()) {
2320 if (TimePassesIsEnabled)
2321 DebugTimer->stopTimer();
2323 return;
2326 // Create DIEs for each of the externally visible global variables.
2327 bool globalDIEs = ConstructGlobalVariableDIEs();
2329 // Create DIEs for each of the externally visible subprograms.
2330 bool subprogramDIEs = ConstructSubprograms();
2332 // If there is not any debug info available for any global variables
2333 // and any subprograms then there is not any debug info to emit.
2334 if (!globalDIEs && !subprogramDIEs) {
2335 if (TimePassesIsEnabled)
2336 DebugTimer->stopTimer();
2338 return;
2341 MMI = mmi;
2342 shouldEmit = true;
2343 MMI->setDebugInfoAvailability(true);
2345 // Prime section data.
2346 SectionMap.insert(TAI->getTextSection());
2348 // Print out .file directives to specify files for .loc directives. These
2349 // are printed out early so that they precede any .loc directives.
2350 if (TAI->hasDotLocAndDotFile()) {
2351 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2352 // Remember source id starts at 1.
2353 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2354 sys::Path FullPath(getSourceDirectoryName(Id.first));
2355 bool AppendOk =
2356 FullPath.appendComponent(getSourceFileName(Id.second));
2357 assert(AppendOk && "Could not append filename to directory!");
2358 AppendOk = false;
2359 Asm->EmitFile(i, FullPath.toString());
2360 Asm->EOL();
2364 // Emit initial sections
2365 EmitInitial();
2367 if (TimePassesIsEnabled)
2368 DebugTimer->stopTimer();
2371 /// BeginModule - Emit all Dwarf sections that should come prior to the
2372 /// content.
2373 void BeginModule(Module *M) {
2374 this->M = M;
2377 /// EndModule - Emit all Dwarf sections that should come after the content.
2379 void EndModule() {
2380 if (!ShouldEmitDwarfDebug())
2381 return;
2383 if (TimePassesIsEnabled)
2384 DebugTimer->startTimer();
2386 // Standard sections final addresses.
2387 Asm->SwitchToSection(TAI->getTextSection());
2388 EmitLabel("text_end", 0);
2389 Asm->SwitchToSection(TAI->getDataSection());
2390 EmitLabel("data_end", 0);
2392 // End text sections.
2393 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2394 Asm->SwitchToSection(SectionMap[i]);
2395 EmitLabel("section_end", i);
2398 // Emit common frame information.
2399 EmitCommonDebugFrame();
2401 // Emit function debug frame information
2402 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2403 E = DebugFrames.end(); I != E; ++I)
2404 EmitFunctionDebugFrame(*I);
2406 // Compute DIE offsets and sizes.
2407 SizeAndOffsets();
2409 // Emit all the DIEs into a debug info section
2410 EmitDebugInfo();
2412 // Corresponding abbreviations into a abbrev section.
2413 EmitAbbreviations();
2415 // Emit source line correspondence into a debug line section.
2416 EmitDebugLines();
2418 // Emit info into a debug pubnames section.
2419 EmitDebugPubNames();
2421 // Emit info into a debug str section.
2422 EmitDebugStr();
2424 // Emit info into a debug loc section.
2425 EmitDebugLoc();
2427 // Emit info into a debug aranges section.
2428 EmitDebugARanges();
2430 // Emit info into a debug ranges section.
2431 EmitDebugRanges();
2433 // Emit info into a debug macinfo section.
2434 EmitDebugMacInfo();
2436 // Emit inline info.
2437 EmitDebugInlineInfo();
2439 if (TimePassesIsEnabled)
2440 DebugTimer->stopTimer();
2443 /// BeginFunction - Gather pre-function debug information. Assumes being
2444 /// emitted immediately after the function entry point.
2445 void BeginFunction(MachineFunction *MF) {
2446 this->MF = MF;
2448 if (!ShouldEmitDwarfDebug()) return;
2450 if (TimePassesIsEnabled)
2451 DebugTimer->startTimer();
2453 // Begin accumulating function debug information.
2454 MMI->BeginFunction(MF);
2456 // Assumes in correct section after the entry point.
2457 EmitLabel("func_begin", ++SubprogramCount);
2459 // Emit label for the implicitly defined dbg.stoppoint at the start of
2460 // the function.
2461 DebugLoc FDL = MF->getDefaultDebugLoc();
2462 if (!FDL.isUnknown()) {
2463 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2464 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
2465 DICompileUnit(DLT.CompileUnit));
2466 Asm->printLabel(LabelID);
2469 if (TimePassesIsEnabled)
2470 DebugTimer->stopTimer();
2473 /// EndFunction - Gather and emit post-function debug information.
2475 void EndFunction(MachineFunction *MF) {
2476 if (!ShouldEmitDwarfDebug()) return;
2478 if (TimePassesIsEnabled)
2479 DebugTimer->startTimer();
2481 // Define end label for subprogram.
2482 EmitLabel("func_end", SubprogramCount);
2484 // Get function line info.
2485 if (!Lines.empty()) {
2486 // Get section line info.
2487 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2488 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2489 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2490 // Append the function info to section info.
2491 SectionLineInfos.insert(SectionLineInfos.end(),
2492 Lines.begin(), Lines.end());
2495 // Construct the DbgScope for abstract instances.
2496 for (SmallVector<DbgScope *, 32>::iterator
2497 I = AbstractInstanceRootList.begin(),
2498 E = AbstractInstanceRootList.end(); I != E; ++I)
2499 ConstructAbstractDbgScope(*I);
2501 // Construct scopes for subprogram.
2502 if (FunctionDbgScope)
2503 ConstructFunctionDbgScope(FunctionDbgScope);
2504 else
2505 // FIXME: This is wrong. We are essentially getting past a problem with
2506 // debug information not being able to handle unreachable blocks that have
2507 // debug information in them. In particular, those unreachable blocks that
2508 // have "region end" info in them. That situation results in the "root
2509 // scope" not being created. If that's the case, then emit a "default"
2510 // scope, i.e., one that encompasses the whole function. This isn't
2511 // desirable. And a better way of handling this (and all of the debugging
2512 // information) needs to be explored.
2513 ConstructDefaultDbgScope(MF);
2515 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2516 MMI->getFrameMoves()));
2518 // Clear debug info
2519 if (FunctionDbgScope) {
2520 delete FunctionDbgScope;
2521 DbgScopeMap.clear();
2522 DbgAbstractScopeMap.clear();
2523 DbgConcreteScopeMap.clear();
2524 InlinedVariableScopes.clear();
2525 FunctionDbgScope = NULL;
2526 LexicalScopeStack.clear();
2527 AbstractInstanceRootList.clear();
2530 Lines.clear();
2532 if (TimePassesIsEnabled)
2533 DebugTimer->stopTimer();
2536 /// RecordSourceLine - Records location information and associates it with a
2537 /// label. Returns a unique label ID used to generate a label and provide
2538 /// correspondence to the source line list.
2539 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2540 if (TimePassesIsEnabled)
2541 DebugTimer->startTimer();
2543 CompileUnit *Unit = CompileUnitMap[V];
2544 assert(Unit && "Unable to find CompileUnit");
2545 unsigned ID = MMI->NextLabelID();
2546 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2548 if (TimePassesIsEnabled)
2549 DebugTimer->stopTimer();
2551 return ID;
2554 /// RecordSourceLine - Records location information and associates it with a
2555 /// label. Returns a unique label ID used to generate a label and provide
2556 /// correspondence to the source line list.
2557 unsigned RecordSourceLine(unsigned Line, unsigned Col, DICompileUnit CU) {
2558 if (TimePassesIsEnabled)
2559 DebugTimer->startTimer();
2561 std::string Dir, Fn;
2562 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
2563 CU.getFilename(Fn));
2564 unsigned ID = MMI->NextLabelID();
2565 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2567 if (TimePassesIsEnabled)
2568 DebugTimer->stopTimer();
2570 return ID;
2573 /// getRecordSourceLineCount - Return the number of source lines in the debug
2574 /// info.
2575 unsigned getRecordSourceLineCount() const {
2576 return Lines.size();
2579 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2580 /// timed. Look up the source id with the given directory and source file
2581 /// names. If none currently exists, create a new id and insert it in the
2582 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2583 /// well.
2584 unsigned getOrCreateSourceID(const std::string &DirName,
2585 const std::string &FileName) {
2586 if (TimePassesIsEnabled)
2587 DebugTimer->startTimer();
2589 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
2591 if (TimePassesIsEnabled)
2592 DebugTimer->stopTimer();
2594 return SrcId;
2597 /// RecordRegionStart - Indicate the start of a region.
2598 unsigned RecordRegionStart(GlobalVariable *V) {
2599 if (TimePassesIsEnabled)
2600 DebugTimer->startTimer();
2602 DbgScope *Scope = getOrCreateScope(V);
2603 unsigned ID = MMI->NextLabelID();
2604 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2605 LexicalScopeStack.push_back(Scope);
2607 if (TimePassesIsEnabled)
2608 DebugTimer->stopTimer();
2610 return ID;
2613 /// RecordRegionEnd - Indicate the end of a region.
2614 unsigned RecordRegionEnd(GlobalVariable *V) {
2615 if (TimePassesIsEnabled)
2616 DebugTimer->startTimer();
2618 DbgScope *Scope = getOrCreateScope(V);
2619 unsigned ID = MMI->NextLabelID();
2620 Scope->setEndLabelID(ID);
2621 if (LexicalScopeStack.size() != 0)
2622 LexicalScopeStack.pop_back();
2624 if (TimePassesIsEnabled)
2625 DebugTimer->stopTimer();
2627 return ID;
2630 /// RecordVariable - Indicate the declaration of a local variable.
2631 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2632 const MachineInstr *MI) {
2633 if (TimePassesIsEnabled)
2634 DebugTimer->startTimer();
2636 DIDescriptor Desc(GV);
2637 DbgScope *Scope = NULL;
2639 if (Desc.getTag() == DW_TAG_variable) {
2640 // GV is a global variable.
2641 DIGlobalVariable DG(GV);
2642 Scope = getOrCreateScope(DG.getContext().getGV());
2643 } else {
2644 DenseMap<const MachineInstr *, DbgScope *>::iterator
2645 SI = InlinedVariableScopes.find(MI);
2647 if (SI != InlinedVariableScopes.end()) {
2648 // or GV is an inlined local variable.
2649 Scope = SI->second;
2650 } else {
2651 DIVariable DV(GV);
2652 GlobalVariable *V = DV.getContext().getGV();
2654 // FIXME: The code that checks for the inlined local variable is a hack!
2655 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2656 AI = AbstractInstanceRootMap.find(V);
2658 if (AI != AbstractInstanceRootMap.end())
2659 // or GV is an inlined local variable.
2660 Scope = AI->second;
2661 else
2662 // or GV is a local variable.
2663 Scope = getOrCreateScope(V);
2667 assert(Scope && "Unable to find the variable's scope");
2668 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
2669 Scope->AddVariable(DV);
2671 if (TimePassesIsEnabled)
2672 DebugTimer->stopTimer();
2675 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2676 unsigned RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2677 unsigned Line, unsigned Col) {
2678 unsigned LabelID = MMI->NextLabelID();
2680 if (!TAI->doesDwarfUsesInlineInfoSection())
2681 return LabelID;
2683 if (TimePassesIsEnabled)
2684 DebugTimer->startTimer();
2686 GlobalVariable *GV = SP.getGV();
2687 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2688 II = AbstractInstanceRootMap.find(GV);
2690 if (II == AbstractInstanceRootMap.end()) {
2691 // Create an abstract instance entry for this inlined function if it
2692 // doesn't already exist.
2693 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
2695 // Get the compile unit context.
2696 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2697 DIE *SPDie = Unit->getDieMapSlotFor(GV);
2698 if (!SPDie)
2699 SPDie = CreateSubprogramDIE(Unit, SP);
2701 // Mark as being inlined. This makes this subprogram entry an abstract
2702 // instance root.
2703 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2704 // that it's defined. It probably won't change in the future, but this
2705 // could be more elegant.
2706 AddUInt(SPDie, DW_AT_inline, 0, DW_INL_declared_not_inlined);
2708 // Keep track of the abstract scope for this function.
2709 DbgAbstractScopeMap[GV] = Scope;
2711 AbstractInstanceRootMap[GV] = Scope;
2712 AbstractInstanceRootList.push_back(Scope);
2715 // Create a concrete inlined instance for this inlined function.
2716 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
2717 DIE *ScopeDie = new DIE(DW_TAG_inlined_subroutine);
2718 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2719 ScopeDie->setAbstractCompileUnit(Unit);
2721 DIE *Origin = Unit->getDieMapSlotFor(GV);
2722 AddDIEEntry(ScopeDie, DW_AT_abstract_origin, DW_FORM_ref4, Origin);
2723 AddUInt(ScopeDie, DW_AT_call_file, 0, Unit->getID());
2724 AddUInt(ScopeDie, DW_AT_call_line, 0, Line);
2725 AddUInt(ScopeDie, DW_AT_call_column, 0, Col);
2727 ConcreteScope->setDie(ScopeDie);
2728 ConcreteScope->setStartLabelID(LabelID);
2729 MMI->RecordUsedDbgLabel(LabelID);
2731 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2733 // Keep track of the concrete scope that's inlined into this function.
2734 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2735 SI = DbgConcreteScopeMap.find(GV);
2737 if (SI == DbgConcreteScopeMap.end())
2738 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
2739 else
2740 SI->second.push_back(ConcreteScope);
2742 // Track the start label for this inlined function.
2743 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2744 I = InlineInfo.find(GV);
2746 if (I == InlineInfo.end())
2747 InlineInfo[GV].push_back(LabelID);
2748 else
2749 I->second.push_back(LabelID);
2751 if (TimePassesIsEnabled)
2752 DebugTimer->stopTimer();
2754 return LabelID;
2757 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2758 unsigned RecordInlinedFnEnd(DISubprogram &SP) {
2759 if (!TAI->doesDwarfUsesInlineInfoSection())
2760 return 0;
2762 if (TimePassesIsEnabled)
2763 DebugTimer->startTimer();
2765 GlobalVariable *GV = SP.getGV();
2766 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2767 I = DbgConcreteScopeMap.find(GV);
2769 if (I == DbgConcreteScopeMap.end()) {
2770 if (TimePassesIsEnabled)
2771 DebugTimer->stopTimer();
2773 return 0;
2776 SmallVector<DbgScope *, 8> &Scopes = I->second;
2777 assert(!Scopes.empty() && "We should have at least one debug scope!");
2778 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2779 unsigned ID = MMI->NextLabelID();
2780 MMI->RecordUsedDbgLabel(ID);
2781 Scope->setEndLabelID(ID);
2783 if (TimePassesIsEnabled)
2784 DebugTimer->stopTimer();
2786 return ID;
2789 /// RecordVariableScope - Record scope for the variable declared by
2790 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
2791 /// for only inlined subroutine variables. Other variables's scopes are
2792 /// determined during RecordVariable().
2793 void RecordVariableScope(DIVariable &DV, const MachineInstr *DeclareMI) {
2794 if (TimePassesIsEnabled)
2795 DebugTimer->startTimer();
2797 DISubprogram SP(DV.getContext().getGV());
2799 if (SP.isNull()) {
2800 if (TimePassesIsEnabled)
2801 DebugTimer->stopTimer();
2803 return;
2806 DenseMap<GlobalVariable *, DbgScope *>::iterator
2807 I = DbgAbstractScopeMap.find(SP.getGV());
2808 if (I != DbgAbstractScopeMap.end())
2809 InlinedVariableScopes[DeclareMI] = I->second;
2811 if (TimePassesIsEnabled)
2812 DebugTimer->stopTimer();
2816 //===----------------------------------------------------------------------===//
2817 /// DwarfException - Emits Dwarf exception handling directives.
2819 class DwarfException : public Dwarf {
2820 struct FunctionEHFrameInfo {
2821 std::string FnName;
2822 unsigned Number;
2823 unsigned PersonalityIndex;
2824 bool hasCalls;
2825 bool hasLandingPads;
2826 std::vector<MachineMove> Moves;
2827 const Function * function;
2829 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2830 bool hC, bool hL,
2831 const std::vector<MachineMove> &M,
2832 const Function *f):
2833 FnName(FN), Number(Num), PersonalityIndex(P),
2834 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2837 std::vector<FunctionEHFrameInfo> EHFrames;
2839 /// shouldEmitTable - Per-function flag to indicate if EH tables should
2840 /// be emitted.
2841 bool shouldEmitTable;
2843 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
2844 /// should be emitted.
2845 bool shouldEmitMoves;
2847 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
2848 /// should be emitted.
2849 bool shouldEmitTableModule;
2851 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
2852 /// should be emitted.
2853 bool shouldEmitMovesModule;
2855 /// ExceptionTimer - Timer for the Dwarf exception writer.
2856 Timer *ExceptionTimer;
2858 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2860 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2861 // Size and sign of stack growth.
2862 int stackGrowth =
2863 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2864 TargetFrameInfo::StackGrowsUp ?
2865 TD->getPointerSize() : -TD->getPointerSize();
2867 // Begin eh frame section.
2868 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2870 if (!TAI->doesRequireNonLocalEHFrameLabel())
2871 O << TAI->getEHGlobalPrefix();
2872 O << "EH_frame" << Index << ":\n";
2873 EmitLabel("section_eh_frame", Index);
2875 // Define base labels.
2876 EmitLabel("eh_frame_common", Index);
2878 // Define the eh frame length.
2879 EmitDifference("eh_frame_common_end", Index,
2880 "eh_frame_common_begin", Index, true);
2881 Asm->EOL("Length of Common Information Entry");
2883 // EH frame header.
2884 EmitLabel("eh_frame_common_begin", Index);
2885 Asm->EmitInt32((int)0);
2886 Asm->EOL("CIE Identifier Tag");
2887 Asm->EmitInt8(DW_CIE_VERSION);
2888 Asm->EOL("CIE Version");
2890 // The personality presence indicates that language specific information
2891 // will show up in the eh frame.
2892 Asm->EmitString(Personality ? "zPLR" : "zR");
2893 Asm->EOL("CIE Augmentation");
2895 // Round out reader.
2896 Asm->EmitULEB128Bytes(1);
2897 Asm->EOL("CIE Code Alignment Factor");
2898 Asm->EmitSLEB128Bytes(stackGrowth);
2899 Asm->EOL("CIE Data Alignment Factor");
2900 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2901 Asm->EOL("CIE Return Address Column");
2903 // If there is a personality, we need to indicate the functions location.
2904 if (Personality) {
2905 Asm->EmitULEB128Bytes(7);
2906 Asm->EOL("Augmentation Size");
2908 if (TAI->getNeedsIndirectEncoding()) {
2909 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2910 Asm->EOL("Personality (pcrel sdata4 indirect)");
2911 } else {
2912 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2913 Asm->EOL("Personality (pcrel sdata4)");
2916 PrintRelDirective(true);
2917 O << TAI->getPersonalityPrefix();
2918 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2919 O << TAI->getPersonalitySuffix();
2920 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
2921 O << "-" << TAI->getPCSymbol();
2922 Asm->EOL("Personality");
2924 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2925 Asm->EOL("LSDA Encoding (pcrel sdata4)");
2927 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2928 Asm->EOL("FDE Encoding (pcrel sdata4)");
2929 } else {
2930 Asm->EmitULEB128Bytes(1);
2931 Asm->EOL("Augmentation Size");
2933 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2934 Asm->EOL("FDE Encoding (pcrel sdata4)");
2937 // Indicate locations of general callee saved registers in frame.
2938 std::vector<MachineMove> Moves;
2939 RI->getInitialFrameState(Moves);
2940 EmitFrameMoves(NULL, 0, Moves, true);
2942 // On Darwin the linker honors the alignment of eh_frame, which means it
2943 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
2944 // you get holes which confuse readers of eh_frame.
2945 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
2946 0, 0, false);
2947 EmitLabel("eh_frame_common_end", Index);
2949 Asm->EOL();
2952 /// EmitEHFrame - Emit function exception frame information.
2954 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2955 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
2957 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
2958 "Should not emit 'available externally' functions at all");
2960 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2962 // Externally visible entry into the functions eh frame info.
2963 // If the corresponding function is static, this should not be
2964 // externally visible.
2965 if (linkage != Function::InternalLinkage &&
2966 linkage != Function::PrivateLinkage) {
2967 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
2968 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
2971 // If corresponding function is weak definition, this should be too.
2972 if ((linkage == Function::WeakAnyLinkage ||
2973 linkage == Function::WeakODRLinkage ||
2974 linkage == Function::LinkOnceAnyLinkage ||
2975 linkage == Function::LinkOnceODRLinkage) &&
2976 TAI->getWeakDefDirective())
2977 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
2979 // If there are no calls then you can't unwind. This may mean we can
2980 // omit the EH Frame, but some environments do not handle weak absolute
2981 // symbols.
2982 // If UnwindTablesMandatory is set we cannot do this optimization; the
2983 // unwind info is to be available for non-EH uses.
2984 if (!EHFrameInfo.hasCalls &&
2985 !UnwindTablesMandatory &&
2986 ((linkage != Function::WeakAnyLinkage &&
2987 linkage != Function::WeakODRLinkage &&
2988 linkage != Function::LinkOnceAnyLinkage &&
2989 linkage != Function::LinkOnceODRLinkage) ||
2990 !TAI->getWeakDefDirective() ||
2991 TAI->getSupportsWeakOmittedEHFrame()))
2993 O << EHFrameInfo.FnName << " = 0\n";
2994 // This name has no connection to the function, so it might get
2995 // dead-stripped when the function is not, erroneously. Prohibit
2996 // dead-stripping unconditionally.
2997 if (const char *UsedDirective = TAI->getUsedDirective())
2998 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2999 } else {
3000 O << EHFrameInfo.FnName << ":\n";
3002 // EH frame header.
3003 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3004 "eh_frame_begin", EHFrameInfo.Number, true);
3005 Asm->EOL("Length of Frame Information Entry");
3007 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3009 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3010 PrintRelDirective(true, true);
3011 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3013 if (!TAI->isAbsoluteEHSectionOffsets())
3014 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3015 } else {
3016 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3017 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3018 true, true, false);
3021 Asm->EOL("FDE CIE offset");
3023 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3024 Asm->EOL("FDE initial location");
3025 EmitDifference("eh_func_end", EHFrameInfo.Number,
3026 "eh_func_begin", EHFrameInfo.Number, true);
3027 Asm->EOL("FDE address range");
3029 // If there is a personality and landing pads then point to the language
3030 // specific data area in the exception table.
3031 if (EHFrameInfo.PersonalityIndex) {
3032 Asm->EmitULEB128Bytes(4);
3033 Asm->EOL("Augmentation size");
3035 if (EHFrameInfo.hasLandingPads)
3036 EmitReference("exception", EHFrameInfo.Number, true, true);
3037 else
3038 Asm->EmitInt32((int)0);
3039 Asm->EOL("Language Specific Data Area");
3040 } else {
3041 Asm->EmitULEB128Bytes(0);
3042 Asm->EOL("Augmentation size");
3045 // Indicate locations of function specific callee saved registers in
3046 // frame.
3047 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3048 true);
3050 // On Darwin the linker honors the alignment of eh_frame, which means it
3051 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3052 // you get holes which confuse readers of eh_frame.
3053 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3054 0, 0, false);
3055 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3057 // If the function is marked used, this table should be also. We cannot
3058 // make the mark unconditional in this case, since retaining the table
3059 // also retains the function in this case, and there is code around
3060 // that depends on unused functions (calling undefined externals) being
3061 // dead-stripped to link correctly. Yes, there really is.
3062 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3063 if (const char *UsedDirective = TAI->getUsedDirective())
3064 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3068 /// EmitExceptionTable - Emit landing pads and actions.
3070 /// The general organization of the table is complex, but the basic concepts
3071 /// are easy. First there is a header which describes the location and
3072 /// organization of the three components that follow.
3073 /// 1. The landing pad site information describes the range of code covered
3074 /// by the try. In our case it's an accumulation of the ranges covered
3075 /// by the invokes in the try. There is also a reference to the landing
3076 /// pad that handles the exception once processed. Finally an index into
3077 /// the actions table.
3078 /// 2. The action table, in our case, is composed of pairs of type ids
3079 /// and next action offset. Starting with the action index from the
3080 /// landing pad site, each type Id is checked for a match to the current
3081 /// exception. If it matches then the exception and type id are passed
3082 /// on to the landing pad. Otherwise the next action is looked up. This
3083 /// chain is terminated with a next action of zero. If no type id is
3084 /// found the the frame is unwound and handling continues.
3085 /// 3. Type id table contains references to all the C++ typeinfo for all
3086 /// catches in the function. This tables is reversed indexed base 1.
3088 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3089 static unsigned SharedTypeIds(const LandingPadInfo *L,
3090 const LandingPadInfo *R) {
3091 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3092 unsigned LSize = LIds.size(), RSize = RIds.size();
3093 unsigned MinSize = LSize < RSize ? LSize : RSize;
3094 unsigned Count = 0;
3096 for (; Count != MinSize; ++Count)
3097 if (LIds[Count] != RIds[Count])
3098 return Count;
3100 return Count;
3103 /// PadLT - Order landing pads lexicographically by type id.
3104 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3105 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3106 unsigned LSize = LIds.size(), RSize = RIds.size();
3107 unsigned MinSize = LSize < RSize ? LSize : RSize;
3109 for (unsigned i = 0; i != MinSize; ++i)
3110 if (LIds[i] != RIds[i])
3111 return LIds[i] < RIds[i];
3113 return LSize < RSize;
3116 struct KeyInfo {
3117 static inline unsigned getEmptyKey() { return -1U; }
3118 static inline unsigned getTombstoneKey() { return -2U; }
3119 static unsigned getHashValue(const unsigned &Key) { return Key; }
3120 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3121 static bool isPod() { return true; }
3124 /// ActionEntry - Structure describing an entry in the actions table.
3125 struct ActionEntry {
3126 int ValueForTypeID; // The value to write - may not be equal to the type id.
3127 int NextAction;
3128 struct ActionEntry *Previous;
3131 /// PadRange - Structure holding a try-range and the associated landing pad.
3132 struct PadRange {
3133 // The index of the landing pad.
3134 unsigned PadIndex;
3135 // The index of the begin and end labels in the landing pad's label lists.
3136 unsigned RangeIndex;
3139 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3141 /// CallSiteEntry - Structure describing an entry in the call-site table.
3142 struct CallSiteEntry {
3143 // The 'try-range' is BeginLabel .. EndLabel.
3144 unsigned BeginLabel; // zero indicates the start of the function.
3145 unsigned EndLabel; // zero indicates the end of the function.
3146 // The landing pad starts at PadLabel.
3147 unsigned PadLabel; // zero indicates that there is no landing pad.
3148 unsigned Action;
3151 void EmitExceptionTable() {
3152 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3153 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3154 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3155 if (PadInfos.empty()) return;
3157 // Sort the landing pads in order of their type ids. This is used to fold
3158 // duplicate actions.
3159 SmallVector<const LandingPadInfo *, 64> LandingPads;
3160 LandingPads.reserve(PadInfos.size());
3161 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3162 LandingPads.push_back(&PadInfos[i]);
3163 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3165 // Negative type ids index into FilterIds, positive type ids index into
3166 // TypeInfos. The value written for a positive type id is just the type
3167 // id itself. For a negative type id, however, the value written is the
3168 // (negative) byte offset of the corresponding FilterIds entry. The byte
3169 // offset is usually equal to the type id, because the FilterIds entries
3170 // are written using a variable width encoding which outputs one byte per
3171 // entry as long as the value written is not too large, but can differ.
3172 // This kind of complication does not occur for positive type ids because
3173 // type infos are output using a fixed width encoding.
3174 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3175 SmallVector<int, 16> FilterOffsets;
3176 FilterOffsets.reserve(FilterIds.size());
3177 int Offset = -1;
3178 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3179 E = FilterIds.end(); I != E; ++I) {
3180 FilterOffsets.push_back(Offset);
3181 Offset -= TargetAsmInfo::getULEB128Size(*I);
3184 // Compute the actions table and gather the first action index for each
3185 // landing pad site.
3186 SmallVector<ActionEntry, 32> Actions;
3187 SmallVector<unsigned, 64> FirstActions;
3188 FirstActions.reserve(LandingPads.size());
3190 int FirstAction = 0;
3191 unsigned SizeActions = 0;
3192 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3193 const LandingPadInfo *LP = LandingPads[i];
3194 const std::vector<int> &TypeIds = LP->TypeIds;
3195 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3196 unsigned SizeSiteActions = 0;
3198 if (NumShared < TypeIds.size()) {
3199 unsigned SizeAction = 0;
3200 ActionEntry *PrevAction = 0;
3202 if (NumShared) {
3203 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3204 assert(Actions.size());
3205 PrevAction = &Actions.back();
3206 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3207 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3208 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3209 SizeAction -=
3210 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3211 SizeAction += -PrevAction->NextAction;
3212 PrevAction = PrevAction->Previous;
3216 // Compute the actions.
3217 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3218 int TypeID = TypeIds[I];
3219 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3220 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3221 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3223 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3224 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3225 SizeSiteActions += SizeAction;
3227 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3228 Actions.push_back(Action);
3230 PrevAction = &Actions.back();
3233 // Record the first action of the landing pad site.
3234 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3235 } // else identical - re-use previous FirstAction
3237 FirstActions.push_back(FirstAction);
3239 // Compute this sites contribution to size.
3240 SizeActions += SizeSiteActions;
3243 // Compute the call-site table. The entry for an invoke has a try-range
3244 // containing the call, a non-zero landing pad and an appropriate action.
3245 // The entry for an ordinary call has a try-range containing the call and
3246 // zero for the landing pad and the action. Calls marked 'nounwind' have
3247 // no entry and must not be contained in the try-range of any entry - they
3248 // form gaps in the table. Entries must be ordered by try-range address.
3249 SmallVector<CallSiteEntry, 64> CallSites;
3251 RangeMapType PadMap;
3252 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3253 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3254 // try-ranges for them need be deduced.
3255 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3256 const LandingPadInfo *LandingPad = LandingPads[i];
3257 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3258 unsigned BeginLabel = LandingPad->BeginLabels[j];
3259 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3260 PadRange P = { i, j };
3261 PadMap[BeginLabel] = P;
3265 // The end label of the previous invoke or nounwind try-range.
3266 unsigned LastLabel = 0;
3268 // Whether there is a potentially throwing instruction (currently this means
3269 // an ordinary call) between the end of the previous try-range and now.
3270 bool SawPotentiallyThrowing = false;
3272 // Whether the last callsite entry was for an invoke.
3273 bool PreviousIsInvoke = false;
3275 // Visit all instructions in order of address.
3276 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3277 I != E; ++I) {
3278 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3279 MI != E; ++MI) {
3280 if (!MI->isLabel()) {
3281 SawPotentiallyThrowing |= MI->getDesc().isCall();
3282 continue;
3285 unsigned BeginLabel = MI->getOperand(0).getImm();
3286 assert(BeginLabel && "Invalid label!");
3288 // End of the previous try-range?
3289 if (BeginLabel == LastLabel)
3290 SawPotentiallyThrowing = false;
3292 // Beginning of a new try-range?
3293 RangeMapType::iterator L = PadMap.find(BeginLabel);
3294 if (L == PadMap.end())
3295 // Nope, it was just some random label.
3296 continue;
3298 PadRange P = L->second;
3299 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3301 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3302 "Inconsistent landing pad map!");
3304 // If some instruction between the previous try-range and this one may
3305 // throw, create a call-site entry with no landing pad for the region
3306 // between the try-ranges.
3307 if (SawPotentiallyThrowing) {
3308 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3309 CallSites.push_back(Site);
3310 PreviousIsInvoke = false;
3313 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3314 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3316 if (LandingPad->LandingPadLabel) {
3317 // This try-range is for an invoke.
3318 CallSiteEntry Site = {BeginLabel, LastLabel,
3319 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3321 // Try to merge with the previous call-site.
3322 if (PreviousIsInvoke) {
3323 CallSiteEntry &Prev = CallSites.back();
3324 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3325 // Extend the range of the previous entry.
3326 Prev.EndLabel = Site.EndLabel;
3327 continue;
3331 // Otherwise, create a new call-site.
3332 CallSites.push_back(Site);
3333 PreviousIsInvoke = true;
3334 } else {
3335 // Create a gap.
3336 PreviousIsInvoke = false;
3340 // If some instruction between the previous try-range and the end of the
3341 // function may throw, create a call-site entry with no landing pad for the
3342 // region following the try-range.
3343 if (SawPotentiallyThrowing) {
3344 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3345 CallSites.push_back(Site);
3348 // Final tallies.
3350 // Call sites.
3351 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3352 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3353 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3354 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3355 SiteLengthSize +
3356 LandingPadSize);
3357 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3358 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3360 // Type infos.
3361 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3362 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3364 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3365 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3366 SizeSites + SizeActions + SizeTypes;
3368 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3369 sizeof(int8_t) + // TType format
3370 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3371 TypeOffset;
3373 unsigned SizeAlign = (4 - TotalSize) & 3;
3375 // Begin the exception table.
3376 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3377 Asm->EmitAlignment(2, 0, 0, false);
3378 O << "GCC_except_table" << SubprogramCount << ":\n";
3379 for (unsigned i = 0; i != SizeAlign; ++i) {
3380 Asm->EmitInt8(0);
3381 Asm->EOL("Padding");
3383 EmitLabel("exception", SubprogramCount);
3385 // Emit the header.
3386 Asm->EmitInt8(DW_EH_PE_omit);
3387 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3388 Asm->EmitInt8(DW_EH_PE_absptr);
3389 Asm->EOL("TType format (DW_EH_PE_absptr)");
3390 Asm->EmitULEB128Bytes(TypeOffset);
3391 Asm->EOL("TType base offset");
3392 Asm->EmitInt8(DW_EH_PE_udata4);
3393 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3394 Asm->EmitULEB128Bytes(SizeSites);
3395 Asm->EOL("Call-site table length");
3397 // Emit the landing pad site information.
3398 for (unsigned i = 0; i < CallSites.size(); ++i) {
3399 CallSiteEntry &S = CallSites[i];
3400 const char *BeginTag;
3401 unsigned BeginNumber;
3403 if (!S.BeginLabel) {
3404 BeginTag = "eh_func_begin";
3405 BeginNumber = SubprogramCount;
3406 } else {
3407 BeginTag = "label";
3408 BeginNumber = S.BeginLabel;
3411 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3412 true, true);
3413 Asm->EOL("Region start");
3415 if (!S.EndLabel) {
3416 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3417 true);
3418 } else {
3419 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3421 Asm->EOL("Region length");
3423 if (!S.PadLabel)
3424 Asm->EmitInt32(0);
3425 else
3426 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3427 true, true);
3428 Asm->EOL("Landing pad");
3430 Asm->EmitULEB128Bytes(S.Action);
3431 Asm->EOL("Action");
3434 // Emit the actions.
3435 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3436 ActionEntry &Action = Actions[I];
3438 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3439 Asm->EOL("TypeInfo index");
3440 Asm->EmitSLEB128Bytes(Action.NextAction);
3441 Asm->EOL("Next action");
3444 // Emit the type ids.
3445 for (unsigned M = TypeInfos.size(); M; --M) {
3446 GlobalVariable *GV = TypeInfos[M - 1];
3448 PrintRelDirective();
3450 if (GV) {
3451 std::string GLN;
3452 O << Asm->getGlobalLinkName(GV, GLN);
3453 } else {
3454 O << "0";
3457 Asm->EOL("TypeInfo");
3460 // Emit the filter typeids.
3461 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3462 unsigned TypeID = FilterIds[j];
3463 Asm->EmitULEB128Bytes(TypeID);
3464 Asm->EOL("Filter TypeInfo index");
3467 Asm->EmitAlignment(2, 0, 0, false);
3470 public:
3471 //===--------------------------------------------------------------------===//
3472 // Main entry points.
3474 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3475 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
3476 shouldEmitTableModule(false), shouldEmitMovesModule(false),
3477 ExceptionTimer(0) {
3478 if (TimePassesIsEnabled)
3479 ExceptionTimer = new Timer("Dwarf Exception Writer",
3480 getDwarfTimerGroup());
3483 virtual ~DwarfException() {
3484 delete ExceptionTimer;
3487 /// SetModuleInfo - Set machine module information when it's known that pass
3488 /// manager has created it. Set by the target AsmPrinter.
3489 void SetModuleInfo(MachineModuleInfo *mmi) {
3490 MMI = mmi;
3493 /// BeginModule - Emit all exception information that should come prior to the
3494 /// content.
3495 void BeginModule(Module *M) {
3496 this->M = M;
3499 /// EndModule - Emit all exception information that should come after the
3500 /// content.
3501 void EndModule() {
3502 if (TimePassesIsEnabled)
3503 ExceptionTimer->startTimer();
3505 if (shouldEmitMovesModule || shouldEmitTableModule) {
3506 const std::vector<Function *> Personalities = MMI->getPersonalities();
3507 for (unsigned i = 0; i < Personalities.size(); ++i)
3508 EmitCommonEHFrame(Personalities[i], i);
3510 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3511 E = EHFrames.end(); I != E; ++I)
3512 EmitEHFrame(*I);
3515 if (TimePassesIsEnabled)
3516 ExceptionTimer->stopTimer();
3519 /// BeginFunction - Gather pre-function exception information. Assumes being
3520 /// emitted immediately after the function entry point.
3521 void BeginFunction(MachineFunction *MF) {
3522 if (TimePassesIsEnabled)
3523 ExceptionTimer->startTimer();
3525 this->MF = MF;
3526 shouldEmitTable = shouldEmitMoves = false;
3528 if (MMI && TAI->doesSupportExceptionHandling()) {
3529 // Map all labels and get rid of any dead landing pads.
3530 MMI->TidyLandingPads();
3532 // If any landing pads survive, we need an EH table.
3533 if (MMI->getLandingPads().size())
3534 shouldEmitTable = true;
3536 // See if we need frame move info.
3537 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3538 shouldEmitMoves = true;
3540 if (shouldEmitMoves || shouldEmitTable)
3541 // Assumes in correct section after the entry point.
3542 EmitLabel("eh_func_begin", ++SubprogramCount);
3545 shouldEmitTableModule |= shouldEmitTable;
3546 shouldEmitMovesModule |= shouldEmitMoves;
3548 if (TimePassesIsEnabled)
3549 ExceptionTimer->stopTimer();
3552 /// EndFunction - Gather and emit post-function exception information.
3554 void EndFunction() {
3555 if (TimePassesIsEnabled)
3556 ExceptionTimer->startTimer();
3558 if (shouldEmitMoves || shouldEmitTable) {
3559 EmitLabel("eh_func_end", SubprogramCount);
3560 EmitExceptionTable();
3562 // Save EH frame information
3563 std::string Name;
3564 EHFrames.push_back(
3565 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF, Name),
3566 SubprogramCount,
3567 MMI->getPersonalityIndex(),
3568 MF->getFrameInfo()->hasCalls(),
3569 !MMI->getLandingPads().empty(),
3570 MMI->getFrameMoves(),
3571 MF->getFunction()));
3574 if (TimePassesIsEnabled)
3575 ExceptionTimer->stopTimer();
3579 } // End of namespace llvm
3581 //===----------------------------------------------------------------------===//
3582 /// DwarfWriter Implementation
3585 DwarfWriter::DwarfWriter()
3586 : ImmutablePass(&ID), DD(0), DE(0) {}
3588 DwarfWriter::~DwarfWriter() {
3589 delete DE;
3590 delete DD;
3593 /// BeginModule - Emit all Dwarf sections that should come prior to the
3594 /// content.
3595 void DwarfWriter::BeginModule(Module *M,
3596 MachineModuleInfo *MMI,
3597 raw_ostream &OS, AsmPrinter *A,
3598 const TargetAsmInfo *T) {
3599 DE = new DwarfException(OS, A, T);
3600 DD = new DwarfDebug(OS, A, T);
3601 DE->BeginModule(M);
3602 DD->BeginModule(M);
3603 DD->SetDebugInfo(MMI);
3604 DE->SetModuleInfo(MMI);
3607 /// EndModule - Emit all Dwarf sections that should come after the content.
3609 void DwarfWriter::EndModule() {
3610 DE->EndModule();
3611 DD->EndModule();
3614 /// BeginFunction - Gather pre-function debug information. Assumes being
3615 /// emitted immediately after the function entry point.
3616 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3617 DE->BeginFunction(MF);
3618 DD->BeginFunction(MF);
3621 /// EndFunction - Gather and emit post-function debug information.
3623 void DwarfWriter::EndFunction(MachineFunction *MF) {
3624 DD->EndFunction(MF);
3625 DE->EndFunction();
3627 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
3628 // Clear function debug information.
3629 MMI->EndFunction();
3632 /// RecordSourceLine - Records location information and associates it with a
3633 /// label. Returns a unique label ID used to generate a label and provide
3634 /// correspondence to the source line list.
3635 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
3636 DICompileUnit CU) {
3637 return DD->RecordSourceLine(Line, Col, CU);
3640 /// RecordRegionStart - Indicate the start of a region.
3641 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
3642 return DD->RecordRegionStart(V);
3645 /// RecordRegionEnd - Indicate the end of a region.
3646 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
3647 return DD->RecordRegionEnd(V);
3650 /// getRecordSourceLineCount - Count source lines.
3651 unsigned DwarfWriter::getRecordSourceLineCount() {
3652 return DD->getRecordSourceLineCount();
3655 /// RecordVariable - Indicate the declaration of a local variable.
3657 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
3658 const MachineInstr *MI) {
3659 DD->RecordVariable(GV, FrameIndex, MI);
3662 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3663 /// be emitted.
3664 bool DwarfWriter::ShouldEmitDwarfDebug() const {
3665 return DD && DD->ShouldEmitDwarfDebug();
3668 //// RecordInlinedFnStart - Global variable GV is inlined at the location marked
3669 //// by LabelID label.
3670 unsigned DwarfWriter::RecordInlinedFnStart(DISubprogram SP, DICompileUnit CU,
3671 unsigned Line, unsigned Col) {
3672 return DD->RecordInlinedFnStart(SP, CU, Line, Col);
3675 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
3676 unsigned DwarfWriter::RecordInlinedFnEnd(DISubprogram SP) {
3677 return DD->RecordInlinedFnEnd(SP);
3680 /// RecordVariableScope - Record scope for the variable declared by
3681 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
3682 void DwarfWriter::RecordVariableScope(DIVariable &DV,
3683 const MachineInstr *DeclareMI) {
3684 DD->RecordVariableScope(DV, DeclareMI);