More whitespace fixin'.
[llvm/msp430.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
blobb12b35b110715515183bdf1523f049ce716ea7f1
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
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"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/DataTypes.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/System/Path.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include <ostream>
43 #include <string>
44 using namespace llvm;
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
51 namespace llvm {
53 //===----------------------------------------------------------------------===//
55 /// Configuration values for initial hash set sizes (log2).
56 ///
57 static const unsigned InitDiesSetSize = 9; // log2(512)
58 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
59 static const unsigned InitValuesSetSize = 9; // log2(512)
61 //===----------------------------------------------------------------------===//
62 /// Forward declarations.
63 ///
64 class DIE;
65 class DIEValue;
67 //===----------------------------------------------------------------------===//
68 /// Utility routines.
69 ///
70 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
71 /// specified value in their initializer somewhere.
72 static void
73 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
74 // Scan though value users.
75 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
76 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
77 // If the user is a GlobalVariable then add to result.
78 Result.push_back(GV);
79 } else if (Constant *C = dyn_cast<Constant>(*I)) {
80 // If the user is a constant variable then scan its users.
81 getGlobalVariablesUsing(C, Result);
86 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
87 /// named GlobalVariable.
88 static void
89 getGlobalVariablesUsing(Module &M, const std::string &RootName,
90 std::vector<GlobalVariable*> &Result) {
91 std::vector<const Type*> FieldTypes;
92 FieldTypes.push_back(Type::Int32Ty);
93 FieldTypes.push_back(Type::Int32Ty);
95 // Get the GlobalVariable root.
96 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
97 StructType::get(FieldTypes));
99 // If present and linkonce then scan for users.
100 if (UseRoot && UseRoot->hasLinkOnceLinkage())
101 getGlobalVariablesUsing(UseRoot, Result);
104 /// getGlobalVariable - Return either a direct or cast Global value.
106 static GlobalVariable *getGlobalVariable(Value *V) {
107 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
108 return GV;
109 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
110 if (CE->getOpcode() == Instruction::BitCast) {
111 return dyn_cast<GlobalVariable>(CE->getOperand(0));
112 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
113 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
114 if (!CE->getOperand(i)->isNullValue())
115 return NULL;
117 return dyn_cast<GlobalVariable>(CE->getOperand(0));
120 return NULL;
123 //===----------------------------------------------------------------------===//
124 /// DWLabel - Labels are used to track locations in the assembler file.
125 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
126 /// where the tag is a category of label (Ex. location) and number is a value
127 /// unique in that category.
128 class DWLabel {
129 public:
130 /// Tag - Label category tag. Should always be a staticly declared C string.
132 const char *Tag;
134 /// Number - Value to make label unique.
136 unsigned Number;
138 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
140 void Profile(FoldingSetNodeID &ID) const {
141 ID.AddString(std::string(Tag));
142 ID.AddInteger(Number);
145 #ifndef NDEBUG
146 void print(std::ostream *O) const {
147 if (O) print(*O);
149 void print(std::ostream &O) const {
150 O << "." << Tag;
151 if (Number) O << Number;
153 #endif
156 //===----------------------------------------------------------------------===//
157 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
158 /// Dwarf abbreviation.
159 class DIEAbbrevData {
160 private:
161 /// Attribute - Dwarf attribute code.
163 unsigned Attribute;
165 /// Form - Dwarf form code.
167 unsigned Form;
169 public:
170 DIEAbbrevData(unsigned A, unsigned F)
171 : Attribute(A)
172 , Form(F)
175 // Accessors.
176 unsigned getAttribute() const { return Attribute; }
177 unsigned getForm() const { return Form; }
179 /// Profile - Used to gather unique data for the abbreviation folding set.
181 void Profile(FoldingSetNodeID &ID)const {
182 ID.AddInteger(Attribute);
183 ID.AddInteger(Form);
187 //===----------------------------------------------------------------------===//
188 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
189 /// information object.
190 class DIEAbbrev : public FoldingSetNode {
191 private:
192 /// Tag - Dwarf tag code.
194 unsigned Tag;
196 /// Unique number for node.
198 unsigned Number;
200 /// ChildrenFlag - Dwarf children flag.
202 unsigned ChildrenFlag;
204 /// Data - Raw data bytes for abbreviation.
206 SmallVector<DIEAbbrevData, 8> Data;
208 public:
210 DIEAbbrev(unsigned T, unsigned C)
211 : Tag(T)
212 , ChildrenFlag(C)
213 , Data()
215 ~DIEAbbrev() {}
217 // Accessors.
218 unsigned getTag() const { return Tag; }
219 unsigned getNumber() const { return Number; }
220 unsigned getChildrenFlag() const { return ChildrenFlag; }
221 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
222 void setTag(unsigned T) { Tag = T; }
223 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
224 void setNumber(unsigned N) { Number = N; }
226 /// AddAttribute - Adds another set of attribute information to the
227 /// abbreviation.
228 void AddAttribute(unsigned Attribute, unsigned Form) {
229 Data.push_back(DIEAbbrevData(Attribute, Form));
232 /// AddFirstAttribute - Adds a set of attribute information to the front
233 /// of the abbreviation.
234 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
235 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
238 /// Profile - Used to gather unique data for the abbreviation folding set.
240 void Profile(FoldingSetNodeID &ID) {
241 ID.AddInteger(Tag);
242 ID.AddInteger(ChildrenFlag);
244 // For each attribute description.
245 for (unsigned i = 0, N = Data.size(); i < N; ++i)
246 Data[i].Profile(ID);
249 /// Emit - Print the abbreviation using the specified Dwarf writer.
251 void Emit(const DwarfDebug &DD) const;
253 #ifndef NDEBUG
254 void print(std::ostream *O) {
255 if (O) print(*O);
257 void print(std::ostream &O);
258 void dump();
259 #endif
262 //===----------------------------------------------------------------------===//
263 /// DIE - A structured debug information entry. Has an abbreviation which
264 /// describes it's organization.
265 class DIE : public FoldingSetNode {
266 protected:
267 /// Abbrev - Buffer for constructing abbreviation.
269 DIEAbbrev Abbrev;
271 /// Offset - Offset in debug info section.
273 unsigned Offset;
275 /// Size - Size of instance + children.
277 unsigned Size;
279 /// Children DIEs.
281 std::vector<DIE *> Children;
283 /// Attributes values.
285 SmallVector<DIEValue*, 32> Values;
287 public:
288 explicit DIE(unsigned Tag)
289 : Abbrev(Tag, DW_CHILDREN_no)
290 , Offset(0)
291 , Size(0)
292 , Children()
293 , Values()
295 virtual ~DIE();
297 // Accessors.
298 DIEAbbrev &getAbbrev() { return Abbrev; }
299 unsigned getAbbrevNumber() const {
300 return Abbrev.getNumber();
302 unsigned getTag() const { return Abbrev.getTag(); }
303 unsigned getOffset() const { return Offset; }
304 unsigned getSize() const { return Size; }
305 const std::vector<DIE *> &getChildren() const { return Children; }
306 SmallVector<DIEValue*, 32> &getValues() { return Values; }
307 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
308 void setOffset(unsigned O) { Offset = O; }
309 void setSize(unsigned S) { Size = S; }
311 /// AddValue - Add a value and attributes to a DIE.
313 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
314 Abbrev.AddAttribute(Attribute, Form);
315 Values.push_back(Value);
318 /// SiblingOffset - Return the offset of the debug information entry's
319 /// sibling.
320 unsigned SiblingOffset() const { return Offset + Size; }
322 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
324 void AddSiblingOffset();
326 /// AddChild - Add a child to the DIE.
328 void AddChild(DIE *Child) {
329 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
330 Children.push_back(Child);
333 /// Detach - Detaches objects connected to it after copying.
335 void Detach() {
336 Children.clear();
339 /// Profile - Used to gather unique data for the value folding set.
341 void Profile(FoldingSetNodeID &ID) ;
343 #ifndef NDEBUG
344 void print(std::ostream *O, unsigned IncIndent = 0) {
345 if (O) print(*O, IncIndent);
347 void print(std::ostream &O, unsigned IncIndent = 0);
348 void dump();
349 #endif
352 //===----------------------------------------------------------------------===//
353 /// DIEValue - A debug information entry value.
355 class DIEValue : public FoldingSetNode {
356 public:
357 enum {
358 isInteger,
359 isString,
360 isLabel,
361 isAsIsLabel,
362 isSectionOffset,
363 isDelta,
364 isEntry,
365 isBlock
368 /// Type - Type of data stored in the value.
370 unsigned Type;
372 explicit DIEValue(unsigned T)
373 : Type(T)
375 virtual ~DIEValue() {}
377 // Accessors
378 unsigned getType() const { return Type; }
380 // Implement isa/cast/dyncast.
381 static bool classof(const DIEValue *) { return true; }
383 /// EmitValue - Emit value via the Dwarf writer.
385 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
387 /// SizeOf - Return the size of a value in bytes.
389 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
391 /// Profile - Used to gather unique data for the value folding set.
393 virtual void Profile(FoldingSetNodeID &ID) = 0;
395 #ifndef NDEBUG
396 void print(std::ostream *O) {
397 if (O) print(*O);
399 virtual void print(std::ostream &O) = 0;
400 void dump();
401 #endif
404 //===----------------------------------------------------------------------===//
405 /// DWInteger - An integer value DIE.
407 class DIEInteger : public DIEValue {
408 private:
409 uint64_t Integer;
411 public:
412 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
414 // Implement isa/cast/dyncast.
415 static bool classof(const DIEInteger *) { return true; }
416 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
418 /// BestForm - Choose the best form for integer.
420 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
421 if (IsSigned) {
422 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
423 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
424 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
425 } else {
426 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
427 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
428 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
430 return DW_FORM_data8;
433 /// EmitValue - Emit integer of appropriate size.
435 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
437 /// SizeOf - Determine size of integer value in bytes.
439 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
441 /// Profile - Used to gather unique data for the value folding set.
443 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
444 ID.AddInteger(isInteger);
445 ID.AddInteger(Integer);
447 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
449 #ifndef NDEBUG
450 virtual void print(std::ostream &O) {
451 O << "Int: " << (int64_t)Integer
452 << " 0x" << std::hex << Integer << std::dec;
454 #endif
457 //===----------------------------------------------------------------------===//
458 /// DIEString - A string value DIE.
460 class DIEString : public DIEValue {
461 public:
462 const std::string String;
464 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
466 // Implement isa/cast/dyncast.
467 static bool classof(const DIEString *) { return true; }
468 static bool classof(const DIEValue *S) { return S->Type == isString; }
470 /// EmitValue - Emit string value.
472 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
474 /// SizeOf - Determine size of string value in bytes.
476 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
477 return String.size() + sizeof(char); // sizeof('\0');
480 /// Profile - Used to gather unique data for the value folding set.
482 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
483 ID.AddInteger(isString);
484 ID.AddString(String);
486 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
488 #ifndef NDEBUG
489 virtual void print(std::ostream &O) {
490 O << "Str: \"" << String << "\"";
492 #endif
495 //===----------------------------------------------------------------------===//
496 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
498 class DIEDwarfLabel : public DIEValue {
499 public:
501 const DWLabel Label;
503 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
505 // Implement isa/cast/dyncast.
506 static bool classof(const DIEDwarfLabel *) { return true; }
507 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
509 /// EmitValue - Emit label value.
511 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
513 /// SizeOf - Determine size of label value in bytes.
515 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
517 /// Profile - Used to gather unique data for the value folding set.
519 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
520 ID.AddInteger(isLabel);
521 Label.Profile(ID);
523 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
525 #ifndef NDEBUG
526 virtual void print(std::ostream &O) {
527 O << "Lbl: ";
528 Label.print(O);
530 #endif
534 //===----------------------------------------------------------------------===//
535 /// DIEObjectLabel - A label to an object in code or data.
537 class DIEObjectLabel : public DIEValue {
538 public:
539 const std::string Label;
541 explicit DIEObjectLabel(const std::string &L)
542 : DIEValue(isAsIsLabel), Label(L) {}
544 // Implement isa/cast/dyncast.
545 static bool classof(const DIEObjectLabel *) { return true; }
546 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
548 /// EmitValue - Emit label value.
550 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
552 /// SizeOf - Determine size of label value in bytes.
554 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
556 /// Profile - Used to gather unique data for the value folding set.
558 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
559 ID.AddInteger(isAsIsLabel);
560 ID.AddString(Label);
562 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
564 #ifndef NDEBUG
565 virtual void print(std::ostream &O) {
566 O << "Obj: " << Label;
568 #endif
571 //===----------------------------------------------------------------------===//
572 /// DIESectionOffset - A section offset DIE.
574 class DIESectionOffset : public DIEValue {
575 public:
576 const DWLabel Label;
577 const DWLabel Section;
578 bool IsEH : 1;
579 bool UseSet : 1;
581 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
582 bool isEH = false, bool useSet = true)
583 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
584 IsEH(isEH), UseSet(useSet) {}
586 // Implement isa/cast/dyncast.
587 static bool classof(const DIESectionOffset *) { return true; }
588 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
590 /// EmitValue - Emit section offset.
592 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
594 /// SizeOf - Determine size of section offset value in bytes.
596 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
598 /// Profile - Used to gather unique data for the value folding set.
600 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
601 const DWLabel &Section) {
602 ID.AddInteger(isSectionOffset);
603 Label.Profile(ID);
604 Section.Profile(ID);
605 // IsEH and UseSet are specific to the Label/Section that we will emit
606 // the offset for; so Label/Section are enough for uniqueness.
608 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
610 #ifndef NDEBUG
611 virtual void print(std::ostream &O) {
612 O << "Off: ";
613 Label.print(O);
614 O << "-";
615 Section.print(O);
616 O << "-" << IsEH << "-" << UseSet;
618 #endif
621 //===----------------------------------------------------------------------===//
622 /// DIEDelta - A simple label difference DIE.
624 class DIEDelta : public DIEValue {
625 public:
626 const DWLabel LabelHi;
627 const DWLabel LabelLo;
629 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
630 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
632 // Implement isa/cast/dyncast.
633 static bool classof(const DIEDelta *) { return true; }
634 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
636 /// EmitValue - Emit delta value.
638 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
640 /// SizeOf - Determine size of delta value in bytes.
642 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
644 /// Profile - Used to gather unique data for the value folding set.
646 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
647 const DWLabel &LabelLo) {
648 ID.AddInteger(isDelta);
649 LabelHi.Profile(ID);
650 LabelLo.Profile(ID);
652 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
654 #ifndef NDEBUG
655 virtual void print(std::ostream &O) {
656 O << "Del: ";
657 LabelHi.print(O);
658 O << "-";
659 LabelLo.print(O);
661 #endif
664 //===----------------------------------------------------------------------===//
665 /// DIEntry - A pointer to another debug information entry. An instance of this
666 /// class can also be used as a proxy for a debug information entry not yet
667 /// defined (ie. types.)
668 class DIEntry : public DIEValue {
669 public:
670 DIE *Entry;
672 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
674 // Implement isa/cast/dyncast.
675 static bool classof(const DIEntry *) { return true; }
676 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
678 /// EmitValue - Emit debug information entry offset.
680 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
682 /// SizeOf - Determine size of debug information entry in bytes.
684 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
685 return sizeof(int32_t);
688 /// Profile - Used to gather unique data for the value folding set.
690 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
691 ID.AddInteger(isEntry);
692 ID.AddPointer(Entry);
694 virtual void Profile(FoldingSetNodeID &ID) {
695 ID.AddInteger(isEntry);
697 if (Entry) {
698 ID.AddPointer(Entry);
699 } else {
700 ID.AddPointer(this);
704 #ifndef NDEBUG
705 virtual void print(std::ostream &O) {
706 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
708 #endif
711 //===----------------------------------------------------------------------===//
712 /// DIEBlock - A block of values. Primarily used for location expressions.
714 class DIEBlock : public DIEValue, public DIE {
715 public:
716 unsigned Size; // Size in bytes excluding size header.
718 DIEBlock()
719 : DIEValue(isBlock)
720 , DIE(0)
721 , Size(0)
723 ~DIEBlock() {
726 // Implement isa/cast/dyncast.
727 static bool classof(const DIEBlock *) { return true; }
728 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
730 /// ComputeSize - calculate the size of the block.
732 unsigned ComputeSize(DwarfDebug &DD);
734 /// BestForm - Choose the best form for data.
736 unsigned BestForm() const {
737 if ((unsigned char)Size == Size) return DW_FORM_block1;
738 if ((unsigned short)Size == Size) return DW_FORM_block2;
739 if ((unsigned int)Size == Size) return DW_FORM_block4;
740 return DW_FORM_block;
743 /// EmitValue - Emit block data.
745 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
747 /// SizeOf - Determine size of block data in bytes.
749 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
752 /// Profile - Used to gather unique data for the value folding set.
754 virtual void Profile(FoldingSetNodeID &ID) {
755 ID.AddInteger(isBlock);
756 DIE::Profile(ID);
759 #ifndef NDEBUG
760 virtual void print(std::ostream &O) {
761 O << "Blk: ";
762 DIE::print(O, 5);
764 #endif
767 //===----------------------------------------------------------------------===//
768 /// CompileUnit - This dwarf writer support class manages information associate
769 /// with a source file.
770 class CompileUnit {
771 private:
772 /// ID - File identifier for source.
774 unsigned ID;
776 /// Die - Compile unit debug information entry.
778 DIE *Die;
780 /// GVToDieMap - Tracks the mapping of unit level debug informaton
781 /// variables to debug information entries.
782 std::map<GlobalVariable *, DIE *> GVToDieMap;
784 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
785 /// descriptors to debug information entries using a DIEntry proxy.
786 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
788 /// Globals - A map of globally visible named entities for this unit.
790 std::map<std::string, DIE *> Globals;
792 /// DiesSet - Used to uniquely define dies within the compile unit.
794 FoldingSet<DIE> DiesSet;
796 public:
797 CompileUnit(unsigned I, DIE *D)
798 : ID(I), Die(D), GVToDieMap(),
799 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
802 ~CompileUnit() {
803 delete Die;
806 // Accessors.
807 unsigned getID() const { return ID; }
808 DIE* getDie() const { return Die; }
809 std::map<std::string, DIE *> &getGlobals() { return Globals; }
811 /// hasContent - Return true if this compile unit has something to write out.
813 bool hasContent() const {
814 return !Die->getChildren().empty();
817 /// AddGlobal - Add a new global entity to the compile unit.
819 void AddGlobal(const std::string &Name, DIE *Die) {
820 Globals[Name] = Die;
823 /// getDieMapSlotFor - Returns the debug information entry map slot for the
824 /// specified debug variable.
825 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
826 return GVToDieMap[GV];
829 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
830 /// specified debug variable.
831 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
832 return GVToDIEntryMap[GV];
835 /// AddDie - Adds or interns the DIE to the compile unit.
837 DIE *AddDie(DIE &Buffer) {
838 FoldingSetNodeID ID;
839 Buffer.Profile(ID);
840 void *Where;
841 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
843 if (!Die) {
844 Die = new DIE(Buffer);
845 DiesSet.InsertNode(Die, Where);
846 this->Die->AddChild(Die);
847 Buffer.Detach();
850 return Die;
854 //===----------------------------------------------------------------------===//
855 /// Dwarf - Emits general Dwarf directives.
857 class Dwarf {
858 protected:
859 //===--------------------------------------------------------------------===//
860 // Core attributes used by the Dwarf writer.
864 /// O - Stream to .s file.
866 raw_ostream &O;
868 /// Asm - Target of Dwarf emission.
870 AsmPrinter *Asm;
872 /// TAI - Target asm information.
873 const TargetAsmInfo *TAI;
875 /// TD - Target data.
876 const TargetData *TD;
878 /// RI - Register Information.
879 const TargetRegisterInfo *RI;
881 /// M - Current module.
883 Module *M;
885 /// MF - Current machine function.
887 MachineFunction *MF;
889 /// MMI - Collected machine module information.
891 MachineModuleInfo *MMI;
893 /// SubprogramCount - The running count of functions being compiled.
895 unsigned SubprogramCount;
897 /// Flavor - A unique string indicating what dwarf producer this is, used to
898 /// unique labels.
899 const char * const Flavor;
901 unsigned SetCounter;
902 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
903 const char *flavor)
904 : O(OS)
905 , Asm(A)
906 , TAI(T)
907 , TD(Asm->TM.getTargetData())
908 , RI(Asm->TM.getRegisterInfo())
909 , M(NULL)
910 , MF(NULL)
911 , MMI(NULL)
912 , SubprogramCount(0)
913 , Flavor(flavor)
914 , SetCounter(1)
918 public:
919 //===--------------------------------------------------------------------===//
920 // Accessors.
922 AsmPrinter *getAsm() const { return Asm; }
923 MachineModuleInfo *getMMI() const { return MMI; }
924 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
925 const TargetData *getTargetData() const { return TD; }
927 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
928 const {
929 if (isInSection && TAI->getDwarfSectionOffsetDirective())
930 O << TAI->getDwarfSectionOffsetDirective();
931 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
932 O << TAI->getData32bitsDirective();
933 else
934 O << TAI->getData64bitsDirective();
937 /// PrintLabelName - Print label name in form used by Dwarf writer.
939 void PrintLabelName(DWLabel Label) const {
940 PrintLabelName(Label.Tag, Label.Number);
942 void PrintLabelName(const char *Tag, unsigned Number) const {
943 O << TAI->getPrivateGlobalPrefix() << Tag;
944 if (Number) O << Number;
947 void PrintLabelName(const char *Tag, unsigned Number,
948 const char *Suffix) const {
949 O << TAI->getPrivateGlobalPrefix() << Tag;
950 if (Number) O << Number;
951 O << Suffix;
954 /// EmitLabel - Emit location label for internal use by Dwarf.
956 void EmitLabel(DWLabel Label) const {
957 EmitLabel(Label.Tag, Label.Number);
959 void EmitLabel(const char *Tag, unsigned Number) const {
960 PrintLabelName(Tag, Number);
961 O << ":\n";
964 /// EmitReference - Emit a reference to a label.
966 void EmitReference(DWLabel Label, bool IsPCRelative = false,
967 bool Force32Bit = false) const {
968 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
970 void EmitReference(const char *Tag, unsigned Number,
971 bool IsPCRelative = false, bool Force32Bit = false) const {
972 PrintRelDirective(Force32Bit);
973 PrintLabelName(Tag, Number);
975 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
977 void EmitReference(const std::string &Name, bool IsPCRelative = false,
978 bool Force32Bit = false) const {
979 PrintRelDirective(Force32Bit);
981 O << Name;
983 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
986 /// EmitDifference - Emit the difference between two labels. Some
987 /// assemblers do not behave with absolute expressions with data directives,
988 /// so there is an option (needsSet) to use an intermediary set expression.
989 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
990 bool IsSmall = false) {
991 EmitDifference(LabelHi.Tag, LabelHi.Number,
992 LabelLo.Tag, LabelLo.Number,
993 IsSmall);
995 void EmitDifference(const char *TagHi, unsigned NumberHi,
996 const char *TagLo, unsigned NumberLo,
997 bool IsSmall = false) {
998 if (TAI->needsSet()) {
999 O << "\t.set\t";
1000 PrintLabelName("set", SetCounter, Flavor);
1001 O << ",";
1002 PrintLabelName(TagHi, NumberHi);
1003 O << "-";
1004 PrintLabelName(TagLo, NumberLo);
1005 O << "\n";
1007 PrintRelDirective(IsSmall);
1008 PrintLabelName("set", SetCounter, Flavor);
1009 ++SetCounter;
1010 } else {
1011 PrintRelDirective(IsSmall);
1013 PrintLabelName(TagHi, NumberHi);
1014 O << "-";
1015 PrintLabelName(TagLo, NumberLo);
1019 void EmitSectionOffset(const char* Label, const char* Section,
1020 unsigned LabelNumber, unsigned SectionNumber,
1021 bool IsSmall = false, bool isEH = false,
1022 bool useSet = true) {
1023 bool printAbsolute = false;
1024 if (isEH)
1025 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1026 else
1027 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1029 if (TAI->needsSet() && useSet) {
1030 O << "\t.set\t";
1031 PrintLabelName("set", SetCounter, Flavor);
1032 O << ",";
1033 PrintLabelName(Label, LabelNumber);
1035 if (!printAbsolute) {
1036 O << "-";
1037 PrintLabelName(Section, SectionNumber);
1039 O << "\n";
1041 PrintRelDirective(IsSmall);
1043 PrintLabelName("set", SetCounter, Flavor);
1044 ++SetCounter;
1045 } else {
1046 PrintRelDirective(IsSmall, true);
1048 PrintLabelName(Label, LabelNumber);
1050 if (!printAbsolute) {
1051 O << "-";
1052 PrintLabelName(Section, SectionNumber);
1057 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1058 /// frame.
1059 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1060 const std::vector<MachineMove> &Moves, bool isEH) {
1061 int stackGrowth =
1062 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1063 TargetFrameInfo::StackGrowsUp ?
1064 TD->getPointerSize() : -TD->getPointerSize();
1065 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1067 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1068 const MachineMove &Move = Moves[i];
1069 unsigned LabelID = Move.getLabelID();
1071 if (LabelID) {
1072 LabelID = MMI->MappedLabel(LabelID);
1074 // Throw out move if the label is invalid.
1075 if (!LabelID) continue;
1078 const MachineLocation &Dst = Move.getDestination();
1079 const MachineLocation &Src = Move.getSource();
1081 // Advance row if new location.
1082 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1083 Asm->EmitInt8(DW_CFA_advance_loc4);
1084 Asm->EOL("DW_CFA_advance_loc4");
1085 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1086 Asm->EOL();
1088 BaseLabelID = LabelID;
1089 BaseLabel = "label";
1090 IsLocal = true;
1093 // If advancing cfa.
1094 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1095 if (!Src.isReg()) {
1096 if (Src.getReg() == MachineLocation::VirtualFP) {
1097 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1098 Asm->EOL("DW_CFA_def_cfa_offset");
1099 } else {
1100 Asm->EmitInt8(DW_CFA_def_cfa);
1101 Asm->EOL("DW_CFA_def_cfa");
1102 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1103 Asm->EOL("Register");
1106 int Offset = -Src.getOffset();
1108 Asm->EmitULEB128Bytes(Offset);
1109 Asm->EOL("Offset");
1110 } else {
1111 assert(0 && "Machine move no supported yet.");
1113 } else if (Src.isReg() &&
1114 Src.getReg() == MachineLocation::VirtualFP) {
1115 if (Dst.isReg()) {
1116 Asm->EmitInt8(DW_CFA_def_cfa_register);
1117 Asm->EOL("DW_CFA_def_cfa_register");
1118 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1119 Asm->EOL("Register");
1120 } else {
1121 assert(0 && "Machine move no supported yet.");
1123 } else {
1124 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1125 int Offset = Dst.getOffset() / stackGrowth;
1127 if (Offset < 0) {
1128 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1129 Asm->EOL("DW_CFA_offset_extended_sf");
1130 Asm->EmitULEB128Bytes(Reg);
1131 Asm->EOL("Reg");
1132 Asm->EmitSLEB128Bytes(Offset);
1133 Asm->EOL("Offset");
1134 } else if (Reg < 64) {
1135 Asm->EmitInt8(DW_CFA_offset + Reg);
1136 if (VerboseAsm)
1137 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1138 else
1139 Asm->EOL();
1140 Asm->EmitULEB128Bytes(Offset);
1141 Asm->EOL("Offset");
1142 } else {
1143 Asm->EmitInt8(DW_CFA_offset_extended);
1144 Asm->EOL("DW_CFA_offset_extended");
1145 Asm->EmitULEB128Bytes(Reg);
1146 Asm->EOL("Reg");
1147 Asm->EmitULEB128Bytes(Offset);
1148 Asm->EOL("Offset");
1156 //===----------------------------------------------------------------------===//
1157 /// SrcLineInfo - This class is used to record source line correspondence.
1159 class SrcLineInfo {
1160 unsigned Line; // Source line number.
1161 unsigned Column; // Source column.
1162 unsigned SourceID; // Source ID number.
1163 unsigned LabelID; // Label in code ID number.
1164 public:
1165 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1166 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1168 // Accessors
1169 unsigned getLine() const { return Line; }
1170 unsigned getColumn() const { return Column; }
1171 unsigned getSourceID() const { return SourceID; }
1172 unsigned getLabelID() const { return LabelID; }
1175 //===----------------------------------------------------------------------===//
1176 /// SrcFileInfo - This class is used to track source information.
1178 class SrcFileInfo {
1179 unsigned DirectoryID; // Directory ID number.
1180 std::string Name; // File name (not including directory.)
1181 public:
1182 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1184 // Accessors
1185 unsigned getDirectoryID() const { return DirectoryID; }
1186 const std::string &getName() const { return Name; }
1188 /// operator== - Used by UniqueVector to locate entry.
1190 bool operator==(const SrcFileInfo &SI) const {
1191 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1194 /// operator< - Used by UniqueVector to locate entry.
1196 bool operator<(const SrcFileInfo &SI) const {
1197 return getDirectoryID() < SI.getDirectoryID() ||
1198 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1202 //===----------------------------------------------------------------------===//
1203 /// DbgVariable - This class is used to track local variable information.
1205 class DbgVariable {
1206 DIVariable Var; // Variable Descriptor.
1207 unsigned FrameIndex; // Variable frame index.
1208 public:
1209 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1211 // Accessors.
1212 DIVariable getVariable() const { return Var; }
1213 unsigned getFrameIndex() const { return FrameIndex; }
1216 //===----------------------------------------------------------------------===//
1217 /// DbgScope - This class is used to track scope information.
1219 class DbgScope {
1220 DbgScope *Parent; // Parent to this scope.
1221 DIDescriptor Desc; // Debug info descriptor for scope.
1222 // Either subprogram or block.
1223 unsigned StartLabelID; // Label ID of the beginning of scope.
1224 unsigned EndLabelID; // Label ID of the end of scope.
1225 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1226 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1227 public:
1228 DbgScope(DbgScope *P, DIDescriptor D)
1229 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1231 ~DbgScope() {
1232 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1233 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1236 // Accessors.
1237 DbgScope *getParent() const { return Parent; }
1238 DIDescriptor getDesc() const { return Desc; }
1239 unsigned getStartLabelID() const { return StartLabelID; }
1240 unsigned getEndLabelID() const { return EndLabelID; }
1241 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1242 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1243 void setStartLabelID(unsigned S) { StartLabelID = S; }
1244 void setEndLabelID(unsigned E) { EndLabelID = E; }
1246 /// AddScope - Add a scope to the scope.
1248 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1250 /// AddVariable - Add a variable to the scope.
1252 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1255 //===----------------------------------------------------------------------===//
1256 /// DwarfDebug - Emits Dwarf debug directives.
1258 class DwarfDebug : public Dwarf {
1259 //===--------------------------------------------------------------------===//
1260 // Attributes used to construct specific Dwarf sections.
1263 /// DW_CUs - All the compile units involved in this build. The index
1264 /// of each entry in this vector corresponds to the sources in MMI.
1265 DenseMap<Value *, CompileUnit *> DW_CUs;
1267 /// MainCU - Some platform prefers one compile unit per .o file. In such
1268 /// cases, all dies are inserted in MainCU.
1269 CompileUnit *MainCU;
1270 /// AbbreviationsSet - Used to uniquely define abbreviations.
1272 FoldingSet<DIEAbbrev> AbbreviationsSet;
1274 /// Abbreviations - A list of all the unique abbreviations in use.
1276 std::vector<DIEAbbrev *> Abbreviations;
1278 /// Directories - Uniquing vector for directories.
1279 UniqueVector<std::string> Directories;
1281 /// SourceFiles - Uniquing vector for source files.
1282 UniqueVector<SrcFileInfo> SrcFiles;
1284 /// Lines - List of of source line correspondence.
1285 std::vector<SrcLineInfo> Lines;
1287 /// ValuesSet - Used to uniquely define values.
1289 FoldingSet<DIEValue> ValuesSet;
1291 /// Values - A list of all the unique values in use.
1293 std::vector<DIEValue *> Values;
1295 /// StringPool - A UniqueVector of strings used by indirect references.
1297 UniqueVector<std::string> StringPool;
1299 /// SectionMap - Provides a unique id per text section.
1301 UniqueVector<const Section*> SectionMap;
1303 /// SectionSourceLines - Tracks line numbers per text section.
1305 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1307 /// didInitial - Flag to indicate if initial emission has been done.
1309 bool didInitial;
1311 /// shouldEmit - Flag to indicate if debug information should be emitted.
1313 bool shouldEmit;
1315 // RootDbgScope - Top level scope for the current function.
1317 DbgScope *RootDbgScope;
1319 // DbgScopeMap - Tracks the scopes in the current function.
1320 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1322 struct FunctionDebugFrameInfo {
1323 unsigned Number;
1324 std::vector<MachineMove> Moves;
1326 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1327 Number(Num), Moves(M) { }
1330 std::vector<FunctionDebugFrameInfo> DebugFrames;
1332 public:
1334 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1336 bool ShouldEmitDwarf() const { return shouldEmit; }
1338 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1340 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1341 // Profile the node so that we can make it unique.
1342 FoldingSetNodeID ID;
1343 Abbrev.Profile(ID);
1345 // Check the set for priors.
1346 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1348 // If it's newly added.
1349 if (InSet == &Abbrev) {
1350 // Add to abbreviation list.
1351 Abbreviations.push_back(&Abbrev);
1352 // Assign the vector position + 1 as its number.
1353 Abbrev.setNumber(Abbreviations.size());
1354 } else {
1355 // Assign existing abbreviation number.
1356 Abbrev.setNumber(InSet->getNumber());
1360 /// NewString - Add a string to the constant pool and returns a label.
1362 DWLabel NewString(const std::string &String) {
1363 unsigned StringID = StringPool.insert(String);
1364 return DWLabel("string", StringID);
1367 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1368 /// entry.
1369 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1370 DIEntry *Value;
1372 if (Entry) {
1373 FoldingSetNodeID ID;
1374 DIEntry::Profile(ID, Entry);
1375 void *Where;
1376 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1378 if (Value) return Value;
1380 Value = new DIEntry(Entry);
1381 ValuesSet.InsertNode(Value, Where);
1382 } else {
1383 Value = new DIEntry(Entry);
1386 Values.push_back(Value);
1387 return Value;
1390 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1392 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1393 Value->Entry = Entry;
1394 // Add to values set if not already there. If it is, we merely have a
1395 // duplicate in the values list (no harm.)
1396 ValuesSet.GetOrInsertNode(Value);
1399 /// AddUInt - Add an unsigned integer attribute data and value.
1401 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1402 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1404 FoldingSetNodeID ID;
1405 DIEInteger::Profile(ID, Integer);
1406 void *Where;
1407 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1408 if (!Value) {
1409 Value = new DIEInteger(Integer);
1410 ValuesSet.InsertNode(Value, Where);
1411 Values.push_back(Value);
1414 Die->AddValue(Attribute, Form, Value);
1417 /// AddSInt - Add an signed integer attribute data and value.
1419 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1420 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1422 FoldingSetNodeID ID;
1423 DIEInteger::Profile(ID, (uint64_t)Integer);
1424 void *Where;
1425 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1426 if (!Value) {
1427 Value = new DIEInteger(Integer);
1428 ValuesSet.InsertNode(Value, Where);
1429 Values.push_back(Value);
1432 Die->AddValue(Attribute, Form, Value);
1435 /// AddString - Add a std::string attribute data and value.
1437 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1438 const std::string &String) {
1439 FoldingSetNodeID ID;
1440 DIEString::Profile(ID, String);
1441 void *Where;
1442 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1443 if (!Value) {
1444 Value = new DIEString(String);
1445 ValuesSet.InsertNode(Value, Where);
1446 Values.push_back(Value);
1449 Die->AddValue(Attribute, Form, Value);
1452 /// AddLabel - Add a Dwarf label attribute data and value.
1454 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1455 const DWLabel &Label) {
1456 FoldingSetNodeID ID;
1457 DIEDwarfLabel::Profile(ID, Label);
1458 void *Where;
1459 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1460 if (!Value) {
1461 Value = new DIEDwarfLabel(Label);
1462 ValuesSet.InsertNode(Value, Where);
1463 Values.push_back(Value);
1466 Die->AddValue(Attribute, Form, Value);
1469 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1471 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1472 const std::string &Label) {
1473 FoldingSetNodeID ID;
1474 DIEObjectLabel::Profile(ID, Label);
1475 void *Where;
1476 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1477 if (!Value) {
1478 Value = new DIEObjectLabel(Label);
1479 ValuesSet.InsertNode(Value, Where);
1480 Values.push_back(Value);
1483 Die->AddValue(Attribute, Form, Value);
1486 /// AddSectionOffset - Add a section offset label attribute data and value.
1488 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1489 const DWLabel &Label, const DWLabel &Section,
1490 bool isEH = false, bool useSet = true) {
1491 FoldingSetNodeID ID;
1492 DIESectionOffset::Profile(ID, Label, Section);
1493 void *Where;
1494 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1495 if (!Value) {
1496 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1497 ValuesSet.InsertNode(Value, Where);
1498 Values.push_back(Value);
1501 Die->AddValue(Attribute, Form, Value);
1504 /// AddDelta - Add a label delta attribute data and value.
1506 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1507 const DWLabel &Hi, const DWLabel &Lo) {
1508 FoldingSetNodeID ID;
1509 DIEDelta::Profile(ID, Hi, Lo);
1510 void *Where;
1511 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1512 if (!Value) {
1513 Value = new DIEDelta(Hi, Lo);
1514 ValuesSet.InsertNode(Value, Where);
1515 Values.push_back(Value);
1518 Die->AddValue(Attribute, Form, Value);
1521 /// AddDIEntry - Add a DIE attribute data and value.
1523 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1524 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1527 /// AddBlock - Add block data.
1529 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1530 Block->ComputeSize(*this);
1531 FoldingSetNodeID ID;
1532 Block->Profile(ID);
1533 void *Where;
1534 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1535 if (!Value) {
1536 Value = Block;
1537 ValuesSet.InsertNode(Value, Where);
1538 Values.push_back(Value);
1539 } else {
1540 // Already exists, reuse the previous one.
1541 delete Block;
1542 Block = cast<DIEBlock>(Value);
1545 Die->AddValue(Attribute, Block->BestForm(), Value);
1548 private:
1550 /// AddSourceLine - Add location information to specified debug information
1551 /// entry.
1552 void AddSourceLine(DIE *Die, const DIVariable *V) {
1553 unsigned FileID = 0;
1554 unsigned Line = V->getLineNumber();
1555 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1556 FileID = Unit->getID();
1557 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1558 AddUInt(Die, DW_AT_decl_line, 0, Line);
1561 /// AddSourceLine - Add location information to specified debug information
1562 /// entry.
1563 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1564 unsigned FileID = 0;
1565 unsigned Line = G->getLineNumber();
1566 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1567 FileID = Unit->getID();
1568 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1569 AddUInt(Die, DW_AT_decl_line, 0, Line);
1572 void AddSourceLine(DIE *Die, const DIType *Ty) {
1573 unsigned FileID = 0;
1574 unsigned Line = Ty->getLineNumber();
1575 DICompileUnit CU = Ty->getCompileUnit();
1576 if (CU.isNull())
1577 return;
1578 CompileUnit *Unit = FindCompileUnit(CU);
1579 FileID = Unit->getID();
1580 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1581 AddUInt(Die, DW_AT_decl_line, 0, Line);
1584 /// AddAddress - Add an address attribute to a die based on the location
1585 /// provided.
1586 void AddAddress(DIE *Die, unsigned Attribute,
1587 const MachineLocation &Location) {
1588 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1589 DIEBlock *Block = new DIEBlock();
1591 if (Location.isReg()) {
1592 if (Reg < 32) {
1593 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1594 } else {
1595 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1596 AddUInt(Block, 0, DW_FORM_udata, Reg);
1598 } else {
1599 if (Reg < 32) {
1600 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1601 } else {
1602 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1603 AddUInt(Block, 0, DW_FORM_udata, Reg);
1605 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1608 AddBlock(Die, Attribute, 0, Block);
1611 /// AddType - Add a new type attribute to the specified entity.
1612 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1613 if (Ty.isNull())
1614 return;
1616 // Check for pre-existence.
1617 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1618 // If it exists then use the existing value.
1619 if (Slot) {
1620 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1621 return;
1624 // Set up proxy.
1625 Slot = NewDIEntry();
1627 // Construct type.
1628 DIE Buffer(DW_TAG_base_type);
1629 if (Ty.isBasicType(Ty.getTag()))
1630 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1631 else if (Ty.isDerivedType(Ty.getTag()))
1632 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1633 else {
1634 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1635 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1638 // Add debug information entry to entity and appropriate context.
1639 DIE *Die = NULL;
1640 DIDescriptor Context = Ty.getContext();
1641 if (!Context.isNull())
1642 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1644 if (Die) {
1645 DIE *Child = new DIE(Buffer);
1646 Die->AddChild(Child);
1647 Buffer.Detach();
1648 SetDIEntry(Slot, Child);
1649 } else {
1650 Die = DW_Unit->AddDie(Buffer);
1651 SetDIEntry(Slot, Die);
1654 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1657 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1658 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1659 DIBasicType BTy) {
1661 // Get core information.
1662 const std::string &Name = BTy.getName();
1663 Buffer.setTag(DW_TAG_base_type);
1664 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1665 // Add name if not anonymous or intermediate type.
1666 if (!Name.empty())
1667 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1668 uint64_t Size = BTy.getSizeInBits() >> 3;
1669 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1672 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1673 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1674 DIDerivedType DTy) {
1676 // Get core information.
1677 const std::string &Name = DTy.getName();
1678 uint64_t Size = DTy.getSizeInBits() >> 3;
1679 unsigned Tag = DTy.getTag();
1680 // FIXME - Workaround for templates.
1681 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1683 Buffer.setTag(Tag);
1684 // Map to main type, void will not have a type.
1685 DIType FromTy = DTy.getTypeDerivedFrom();
1686 AddType(DW_Unit, &Buffer, FromTy);
1688 // Add name if not anonymous or intermediate type.
1689 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1691 // Add size if non-zero (derived types might be zero-sized.)
1692 if (Size)
1693 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1695 // Add source line info if available and TyDesc is not a forward
1696 // declaration.
1697 if (!DTy.isForwardDecl())
1698 AddSourceLine(&Buffer, &DTy);
1701 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1702 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1703 DICompositeType CTy) {
1705 // Get core information.
1706 const std::string &Name = CTy.getName();
1707 uint64_t Size = CTy.getSizeInBits() >> 3;
1708 unsigned Tag = CTy.getTag();
1709 Buffer.setTag(Tag);
1710 switch (Tag) {
1711 case DW_TAG_vector_type:
1712 case DW_TAG_array_type:
1713 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1714 break;
1715 case DW_TAG_enumeration_type:
1717 DIArray Elements = CTy.getTypeArray();
1718 // Add enumerators to enumeration type.
1719 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1720 DIE *ElemDie = NULL;
1721 DIEnumerator Enum(Elements.getElement(i).getGV());
1722 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1723 Buffer.AddChild(ElemDie);
1726 break;
1727 case DW_TAG_subroutine_type:
1729 // Add prototype flag.
1730 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1731 DIArray Elements = CTy.getTypeArray();
1732 // Add return type.
1733 DIDescriptor RTy = Elements.getElement(0);
1734 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1736 // Add arguments.
1737 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1738 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1739 DIDescriptor Ty = Elements.getElement(i);
1740 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1741 Buffer.AddChild(Arg);
1744 break;
1745 case DW_TAG_structure_type:
1746 case DW_TAG_union_type:
1748 // Add elements to structure type.
1749 DIArray Elements = CTy.getTypeArray();
1751 // A forward struct declared type may not have elements available.
1752 if (Elements.isNull())
1753 break;
1755 // Add elements to structure type.
1756 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1757 DIDescriptor Element = Elements.getElement(i);
1758 DIE *ElemDie = NULL;
1759 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1760 ElemDie = CreateSubprogramDIE(DW_Unit,
1761 DISubprogram(Element.getGV()));
1762 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1763 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1764 DIGlobalVariable(Element.getGV()));
1765 else
1766 ElemDie = CreateMemberDIE(DW_Unit,
1767 DIDerivedType(Element.getGV()));
1768 Buffer.AddChild(ElemDie);
1771 break;
1772 default:
1773 break;
1776 // Add name if not anonymous or intermediate type.
1777 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1779 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1780 || Tag == DW_TAG_union_type) {
1781 // Add size if non-zero (derived types might be zero-sized.)
1782 if (Size)
1783 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1784 else {
1785 // Add zero size if it is not a forward declaration.
1786 if (CTy.isForwardDecl())
1787 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1788 else
1789 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1792 // Add source line info if available.
1793 if (!CTy.isForwardDecl())
1794 AddSourceLine(&Buffer, &CTy);
1798 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1799 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1800 int64_t L = SR.getLo();
1801 int64_t H = SR.getHi();
1802 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1803 if (L != H) {
1804 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1805 if (L)
1806 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1807 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1809 Buffer.AddChild(DW_Subrange);
1812 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1813 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1814 DICompositeType *CTy) {
1815 Buffer.setTag(DW_TAG_array_type);
1816 if (CTy->getTag() == DW_TAG_vector_type)
1817 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1819 // Emit derived type.
1820 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1821 DIArray Elements = CTy->getTypeArray();
1823 // Construct an anonymous type for index type.
1824 DIE IdxBuffer(DW_TAG_base_type);
1825 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1826 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1827 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1829 // Add subranges to array type.
1830 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1831 DIDescriptor Element = Elements.getElement(i);
1832 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1833 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1837 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1838 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1840 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1841 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1842 int64_t Value = ETy->getEnumValue();
1843 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1844 return Enumerator;
1847 /// CreateGlobalVariableDIE - Create new DIE using GV.
1848 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1850 DIE *GVDie = new DIE(DW_TAG_variable);
1851 AddString(GVDie, DW_AT_name, DW_FORM_string, GV.getName());
1852 const std::string &LinkageName = GV.getLinkageName();
1853 if (!LinkageName.empty())
1854 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1855 AddType(DW_Unit, GVDie, GV.getType());
1856 if (!GV.isLocalToUnit())
1857 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1858 AddSourceLine(GVDie, &GV);
1859 return GVDie;
1862 /// CreateMemberDIE - Create new member DIE.
1863 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1864 DIE *MemberDie = new DIE(DT.getTag());
1865 std::string Name = DT.getName();
1866 if (!Name.empty())
1867 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1869 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1871 AddSourceLine(MemberDie, &DT);
1873 // FIXME _ Handle bitfields
1874 DIEBlock *Block = new DIEBlock();
1875 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1876 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1877 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1879 if (DT.isProtected())
1880 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1881 else if (DT.isPrivate())
1882 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1884 return MemberDie;
1887 /// CreateSubprogramDIE - Create new DIE using SP.
1888 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1889 const DISubprogram &SP,
1890 bool IsConstructor = false) {
1891 DIE *SPDie = new DIE(DW_TAG_subprogram);
1892 AddString(SPDie, DW_AT_name, DW_FORM_string, SP.getName());
1893 const std::string &LinkageName = SP.getLinkageName();
1894 if (!LinkageName.empty())
1895 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1896 LinkageName);
1897 AddSourceLine(SPDie, &SP);
1899 DICompositeType SPTy = SP.getType();
1900 DIArray Args = SPTy.getTypeArray();
1902 // Add Return Type.
1903 if (!IsConstructor)
1904 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1906 if (!SP.isDefinition()) {
1907 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1908 // Add arguments.
1909 // Do not add arguments for subprogram definition. They will be
1910 // handled through RecordVariable.
1911 if (!Args.isNull())
1912 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1913 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1914 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1915 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1916 SPDie->AddChild(Arg);
1920 if (!SP.isLocalToUnit())
1921 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1922 return SPDie;
1925 /// FindCompileUnit - Get the compile unit for the given descriptor.
1927 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1928 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
1929 assert(DW_Unit && "Missing compile unit.");
1930 return DW_Unit;
1933 /// NewDbgScopeVariable - Create a new scope variable.
1935 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1936 // Get the descriptor.
1937 const DIVariable &VD = DV->getVariable();
1939 // Translate tag to proper Dwarf tag. The result variable is dropped for
1940 // now.
1941 unsigned Tag;
1942 switch (VD.getTag()) {
1943 case DW_TAG_return_variable: return NULL;
1944 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1945 case DW_TAG_auto_variable: // fall thru
1946 default: Tag = DW_TAG_variable; break;
1949 // Define variable debug information entry.
1950 DIE *VariableDie = new DIE(Tag);
1951 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD.getName());
1953 // Add source line info if available.
1954 AddSourceLine(VariableDie, &VD);
1956 // Add variable type.
1957 AddType(Unit, VariableDie, VD.getType());
1959 // Add variable address.
1960 MachineLocation Location;
1961 Location.set(RI->getFrameRegister(*MF),
1962 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1963 AddAddress(VariableDie, DW_AT_location, Location);
1965 return VariableDie;
1968 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1970 DbgScope *getOrCreateScope(GlobalVariable *V) {
1971 DbgScope *&Slot = DbgScopeMap[V];
1972 if (!Slot) {
1973 // FIXME - breaks down when the context is an inlined function.
1974 DIDescriptor ParentDesc;
1975 DIDescriptor Desc(V);
1976 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
1977 DIBlock Block(V);
1978 ParentDesc = Block.getContext();
1980 DbgScope *Parent = ParentDesc.isNull() ?
1981 NULL : getOrCreateScope(ParentDesc.getGV());
1982 Slot = new DbgScope(Parent, Desc);
1983 if (Parent) {
1984 Parent->AddScope(Slot);
1985 } else if (RootDbgScope) {
1986 // FIXME - Add inlined function scopes to the root so we can delete
1987 // them later. Long term, handle inlined functions properly.
1988 RootDbgScope->AddScope(Slot);
1989 } else {
1990 // First function is top level function.
1991 RootDbgScope = Slot;
1994 return Slot;
1997 /// ConstructDbgScope - Construct the components of a scope.
1999 void ConstructDbgScope(DbgScope *ParentScope,
2000 unsigned ParentStartID, unsigned ParentEndID,
2001 DIE *ParentDie, CompileUnit *Unit) {
2002 // Add variables to scope.
2003 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2004 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2005 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2006 if (VariableDie) ParentDie->AddChild(VariableDie);
2009 // Add nested scopes.
2010 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2011 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2012 // Define the Scope debug information entry.
2013 DbgScope *Scope = Scopes[j];
2014 // FIXME - Ignore inlined functions for the time being.
2015 if (!Scope->getParent()) continue;
2017 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2018 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2020 // Ignore empty scopes.
2021 if (StartID == EndID && StartID != 0) continue;
2022 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2024 if (StartID == ParentStartID && EndID == ParentEndID) {
2025 // Just add stuff to the parent scope.
2026 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2027 } else {
2028 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2030 // Add the scope bounds.
2031 if (StartID) {
2032 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2033 DWLabel("label", StartID));
2034 } else {
2035 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2036 DWLabel("func_begin", SubprogramCount));
2038 if (EndID) {
2039 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2040 DWLabel("label", EndID));
2041 } else {
2042 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2043 DWLabel("func_end", SubprogramCount));
2046 // Add the scope contents.
2047 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2048 ParentDie->AddChild(ScopeDie);
2053 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2055 void ConstructRootDbgScope(DbgScope *RootScope) {
2056 // Exit if there is no root scope.
2057 if (!RootScope) return;
2058 DIDescriptor Desc = RootScope->getDesc();
2059 if (Desc.isNull())
2060 return;
2062 // Get the subprogram debug information entry.
2063 DISubprogram SPD(Desc.getGV());
2065 // Get the compile unit context.
2066 CompileUnit *Unit = MainCU;
2067 if (!Unit)
2068 Unit = FindCompileUnit(SPD.getCompileUnit());
2070 // Get the subprogram die.
2071 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2072 assert(SPDie && "Missing subprogram descriptor");
2074 // Add the function bounds.
2075 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2076 DWLabel("func_begin", SubprogramCount));
2077 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2078 DWLabel("func_end", SubprogramCount));
2079 MachineLocation Location(RI->getFrameRegister(*MF));
2080 AddAddress(SPDie, DW_AT_frame_base, Location);
2082 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2085 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2087 void ConstructDefaultDbgScope(MachineFunction *MF) {
2088 // Find the correct subprogram descriptor.
2089 std::string SPName = "llvm.dbg.subprograms";
2090 std::vector<GlobalVariable*> Result;
2091 getGlobalVariablesUsing(*M, SPName, Result);
2093 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2094 E = Result.end(); I != E; ++I) {
2095 DISubprogram SPD(*I);
2097 if (SPD.getName() == MF->getFunction()->getName()) {
2098 // Get the compile unit context.
2099 CompileUnit *Unit = MainCU;
2100 if (!Unit)
2101 Unit = FindCompileUnit(SPD.getCompileUnit());
2103 // Get the subprogram die.
2104 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2105 assert(SPDie && "Missing subprogram descriptor");
2107 // Add the function bounds.
2108 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2109 DWLabel("func_begin", SubprogramCount));
2110 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2111 DWLabel("func_end", SubprogramCount));
2113 MachineLocation Location(RI->getFrameRegister(*MF));
2114 AddAddress(SPDie, DW_AT_frame_base, Location);
2115 return;
2118 #if 0
2119 // FIXME: This is causing an abort because C++ mangled names are compared
2120 // with their unmangled counterparts. See PR2885. Don't do this assert.
2121 assert(0 && "Couldn't find DIE for machine function!");
2122 #endif
2125 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2126 /// tools to recognize the object file contains Dwarf information.
2127 void EmitInitial() {
2128 // Check to see if we already emitted intial headers.
2129 if (didInitial) return;
2130 didInitial = true;
2132 // Dwarf sections base addresses.
2133 if (TAI->doesDwarfRequireFrameSection()) {
2134 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2135 EmitLabel("section_debug_frame", 0);
2137 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2138 EmitLabel("section_info", 0);
2139 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2140 EmitLabel("section_abbrev", 0);
2141 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2142 EmitLabel("section_aranges", 0);
2143 if (TAI->doesSupportMacInfoSection()) {
2144 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2145 EmitLabel("section_macinfo", 0);
2147 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2148 EmitLabel("section_line", 0);
2149 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2150 EmitLabel("section_loc", 0);
2151 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2152 EmitLabel("section_pubnames", 0);
2153 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2154 EmitLabel("section_str", 0);
2155 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2156 EmitLabel("section_ranges", 0);
2158 Asm->SwitchToSection(TAI->getTextSection());
2159 EmitLabel("text_begin", 0);
2160 Asm->SwitchToSection(TAI->getDataSection());
2161 EmitLabel("data_begin", 0);
2164 /// EmitDIE - Recusively Emits a debug information entry.
2166 void EmitDIE(DIE *Die) {
2167 // Get the abbreviation for this DIE.
2168 unsigned AbbrevNumber = Die->getAbbrevNumber();
2169 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2171 Asm->EOL();
2173 // Emit the code (index) for the abbreviation.
2174 Asm->EmitULEB128Bytes(AbbrevNumber);
2176 if (VerboseAsm)
2177 Asm->EOL(std::string("Abbrev [" +
2178 utostr(AbbrevNumber) +
2179 "] 0x" + utohexstr(Die->getOffset()) +
2180 ":0x" + utohexstr(Die->getSize()) + " " +
2181 TagString(Abbrev->getTag())));
2182 else
2183 Asm->EOL();
2185 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2186 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2188 // Emit the DIE attribute values.
2189 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2190 unsigned Attr = AbbrevData[i].getAttribute();
2191 unsigned Form = AbbrevData[i].getForm();
2192 assert(Form && "Too many attributes for DIE (check abbreviation)");
2194 switch (Attr) {
2195 case DW_AT_sibling: {
2196 Asm->EmitInt32(Die->SiblingOffset());
2197 break;
2199 default: {
2200 // Emit an attribute using the defined form.
2201 Values[i]->EmitValue(*this, Form);
2202 break;
2206 Asm->EOL(AttributeString(Attr));
2209 // Emit the DIE children if any.
2210 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2211 const std::vector<DIE *> &Children = Die->getChildren();
2213 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2214 EmitDIE(Children[j]);
2217 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2221 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2223 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2224 // Get the children.
2225 const std::vector<DIE *> &Children = Die->getChildren();
2227 // If not last sibling and has children then add sibling offset attribute.
2228 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2230 // Record the abbreviation.
2231 AssignAbbrevNumber(Die->getAbbrev());
2233 // Get the abbreviation for this DIE.
2234 unsigned AbbrevNumber = Die->getAbbrevNumber();
2235 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2237 // Set DIE offset
2238 Die->setOffset(Offset);
2240 // Start the size with the size of abbreviation code.
2241 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2243 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2244 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2246 // Size the DIE attribute values.
2247 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2248 // Size attribute value.
2249 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2252 // Size the DIE children if any.
2253 if (!Children.empty()) {
2254 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2255 "Children flag not set");
2257 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2258 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2261 // End of children marker.
2262 Offset += sizeof(int8_t);
2265 Die->setSize(Offset - Die->getOffset());
2266 return Offset;
2269 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2271 void SizeAndOffsets() {
2272 // Process base compile unit.
2273 if (MainCU) {
2274 // Compute size of compile unit header
2275 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2276 sizeof(int16_t) + // DWARF version number
2277 sizeof(int32_t) + // Offset Into Abbrev. Section
2278 sizeof(int8_t); // Pointer Size (in bytes)
2279 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2280 return;
2282 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2283 CE = DW_CUs.end(); CI != CE; ++CI) {
2284 CompileUnit *Unit = CI->second;
2285 // Compute size of compile unit header
2286 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2287 sizeof(int16_t) + // DWARF version number
2288 sizeof(int32_t) + // Offset Into Abbrev. Section
2289 sizeof(int8_t); // Pointer Size (in bytes)
2290 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2294 /// EmitDebugInfo - Emit the debug info section.
2296 void EmitDebugInfo() {
2297 // Start debug info section.
2298 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2300 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2301 CE = DW_CUs.end(); CI != CE; ++CI) {
2302 CompileUnit *Unit = CI->second;
2303 if (MainCU)
2304 Unit = MainCU;
2305 DIE *Die = Unit->getDie();
2306 // Emit the compile units header.
2307 EmitLabel("info_begin", Unit->getID());
2308 // Emit size of content not including length itself
2309 unsigned ContentSize = Die->getSize() +
2310 sizeof(int16_t) + // DWARF version number
2311 sizeof(int32_t) + // Offset Into Abbrev. Section
2312 sizeof(int8_t) + // Pointer Size (in bytes)
2313 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2315 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2316 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2317 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2318 Asm->EOL("Offset Into Abbrev. Section");
2319 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2321 EmitDIE(Die);
2322 // FIXME - extra padding for gdb bug.
2323 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2324 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2325 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2326 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2327 EmitLabel("info_end", Unit->getID());
2329 Asm->EOL();
2330 if (MainCU)
2331 return;
2335 /// EmitAbbreviations - Emit the abbreviation section.
2337 void EmitAbbreviations() const {
2338 // Check to see if it is worth the effort.
2339 if (!Abbreviations.empty()) {
2340 // Start the debug abbrev section.
2341 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2343 EmitLabel("abbrev_begin", 0);
2345 // For each abbrevation.
2346 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2347 // Get abbreviation data
2348 const DIEAbbrev *Abbrev = Abbreviations[i];
2350 // Emit the abbrevations code (base 1 index.)
2351 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2352 Asm->EOL("Abbreviation Code");
2354 // Emit the abbreviations data.
2355 Abbrev->Emit(*this);
2357 Asm->EOL();
2360 // Mark end of abbreviations.
2361 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2363 EmitLabel("abbrev_end", 0);
2365 Asm->EOL();
2369 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2370 /// the line matrix.
2372 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2373 // Define last address of section.
2374 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2375 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2376 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2377 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2379 // Mark end of matrix.
2380 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2381 Asm->EmitULEB128Bytes(1); Asm->EOL();
2382 Asm->EmitInt8(1); Asm->EOL();
2385 /// EmitDebugLines - Emit source line information.
2387 void EmitDebugLines() {
2388 // If the target is using .loc/.file, the assembler will be emitting the
2389 // .debug_line table automatically.
2390 if (TAI->hasDotLocAndDotFile())
2391 return;
2393 // Minimum line delta, thus ranging from -10..(255-10).
2394 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2395 // Maximum line delta, thus ranging from -10..(255-10).
2396 const int MaxLineDelta = 255 + MinLineDelta;
2398 // Start the dwarf line section.
2399 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2401 // Construct the section header.
2403 EmitDifference("line_end", 0, "line_begin", 0, true);
2404 Asm->EOL("Length of Source Line Info");
2405 EmitLabel("line_begin", 0);
2407 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2409 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2410 Asm->EOL("Prolog Length");
2411 EmitLabel("line_prolog_begin", 0);
2413 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2415 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2417 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2419 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2421 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2423 // Line number standard opcode encodings argument count
2424 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2425 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2426 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2427 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2428 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2429 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2430 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2431 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2432 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2434 // Emit directories.
2435 for (unsigned DirectoryID = 1, NDID = Directories.size();
2436 DirectoryID <= NDID; ++DirectoryID) {
2437 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2439 Asm->EmitInt8(0); Asm->EOL("End of directories");
2441 // Emit files.
2442 for (unsigned SourceID = 1, NSID = SrcFiles.size();
2443 SourceID <= NSID; ++SourceID) {
2444 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2445 Asm->EmitString(SourceFile.getName());
2446 Asm->EOL("Source");
2447 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2448 Asm->EOL("Directory #");
2449 Asm->EmitULEB128Bytes(0);
2450 Asm->EOL("Mod date");
2451 Asm->EmitULEB128Bytes(0);
2452 Asm->EOL("File size");
2454 Asm->EmitInt8(0); Asm->EOL("End of files");
2456 EmitLabel("line_prolog_end", 0);
2458 // A sequence for each text section.
2459 unsigned SecSrcLinesSize = SectionSourceLines.size();
2461 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2462 // Isolate current sections line info.
2463 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2465 if (VerboseAsm) {
2466 const Section* S = SectionMap[j + 1];
2467 Asm->EOL(std::string("Section ") + S->getName());
2468 } else
2469 Asm->EOL();
2471 // Dwarf assumes we start with first line of first source file.
2472 unsigned Source = 1;
2473 unsigned Line = 1;
2475 // Construct rows of the address, source, line, column matrix.
2476 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2477 const SrcLineInfo &LineInfo = LineInfos[i];
2478 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2479 if (!LabelID) continue;
2481 unsigned SourceID = LineInfo.getSourceID();
2482 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2483 unsigned DirectoryID = SourceFile.getDirectoryID();
2484 if (VerboseAsm)
2485 Asm->EOL(Directories[DirectoryID]
2486 + SourceFile.getName()
2487 + ":"
2488 + utostr_32(LineInfo.getLine()));
2489 else
2490 Asm->EOL();
2492 // Define the line address.
2493 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2494 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2495 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2496 EmitReference("label", LabelID); Asm->EOL("Location label");
2498 // If change of source, then switch to the new source.
2499 if (Source != LineInfo.getSourceID()) {
2500 Source = LineInfo.getSourceID();
2501 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2502 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2505 // If change of line.
2506 if (Line != LineInfo.getLine()) {
2507 // Determine offset.
2508 int Offset = LineInfo.getLine() - Line;
2509 int Delta = Offset - MinLineDelta;
2511 // Update line.
2512 Line = LineInfo.getLine();
2514 // If delta is small enough and in range...
2515 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2516 // ... then use fast opcode.
2517 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2518 } else {
2519 // ... otherwise use long hand.
2520 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2521 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2522 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2524 } else {
2525 // Copy the previous row (different address or source)
2526 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2530 EmitEndOfLineMatrix(j + 1);
2533 if (SecSrcLinesSize == 0)
2534 // Because we're emitting a debug_line section, we still need a line
2535 // table. The linker and friends expect it to exist. If there's nothing to
2536 // put into it, emit an empty table.
2537 EmitEndOfLineMatrix(1);
2539 EmitLabel("line_end", 0);
2541 Asm->EOL();
2544 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2546 void EmitCommonDebugFrame() {
2547 if (!TAI->doesDwarfRequireFrameSection())
2548 return;
2550 int stackGrowth =
2551 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2552 TargetFrameInfo::StackGrowsUp ?
2553 TD->getPointerSize() : -TD->getPointerSize();
2555 // Start the dwarf frame section.
2556 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2558 EmitLabel("debug_frame_common", 0);
2559 EmitDifference("debug_frame_common_end", 0,
2560 "debug_frame_common_begin", 0, true);
2561 Asm->EOL("Length of Common Information Entry");
2563 EmitLabel("debug_frame_common_begin", 0);
2564 Asm->EmitInt32((int)DW_CIE_ID);
2565 Asm->EOL("CIE Identifier Tag");
2566 Asm->EmitInt8(DW_CIE_VERSION);
2567 Asm->EOL("CIE Version");
2568 Asm->EmitString("");
2569 Asm->EOL("CIE Augmentation");
2570 Asm->EmitULEB128Bytes(1);
2571 Asm->EOL("CIE Code Alignment Factor");
2572 Asm->EmitSLEB128Bytes(stackGrowth);
2573 Asm->EOL("CIE Data Alignment Factor");
2574 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2575 Asm->EOL("CIE RA Column");
2577 std::vector<MachineMove> Moves;
2578 RI->getInitialFrameState(Moves);
2580 EmitFrameMoves(NULL, 0, Moves, false);
2582 Asm->EmitAlignment(2, 0, 0, false);
2583 EmitLabel("debug_frame_common_end", 0);
2585 Asm->EOL();
2588 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2589 /// section.
2590 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2591 if (!TAI->doesDwarfRequireFrameSection())
2592 return;
2594 // Start the dwarf frame section.
2595 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2597 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2598 "debug_frame_begin", DebugFrameInfo.Number, true);
2599 Asm->EOL("Length of Frame Information Entry");
2601 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2603 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2604 0, 0, true, false);
2605 Asm->EOL("FDE CIE offset");
2607 EmitReference("func_begin", DebugFrameInfo.Number);
2608 Asm->EOL("FDE initial location");
2609 EmitDifference("func_end", DebugFrameInfo.Number,
2610 "func_begin", DebugFrameInfo.Number);
2611 Asm->EOL("FDE address range");
2613 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2614 false);
2616 Asm->EmitAlignment(2, 0, 0, false);
2617 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2619 Asm->EOL();
2622 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2624 void EmitDebugPubNames() {
2625 // Start the dwarf pubnames section.
2626 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2628 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2629 CE = DW_CUs.end(); CI != CE; ++CI) {
2630 CompileUnit *Unit = CI->second;
2631 if (MainCU)
2632 Unit = MainCU;
2634 EmitDifference("pubnames_end", Unit->getID(),
2635 "pubnames_begin", Unit->getID(), true);
2636 Asm->EOL("Length of Public Names Info");
2638 EmitLabel("pubnames_begin", Unit->getID());
2640 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2642 EmitSectionOffset("info_begin", "section_info",
2643 Unit->getID(), 0, true, false);
2644 Asm->EOL("Offset of Compilation Unit Info");
2646 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2647 true);
2648 Asm->EOL("Compilation Unit Length");
2650 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2652 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2653 GE = Globals.end();
2654 GI != GE; ++GI) {
2655 const std::string &Name = GI->first;
2656 DIE * Entity = GI->second;
2658 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2659 Asm->EmitString(Name); Asm->EOL("External Name");
2662 Asm->EmitInt32(0); Asm->EOL("End Mark");
2663 EmitLabel("pubnames_end", Unit->getID());
2665 Asm->EOL();
2666 if (MainCU)
2667 return;
2671 /// EmitDebugStr - Emit visible names into a debug str section.
2673 void EmitDebugStr() {
2674 // Check to see if it is worth the effort.
2675 if (!StringPool.empty()) {
2676 // Start the dwarf str section.
2677 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2679 // For each of strings in the string pool.
2680 for (unsigned StringID = 1, N = StringPool.size();
2681 StringID <= N; ++StringID) {
2682 // Emit a label for reference from debug information entries.
2683 EmitLabel("string", StringID);
2684 // Emit the string itself.
2685 const std::string &String = StringPool[StringID];
2686 Asm->EmitString(String); Asm->EOL();
2689 Asm->EOL();
2693 /// EmitDebugLoc - Emit visible names into a debug loc section.
2695 void EmitDebugLoc() {
2696 // Start the dwarf loc section.
2697 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2699 Asm->EOL();
2702 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2704 void EmitDebugARanges() {
2705 // Start the dwarf aranges section.
2706 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2708 // FIXME - Mock up
2709 #if 0
2710 CompileUnit *Unit = GetBaseCompileUnit();
2712 // Don't include size of length
2713 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2715 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2717 EmitReference("info_begin", Unit->getID());
2718 Asm->EOL("Offset of Compilation Unit Info");
2720 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2722 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2724 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2725 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2727 // Range 1
2728 EmitReference("text_begin", 0); Asm->EOL("Address");
2729 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2731 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2732 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2733 #endif
2735 Asm->EOL();
2738 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2740 void EmitDebugRanges() {
2741 // Start the dwarf ranges section.
2742 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2744 Asm->EOL();
2747 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2749 void EmitDebugMacInfo() {
2750 if (TAI->doesSupportMacInfoSection()) {
2751 // Start the dwarf macinfo section.
2752 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2754 Asm->EOL();
2758 /// ConstructCompileUnits - Create a compile unit DIEs.
2759 void ConstructCompileUnits() {
2760 std::string CUName = "llvm.dbg.compile_units";
2761 std::vector<GlobalVariable*> Result;
2762 getGlobalVariablesUsing(*M, CUName, Result);
2763 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2764 RE = Result.end(); RI != RE; ++RI) {
2765 DICompileUnit DIUnit(*RI);
2766 unsigned ID = RecordSource(DIUnit.getDirectory(),
2767 DIUnit.getFilename());
2769 DIE *Die = new DIE(DW_TAG_compile_unit);
2770 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2771 DWLabel("section_line", 0), DWLabel("section_line", 0),
2772 false);
2773 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer());
2774 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2775 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit.getFilename());
2776 if (!DIUnit.getDirectory().empty())
2777 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit.getDirectory());
2778 if (DIUnit.isOptimized())
2779 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2780 const std::string &Flags = DIUnit.getFlags();
2781 if (!Flags.empty())
2782 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2784 CompileUnit *Unit = new CompileUnit(ID, Die);
2785 if (DIUnit.isMain()) {
2786 assert(!MainCU && "Multiple main compile units are found!");
2787 MainCU = Unit;
2789 DW_CUs[DIUnit.getGV()] = Unit;
2793 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2794 /// visible global variables.
2795 void ConstructGlobalVariableDIEs() {
2796 std::string GVName = "llvm.dbg.global_variables";
2797 std::vector<GlobalVariable*> Result;
2798 getGlobalVariablesUsing(*M, GVName, Result);
2799 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
2800 GVE = Result.end(); GVI != GVE; ++GVI) {
2801 DIGlobalVariable DI_GV(*GVI);
2802 CompileUnit *DW_Unit = MainCU;
2803 if (!DW_Unit)
2804 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2806 // Check for pre-existence.
2807 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2808 if (Slot) continue;
2810 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2812 // Add address.
2813 DIEBlock *Block = new DIEBlock();
2814 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2815 AddObjectLabel(Block, 0, DW_FORM_udata,
2816 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2817 AddBlock(VariableDie, DW_AT_location, 0, Block);
2819 //Add to map.
2820 Slot = VariableDie;
2822 //Add to context owner.
2823 DW_Unit->getDie()->AddChild(VariableDie);
2825 //Expose as global. FIXME - need to check external flag.
2826 DW_Unit->AddGlobal(DI_GV.getName(), VariableDie);
2830 /// ConstructSubprograms - Create DIEs for each of the externally visible
2831 /// subprograms.
2832 void ConstructSubprograms() {
2834 std::string SPName = "llvm.dbg.subprograms";
2835 std::vector<GlobalVariable*> Result;
2836 getGlobalVariablesUsing(*M, SPName, Result);
2837 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2838 RE = Result.end(); RI != RE; ++RI) {
2840 DISubprogram SP(*RI);
2841 CompileUnit *Unit = MainCU;
2842 if (!Unit)
2843 Unit = FindCompileUnit(SP.getCompileUnit());
2845 // Check for pre-existence.
2846 DIE *&Slot = Unit->getDieMapSlotFor(SP.getGV());
2847 if (Slot) continue;
2849 if (!SP.isDefinition())
2850 // This is a method declaration which will be handled while
2851 // constructing class type.
2852 continue;
2854 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2856 //Add to map.
2857 Slot = SubprogramDie;
2858 //Add to context owner.
2859 Unit->getDie()->AddChild(SubprogramDie);
2860 //Expose as global.
2861 Unit->AddGlobal(SP.getName(), SubprogramDie);
2865 public:
2866 //===--------------------------------------------------------------------===//
2867 // Main entry points.
2869 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2870 : Dwarf(OS, A, T, "dbg")
2871 , MainCU(NULL)
2872 , AbbreviationsSet(InitAbbreviationsSetSize)
2873 , Abbreviations()
2874 , ValuesSet(InitValuesSetSize)
2875 , Values()
2876 , StringPool()
2877 , SectionMap()
2878 , SectionSourceLines()
2879 , didInitial(false)
2880 , shouldEmit(false)
2881 , RootDbgScope(NULL)
2884 virtual ~DwarfDebug() {
2885 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2886 delete Values[j];
2889 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2890 /// This is inovked by the target AsmPrinter.
2891 void SetDebugInfo(MachineModuleInfo *mmi) {
2892 // Create all the compile unit DIEs.
2893 ConstructCompileUnits();
2895 if (DW_CUs.empty())
2896 return;
2898 MMI = mmi;
2899 shouldEmit = true;
2900 MMI->setDebugInfoAvailability(true);
2902 // Create DIEs for each of the externally visible global variables.
2903 ConstructGlobalVariableDIEs();
2905 // Create DIEs for each of the externally visible subprograms.
2906 ConstructSubprograms();
2908 // Prime section data.
2909 SectionMap.insert(TAI->getTextSection());
2911 // Print out .file directives to specify files for .loc directives. These
2912 // are printed out early so that they precede any .loc directives.
2913 if (TAI->hasDotLocAndDotFile()) {
2914 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
2915 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
2916 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
2917 assert(AppendOk && "Could not append filename to directory!");
2918 AppendOk = false;
2919 Asm->EmitFile(i, FullPath.toString());
2920 Asm->EOL();
2924 // Emit initial sections
2925 EmitInitial();
2928 /// BeginModule - Emit all Dwarf sections that should come prior to the
2929 /// content.
2930 void BeginModule(Module *M) {
2931 this->M = M;
2934 /// EndModule - Emit all Dwarf sections that should come after the content.
2936 void EndModule() {
2937 if (!ShouldEmitDwarf()) return;
2939 // Standard sections final addresses.
2940 Asm->SwitchToSection(TAI->getTextSection());
2941 EmitLabel("text_end", 0);
2942 Asm->SwitchToSection(TAI->getDataSection());
2943 EmitLabel("data_end", 0);
2945 // End text sections.
2946 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2947 Asm->SwitchToSection(SectionMap[i]);
2948 EmitLabel("section_end", i);
2951 // Emit common frame information.
2952 EmitCommonDebugFrame();
2954 // Emit function debug frame information
2955 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2956 E = DebugFrames.end(); I != E; ++I)
2957 EmitFunctionDebugFrame(*I);
2959 // Compute DIE offsets and sizes.
2960 SizeAndOffsets();
2962 // Emit all the DIEs into a debug info section
2963 EmitDebugInfo();
2965 // Corresponding abbreviations into a abbrev section.
2966 EmitAbbreviations();
2968 // Emit source line correspondence into a debug line section.
2969 EmitDebugLines();
2971 // Emit info into a debug pubnames section.
2972 EmitDebugPubNames();
2974 // Emit info into a debug str section.
2975 EmitDebugStr();
2977 // Emit info into a debug loc section.
2978 EmitDebugLoc();
2980 // Emit info into a debug aranges section.
2981 EmitDebugARanges();
2983 // Emit info into a debug ranges section.
2984 EmitDebugRanges();
2986 // Emit info into a debug macinfo section.
2987 EmitDebugMacInfo();
2990 /// BeginFunction - Gather pre-function debug information. Assumes being
2991 /// emitted immediately after the function entry point.
2992 void BeginFunction(MachineFunction *MF) {
2993 this->MF = MF;
2995 if (!ShouldEmitDwarf()) return;
2997 // Begin accumulating function debug information.
2998 MMI->BeginFunction(MF);
3000 // Assumes in correct section after the entry point.
3001 EmitLabel("func_begin", ++SubprogramCount);
3003 // Emit label for the implicitly defined dbg.stoppoint at the start of
3004 // the function.
3005 if (!Lines.empty()) {
3006 const SrcLineInfo &LineInfo = Lines[0];
3007 Asm->printLabel(LineInfo.getLabelID());
3011 /// EndFunction - Gather and emit post-function debug information.
3013 void EndFunction(MachineFunction *MF) {
3014 if (!ShouldEmitDwarf()) return;
3016 // Define end label for subprogram.
3017 EmitLabel("func_end", SubprogramCount);
3019 // Get function line info.
3020 if (!Lines.empty()) {
3021 // Get section line info.
3022 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3023 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3024 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3025 // Append the function info to section info.
3026 SectionLineInfos.insert(SectionLineInfos.end(),
3027 Lines.begin(), Lines.end());
3030 // Construct scopes for subprogram.
3031 if (RootDbgScope)
3032 ConstructRootDbgScope(RootDbgScope);
3033 else
3034 // FIXME: This is wrong. We are essentially getting past a problem with
3035 // debug information not being able to handle unreachable blocks that have
3036 // debug information in them. In particular, those unreachable blocks that
3037 // have "region end" info in them. That situation results in the "root
3038 // scope" not being created. If that's the case, then emit a "default"
3039 // scope, i.e., one that encompasses the whole function. This isn't
3040 // desirable. And a better way of handling this (and all of the debugging
3041 // information) needs to be explored.
3042 ConstructDefaultDbgScope(MF);
3044 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3045 MMI->getFrameMoves()));
3047 // Clear debug info
3048 if (RootDbgScope) {
3049 delete RootDbgScope;
3050 DbgScopeMap.clear();
3051 RootDbgScope = NULL;
3053 Lines.clear();
3056 public:
3058 /// ValidDebugInfo - Return true if V represents valid debug info value.
3059 bool ValidDebugInfo(Value *V) {
3061 if (!V)
3062 return false;
3064 if (!shouldEmit)
3065 return false;
3067 GlobalVariable *GV = getGlobalVariable(V);
3068 if (!GV)
3069 return false;
3071 if (GV->getLinkage() != GlobalValue::InternalLinkage
3072 && GV->getLinkage() != GlobalValue::LinkOnceLinkage)
3073 return false;
3075 DIDescriptor DI(GV);
3076 // Check current version. Allow Version6 for now.
3077 unsigned Version = DI.getVersion();
3078 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
3079 return false;
3081 unsigned Tag = DI.getTag();
3082 switch (Tag) {
3083 case DW_TAG_variable:
3084 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3085 break;
3086 case DW_TAG_compile_unit:
3087 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3088 break;
3089 case DW_TAG_subprogram:
3090 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3091 break;
3092 default:
3093 break;
3096 return true;
3099 /// RecordSourceLine - Records location information and associates it with a
3100 /// label. Returns a unique label ID used to generate a label and provide
3101 /// correspondence to the source line list.
3102 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3103 CompileUnit *Unit = DW_CUs[V];
3104 assert(Unit && "Unable to find CompileUnit");
3105 unsigned ID = MMI->NextLabelID();
3106 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3107 return ID;
3110 /// RecordSourceLine - Records location information and associates it with a
3111 /// label. Returns a unique label ID used to generate a label and provide
3112 /// correspondence to the source line list.
3113 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3114 unsigned ID = MMI->NextLabelID();
3115 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3116 return ID;
3119 unsigned getRecordSourceLineCount() {
3120 return Lines.size();
3123 /// RecordSource - Register a source file with debug info. Returns an source
3124 /// ID.
3125 unsigned RecordSource(const std::string &Directory,
3126 const std::string &File) {
3127 unsigned DID = Directories.insert(Directory);
3128 return SrcFiles.insert(SrcFileInfo(DID,File));
3131 /// RecordRegionStart - Indicate the start of a region.
3133 unsigned RecordRegionStart(GlobalVariable *V) {
3134 DbgScope *Scope = getOrCreateScope(V);
3135 unsigned ID = MMI->NextLabelID();
3136 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3137 return ID;
3140 /// RecordRegionEnd - Indicate the end of a region.
3142 unsigned RecordRegionEnd(GlobalVariable *V) {
3143 DbgScope *Scope = getOrCreateScope(V);
3144 unsigned ID = MMI->NextLabelID();
3145 Scope->setEndLabelID(ID);
3146 return ID;
3149 /// RecordVariable - Indicate the declaration of a local variable.
3151 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3152 DIDescriptor Desc(GV);
3153 DbgScope *Scope = NULL;
3154 if (Desc.getTag() == DW_TAG_variable) {
3155 // GV is a global variable.
3156 DIGlobalVariable DG(GV);
3157 Scope = getOrCreateScope(DG.getContext().getGV());
3158 } else {
3159 // or GV is a local variable.
3160 DIVariable DV(GV);
3161 Scope = getOrCreateScope(DV.getContext().getGV());
3163 assert(Scope && "Unable to find variable' scope");
3164 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3165 Scope->AddVariable(DV);
3169 //===----------------------------------------------------------------------===//
3170 /// DwarfException - Emits Dwarf exception handling directives.
3172 class DwarfException : public Dwarf {
3173 struct FunctionEHFrameInfo {
3174 std::string FnName;
3175 unsigned Number;
3176 unsigned PersonalityIndex;
3177 bool hasCalls;
3178 bool hasLandingPads;
3179 std::vector<MachineMove> Moves;
3180 const Function * function;
3182 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3183 bool hC, bool hL,
3184 const std::vector<MachineMove> &M,
3185 const Function *f):
3186 FnName(FN), Number(Num), PersonalityIndex(P),
3187 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3190 std::vector<FunctionEHFrameInfo> EHFrames;
3192 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3193 /// be emitted.
3194 bool shouldEmitTable;
3196 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3197 /// should be emitted.
3198 bool shouldEmitMoves;
3200 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3201 /// should be emitted.
3202 bool shouldEmitTableModule;
3204 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3205 /// should be emitted.
3206 bool shouldEmitMovesModule;
3208 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3210 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3211 // Size and sign of stack growth.
3212 int stackGrowth =
3213 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3214 TargetFrameInfo::StackGrowsUp ?
3215 TD->getPointerSize() : -TD->getPointerSize();
3217 // Begin eh frame section.
3218 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3220 if (!TAI->doesRequireNonLocalEHFrameLabel())
3221 O << TAI->getEHGlobalPrefix();
3222 O << "EH_frame" << Index << ":\n";
3223 EmitLabel("section_eh_frame", Index);
3225 // Define base labels.
3226 EmitLabel("eh_frame_common", Index);
3228 // Define the eh frame length.
3229 EmitDifference("eh_frame_common_end", Index,
3230 "eh_frame_common_begin", Index, true);
3231 Asm->EOL("Length of Common Information Entry");
3233 // EH frame header.
3234 EmitLabel("eh_frame_common_begin", Index);
3235 Asm->EmitInt32((int)0);
3236 Asm->EOL("CIE Identifier Tag");
3237 Asm->EmitInt8(DW_CIE_VERSION);
3238 Asm->EOL("CIE Version");
3240 // The personality presence indicates that language specific information
3241 // will show up in the eh frame.
3242 Asm->EmitString(Personality ? "zPLR" : "zR");
3243 Asm->EOL("CIE Augmentation");
3245 // Round out reader.
3246 Asm->EmitULEB128Bytes(1);
3247 Asm->EOL("CIE Code Alignment Factor");
3248 Asm->EmitSLEB128Bytes(stackGrowth);
3249 Asm->EOL("CIE Data Alignment Factor");
3250 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3251 Asm->EOL("CIE Return Address Column");
3253 // If there is a personality, we need to indicate the functions location.
3254 if (Personality) {
3255 Asm->EmitULEB128Bytes(7);
3256 Asm->EOL("Augmentation Size");
3258 if (TAI->getNeedsIndirectEncoding()) {
3259 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3260 Asm->EOL("Personality (pcrel sdata4 indirect)");
3261 } else {
3262 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3263 Asm->EOL("Personality (pcrel sdata4)");
3266 PrintRelDirective(true);
3267 O << TAI->getPersonalityPrefix();
3268 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3269 O << TAI->getPersonalitySuffix();
3270 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3271 O << "-" << TAI->getPCSymbol();
3272 Asm->EOL("Personality");
3274 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3275 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3277 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3278 Asm->EOL("FDE Encoding (pcrel sdata4)");
3279 } else {
3280 Asm->EmitULEB128Bytes(1);
3281 Asm->EOL("Augmentation Size");
3283 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3284 Asm->EOL("FDE Encoding (pcrel sdata4)");
3287 // Indicate locations of general callee saved registers in frame.
3288 std::vector<MachineMove> Moves;
3289 RI->getInitialFrameState(Moves);
3290 EmitFrameMoves(NULL, 0, Moves, true);
3292 // On Darwin the linker honors the alignment of eh_frame, which means it
3293 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3294 // you get holes which confuse readers of eh_frame.
3295 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3296 0, 0, false);
3297 EmitLabel("eh_frame_common_end", Index);
3299 Asm->EOL();
3302 /// EmitEHFrame - Emit function exception frame information.
3304 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3305 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3307 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3309 // Externally visible entry into the functions eh frame info.
3310 // If the corresponding function is static, this should not be
3311 // externally visible.
3312 if (linkage != Function::InternalLinkage &&
3313 linkage != Function::PrivateLinkage) {
3314 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3315 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3318 // If corresponding function is weak definition, this should be too.
3319 if ((linkage == Function::WeakLinkage ||
3320 linkage == Function::LinkOnceLinkage) &&
3321 TAI->getWeakDefDirective())
3322 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3324 // If there are no calls then you can't unwind. This may mean we can
3325 // omit the EH Frame, but some environments do not handle weak absolute
3326 // symbols.
3327 // If UnwindTablesMandatory is set we cannot do this optimization; the
3328 // unwind info is to be available for non-EH uses.
3329 if (!EHFrameInfo.hasCalls &&
3330 !UnwindTablesMandatory &&
3331 ((linkage != Function::WeakLinkage &&
3332 linkage != Function::LinkOnceLinkage) ||
3333 !TAI->getWeakDefDirective() ||
3334 TAI->getSupportsWeakOmittedEHFrame()))
3336 O << EHFrameInfo.FnName << " = 0\n";
3337 // This name has no connection to the function, so it might get
3338 // dead-stripped when the function is not, erroneously. Prohibit
3339 // dead-stripping unconditionally.
3340 if (const char *UsedDirective = TAI->getUsedDirective())
3341 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3342 } else {
3343 O << EHFrameInfo.FnName << ":\n";
3345 // EH frame header.
3346 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3347 "eh_frame_begin", EHFrameInfo.Number, true);
3348 Asm->EOL("Length of Frame Information Entry");
3350 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3352 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3353 PrintRelDirective(true, true);
3354 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3356 if (!TAI->isAbsoluteEHSectionOffsets())
3357 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3358 } else {
3359 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3360 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3361 true, true, false);
3364 Asm->EOL("FDE CIE offset");
3366 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3367 Asm->EOL("FDE initial location");
3368 EmitDifference("eh_func_end", EHFrameInfo.Number,
3369 "eh_func_begin", EHFrameInfo.Number, true);
3370 Asm->EOL("FDE address range");
3372 // If there is a personality and landing pads then point to the language
3373 // specific data area in the exception table.
3374 if (EHFrameInfo.PersonalityIndex) {
3375 Asm->EmitULEB128Bytes(4);
3376 Asm->EOL("Augmentation size");
3378 if (EHFrameInfo.hasLandingPads)
3379 EmitReference("exception", EHFrameInfo.Number, true, true);
3380 else
3381 Asm->EmitInt32((int)0);
3382 Asm->EOL("Language Specific Data Area");
3383 } else {
3384 Asm->EmitULEB128Bytes(0);
3385 Asm->EOL("Augmentation size");
3388 // Indicate locations of function specific callee saved registers in
3389 // frame.
3390 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3391 true);
3393 // On Darwin the linker honors the alignment of eh_frame, which means it
3394 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3395 // you get holes which confuse readers of eh_frame.
3396 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3397 0, 0, false);
3398 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3400 // If the function is marked used, this table should be also. We cannot
3401 // make the mark unconditional in this case, since retaining the table
3402 // also retains the function in this case, and there is code around
3403 // that depends on unused functions (calling undefined externals) being
3404 // dead-stripped to link correctly. Yes, there really is.
3405 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3406 if (const char *UsedDirective = TAI->getUsedDirective())
3407 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3411 /// EmitExceptionTable - Emit landing pads and actions.
3413 /// The general organization of the table is complex, but the basic concepts
3414 /// are easy. First there is a header which describes the location and
3415 /// organization of the three components that follow.
3416 /// 1. The landing pad site information describes the range of code covered
3417 /// by the try. In our case it's an accumulation of the ranges covered
3418 /// by the invokes in the try. There is also a reference to the landing
3419 /// pad that handles the exception once processed. Finally an index into
3420 /// the actions table.
3421 /// 2. The action table, in our case, is composed of pairs of type ids
3422 /// and next action offset. Starting with the action index from the
3423 /// landing pad site, each type Id is checked for a match to the current
3424 /// exception. If it matches then the exception and type id are passed
3425 /// on to the landing pad. Otherwise the next action is looked up. This
3426 /// chain is terminated with a next action of zero. If no type id is
3427 /// found the the frame is unwound and handling continues.
3428 /// 3. Type id table contains references to all the C++ typeinfo for all
3429 /// catches in the function. This tables is reversed indexed base 1.
3431 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3432 static unsigned SharedTypeIds(const LandingPadInfo *L,
3433 const LandingPadInfo *R) {
3434 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3435 unsigned LSize = LIds.size(), RSize = RIds.size();
3436 unsigned MinSize = LSize < RSize ? LSize : RSize;
3437 unsigned Count = 0;
3439 for (; Count != MinSize; ++Count)
3440 if (LIds[Count] != RIds[Count])
3441 return Count;
3443 return Count;
3446 /// PadLT - Order landing pads lexicographically by type id.
3447 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3448 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3449 unsigned LSize = LIds.size(), RSize = RIds.size();
3450 unsigned MinSize = LSize < RSize ? LSize : RSize;
3452 for (unsigned i = 0; i != MinSize; ++i)
3453 if (LIds[i] != RIds[i])
3454 return LIds[i] < RIds[i];
3456 return LSize < RSize;
3459 struct KeyInfo {
3460 static inline unsigned getEmptyKey() { return -1U; }
3461 static inline unsigned getTombstoneKey() { return -2U; }
3462 static unsigned getHashValue(const unsigned &Key) { return Key; }
3463 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3464 static bool isPod() { return true; }
3467 /// ActionEntry - Structure describing an entry in the actions table.
3468 struct ActionEntry {
3469 int ValueForTypeID; // The value to write - may not be equal to the type id.
3470 int NextAction;
3471 struct ActionEntry *Previous;
3474 /// PadRange - Structure holding a try-range and the associated landing pad.
3475 struct PadRange {
3476 // The index of the landing pad.
3477 unsigned PadIndex;
3478 // The index of the begin and end labels in the landing pad's label lists.
3479 unsigned RangeIndex;
3482 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3484 /// CallSiteEntry - Structure describing an entry in the call-site table.
3485 struct CallSiteEntry {
3486 // The 'try-range' is BeginLabel .. EndLabel.
3487 unsigned BeginLabel; // zero indicates the start of the function.
3488 unsigned EndLabel; // zero indicates the end of the function.
3489 // The landing pad starts at PadLabel.
3490 unsigned PadLabel; // zero indicates that there is no landing pad.
3491 unsigned Action;
3494 void EmitExceptionTable() {
3495 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3496 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3497 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3498 if (PadInfos.empty()) return;
3500 // Sort the landing pads in order of their type ids. This is used to fold
3501 // duplicate actions.
3502 SmallVector<const LandingPadInfo *, 64> LandingPads;
3503 LandingPads.reserve(PadInfos.size());
3504 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3505 LandingPads.push_back(&PadInfos[i]);
3506 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3508 // Negative type ids index into FilterIds, positive type ids index into
3509 // TypeInfos. The value written for a positive type id is just the type
3510 // id itself. For a negative type id, however, the value written is the
3511 // (negative) byte offset of the corresponding FilterIds entry. The byte
3512 // offset is usually equal to the type id, because the FilterIds entries
3513 // are written using a variable width encoding which outputs one byte per
3514 // entry as long as the value written is not too large, but can differ.
3515 // This kind of complication does not occur for positive type ids because
3516 // type infos are output using a fixed width encoding.
3517 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3518 SmallVector<int, 16> FilterOffsets;
3519 FilterOffsets.reserve(FilterIds.size());
3520 int Offset = -1;
3521 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3522 E = FilterIds.end(); I != E; ++I) {
3523 FilterOffsets.push_back(Offset);
3524 Offset -= TargetAsmInfo::getULEB128Size(*I);
3527 // Compute the actions table and gather the first action index for each
3528 // landing pad site.
3529 SmallVector<ActionEntry, 32> Actions;
3530 SmallVector<unsigned, 64> FirstActions;
3531 FirstActions.reserve(LandingPads.size());
3533 int FirstAction = 0;
3534 unsigned SizeActions = 0;
3535 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3536 const LandingPadInfo *LP = LandingPads[i];
3537 const std::vector<int> &TypeIds = LP->TypeIds;
3538 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3539 unsigned SizeSiteActions = 0;
3541 if (NumShared < TypeIds.size()) {
3542 unsigned SizeAction = 0;
3543 ActionEntry *PrevAction = 0;
3545 if (NumShared) {
3546 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3547 assert(Actions.size());
3548 PrevAction = &Actions.back();
3549 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3550 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3551 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3552 SizeAction -=
3553 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3554 SizeAction += -PrevAction->NextAction;
3555 PrevAction = PrevAction->Previous;
3559 // Compute the actions.
3560 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3561 int TypeID = TypeIds[I];
3562 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3563 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3564 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3566 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3567 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3568 SizeSiteActions += SizeAction;
3570 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3571 Actions.push_back(Action);
3573 PrevAction = &Actions.back();
3576 // Record the first action of the landing pad site.
3577 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3578 } // else identical - re-use previous FirstAction
3580 FirstActions.push_back(FirstAction);
3582 // Compute this sites contribution to size.
3583 SizeActions += SizeSiteActions;
3586 // Compute the call-site table. The entry for an invoke has a try-range
3587 // containing the call, a non-zero landing pad and an appropriate action.
3588 // The entry for an ordinary call has a try-range containing the call and
3589 // zero for the landing pad and the action. Calls marked 'nounwind' have
3590 // no entry and must not be contained in the try-range of any entry - they
3591 // form gaps in the table. Entries must be ordered by try-range address.
3592 SmallVector<CallSiteEntry, 64> CallSites;
3594 RangeMapType PadMap;
3595 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3596 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3597 // try-ranges for them need be deduced.
3598 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3599 const LandingPadInfo *LandingPad = LandingPads[i];
3600 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3601 unsigned BeginLabel = LandingPad->BeginLabels[j];
3602 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3603 PadRange P = { i, j };
3604 PadMap[BeginLabel] = P;
3608 // The end label of the previous invoke or nounwind try-range.
3609 unsigned LastLabel = 0;
3611 // Whether there is a potentially throwing instruction (currently this means
3612 // an ordinary call) between the end of the previous try-range and now.
3613 bool SawPotentiallyThrowing = false;
3615 // Whether the last callsite entry was for an invoke.
3616 bool PreviousIsInvoke = false;
3618 // Visit all instructions in order of address.
3619 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3620 I != E; ++I) {
3621 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3622 MI != E; ++MI) {
3623 if (!MI->isLabel()) {
3624 SawPotentiallyThrowing |= MI->getDesc().isCall();
3625 continue;
3628 unsigned BeginLabel = MI->getOperand(0).getImm();
3629 assert(BeginLabel && "Invalid label!");
3631 // End of the previous try-range?
3632 if (BeginLabel == LastLabel)
3633 SawPotentiallyThrowing = false;
3635 // Beginning of a new try-range?
3636 RangeMapType::iterator L = PadMap.find(BeginLabel);
3637 if (L == PadMap.end())
3638 // Nope, it was just some random label.
3639 continue;
3641 PadRange P = L->second;
3642 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3644 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3645 "Inconsistent landing pad map!");
3647 // If some instruction between the previous try-range and this one may
3648 // throw, create a call-site entry with no landing pad for the region
3649 // between the try-ranges.
3650 if (SawPotentiallyThrowing) {
3651 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3652 CallSites.push_back(Site);
3653 PreviousIsInvoke = false;
3656 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3657 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3659 if (LandingPad->LandingPadLabel) {
3660 // This try-range is for an invoke.
3661 CallSiteEntry Site = {BeginLabel, LastLabel,
3662 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3664 // Try to merge with the previous call-site.
3665 if (PreviousIsInvoke) {
3666 CallSiteEntry &Prev = CallSites.back();
3667 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3668 // Extend the range of the previous entry.
3669 Prev.EndLabel = Site.EndLabel;
3670 continue;
3674 // Otherwise, create a new call-site.
3675 CallSites.push_back(Site);
3676 PreviousIsInvoke = true;
3677 } else {
3678 // Create a gap.
3679 PreviousIsInvoke = false;
3683 // If some instruction between the previous try-range and the end of the
3684 // function may throw, create a call-site entry with no landing pad for the
3685 // region following the try-range.
3686 if (SawPotentiallyThrowing) {
3687 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3688 CallSites.push_back(Site);
3691 // Final tallies.
3693 // Call sites.
3694 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3695 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3696 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3697 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3698 SiteLengthSize +
3699 LandingPadSize);
3700 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3701 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3703 // Type infos.
3704 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3705 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3707 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3708 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3709 SizeSites + SizeActions + SizeTypes;
3711 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3712 sizeof(int8_t) + // TType format
3713 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3714 TypeOffset;
3716 unsigned SizeAlign = (4 - TotalSize) & 3;
3718 // Begin the exception table.
3719 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3720 Asm->EmitAlignment(2, 0, 0, false);
3721 O << "GCC_except_table" << SubprogramCount << ":\n";
3722 for (unsigned i = 0; i != SizeAlign; ++i) {
3723 Asm->EmitInt8(0);
3724 Asm->EOL("Padding");
3726 EmitLabel("exception", SubprogramCount);
3728 // Emit the header.
3729 Asm->EmitInt8(DW_EH_PE_omit);
3730 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3731 Asm->EmitInt8(DW_EH_PE_absptr);
3732 Asm->EOL("TType format (DW_EH_PE_absptr)");
3733 Asm->EmitULEB128Bytes(TypeOffset);
3734 Asm->EOL("TType base offset");
3735 Asm->EmitInt8(DW_EH_PE_udata4);
3736 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3737 Asm->EmitULEB128Bytes(SizeSites);
3738 Asm->EOL("Call-site table length");
3740 // Emit the landing pad site information.
3741 for (unsigned i = 0; i < CallSites.size(); ++i) {
3742 CallSiteEntry &S = CallSites[i];
3743 const char *BeginTag;
3744 unsigned BeginNumber;
3746 if (!S.BeginLabel) {
3747 BeginTag = "eh_func_begin";
3748 BeginNumber = SubprogramCount;
3749 } else {
3750 BeginTag = "label";
3751 BeginNumber = S.BeginLabel;
3754 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3755 true, true);
3756 Asm->EOL("Region start");
3758 if (!S.EndLabel) {
3759 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3760 true);
3761 } else {
3762 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3764 Asm->EOL("Region length");
3766 if (!S.PadLabel)
3767 Asm->EmitInt32(0);
3768 else
3769 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3770 true, true);
3771 Asm->EOL("Landing pad");
3773 Asm->EmitULEB128Bytes(S.Action);
3774 Asm->EOL("Action");
3777 // Emit the actions.
3778 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3779 ActionEntry &Action = Actions[I];
3781 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3782 Asm->EOL("TypeInfo index");
3783 Asm->EmitSLEB128Bytes(Action.NextAction);
3784 Asm->EOL("Next action");
3787 // Emit the type ids.
3788 for (unsigned M = TypeInfos.size(); M; --M) {
3789 GlobalVariable *GV = TypeInfos[M - 1];
3791 PrintRelDirective();
3793 if (GV)
3794 O << Asm->getGlobalLinkName(GV);
3795 else
3796 O << "0";
3798 Asm->EOL("TypeInfo");
3801 // Emit the filter typeids.
3802 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3803 unsigned TypeID = FilterIds[j];
3804 Asm->EmitULEB128Bytes(TypeID);
3805 Asm->EOL("Filter TypeInfo index");
3808 Asm->EmitAlignment(2, 0, 0, false);
3811 public:
3812 //===--------------------------------------------------------------------===//
3813 // Main entry points.
3815 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3816 : Dwarf(OS, A, T, "eh")
3817 , shouldEmitTable(false)
3818 , shouldEmitMoves(false)
3819 , shouldEmitTableModule(false)
3820 , shouldEmitMovesModule(false)
3823 virtual ~DwarfException() {}
3825 /// SetModuleInfo - Set machine module information when it's known that pass
3826 /// manager has created it. Set by the target AsmPrinter.
3827 void SetModuleInfo(MachineModuleInfo *mmi) {
3828 MMI = mmi;
3831 /// BeginModule - Emit all exception information that should come prior to the
3832 /// content.
3833 void BeginModule(Module *M) {
3834 this->M = M;
3837 /// EndModule - Emit all exception information that should come after the
3838 /// content.
3839 void EndModule() {
3840 if (shouldEmitMovesModule || shouldEmitTableModule) {
3841 const std::vector<Function *> Personalities = MMI->getPersonalities();
3842 for (unsigned i =0; i < Personalities.size(); ++i)
3843 EmitCommonEHFrame(Personalities[i], i);
3845 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3846 E = EHFrames.end(); I != E; ++I)
3847 EmitEHFrame(*I);
3851 /// BeginFunction - Gather pre-function exception information. Assumes being
3852 /// emitted immediately after the function entry point.
3853 void BeginFunction(MachineFunction *MF) {
3854 this->MF = MF;
3855 shouldEmitTable = shouldEmitMoves = false;
3856 if (MMI && TAI->doesSupportExceptionHandling()) {
3858 // Map all labels and get rid of any dead landing pads.
3859 MMI->TidyLandingPads();
3860 // If any landing pads survive, we need an EH table.
3861 if (MMI->getLandingPads().size())
3862 shouldEmitTable = true;
3864 // See if we need frame move info.
3865 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3866 shouldEmitMoves = true;
3868 if (shouldEmitMoves || shouldEmitTable)
3869 // Assumes in correct section after the entry point.
3870 EmitLabel("eh_func_begin", ++SubprogramCount);
3872 shouldEmitTableModule |= shouldEmitTable;
3873 shouldEmitMovesModule |= shouldEmitMoves;
3876 /// EndFunction - Gather and emit post-function exception information.
3878 void EndFunction() {
3879 if (shouldEmitMoves || shouldEmitTable) {
3880 EmitLabel("eh_func_end", SubprogramCount);
3881 EmitExceptionTable();
3883 // Save EH frame information
3884 EHFrames.
3885 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3886 SubprogramCount,
3887 MMI->getPersonalityIndex(),
3888 MF->getFrameInfo()->hasCalls(),
3889 !MMI->getLandingPads().empty(),
3890 MMI->getFrameMoves(),
3891 MF->getFunction()));
3896 } // End of namespace llvm
3898 //===----------------------------------------------------------------------===//
3900 /// Emit - Print the abbreviation using the specified Dwarf writer.
3902 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3903 // Emit its Dwarf tag type.
3904 DD.getAsm()->EmitULEB128Bytes(Tag);
3905 DD.getAsm()->EOL(TagString(Tag));
3907 // Emit whether it has children DIEs.
3908 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3909 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3911 // For each attribute description.
3912 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3913 const DIEAbbrevData &AttrData = Data[i];
3915 // Emit attribute type.
3916 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3917 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3919 // Emit form type.
3920 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3921 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3924 // Mark end of abbreviation.
3925 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3926 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3929 #ifndef NDEBUG
3930 void DIEAbbrev::print(std::ostream &O) {
3931 O << "Abbreviation @"
3932 << std::hex << (intptr_t)this << std::dec
3933 << " "
3934 << TagString(Tag)
3935 << " "
3936 << ChildrenString(ChildrenFlag)
3937 << "\n";
3939 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3940 O << " "
3941 << AttributeString(Data[i].getAttribute())
3942 << " "
3943 << FormEncodingString(Data[i].getForm())
3944 << "\n";
3947 void DIEAbbrev::dump() { print(cerr); }
3948 #endif
3950 //===----------------------------------------------------------------------===//
3952 #ifndef NDEBUG
3953 void DIEValue::dump() {
3954 print(cerr);
3956 #endif
3958 //===----------------------------------------------------------------------===//
3960 /// EmitValue - Emit integer of appropriate size.
3962 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3963 switch (Form) {
3964 case DW_FORM_flag: // Fall thru
3965 case DW_FORM_ref1: // Fall thru
3966 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3967 case DW_FORM_ref2: // Fall thru
3968 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3969 case DW_FORM_ref4: // Fall thru
3970 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3971 case DW_FORM_ref8: // Fall thru
3972 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3973 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3974 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3975 default: assert(0 && "DIE Value form not supported yet"); break;
3979 /// SizeOf - Determine size of integer value in bytes.
3981 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3982 switch (Form) {
3983 case DW_FORM_flag: // Fall thru
3984 case DW_FORM_ref1: // Fall thru
3985 case DW_FORM_data1: return sizeof(int8_t);
3986 case DW_FORM_ref2: // Fall thru
3987 case DW_FORM_data2: return sizeof(int16_t);
3988 case DW_FORM_ref4: // Fall thru
3989 case DW_FORM_data4: return sizeof(int32_t);
3990 case DW_FORM_ref8: // Fall thru
3991 case DW_FORM_data8: return sizeof(int64_t);
3992 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
3993 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
3994 default: assert(0 && "DIE Value form not supported yet"); break;
3996 return 0;
3999 //===----------------------------------------------------------------------===//
4001 /// EmitValue - Emit string value.
4003 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4004 DD.getAsm()->EmitString(String);
4007 //===----------------------------------------------------------------------===//
4009 /// EmitValue - Emit label value.
4011 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4012 bool IsSmall = Form == DW_FORM_data4;
4013 DD.EmitReference(Label, false, IsSmall);
4016 /// SizeOf - Determine size of label value in bytes.
4018 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4019 if (Form == DW_FORM_data4) return 4;
4020 return DD.getTargetData()->getPointerSize();
4023 //===----------------------------------------------------------------------===//
4025 /// EmitValue - Emit label value.
4027 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4028 bool IsSmall = Form == DW_FORM_data4;
4029 DD.EmitReference(Label, false, IsSmall);
4032 /// SizeOf - Determine size of label value in bytes.
4034 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4035 if (Form == DW_FORM_data4) return 4;
4036 return DD.getTargetData()->getPointerSize();
4039 //===----------------------------------------------------------------------===//
4041 /// EmitValue - Emit delta value.
4043 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4044 bool IsSmall = Form == DW_FORM_data4;
4045 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4046 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4049 /// SizeOf - Determine size of delta value in bytes.
4051 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4052 if (Form == DW_FORM_data4) return 4;
4053 return DD.getTargetData()->getPointerSize();
4056 //===----------------------------------------------------------------------===//
4058 /// EmitValue - Emit delta value.
4060 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4061 bool IsSmall = Form == DW_FORM_data4;
4062 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4065 /// SizeOf - Determine size of delta value in bytes.
4067 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4068 if (Form == DW_FORM_data4) return 4;
4069 return DD.getTargetData()->getPointerSize();
4072 //===----------------------------------------------------------------------===//
4074 /// EmitValue - Emit debug information entry offset.
4076 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4077 DD.getAsm()->EmitInt32(Entry->getOffset());
4080 //===----------------------------------------------------------------------===//
4082 /// ComputeSize - calculate the size of the block.
4084 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4085 if (!Size) {
4086 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4088 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4089 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4092 return Size;
4095 /// EmitValue - Emit block data.
4097 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4098 switch (Form) {
4099 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4100 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4101 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4102 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4103 default: assert(0 && "Improper form for block"); break;
4106 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4108 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4109 DD.getAsm()->EOL();
4110 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4114 /// SizeOf - Determine size of block data in bytes.
4116 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4117 switch (Form) {
4118 case DW_FORM_block1: return Size + sizeof(int8_t);
4119 case DW_FORM_block2: return Size + sizeof(int16_t);
4120 case DW_FORM_block4: return Size + sizeof(int32_t);
4121 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4122 default: assert(0 && "Improper form for block"); break;
4124 return 0;
4127 //===----------------------------------------------------------------------===//
4128 /// DIE Implementation
4130 DIE::~DIE() {
4131 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4132 delete Children[i];
4135 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4137 void DIE::AddSiblingOffset() {
4138 DIEInteger *DI = new DIEInteger(0);
4139 Values.insert(Values.begin(), DI);
4140 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4143 /// Profile - Used to gather unique data for the value folding set.
4145 void DIE::Profile(FoldingSetNodeID &ID) {
4146 Abbrev.Profile(ID);
4148 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4149 ID.AddPointer(Children[i]);
4151 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4152 ID.AddPointer(Values[j]);
4155 #ifndef NDEBUG
4156 void DIE::print(std::ostream &O, unsigned IncIndent) {
4157 static unsigned IndentCount = 0;
4158 IndentCount += IncIndent;
4159 const std::string Indent(IndentCount, ' ');
4160 bool isBlock = Abbrev.getTag() == 0;
4162 if (!isBlock) {
4163 O << Indent
4164 << "Die: "
4165 << "0x" << std::hex << (intptr_t)this << std::dec
4166 << ", Offset: " << Offset
4167 << ", Size: " << Size
4168 << "\n";
4170 O << Indent
4171 << TagString(Abbrev.getTag())
4172 << " "
4173 << ChildrenString(Abbrev.getChildrenFlag());
4174 } else {
4175 O << "Size: " << Size;
4177 O << "\n";
4179 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4181 IndentCount += 2;
4182 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4183 O << Indent;
4185 if (!isBlock)
4186 O << AttributeString(Data[i].getAttribute());
4187 else
4188 O << "Blk[" << i << "]";
4190 O << " "
4191 << FormEncodingString(Data[i].getForm())
4192 << " ";
4193 Values[i]->print(O);
4194 O << "\n";
4196 IndentCount -= 2;
4198 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4199 Children[j]->print(O, 4);
4202 if (!isBlock) O << "\n";
4203 IndentCount -= IncIndent;
4206 void DIE::dump() {
4207 print(cerr);
4209 #endif
4211 //===----------------------------------------------------------------------===//
4212 /// DwarfWriter Implementation
4215 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4218 DwarfWriter::~DwarfWriter() {
4219 delete DE;
4220 delete DD;
4223 /// BeginModule - Emit all Dwarf sections that should come prior to the
4224 /// content.
4225 void DwarfWriter::BeginModule(Module *M,
4226 MachineModuleInfo *MMI,
4227 raw_ostream &OS, AsmPrinter *A,
4228 const TargetAsmInfo *T) {
4229 DE = new DwarfException(OS, A, T);
4230 DD = new DwarfDebug(OS, A, T);
4231 DE->BeginModule(M);
4232 DD->BeginModule(M);
4233 DD->SetDebugInfo(MMI);
4234 DE->SetModuleInfo(MMI);
4237 /// EndModule - Emit all Dwarf sections that should come after the content.
4239 void DwarfWriter::EndModule() {
4240 DE->EndModule();
4241 DD->EndModule();
4244 /// BeginFunction - Gather pre-function debug information. Assumes being
4245 /// emitted immediately after the function entry point.
4246 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4247 DE->BeginFunction(MF);
4248 DD->BeginFunction(MF);
4251 /// EndFunction - Gather and emit post-function debug information.
4253 void DwarfWriter::EndFunction(MachineFunction *MF) {
4254 DD->EndFunction(MF);
4255 DE->EndFunction();
4257 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4258 // Clear function debug information.
4259 MMI->EndFunction();
4262 /// ValidDebugInfo - Return true if V represents valid debug info value.
4263 bool DwarfWriter::ValidDebugInfo(Value *V) {
4264 return DD && DD->ValidDebugInfo(V);
4267 /// RecordSourceLine - Records location information and associates it with a
4268 /// label. Returns a unique label ID used to generate a label and provide
4269 /// correspondence to the source line list.
4270 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4271 unsigned Src) {
4272 return DD->RecordSourceLine(Line, Col, Src);
4275 /// RecordSource - Register a source file with debug info. Returns an source
4276 /// ID.
4277 unsigned DwarfWriter::RecordSource(const std::string &Dir,
4278 const std::string &File) {
4279 return DD->RecordSource(Dir, File);
4282 /// RecordRegionStart - Indicate the start of a region.
4283 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4284 return DD->RecordRegionStart(V);
4287 /// RecordRegionEnd - Indicate the end of a region.
4288 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4289 return DD->RecordRegionEnd(V);
4292 /// getRecordSourceLineCount - Count source lines.
4293 unsigned DwarfWriter::getRecordSourceLineCount() {
4294 return DD->getRecordSourceLineCount();
4297 /// RecordVariable - Indicate the declaration of a local variable.
4299 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4300 DD->RecordVariable(GV, FrameIndex);