1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
44 using namespace llvm::dwarf;
46 static RegisterPass<DwarfWriter>
47 X("dwarfwriter", "DWARF Information Writer");
48 char DwarfWriter::ID = 0;
52 //===----------------------------------------------------------------------===//
54 /// Configuration values for initial hash set sizes (log2).
56 static const unsigned InitDiesSetSize = 9; // 512
57 static const unsigned InitAbbreviationsSetSize = 9; // 512
58 static const unsigned InitValuesSetSize = 9; // 512
60 //===----------------------------------------------------------------------===//
61 /// Forward declarations.
66 //===----------------------------------------------------------------------===//
69 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
70 /// specified value in their initializer somewhere.
72 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
73 // Scan though value users.
74 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
75 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
76 // If the user is a GlobalVariable then add to result.
78 } else if (Constant *C = dyn_cast<Constant>(*I)) {
79 // If the user is a constant variable then scan its users
80 getGlobalVariablesUsing(C, Result);
85 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
86 /// named GlobalVariable.
88 getGlobalVariablesUsing(Module &M, const std::string &RootName,
89 std::vector<GlobalVariable*> &Result) {
90 std::vector<const Type*> FieldTypes;
91 FieldTypes.push_back(Type::Int32Ty);
92 FieldTypes.push_back(Type::Int32Ty);
94 // Get the GlobalVariable root.
95 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
96 StructType::get(FieldTypes));
98 // If present and linkonce then scan for users.
99 if (UseRoot && UseRoot->hasLinkOnceLinkage())
100 getGlobalVariablesUsing(UseRoot, Result);
103 //===----------------------------------------------------------------------===//
104 /// DWLabel - Labels are used to track locations in the assembler file.
105 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
106 /// where the tag is a category of label (Ex. location) and number is a value
107 /// unique in that category.
110 /// Tag - Label category tag. Should always be a staticly declared C string.
114 /// Number - Value to make label unique.
118 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
120 void Profile(FoldingSetNodeID &ID) const {
121 ID.AddString(std::string(Tag));
122 ID.AddInteger(Number);
126 void print(std::ostream *O) const {
129 void print(std::ostream &O) const {
131 if (Number) O << Number;
136 //===----------------------------------------------------------------------===//
137 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
138 /// Dwarf abbreviation.
139 class DIEAbbrevData {
141 /// Attribute - Dwarf attribute code.
145 /// Form - Dwarf form code.
150 DIEAbbrevData(unsigned A, unsigned F)
156 unsigned getAttribute() const { return Attribute; }
157 unsigned getForm() const { return Form; }
159 /// Profile - Used to gather unique data for the abbreviation folding set.
161 void Profile(FoldingSetNodeID &ID)const {
162 ID.AddInteger(Attribute);
167 //===----------------------------------------------------------------------===//
168 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
169 /// information object.
170 class DIEAbbrev : public FoldingSetNode {
172 /// Tag - Dwarf tag code.
176 /// Unique number for node.
180 /// ChildrenFlag - Dwarf children flag.
182 unsigned ChildrenFlag;
184 /// Data - Raw data bytes for abbreviation.
186 SmallVector<DIEAbbrevData, 8> Data;
190 DIEAbbrev(unsigned T, unsigned C)
198 unsigned getTag() const { return Tag; }
199 unsigned getNumber() const { return Number; }
200 unsigned getChildrenFlag() const { return ChildrenFlag; }
201 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
202 void setTag(unsigned T) { Tag = T; }
203 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
204 void setNumber(unsigned N) { Number = N; }
206 /// AddAttribute - Adds another set of attribute information to the
208 void AddAttribute(unsigned Attribute, unsigned Form) {
209 Data.push_back(DIEAbbrevData(Attribute, Form));
212 /// AddFirstAttribute - Adds a set of attribute information to the front
213 /// of the abbreviation.
214 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
215 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
218 /// Profile - Used to gather unique data for the abbreviation folding set.
220 void Profile(FoldingSetNodeID &ID) {
222 ID.AddInteger(ChildrenFlag);
224 // For each attribute description.
225 for (unsigned i = 0, N = Data.size(); i < N; ++i)
229 /// Emit - Print the abbreviation using the specified Dwarf writer.
231 void Emit(const DwarfDebug &DD) const;
234 void print(std::ostream *O) {
237 void print(std::ostream &O);
242 //===----------------------------------------------------------------------===//
243 /// DIE - A structured debug information entry. Has an abbreviation which
244 /// describes it's organization.
245 class DIE : public FoldingSetNode {
247 /// Abbrev - Buffer for constructing abbreviation.
251 /// Offset - Offset in debug info section.
255 /// Size - Size of instance + children.
261 std::vector<DIE *> Children;
263 /// Attributes values.
265 SmallVector<DIEValue*, 32> Values;
268 explicit DIE(unsigned Tag)
269 : Abbrev(Tag, DW_CHILDREN_no)
278 DIEAbbrev &getAbbrev() { return Abbrev; }
279 unsigned getAbbrevNumber() const {
280 return Abbrev.getNumber();
282 unsigned getTag() const { return Abbrev.getTag(); }
283 unsigned getOffset() const { return Offset; }
284 unsigned getSize() const { return Size; }
285 const std::vector<DIE *> &getChildren() const { return Children; }
286 SmallVector<DIEValue*, 32> &getValues() { return Values; }
287 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
288 void setOffset(unsigned O) { Offset = O; }
289 void setSize(unsigned S) { Size = S; }
291 /// AddValue - Add a value and attributes to a DIE.
293 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
294 Abbrev.AddAttribute(Attribute, Form);
295 Values.push_back(Value);
298 /// SiblingOffset - Return the offset of the debug information entry's
300 unsigned SiblingOffset() const { return Offset + Size; }
302 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
304 void AddSiblingOffset();
306 /// AddChild - Add a child to the DIE.
308 void AddChild(DIE *Child) {
309 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
310 Children.push_back(Child);
313 /// Detach - Detaches objects connected to it after copying.
319 /// Profile - Used to gather unique data for the value folding set.
321 void Profile(FoldingSetNodeID &ID) ;
324 void print(std::ostream *O, unsigned IncIndent = 0) {
325 if (O) print(*O, IncIndent);
327 void print(std::ostream &O, unsigned IncIndent = 0);
332 //===----------------------------------------------------------------------===//
333 /// DIEValue - A debug information entry value.
335 class DIEValue : public FoldingSetNode {
348 /// Type - Type of data stored in the value.
352 explicit DIEValue(unsigned T)
355 virtual ~DIEValue() {}
358 unsigned getType() const { return Type; }
360 // Implement isa/cast/dyncast.
361 static bool classof(const DIEValue *) { return true; }
363 /// EmitValue - Emit value via the Dwarf writer.
365 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
367 /// SizeOf - Return the size of a value in bytes.
369 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
371 /// Profile - Used to gather unique data for the value folding set.
373 virtual void Profile(FoldingSetNodeID &ID) = 0;
376 void print(std::ostream *O) {
379 virtual void print(std::ostream &O) = 0;
384 //===----------------------------------------------------------------------===//
385 /// DWInteger - An integer value DIE.
387 class DIEInteger : public DIEValue {
392 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
394 // Implement isa/cast/dyncast.
395 static bool classof(const DIEInteger *) { return true; }
396 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
398 /// BestForm - Choose the best form for integer.
400 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
402 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
403 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
404 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
406 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
407 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
408 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
410 return DW_FORM_data8;
413 /// EmitValue - Emit integer of appropriate size.
415 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
417 /// SizeOf - Determine size of integer value in bytes.
419 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
421 /// Profile - Used to gather unique data for the value folding set.
423 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
424 ID.AddInteger(isInteger);
425 ID.AddInteger(Integer);
427 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
430 virtual void print(std::ostream &O) {
431 O << "Int: " << (int64_t)Integer
432 << " 0x" << std::hex << Integer << std::dec;
437 //===----------------------------------------------------------------------===//
438 /// DIEString - A string value DIE.
440 class DIEString : public DIEValue {
442 const std::string String;
444 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
446 // Implement isa/cast/dyncast.
447 static bool classof(const DIEString *) { return true; }
448 static bool classof(const DIEValue *S) { return S->Type == isString; }
450 /// EmitValue - Emit string value.
452 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
454 /// SizeOf - Determine size of string value in bytes.
456 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
457 return String.size() + sizeof(char); // sizeof('\0');
460 /// Profile - Used to gather unique data for the value folding set.
462 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
463 ID.AddInteger(isString);
464 ID.AddString(String);
466 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
469 virtual void print(std::ostream &O) {
470 O << "Str: \"" << String << "\"";
475 //===----------------------------------------------------------------------===//
476 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
478 class DIEDwarfLabel : public DIEValue {
483 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
485 // Implement isa/cast/dyncast.
486 static bool classof(const DIEDwarfLabel *) { return true; }
487 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
489 /// EmitValue - Emit label value.
491 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
493 /// SizeOf - Determine size of label value in bytes.
495 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
497 /// Profile - Used to gather unique data for the value folding set.
499 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
500 ID.AddInteger(isLabel);
503 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
506 virtual void print(std::ostream &O) {
514 //===----------------------------------------------------------------------===//
515 /// DIEObjectLabel - A label to an object in code or data.
517 class DIEObjectLabel : public DIEValue {
519 const std::string Label;
521 explicit DIEObjectLabel(const std::string &L)
522 : DIEValue(isAsIsLabel), Label(L) {}
524 // Implement isa/cast/dyncast.
525 static bool classof(const DIEObjectLabel *) { return true; }
526 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
528 /// EmitValue - Emit label value.
530 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
532 /// SizeOf - Determine size of label value in bytes.
534 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
536 /// Profile - Used to gather unique data for the value folding set.
538 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
539 ID.AddInteger(isAsIsLabel);
542 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
545 virtual void print(std::ostream &O) {
546 O << "Obj: " << Label;
551 //===----------------------------------------------------------------------===//
552 /// DIESectionOffset - A section offset DIE.
554 class DIESectionOffset : public DIEValue {
557 const DWLabel Section;
561 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
562 bool isEH = false, bool useSet = true)
563 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
564 IsEH(isEH), UseSet(useSet) {}
566 // Implement isa/cast/dyncast.
567 static bool classof(const DIESectionOffset *) { return true; }
568 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
570 /// EmitValue - Emit section offset.
572 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
574 /// SizeOf - Determine size of section offset value in bytes.
576 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
578 /// Profile - Used to gather unique data for the value folding set.
580 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
581 const DWLabel &Section) {
582 ID.AddInteger(isSectionOffset);
585 // IsEH and UseSet are specific to the Label/Section that we will emit
586 // the offset for; so Label/Section are enough for uniqueness.
588 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
591 virtual void print(std::ostream &O) {
596 O << "-" << IsEH << "-" << UseSet;
601 //===----------------------------------------------------------------------===//
602 /// DIEDelta - A simple label difference DIE.
604 class DIEDelta : public DIEValue {
606 const DWLabel LabelHi;
607 const DWLabel LabelLo;
609 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
610 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
612 // Implement isa/cast/dyncast.
613 static bool classof(const DIEDelta *) { return true; }
614 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
616 /// EmitValue - Emit delta value.
618 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
620 /// SizeOf - Determine size of delta value in bytes.
622 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
624 /// Profile - Used to gather unique data for the value folding set.
626 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
627 const DWLabel &LabelLo) {
628 ID.AddInteger(isDelta);
632 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
635 virtual void print(std::ostream &O) {
644 //===----------------------------------------------------------------------===//
645 /// DIEntry - A pointer to another debug information entry. An instance of this
646 /// class can also be used as a proxy for a debug information entry not yet
647 /// defined (ie. types.)
648 class DIEntry : public DIEValue {
652 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
654 // Implement isa/cast/dyncast.
655 static bool classof(const DIEntry *) { return true; }
656 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
658 /// EmitValue - Emit debug information entry offset.
660 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
662 /// SizeOf - Determine size of debug information entry in bytes.
664 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
665 return sizeof(int32_t);
668 /// Profile - Used to gather unique data for the value folding set.
670 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
671 ID.AddInteger(isEntry);
672 ID.AddPointer(Entry);
674 virtual void Profile(FoldingSetNodeID &ID) {
675 ID.AddInteger(isEntry);
678 ID.AddPointer(Entry);
685 virtual void print(std::ostream &O) {
686 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
691 //===----------------------------------------------------------------------===//
692 /// DIEBlock - A block of values. Primarily used for location expressions.
694 class DIEBlock : public DIEValue, public DIE {
696 unsigned Size; // Size in bytes excluding size header.
706 // Implement isa/cast/dyncast.
707 static bool classof(const DIEBlock *) { return true; }
708 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
710 /// ComputeSize - calculate the size of the block.
712 unsigned ComputeSize(DwarfDebug &DD);
714 /// BestForm - Choose the best form for data.
716 unsigned BestForm() const {
717 if ((unsigned char)Size == Size) return DW_FORM_block1;
718 if ((unsigned short)Size == Size) return DW_FORM_block2;
719 if ((unsigned int)Size == Size) return DW_FORM_block4;
720 return DW_FORM_block;
723 /// EmitValue - Emit block data.
725 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
727 /// SizeOf - Determine size of block data in bytes.
729 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
732 /// Profile - Used to gather unique data for the value folding set.
734 virtual void Profile(FoldingSetNodeID &ID) {
735 ID.AddInteger(isBlock);
740 virtual void print(std::ostream &O) {
747 //===----------------------------------------------------------------------===//
748 /// CompileUnit - This dwarf writer support class manages information associate
749 /// with a source file.
752 /// Desc - Compile unit debug descriptor.
754 CompileUnitDesc *Desc;
756 /// ID - File identifier for source.
760 /// Die - Compile unit debug information entry.
764 /// DescToDieMap - Tracks the mapping of unit level debug informaton
765 /// descriptors to debug information entries.
766 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
767 DenseMap<GlobalVariable *, DIE *> GVToDieMap;
769 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
770 /// descriptors to debug information entries using a DIEntry proxy.
771 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
772 DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
774 /// Globals - A map of globally visible named entities for this unit.
776 std::map<std::string, DIE *> Globals;
778 /// DiesSet - Used to uniquely define dies within the compile unit.
780 FoldingSet<DIE> DiesSet;
782 /// Dies - List of all dies in the compile unit.
784 std::vector<DIE *> Dies;
787 CompileUnit(unsigned I, DIE *D)
788 : ID(I), Die(D), DescToDieMap(), GVToDieMap(), DescToDIEntryMap(),
789 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
792 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
801 , DiesSet(InitDiesSetSize)
808 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
813 CompileUnitDesc *getDesc() const { return Desc; }
814 unsigned getID() const { return ID; }
815 DIE* getDie() const { return Die; }
816 std::map<std::string, DIE *> &getGlobals() { return Globals; }
818 /// hasContent - Return true if this compile unit has something to write out.
820 bool hasContent() const {
821 return !Die->getChildren().empty();
824 /// AddGlobal - Add a new global entity to the compile unit.
826 void AddGlobal(const std::string &Name, DIE *Die) {
830 /// getDieMapSlotFor - Returns the debug information entry map slot for the
831 /// specified debug descriptor.
832 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
833 return DescToDieMap[DID];
835 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
836 return GVToDieMap[GV];
839 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
840 /// specified debug descriptor.
841 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
842 return DescToDIEntryMap[DID];
844 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
845 return GVToDIEntryMap[GV];
848 /// AddDie - Adds or interns the DIE to the compile unit.
850 DIE *AddDie(DIE &Buffer) {
854 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
857 Die = new DIE(Buffer);
858 DiesSet.InsertNode(Die, Where);
859 this->Die->AddChild(Die);
867 //===----------------------------------------------------------------------===//
868 /// Dwarf - Emits general Dwarf directives.
874 //===--------------------------------------------------------------------===//
875 // Core attributes used by the Dwarf writer.
879 /// O - Stream to .s file.
883 /// Asm - Target of Dwarf emission.
887 /// TAI - Target asm information.
888 const TargetAsmInfo *TAI;
890 /// TD - Target data.
891 const TargetData *TD;
893 /// RI - Register Information.
894 const TargetRegisterInfo *RI;
896 /// M - Current module.
900 /// MF - Current machine function.
904 /// MMI - Collected machine module information.
906 MachineModuleInfo *MMI;
908 /// SubprogramCount - The running count of functions being compiled.
910 unsigned SubprogramCount;
912 /// Flavor - A unique string indicating what dwarf producer this is, used to
914 const char * const Flavor;
917 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
922 , TD(Asm->TM.getTargetData())
923 , RI(Asm->TM.getRegisterInfo())
935 //===--------------------------------------------------------------------===//
938 AsmPrinter *getAsm() const { return Asm; }
939 MachineModuleInfo *getMMI() const { return MMI; }
940 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
941 const TargetData *getTargetData() const { return TD; }
943 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
945 if (isInSection && TAI->getDwarfSectionOffsetDirective())
946 O << TAI->getDwarfSectionOffsetDirective();
947 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
948 O << TAI->getData32bitsDirective();
950 O << TAI->getData64bitsDirective();
953 /// PrintLabelName - Print label name in form used by Dwarf writer.
955 void PrintLabelName(DWLabel Label) const {
956 PrintLabelName(Label.Tag, Label.Number);
958 void PrintLabelName(const char *Tag, unsigned Number) const {
959 O << TAI->getPrivateGlobalPrefix() << Tag;
960 if (Number) O << Number;
963 void PrintLabelName(const char *Tag, unsigned Number,
964 const char *Suffix) const {
965 O << TAI->getPrivateGlobalPrefix() << Tag;
966 if (Number) O << Number;
970 /// EmitLabel - Emit location label for internal use by Dwarf.
972 void EmitLabel(DWLabel Label) const {
973 EmitLabel(Label.Tag, Label.Number);
975 void EmitLabel(const char *Tag, unsigned Number) const {
976 PrintLabelName(Tag, Number);
980 /// EmitReference - Emit a reference to a label.
982 void EmitReference(DWLabel Label, bool IsPCRelative = false,
983 bool Force32Bit = false) const {
984 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
986 void EmitReference(const char *Tag, unsigned Number,
987 bool IsPCRelative = false, bool Force32Bit = false) const {
988 PrintRelDirective(Force32Bit);
989 PrintLabelName(Tag, Number);
991 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
993 void EmitReference(const std::string &Name, bool IsPCRelative = false,
994 bool Force32Bit = false) const {
995 PrintRelDirective(Force32Bit);
999 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
1002 /// EmitDifference - Emit the difference between two labels. Some
1003 /// assemblers do not behave with absolute expressions with data directives,
1004 /// so there is an option (needsSet) to use an intermediary set expression.
1005 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
1006 bool IsSmall = false) {
1007 EmitDifference(LabelHi.Tag, LabelHi.Number,
1008 LabelLo.Tag, LabelLo.Number,
1011 void EmitDifference(const char *TagHi, unsigned NumberHi,
1012 const char *TagLo, unsigned NumberLo,
1013 bool IsSmall = false) {
1014 if (TAI->needsSet()) {
1016 PrintLabelName("set", SetCounter, Flavor);
1018 PrintLabelName(TagHi, NumberHi);
1020 PrintLabelName(TagLo, NumberLo);
1023 PrintRelDirective(IsSmall);
1024 PrintLabelName("set", SetCounter, Flavor);
1027 PrintRelDirective(IsSmall);
1029 PrintLabelName(TagHi, NumberHi);
1031 PrintLabelName(TagLo, NumberLo);
1035 void EmitSectionOffset(const char* Label, const char* Section,
1036 unsigned LabelNumber, unsigned SectionNumber,
1037 bool IsSmall = false, bool isEH = false,
1038 bool useSet = true) {
1039 bool printAbsolute = false;
1041 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1043 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1045 if (TAI->needsSet() && useSet) {
1047 PrintLabelName("set", SetCounter, Flavor);
1049 PrintLabelName(Label, LabelNumber);
1051 if (!printAbsolute) {
1053 PrintLabelName(Section, SectionNumber);
1057 PrintRelDirective(IsSmall);
1059 PrintLabelName("set", SetCounter, Flavor);
1062 PrintRelDirective(IsSmall, true);
1064 PrintLabelName(Label, LabelNumber);
1066 if (!printAbsolute) {
1068 PrintLabelName(Section, SectionNumber);
1073 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1075 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1076 const std::vector<MachineMove> &Moves, bool isEH) {
1078 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1079 TargetFrameInfo::StackGrowsUp ?
1080 TD->getPointerSize() : -TD->getPointerSize();
1081 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1083 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1084 const MachineMove &Move = Moves[i];
1085 unsigned LabelID = Move.getLabelID();
1088 LabelID = MMI->MappedLabel(LabelID);
1090 // Throw out move if the label is invalid.
1091 if (!LabelID) continue;
1094 const MachineLocation &Dst = Move.getDestination();
1095 const MachineLocation &Src = Move.getSource();
1097 // Advance row if new location.
1098 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1099 Asm->EmitInt8(DW_CFA_advance_loc4);
1100 Asm->EOL("DW_CFA_advance_loc4");
1101 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1104 BaseLabelID = LabelID;
1105 BaseLabel = "label";
1109 // If advancing cfa.
1110 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1112 if (Src.getReg() == MachineLocation::VirtualFP) {
1113 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1114 Asm->EOL("DW_CFA_def_cfa_offset");
1116 Asm->EmitInt8(DW_CFA_def_cfa);
1117 Asm->EOL("DW_CFA_def_cfa");
1118 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1119 Asm->EOL("Register");
1122 int Offset = -Src.getOffset();
1124 Asm->EmitULEB128Bytes(Offset);
1127 assert(0 && "Machine move no supported yet.");
1129 } else if (Src.isReg() &&
1130 Src.getReg() == MachineLocation::VirtualFP) {
1132 Asm->EmitInt8(DW_CFA_def_cfa_register);
1133 Asm->EOL("DW_CFA_def_cfa_register");
1134 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1135 Asm->EOL("Register");
1137 assert(0 && "Machine move no supported yet.");
1140 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1141 int Offset = Dst.getOffset() / stackGrowth;
1144 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1145 Asm->EOL("DW_CFA_offset_extended_sf");
1146 Asm->EmitULEB128Bytes(Reg);
1148 Asm->EmitSLEB128Bytes(Offset);
1150 } else if (Reg < 64) {
1151 Asm->EmitInt8(DW_CFA_offset + Reg);
1153 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1156 Asm->EmitULEB128Bytes(Offset);
1159 Asm->EmitInt8(DW_CFA_offset_extended);
1160 Asm->EOL("DW_CFA_offset_extended");
1161 Asm->EmitULEB128Bytes(Reg);
1163 Asm->EmitULEB128Bytes(Offset);
1172 //===----------------------------------------------------------------------===//
1173 /// SourceLineInfo - This class is used to record source line correspondence.
1176 unsigned Line; // Source line number.
1177 unsigned Column; // Source column.
1178 unsigned SourceID; // Source ID number.
1179 unsigned LabelID; // Label in code ID number.
1181 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1182 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1185 unsigned getLine() const { return Line; }
1186 unsigned getColumn() const { return Column; }
1187 unsigned getSourceID() const { return SourceID; }
1188 unsigned getLabelID() const { return LabelID; }
1192 //===----------------------------------------------------------------------===//
1193 /// SrcFileInfo - This class is used to track source information.
1196 unsigned DirectoryID; // Directory ID number.
1197 std::string Name; // File name (not including directory.)
1199 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1202 unsigned getDirectoryID() const { return DirectoryID; }
1203 const std::string &getName() const { return Name; }
1205 /// operator== - Used by UniqueVector to locate entry.
1207 bool operator==(const SourceFileInfo &SI) const {
1208 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1211 /// operator< - Used by UniqueVector to locate entry.
1213 bool operator<(const SrcFileInfo &SI) const {
1214 return getDirectoryID() < SI.getDirectoryID() ||
1215 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1219 //===----------------------------------------------------------------------===//
1220 /// DbgVariable - This class is used to track local variable information.
1224 DIVariable *Var; // Variable Descriptor.
1225 unsigned FrameIndex; // Variable frame index.
1228 DbgVariable(DIVariable *V, unsigned I) : Var(V), FrameIndex(I) {}
1231 DIVariable *getVariable() const { return Var; }
1232 unsigned getFrameIndex() const { return FrameIndex; }
1235 //===----------------------------------------------------------------------===//
1236 /// DbgScope - This class is used to track scope information.
1240 DbgScope *Parent; // Parent to this scope.
1241 DIDescriptor *Desc; // Debug info descriptor for scope.
1242 // Either subprogram or block.
1243 unsigned StartLabelID; // Label ID of the beginning of scope.
1244 unsigned EndLabelID; // Label ID of the end of scope.
1245 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1246 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1249 DbgScope(DbgScope *P, DIDescriptor *D)
1250 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1255 DbgScope *getParent() const { return Parent; }
1256 DIDescriptor *getDesc() const { return Desc; }
1257 unsigned getStartLabelID() const { return StartLabelID; }
1258 unsigned getEndLabelID() const { return EndLabelID; }
1259 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1260 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1261 void setStartLabelID(unsigned S) { StartLabelID = S; }
1262 void setEndLabelID(unsigned E) { EndLabelID = E; }
1264 /// AddScope - Add a scope to the scope.
1266 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1268 /// AddVariable - Add a variable to the scope.
1270 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1273 //===----------------------------------------------------------------------===//
1274 /// DwarfDebug - Emits Dwarf debug directives.
1276 class DwarfDebug : public Dwarf {
1279 //===--------------------------------------------------------------------===//
1280 // Attributes used to construct specific Dwarf sections.
1283 /// CompileUnits - All the compile units involved in this build. The index
1284 /// of each entry in this vector corresponds to the sources in MMI.
1285 std::vector<CompileUnit *> CompileUnits;
1286 DenseMap<Value *, CompileUnit *> DW_CUs;
1288 /// AbbreviationsSet - Used to uniquely define abbreviations.
1290 FoldingSet<DIEAbbrev> AbbreviationsSet;
1292 /// Abbreviations - A list of all the unique abbreviations in use.
1294 std::vector<DIEAbbrev *> Abbreviations;
1296 /// ValuesSet - Used to uniquely define values.
1298 // Directories - Uniquing vector for directories.
1299 UniqueVector<std::string> Directories;
1301 // SourceFiles - Uniquing vector for source files.
1302 UniqueVector<SrcFileInfo> SrcFiles;
1304 // Lines - List of of source line correspondence.
1305 std::vector<SrcLineInfo> Lines;
1307 FoldingSet<DIEValue> ValuesSet;
1309 /// Values - A list of all the unique values in use.
1311 std::vector<DIEValue *> Values;
1313 /// StringPool - A UniqueVector of strings used by indirect references.
1315 UniqueVector<std::string> StringPool;
1317 /// UnitMap - Map debug information descriptor to compile unit.
1319 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1321 /// SectionMap - Provides a unique id per text section.
1323 UniqueVector<const Section*> SectionMap;
1325 /// SectionSourceLines - Tracks line numbers per text section.
1327 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1329 /// didInitial - Flag to indicate if initial emission has been done.
1333 /// shouldEmit - Flag to indicate if debug information should be emitted.
1337 // RootScope - Top level scope for the current function.
1339 DbgScope *RootDbgScope;
1341 // DbgScopeMap - Tracks the scopes in the current function.
1342 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1344 struct FunctionDebugFrameInfo {
1346 std::vector<MachineMove> Moves;
1348 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1349 Number(Num), Moves(M) { }
1352 std::vector<FunctionDebugFrameInfo> DebugFrames;
1356 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1358 bool ShouldEmitDwarf() const { return shouldEmit; }
1360 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1362 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1363 // Profile the node so that we can make it unique.
1364 FoldingSetNodeID ID;
1367 // Check the set for priors.
1368 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1370 // If it's newly added.
1371 if (InSet == &Abbrev) {
1372 // Add to abbreviation list.
1373 Abbreviations.push_back(&Abbrev);
1374 // Assign the vector position + 1 as its number.
1375 Abbrev.setNumber(Abbreviations.size());
1377 // Assign existing abbreviation number.
1378 Abbrev.setNumber(InSet->getNumber());
1382 /// NewString - Add a string to the constant pool and returns a label.
1384 DWLabel NewString(const std::string &String) {
1385 unsigned StringID = StringPool.insert(String);
1386 return DWLabel("string", StringID);
1389 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1391 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1395 FoldingSetNodeID ID;
1396 DIEntry::Profile(ID, Entry);
1398 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1400 if (Value) return Value;
1402 Value = new DIEntry(Entry);
1403 ValuesSet.InsertNode(Value, Where);
1405 Value = new DIEntry(Entry);
1408 Values.push_back(Value);
1412 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1414 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1415 Value->Entry = Entry;
1416 // Add to values set if not already there. If it is, we merely have a
1417 // duplicate in the values list (no harm.)
1418 ValuesSet.GetOrInsertNode(Value);
1421 /// AddUInt - Add an unsigned integer attribute data and value.
1423 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1424 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1426 FoldingSetNodeID ID;
1427 DIEInteger::Profile(ID, Integer);
1429 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1431 Value = new DIEInteger(Integer);
1432 ValuesSet.InsertNode(Value, Where);
1433 Values.push_back(Value);
1436 Die->AddValue(Attribute, Form, Value);
1439 /// AddSInt - Add an signed integer attribute data and value.
1441 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1442 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1444 FoldingSetNodeID ID;
1445 DIEInteger::Profile(ID, (uint64_t)Integer);
1447 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1449 Value = new DIEInteger(Integer);
1450 ValuesSet.InsertNode(Value, Where);
1451 Values.push_back(Value);
1454 Die->AddValue(Attribute, Form, Value);
1457 /// AddString - Add a std::string attribute data and value.
1459 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1460 const std::string &String) {
1461 FoldingSetNodeID ID;
1462 DIEString::Profile(ID, String);
1464 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1466 Value = new DIEString(String);
1467 ValuesSet.InsertNode(Value, Where);
1468 Values.push_back(Value);
1471 Die->AddValue(Attribute, Form, Value);
1474 /// AddLabel - Add a Dwarf label attribute data and value.
1476 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1477 const DWLabel &Label) {
1478 FoldingSetNodeID ID;
1479 DIEDwarfLabel::Profile(ID, Label);
1481 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1483 Value = new DIEDwarfLabel(Label);
1484 ValuesSet.InsertNode(Value, Where);
1485 Values.push_back(Value);
1488 Die->AddValue(Attribute, Form, Value);
1491 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1493 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1494 const std::string &Label) {
1495 FoldingSetNodeID ID;
1496 DIEObjectLabel::Profile(ID, Label);
1498 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1500 Value = new DIEObjectLabel(Label);
1501 ValuesSet.InsertNode(Value, Where);
1502 Values.push_back(Value);
1505 Die->AddValue(Attribute, Form, Value);
1508 /// AddSectionOffset - Add a section offset label attribute data and value.
1510 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1511 const DWLabel &Label, const DWLabel &Section,
1512 bool isEH = false, bool useSet = true) {
1513 FoldingSetNodeID ID;
1514 DIESectionOffset::Profile(ID, Label, Section);
1516 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1518 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1519 ValuesSet.InsertNode(Value, Where);
1520 Values.push_back(Value);
1523 Die->AddValue(Attribute, Form, Value);
1526 /// AddDelta - Add a label delta attribute data and value.
1528 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1529 const DWLabel &Hi, const DWLabel &Lo) {
1530 FoldingSetNodeID ID;
1531 DIEDelta::Profile(ID, Hi, Lo);
1533 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1535 Value = new DIEDelta(Hi, Lo);
1536 ValuesSet.InsertNode(Value, Where);
1537 Values.push_back(Value);
1540 Die->AddValue(Attribute, Form, Value);
1543 /// AddDIEntry - Add a DIE attribute data and value.
1545 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1546 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1549 /// AddBlock - Add block data.
1551 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1552 Block->ComputeSize(*this);
1553 FoldingSetNodeID ID;
1556 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1559 ValuesSet.InsertNode(Value, Where);
1560 Values.push_back(Value);
1562 // Already exists, reuse the previous one.
1564 Block = cast<DIEBlock>(Value);
1567 Die->AddValue(Attribute, Block->BestForm(), Value);
1572 /// AddSourceLine - Add location information to specified debug information
1574 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1576 CompileUnit *FileUnit = FindCompileUnit(File);
1577 unsigned FileID = FileUnit->getID();
1578 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1579 AddUInt(Die, DW_AT_decl_line, 0, Line);
1583 /// AddSourceLine - Add location information to specified debug information
1585 void AddSourceLine(DIE *Die, DIVariable *V) {
1586 unsigned FileID = 0;
1587 unsigned Line = V->getLineNumber();
1588 if (V->getVersion() < DIDescriptor::Version7) {
1589 // Version6 or earlier. Use compile unit info to get file id.
1590 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1591 FileID = Unit->getID();
1593 // Version7 or newer, use filename and directory info from DIVariable
1595 unsigned DID = Directories.idFor(V->getDirectory());
1596 FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1598 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1599 AddUInt(Die, DW_AT_decl_line, 0, Line);
1602 /// AddSourceLine - Add location information to specified debug information
1604 void AddSourceLine(DIE *Die, DIGlobal *G) {
1605 unsigned FileID = 0;
1606 unsigned Line = G->getLineNumber();
1607 if (G->getVersion() < DIDescriptor::Version7) {
1608 // Version6 or earlier. Use compile unit info to get file id.
1609 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1610 FileID = Unit->getID();
1612 // Version7 or newer, use filename and directory info from DIGlobal
1614 unsigned DID = Directories.idFor(G->getDirectory());
1615 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1617 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1618 AddUInt(Die, DW_AT_decl_line, 0, Line);
1621 void AddSourceLine(DIE *Die, DIType *G) {
1622 unsigned FileID = 0;
1623 unsigned Line = G->getLineNumber();
1624 if (G->getVersion() < DIDescriptor::Version7) {
1625 // Version6 or earlier. Use compile unit info to get file id.
1626 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1627 FileID = Unit->getID();
1629 // Version7 or newer, use filename and directory info from DIGlobal
1631 unsigned DID = Directories.idFor(G->getDirectory());
1632 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1634 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1635 AddUInt(Die, DW_AT_decl_line, 0, Line);
1638 /// AddAddress - Add an address attribute to a die based on the location
1640 void AddAddress(DIE *Die, unsigned Attribute,
1641 const MachineLocation &Location) {
1642 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1643 DIEBlock *Block = new DIEBlock();
1645 if (Location.isReg()) {
1647 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1649 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1650 AddUInt(Block, 0, DW_FORM_udata, Reg);
1654 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1656 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1657 AddUInt(Block, 0, DW_FORM_udata, Reg);
1659 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1662 AddBlock(Die, Attribute, 0, Block);
1665 /// AddBasicType - Add a new basic type attribute to the specified entity.
1667 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1668 const std::string &Name,
1669 unsigned Encoding, unsigned Size) {
1671 DIE Buffer(DW_TAG_base_type);
1672 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1673 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1674 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1675 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1676 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1679 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1681 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1682 DIE Buffer(DW_TAG_pointer_type);
1683 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1684 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1685 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1686 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1689 /// AddType - Add a new type attribute to the specified entity.
1691 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1693 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1695 // Check for pre-existence.
1696 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1698 // If it exists then use the existing value.
1700 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1704 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1705 // FIXME - Not sure why programs and variables are coming through here.
1706 // Short cut for handling subprogram types (not really a TyDesc.)
1707 AddPointerType(Entity, Unit, SubprogramTy->getName());
1708 } else if (GlobalVariableDesc *GlobalTy =
1709 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1710 // FIXME - Not sure why programs and variables are coming through here.
1711 // Short cut for handling global variable types (not really a TyDesc.)
1712 AddPointerType(Entity, Unit, GlobalTy->getName());
1715 Slot = NewDIEntry();
1718 DIE Buffer(DW_TAG_base_type);
1719 ConstructType(Buffer, TyDesc, Unit);
1721 // Add debug information entry to entity and unit.
1722 DIE *Die = Unit->AddDie(Buffer);
1723 SetDIEntry(Slot, Die);
1724 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1729 /// AddType - Add a new type attribute to the specified entity.
1730 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1732 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1736 // Check for pre-existence.
1737 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1738 // If it exists then use the existing value.
1740 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1745 Slot = NewDIEntry();
1748 DIE Buffer(DW_TAG_base_type);
1749 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1750 ConstructTypeDIE(DW_Unit, Buffer, BT);
1751 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1752 ConstructTypeDIE(DW_Unit, Buffer, DT);
1753 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1754 ConstructTypeDIE(DW_Unit, Buffer, CT);
1756 // Add debug information entry to entity and unit.
1757 DIE *Die = DW_Unit->AddDie(Buffer);
1758 SetDIEntry(Slot, Die);
1759 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1762 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1763 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1766 // Get core information.
1767 const std::string &Name = BTy->getName();
1768 Buffer.setTag(DW_TAG_base_type);
1769 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1770 // Add name if not anonymous or intermediate type.
1772 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1773 uint64_t Size = BTy->getSizeInBits() >> 3;
1774 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1777 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1778 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1779 DIDerivedType *DTy) {
1781 // Get core information.
1782 const std::string &Name = DTy->getName();
1783 uint64_t Size = DTy->getSizeInBits() >> 3;
1784 unsigned Tag = DTy->getTag();
1785 // FIXME - Workaround for templates.
1786 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1789 // Map to main type, void will not have a type.
1790 DIType FromTy = DTy->getTypeDerivedFrom();
1791 AddType(DW_Unit, &Buffer, FromTy);
1793 // Add name if not anonymous or intermediate type.
1794 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1796 // Add size if non-zero (derived types might be zero-sized.)
1798 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1800 // Add source line info if available and TyDesc is not a forward
1802 // FIXME - Enable this. if (!DTy->isForwardDecl())
1803 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1806 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1807 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1808 DICompositeType *CTy) {
1810 // Get core information.
1811 const std::string &Name = CTy->getName();
1812 uint64_t Size = CTy->getSizeInBits() >> 3;
1813 unsigned Tag = CTy->getTag();
1815 case DW_TAG_vector_type:
1816 case DW_TAG_array_type:
1817 ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1819 //FIXME - Enable this.
1820 // case DW_TAG_enumeration_type:
1821 // DIArray Elements = CTy->getTypeArray();
1822 // // Add enumerators to enumeration type.
1823 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1824 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1826 case DW_TAG_subroutine_type:
1828 // Add prototype flag.
1829 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1830 DIArray Elements = CTy->getTypeArray();
1832 DIDescriptor RTy = Elements.getElement(0);
1833 if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1834 AddType(DW_Unit, &Buffer, *BT);
1835 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1836 AddType(DW_Unit, &Buffer, *DT);
1837 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1838 AddType(DW_Unit, &Buffer, *CT);
1840 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1842 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1843 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1844 DIDescriptor Ty = Elements.getElement(i);
1845 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1846 AddType(DW_Unit, &Buffer, *BT);
1847 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1848 AddType(DW_Unit, &Buffer, *DT);
1849 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1850 AddType(DW_Unit, &Buffer, *CT);
1851 Buffer.AddChild(Arg);
1855 case DW_TAG_structure_type:
1856 case DW_TAG_union_type:
1858 // Add elements to structure type.
1859 DIArray Elements = CTy->getTypeArray();
1860 // Add elements to structure type.
1861 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1862 DIDescriptor Element = Elements.getElement(i);
1863 if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1864 ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1865 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1866 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1867 else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1868 ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1876 // Add name if not anonymous or intermediate type.
1877 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1879 // Add size if non-zero (derived types might be zero-sized.)
1881 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1883 // Add zero size even if it is not a forward declaration.
1884 // FIXME - Enable this.
1885 // if (!CTy->isDefinition())
1886 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1888 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1891 // Add source line info if available and TyDesc is not a forward
1893 // FIXME - Enable this.
1894 // if (CTy->isForwardDecl())
1895 // AddSourceLine(&Buffer, *CTy);
1898 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1899 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1900 int64_t L = SR->getLo();
1901 int64_t H = SR->getHi();
1902 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1904 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1906 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1907 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1909 Buffer.AddChild(DW_Subrange);
1912 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1913 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1914 DICompositeType *CTy) {
1915 Buffer.setTag(DW_TAG_array_type);
1916 if (CTy->getTag() == DW_TAG_vector_type)
1917 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1919 DIArray Elements = CTy->getTypeArray();
1920 // FIXME - Enable this.
1921 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1923 // Construct an anonymous type for index type.
1924 DIE IdxBuffer(DW_TAG_base_type);
1925 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1926 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1927 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1929 // Add subranges to array type.
1930 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1931 DIDescriptor Element = Elements.getElement(i);
1932 if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1933 ConstructSubrangeDIE(Buffer, SR, IndexTy);
1937 /// ConstructEnumTypeDIE - Construct enum type DIE from
1939 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1940 DIE &Buffer, DIEnumerator *ETy) {
1942 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1943 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1944 int64_t Value = ETy->getEnumValue();
1945 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1946 Buffer.AddChild(Enumerator);
1949 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1950 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1951 DIE &Buffer, DIGlobalVariable *V) {
1953 DIE *VariableDie = new DIE(DW_TAG_variable);
1954 const std::string &LinkageName = V->getLinkageName();
1955 if (!LinkageName.empty())
1956 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1958 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1959 AddType(DW_Unit, VariableDie, V->getType());
1960 if (!V->isLocalToUnit())
1961 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1962 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1963 Buffer.AddChild(VariableDie);
1966 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1967 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1968 DIE &Buffer, DISubprogram *SP,
1969 bool IsConstructor = false) {
1970 DIE *Method = new DIE(DW_TAG_subprogram);
1971 AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1972 const std::string &LinkageName = SP->getLinkageName();
1973 if (!LinkageName.empty())
1974 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1975 // FIXME - Enable this. AddSourceLine(Method, SP);
1977 DICompositeType MTy = SP->getType();
1978 DIArray Args = MTy.getTypeArray();
1981 if (!IsConstructor) {
1982 DIDescriptor Ty = Args.getElement(0);
1983 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1984 AddType(DW_Unit, Method, *BT);
1985 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1986 AddType(DW_Unit, Method, *DT);
1987 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1988 AddType(DW_Unit, Method, *CT);
1992 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1993 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1994 DIDescriptor Ty = Args.getElement(i);
1995 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1996 AddType(DW_Unit, Method, *BT);
1997 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1998 AddType(DW_Unit, Method, *DT);
1999 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2000 AddType(DW_Unit, Method, *CT);
2001 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
2002 Method->AddChild(Arg);
2005 if (!SP->isLocalToUnit())
2006 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2007 Buffer.AddChild(Method);
2010 /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
2011 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
2012 DIDerivedType *DTy) {
2013 unsigned Tag = DTy->getTag();
2014 DIE *MemberDie = new DIE(Tag);
2015 if (!DTy->getName().empty())
2016 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
2017 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
2019 DIType FromTy = DTy->getTypeDerivedFrom();
2020 AddType(DW_Unit, MemberDie, FromTy);
2022 uint64_t Size = DTy->getSizeInBits();
2023 uint64_t Offset = DTy->getOffsetInBits();
2025 // FIXME Handle bitfields
2028 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
2029 // Add computation for offset.
2030 DIEBlock *Block = new DIEBlock();
2031 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2032 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
2033 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
2035 // FIXME Handle DW_AT_accessibility.
2037 Buffer.AddChild(MemberDie);
2040 /// ConstructType - Adds all the required attributes to the type.
2042 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
2043 // Get core information.
2044 const std::string &Name = TyDesc->getName();
2045 uint64_t Size = TyDesc->getSize() >> 3;
2047 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
2048 // Fundamental types like int, float, bool
2049 Buffer.setTag(DW_TAG_base_type);
2050 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
2051 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
2053 unsigned Tag = DerivedTy->getTag();
2054 // FIXME - Workaround for templates.
2055 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
2056 // Pointers, typedefs et al.
2058 // Map to main type, void will not have a type.
2059 if (TypeDesc *FromTy = DerivedTy->getFromType())
2060 AddType(&Buffer, FromTy, Unit);
2061 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
2063 unsigned Tag = CompTy->getTag();
2065 // Set tag accordingly.
2066 if (Tag == DW_TAG_vector_type)
2067 Buffer.setTag(DW_TAG_array_type);
2071 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
2074 case DW_TAG_vector_type:
2075 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
2077 case DW_TAG_array_type: {
2078 // Add element type.
2079 if (TypeDesc *FromTy = CompTy->getFromType())
2080 AddType(&Buffer, FromTy, Unit);
2082 // Don't emit size attribute.
2085 // Construct an anonymous type for index type.
2086 DIE Buffer(DW_TAG_base_type);
2087 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
2088 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
2089 DIE *IndexTy = Unit->AddDie(Buffer);
2091 // Add subranges to array type.
2092 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2093 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
2094 int64_t Lo = SRD->getLo();
2095 int64_t Hi = SRD->getHi();
2096 DIE *Subrange = new DIE(DW_TAG_subrange_type);
2098 // If a range is available.
2100 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
2101 // Only add low if non-zero.
2102 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
2103 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
2106 Buffer.AddChild(Subrange);
2110 case DW_TAG_structure_type:
2111 case DW_TAG_union_type: {
2112 // Add elements to structure type.
2113 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2114 DebugInfoDesc *Element = Elements[i];
2116 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
2117 // Add field or base class.
2118 unsigned Tag = MemberDesc->getTag();
2120 // Extract the basic information.
2121 const std::string &Name = MemberDesc->getName();
2122 uint64_t Size = MemberDesc->getSize();
2123 uint64_t Align = MemberDesc->getAlign();
2124 uint64_t Offset = MemberDesc->getOffset();
2126 // Construct member debug information entry.
2127 DIE *Member = new DIE(Tag);
2129 // Add name if not "".
2131 AddString(Member, DW_AT_name, DW_FORM_string, Name);
2133 // Add location if available.
2134 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
2136 // Most of the time the field info is the same as the members.
2137 uint64_t FieldSize = Size;
2138 uint64_t FieldAlign = Align;
2139 uint64_t FieldOffset = Offset;
2141 // Set the member type.
2142 TypeDesc *FromTy = MemberDesc->getFromType();
2143 AddType(Member, FromTy, Unit);
2145 // Walk up typedefs until a real size is found.
2147 if (FromTy->getTag() != DW_TAG_typedef) {
2148 FieldSize = FromTy->getSize();
2149 FieldAlign = FromTy->getAlign();
2153 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
2156 // Unless we have a bit field.
2157 if (Tag == DW_TAG_member && FieldSize != Size) {
2158 // Construct the alignment mask.
2159 uint64_t AlignMask = ~(FieldAlign - 1);
2160 // Determine the high bit + 1 of the declared size.
2161 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
2162 // Work backwards to determine the base offset of the field.
2163 FieldOffset = HiMark - FieldSize;
2164 // Now normalize offset to the field.
2165 Offset -= FieldOffset;
2167 // Maybe we need to work from the other end.
2168 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
2170 // Add size and offset.
2171 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
2172 AddUInt(Member, DW_AT_bit_size, 0, Size);
2173 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
2176 // Add computation for offset.
2177 DIEBlock *Block = new DIEBlock();
2178 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2179 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
2180 AddBlock(Member, DW_AT_data_member_location, 0, Block);
2182 // Add accessibility (public default unless is base class.
2183 if (MemberDesc->isProtected()) {
2184 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
2185 } else if (MemberDesc->isPrivate()) {
2186 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
2187 } else if (Tag == DW_TAG_inheritance) {
2188 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
2191 Buffer.AddChild(Member);
2192 } else if (GlobalVariableDesc *StaticDesc =
2193 dyn_cast<GlobalVariableDesc>(Element)) {
2194 // Add static member.
2196 // Construct member debug information entry.
2197 DIE *Static = new DIE(DW_TAG_variable);
2199 // Add name and mangled name.
2200 const std::string &Name = StaticDesc->getName();
2201 const std::string &LinkageName = StaticDesc->getLinkageName();
2202 AddString(Static, DW_AT_name, DW_FORM_string, Name);
2203 if (!LinkageName.empty()) {
2204 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
2209 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
2212 if (TypeDesc *StaticTy = StaticDesc->getType())
2213 AddType(Static, StaticTy, Unit);
2216 if (!StaticDesc->isStatic())
2217 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
2218 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2220 Buffer.AddChild(Static);
2221 } else if (SubprogramDesc *MethodDesc =
2222 dyn_cast<SubprogramDesc>(Element)) {
2223 // Add member function.
2225 // Construct member debug information entry.
2226 DIE *Method = new DIE(DW_TAG_subprogram);
2228 // Add name and mangled name.
2229 const std::string &Name = MethodDesc->getName();
2230 const std::string &LinkageName = MethodDesc->getLinkageName();
2232 AddString(Method, DW_AT_name, DW_FORM_string, Name);
2233 bool IsCTor = TyDesc->getName() == Name;
2235 if (!LinkageName.empty()) {
2236 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2241 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2244 if (CompositeTypeDesc *MethodTy =
2245 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2246 // Get argument information.
2247 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2252 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2256 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2257 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2258 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2259 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2260 Method->AddChild(Arg);
2265 if (!MethodDesc->isStatic())
2266 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2267 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2269 Buffer.AddChild(Method);
2274 case DW_TAG_enumeration_type: {
2275 // Add enumerators to enumeration type.
2276 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2277 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2278 const std::string &Name = ED->getName();
2279 int64_t Value = ED->getValue();
2280 DIE *Enumerator = new DIE(DW_TAG_enumerator);
2281 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2282 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2283 Buffer.AddChild(Enumerator);
2288 case DW_TAG_subroutine_type: {
2289 // Add prototype flag.
2290 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2292 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2295 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2296 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2297 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2298 Buffer.AddChild(Arg);
2307 // Add name if not anonymous or intermediate type.
2308 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2310 // Add size if non-zero (derived types might be zero-sized.)
2312 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2313 else if (isa<CompositeTypeDesc>(TyDesc)) {
2314 // If TyDesc is a composite type, then add size even if it's zero unless
2315 // it's a forward declaration.
2316 if (TyDesc->isForwardDecl())
2317 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2319 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2322 // Add source line info if available and TyDesc is not a forward
2324 if (!TyDesc->isForwardDecl())
2325 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2328 /// NewCompileUnit - Create new compile unit and it's debug information entry.
2330 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2331 // Construct debug information entry.
2332 DIE *Die = new DIE(DW_TAG_compile_unit);
2333 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2334 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2335 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
2336 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
2337 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
2338 if (!UnitDesc->getDirectory().empty())
2339 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
2341 // Construct compile unit.
2342 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2344 // Add Unit to compile unit map.
2345 DescToUnitMap[UnitDesc] = Unit;
2350 /// GetBaseCompileUnit - Get the main compile unit.
2352 CompileUnit *GetBaseCompileUnit() const {
2353 CompileUnit *Unit = CompileUnits[0];
2354 assert(Unit && "Missing compile unit.");
2358 /// FindCompileUnit - Get the compile unit for the given descriptor.
2360 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2361 CompileUnit *Unit = DescToUnitMap[UnitDesc];
2362 assert(Unit && "Missing compile unit.");
2366 /// FindCompileUnit - Get the compile unit for the given descriptor.
2368 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
2369 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
2370 assert(DW_Unit && "Missing compile unit.");
2374 /// NewGlobalVariable - Add a new global variable DIE.
2376 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2377 // Get the compile unit context.
2378 CompileUnitDesc *UnitDesc =
2379 static_cast<CompileUnitDesc *>(GVD->getContext());
2380 CompileUnit *Unit = GetBaseCompileUnit();
2382 // Check for pre-existence.
2383 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2384 if (Slot) return Slot;
2386 // Get the global variable itself.
2387 GlobalVariable *GV = GVD->getGlobalVariable();
2389 const std::string &Name = GVD->getName();
2390 const std::string &FullName = GVD->getFullName();
2391 const std::string &LinkageName = GVD->getLinkageName();
2392 // Create the global's variable DIE.
2393 DIE *VariableDie = new DIE(DW_TAG_variable);
2394 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2395 if (!LinkageName.empty()) {
2396 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2399 AddType(VariableDie, GVD->getType(), Unit);
2400 if (!GVD->isStatic())
2401 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2403 // Add source line info if available.
2404 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2407 DIEBlock *Block = new DIEBlock();
2408 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2409 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2410 AddBlock(VariableDie, DW_AT_location, 0, Block);
2415 // Add to context owner.
2416 Unit->getDie()->AddChild(VariableDie);
2418 // Expose as global.
2419 // FIXME - need to check external flag.
2420 Unit->AddGlobal(FullName, VariableDie);
2425 /// NewSubprogram - Add a new subprogram DIE.
2427 DIE *NewSubprogram(SubprogramDesc *SPD) {
2428 // Get the compile unit context.
2429 CompileUnitDesc *UnitDesc =
2430 static_cast<CompileUnitDesc *>(SPD->getContext());
2431 CompileUnit *Unit = GetBaseCompileUnit();
2433 // Check for pre-existence.
2434 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2435 if (Slot) return Slot;
2437 // Gather the details (simplify add attribute code.)
2438 const std::string &Name = SPD->getName();
2439 const std::string &FullName = SPD->getFullName();
2440 const std::string &LinkageName = SPD->getLinkageName();
2442 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2443 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2444 if (!LinkageName.empty()) {
2445 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2448 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2449 if (!SPD->isStatic())
2450 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2451 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2453 // Add source line info if available.
2454 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2457 Slot = SubprogramDie;
2459 // Add to context owner.
2460 Unit->getDie()->AddChild(SubprogramDie);
2462 // Expose as global.
2463 Unit->AddGlobal(FullName, SubprogramDie);
2465 return SubprogramDie;
2468 /// NewScopeVariable - Create a new scope variable.
2470 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2471 // Get the descriptor.
2472 VariableDesc *VD = DV->getDesc();
2474 // Translate tag to proper Dwarf tag. The result variable is dropped for
2477 switch (VD->getTag()) {
2478 case DW_TAG_return_variable: return NULL;
2479 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2480 case DW_TAG_auto_variable: // fall thru
2481 default: Tag = DW_TAG_variable; break;
2484 // Define variable debug information entry.
2485 DIE *VariableDie = new DIE(Tag);
2486 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2488 // Add source line info if available.
2489 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2491 // Add variable type.
2492 AddType(VariableDie, VD->getType(), Unit);
2494 // Add variable address.
2495 MachineLocation Location;
2496 Location.set(RI->getFrameRegister(*MF),
2497 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2498 AddAddress(VariableDie, DW_AT_location, Location);
2503 /// NewScopeVariable - Create a new scope variable.
2505 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
2506 // Get the descriptor.
2507 DIVariable *VD = DV->getVariable();
2509 // Translate tag to proper Dwarf tag. The result variable is dropped for
2512 switch (VD->getTag()) {
2513 case DW_TAG_return_variable: return NULL;
2514 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2515 case DW_TAG_auto_variable: // fall thru
2516 default: Tag = DW_TAG_variable; break;
2519 // Define variable debug information entry.
2520 DIE *VariableDie = new DIE(Tag);
2521 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2523 // Add source line info if available.
2524 AddSourceLine(VariableDie, VD);
2526 // Add variable type.
2527 AddType(Unit, VariableDie, VD->getType());
2529 // Add variable address.
2530 MachineLocation Location;
2531 Location.set(RI->getFrameRegister(*MF),
2532 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2533 AddAddress(VariableDie, DW_AT_location, Location);
2538 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2539 CompileUnit *Unit = DW_CUs[V];
2540 assert (Unit && "Unable to find CompileUnit");
2541 unsigned ID = MMI->NextLabelID();
2542 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2546 unsigned getRecordSourceLineCount() {
2547 return Lines.size();
2550 unsigned RecordSource(const std::string &Directory,
2551 const std::string &File) {
2552 unsigned DID = Directories.insert(Directory);
2553 return SrcFiles.insert(SrcFileInfo(DID,File));
2556 /// RecordRegionStart - Indicate the start of a region.
2558 unsigned RecordRegionStart(GlobalVariable *V) {
2559 DbgScope *Scope = getOrCreateScope(V);
2560 unsigned ID = MMI->NextLabelID();
2561 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2565 /// RecordRegionEnd - Indicate the end of a region.
2567 unsigned RecordRegionEnd(GlobalVariable *V) {
2568 DbgScope *Scope = getOrCreateScope(V);
2569 unsigned ID = MMI->NextLabelID();
2570 Scope->setEndLabelID(ID);
2574 /// RecordVariable - Indicate the declaration of a local variable.
2576 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
2577 DbgScope *Scope = getOrCreateScope(GV);
2578 DIVariable *VD = new DIVariable(GV);
2579 DbgVariable *DV = new DbgVariable(VD, FrameIndex);
2580 Scope->AddVariable(DV);
2583 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2585 DbgScope *getOrCreateScope(GlobalVariable *V) {
2586 DbgScope *&Slot = DbgScopeMap[V];
2588 // FIXME - breaks down when the context is an inlined function.
2589 DIDescriptor ParentDesc;
2590 DIDescriptor *DB = new DIBlock(V);
2591 if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
2592 ParentDesc = Block->getContext();
2594 DbgScope *Parent = ParentDesc.isNull() ?
2595 NULL : getOrCreateScope(ParentDesc.getGV());
2596 Slot = new DbgScope(Parent, DB);
2598 Parent->AddScope(Slot);
2599 } else if (RootDbgScope) {
2600 // FIXME - Add inlined function scopes to the root so we can delete
2601 // them later. Long term, handle inlined functions properly.
2602 RootDbgScope->AddScope(Slot);
2604 // First function is top level function.
2605 RootDbgScope = Slot;
2611 /// ConstructDbgScope - Construct the components of a scope.
2613 void ConstructDbgScope(DbgScope *ParentScope,
2614 unsigned ParentStartID, unsigned ParentEndID,
2615 DIE *ParentDie, CompileUnit *Unit) {
2616 // Add variables to scope.
2617 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2618 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2619 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2620 if (VariableDie) ParentDie->AddChild(VariableDie);
2623 // Add nested scopes.
2624 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2625 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2626 // Define the Scope debug information entry.
2627 DbgScope *Scope = Scopes[j];
2628 // FIXME - Ignore inlined functions for the time being.
2629 if (!Scope->getParent()) continue;
2631 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2632 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2634 // Ignore empty scopes.
2635 if (StartID == EndID && StartID != 0) continue;
2636 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2638 if (StartID == ParentStartID && EndID == ParentEndID) {
2639 // Just add stuff to the parent scope.
2640 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2642 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2644 // Add the scope bounds.
2646 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2647 DWLabel("label", StartID));
2649 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2650 DWLabel("func_begin", SubprogramCount));
2653 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2654 DWLabel("label", EndID));
2656 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2657 DWLabel("func_end", SubprogramCount));
2660 // Add the scope contents.
2661 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2662 ParentDie->AddChild(ScopeDie);
2667 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2669 void ConstructRootDbgScope(DbgScope *RootScope) {
2670 // Exit if there is no root scope.
2671 if (!RootScope) return;
2673 // Get the subprogram debug information entry.
2674 DISubprogram *SPD = cast<DISubprogram>(RootScope->getDesc());
2676 // Get the compile unit context.
2677 CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2679 // Get the subprogram die.
2680 DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2681 assert(SPDie && "Missing subprogram descriptor");
2683 // Add the function bounds.
2684 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2685 DWLabel("func_begin", SubprogramCount));
2686 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2687 DWLabel("func_end", SubprogramCount));
2688 MachineLocation Location(RI->getFrameRegister(*MF));
2689 AddAddress(SPDie, DW_AT_frame_base, Location);
2691 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2694 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2696 void ConstructDefaultDbgScope(MachineFunction *MF) {
2697 // Find the correct subprogram descriptor.
2698 std::string SPName = "llvm.dbg.subprograms";
2699 std::vector<GlobalVariable*> Result;
2700 getGlobalVariablesUsing(*M, SPName, Result);
2701 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2702 E = Result.end(); I != E; ++I) {
2704 DISubprogram *SPD = new DISubprogram(*I);
2706 if (SPD->getName() == MF->getFunction()->getName()) {
2707 // Get the compile unit context.
2708 CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2710 // Get the subprogram die.
2711 DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2712 assert(SPDie && "Missing subprogram descriptor");
2714 // Add the function bounds.
2715 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2716 DWLabel("func_begin", SubprogramCount));
2717 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2718 DWLabel("func_end", SubprogramCount));
2720 MachineLocation Location(RI->getFrameRegister(*MF));
2721 AddAddress(SPDie, DW_AT_frame_base, Location);
2726 // FIXME: This is causing an abort because C++ mangled names are compared
2727 // with their unmangled counterparts. See PR2885. Don't do this assert.
2728 assert(0 && "Couldn't find DIE for machine function!");
2732 /// ConstructScope - Construct the components of a scope.
2734 void ConstructScope(DebugScope *ParentScope,
2735 unsigned ParentStartID, unsigned ParentEndID,
2736 DIE *ParentDie, CompileUnit *Unit) {
2737 // Add variables to scope.
2738 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2739 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2740 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2741 if (VariableDie) ParentDie->AddChild(VariableDie);
2744 // Add nested scopes.
2745 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2746 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2747 // Define the Scope debug information entry.
2748 DebugScope *Scope = Scopes[j];
2749 // FIXME - Ignore inlined functions for the time being.
2750 if (!Scope->getParent()) continue;
2752 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2753 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2755 // Ignore empty scopes.
2756 if (StartID == EndID && StartID != 0) continue;
2757 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2759 if (StartID == ParentStartID && EndID == ParentEndID) {
2760 // Just add stuff to the parent scope.
2761 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2763 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2765 // Add the scope bounds.
2767 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2768 DWLabel("label", StartID));
2770 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2771 DWLabel("func_begin", SubprogramCount));
2774 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2775 DWLabel("label", EndID));
2777 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2778 DWLabel("func_end", SubprogramCount));
2781 // Add the scope contents.
2782 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2783 ParentDie->AddChild(ScopeDie);
2788 /// ConstructRootScope - Construct the scope for the subprogram.
2790 void ConstructRootScope(DebugScope *RootScope) {
2791 // Exit if there is no root scope.
2792 if (!RootScope) return;
2794 // Get the subprogram debug information entry.
2795 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2797 // Get the compile unit context.
2798 CompileUnit *Unit = GetBaseCompileUnit();
2800 // Get the subprogram die.
2801 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2802 assert(SPDie && "Missing subprogram descriptor");
2804 // Add the function bounds.
2805 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2806 DWLabel("func_begin", SubprogramCount));
2807 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2808 DWLabel("func_end", SubprogramCount));
2809 MachineLocation Location(RI->getFrameRegister(*MF));
2810 AddAddress(SPDie, DW_AT_frame_base, Location);
2812 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2815 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2817 void ConstructDefaultScope(MachineFunction *MF) {
2818 // Find the correct subprogram descriptor.
2819 std::vector<SubprogramDesc *> Subprograms;
2820 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2822 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2823 SubprogramDesc *SPD = Subprograms[i];
2825 if (SPD->getName() == MF->getFunction()->getName()) {
2826 // Get the compile unit context.
2827 CompileUnit *Unit = GetBaseCompileUnit();
2829 // Get the subprogram die.
2830 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2831 assert(SPDie && "Missing subprogram descriptor");
2833 // Add the function bounds.
2834 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2835 DWLabel("func_begin", SubprogramCount));
2836 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2837 DWLabel("func_end", SubprogramCount));
2839 MachineLocation Location(RI->getFrameRegister(*MF));
2840 AddAddress(SPDie, DW_AT_frame_base, Location);
2845 // FIXME: This is causing an abort because C++ mangled names are compared
2846 // with their unmangled counterparts. See PR2885. Don't do this assert.
2847 assert(0 && "Couldn't find DIE for machine function!");
2851 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2852 /// tools to recognize the object file contains Dwarf information.
2853 void EmitInitial() {
2854 // Check to see if we already emitted intial headers.
2855 if (didInitial) return;
2858 // Dwarf sections base addresses.
2859 if (TAI->doesDwarfRequireFrameSection()) {
2860 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2861 EmitLabel("section_debug_frame", 0);
2863 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2864 EmitLabel("section_info", 0);
2865 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2866 EmitLabel("section_abbrev", 0);
2867 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2868 EmitLabel("section_aranges", 0);
2869 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2870 EmitLabel("section_macinfo", 0);
2871 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2872 EmitLabel("section_line", 0);
2873 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2874 EmitLabel("section_loc", 0);
2875 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2876 EmitLabel("section_pubnames", 0);
2877 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2878 EmitLabel("section_str", 0);
2879 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2880 EmitLabel("section_ranges", 0);
2882 Asm->SwitchToSection(TAI->getTextSection());
2883 EmitLabel("text_begin", 0);
2884 Asm->SwitchToSection(TAI->getDataSection());
2885 EmitLabel("data_begin", 0);
2888 /// EmitDIE - Recusively Emits a debug information entry.
2890 void EmitDIE(DIE *Die) {
2891 // Get the abbreviation for this DIE.
2892 unsigned AbbrevNumber = Die->getAbbrevNumber();
2893 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2897 // Emit the code (index) for the abbreviation.
2898 Asm->EmitULEB128Bytes(AbbrevNumber);
2901 Asm->EOL(std::string("Abbrev [" +
2902 utostr(AbbrevNumber) +
2903 "] 0x" + utohexstr(Die->getOffset()) +
2904 ":0x" + utohexstr(Die->getSize()) + " " +
2905 TagString(Abbrev->getTag())));
2909 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2910 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2912 // Emit the DIE attribute values.
2913 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2914 unsigned Attr = AbbrevData[i].getAttribute();
2915 unsigned Form = AbbrevData[i].getForm();
2916 assert(Form && "Too many attributes for DIE (check abbreviation)");
2919 case DW_AT_sibling: {
2920 Asm->EmitInt32(Die->SiblingOffset());
2924 // Emit an attribute using the defined form.
2925 Values[i]->EmitValue(*this, Form);
2930 Asm->EOL(AttributeString(Attr));
2933 // Emit the DIE children if any.
2934 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2935 const std::vector<DIE *> &Children = Die->getChildren();
2937 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2938 EmitDIE(Children[j]);
2941 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2945 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2947 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2948 // Get the children.
2949 const std::vector<DIE *> &Children = Die->getChildren();
2951 // If not last sibling and has children then add sibling offset attribute.
2952 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2954 // Record the abbreviation.
2955 AssignAbbrevNumber(Die->getAbbrev());
2957 // Get the abbreviation for this DIE.
2958 unsigned AbbrevNumber = Die->getAbbrevNumber();
2959 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2962 Die->setOffset(Offset);
2964 // Start the size with the size of abbreviation code.
2965 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2967 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2968 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2970 // Size the DIE attribute values.
2971 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2972 // Size attribute value.
2973 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2976 // Size the DIE children if any.
2977 if (!Children.empty()) {
2978 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2979 "Children flag not set");
2981 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2982 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2985 // End of children marker.
2986 Offset += sizeof(int8_t);
2989 Die->setSize(Offset - Die->getOffset());
2993 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2995 void SizeAndOffsets() {
2996 // Process base compile unit.
2997 CompileUnit *Unit = GetBaseCompileUnit();
2998 // Compute size of compile unit header
2999 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
3000 sizeof(int16_t) + // DWARF version number
3001 sizeof(int32_t) + // Offset Into Abbrev. Section
3002 sizeof(int8_t); // Pointer Size (in bytes)
3003 SizeAndOffsetDie(Unit->getDie(), Offset, true);
3006 /// EmitDebugInfo - Emit the debug info section.
3008 void EmitDebugInfo() {
3009 // Start debug info section.
3010 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
3012 CompileUnit *Unit = GetBaseCompileUnit();
3013 DIE *Die = Unit->getDie();
3014 // Emit the compile units header.
3015 EmitLabel("info_begin", Unit->getID());
3016 // Emit size of content not including length itself
3017 unsigned ContentSize = Die->getSize() +
3018 sizeof(int16_t) + // DWARF version number
3019 sizeof(int32_t) + // Offset Into Abbrev. Section
3020 sizeof(int8_t) + // Pointer Size (in bytes)
3021 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3023 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
3024 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3025 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
3026 Asm->EOL("Offset Into Abbrev. Section");
3027 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
3030 // FIXME - extra padding for gdb bug.
3031 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3032 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3033 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3034 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3035 EmitLabel("info_end", Unit->getID());
3040 /// EmitAbbreviations - Emit the abbreviation section.
3042 void EmitAbbreviations() const {
3043 // Check to see if it is worth the effort.
3044 if (!Abbreviations.empty()) {
3045 // Start the debug abbrev section.
3046 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
3048 EmitLabel("abbrev_begin", 0);
3050 // For each abbrevation.
3051 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3052 // Get abbreviation data
3053 const DIEAbbrev *Abbrev = Abbreviations[i];
3055 // Emit the abbrevations code (base 1 index.)
3056 Asm->EmitULEB128Bytes(Abbrev->getNumber());
3057 Asm->EOL("Abbreviation Code");
3059 // Emit the abbreviations data.
3060 Abbrev->Emit(*this);
3065 // Mark end of abbreviations.
3066 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
3068 EmitLabel("abbrev_end", 0);
3074 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
3075 /// the line matrix.
3077 void EmitEndOfLineMatrix(unsigned SectionEnd) {
3078 // Define last address of section.
3079 Asm->EmitInt8(0); Asm->EOL("Extended Op");
3080 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3081 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3082 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
3084 // Mark end of matrix.
3085 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
3086 Asm->EmitULEB128Bytes(1); Asm->EOL();
3087 Asm->EmitInt8(1); Asm->EOL();
3090 /// EmitDebugLines - Emit source line information.
3092 void EmitDebugLines() {
3093 // If the target is using .loc/.file, the assembler will be emitting the
3094 // .debug_line table automatically.
3095 if (TAI->hasDotLocAndDotFile())
3098 // Minimum line delta, thus ranging from -10..(255-10).
3099 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
3100 // Maximum line delta, thus ranging from -10..(255-10).
3101 const int MaxLineDelta = 255 + MinLineDelta;
3103 // Start the dwarf line section.
3104 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
3106 // Construct the section header.
3108 EmitDifference("line_end", 0, "line_begin", 0, true);
3109 Asm->EOL("Length of Source Line Info");
3110 EmitLabel("line_begin", 0);
3112 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3114 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
3115 Asm->EOL("Prolog Length");
3116 EmitLabel("line_prolog_begin", 0);
3118 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
3120 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
3122 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
3124 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
3126 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
3128 // Line number standard opcode encodings argument count
3129 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
3130 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
3131 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
3132 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
3133 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
3134 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
3135 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
3136 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
3137 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
3139 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3140 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3142 // Emit directories.
3143 for (unsigned DirectoryID = 1, NDID = Directories.size();
3144 DirectoryID <= NDID; ++DirectoryID) {
3145 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
3147 Asm->EmitInt8(0); Asm->EOL("End of directories");
3150 for (unsigned SourceID = 1, NSID = SourceFiles.size();
3151 SourceID <= NSID; ++SourceID) {
3152 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3153 Asm->EmitString(SourceFile.getName());
3155 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
3156 Asm->EOL("Directory #");
3157 Asm->EmitULEB128Bytes(0);
3158 Asm->EOL("Mod date");
3159 Asm->EmitULEB128Bytes(0);
3160 Asm->EOL("File size");
3162 Asm->EmitInt8(0); Asm->EOL("End of files");
3164 EmitLabel("line_prolog_end", 0);
3166 // A sequence for each text section.
3167 unsigned SecSrcLinesSize = SectionSourceLines.size();
3169 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3170 // Isolate current sections line info.
3171 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
3174 const Section* S = SectionMap[j + 1];
3175 Asm->EOL(std::string("Section ") + S->getName());
3179 // Dwarf assumes we start with first line of first source file.
3180 unsigned Source = 1;
3183 // Construct rows of the address, source, line, column matrix.
3184 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3185 const SourceLineInfo &LineInfo = LineInfos[i];
3186 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
3187 if (!LabelID) continue;
3189 unsigned SourceID = LineInfo.getSourceID();
3190 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3191 unsigned DirectoryID = SourceFile.getDirectoryID();
3193 Asm->EOL(Directories[DirectoryID]
3194 + SourceFile.getName()
3196 + utostr_32(LineInfo.getLine()));
3200 // Define the line address.
3201 Asm->EmitInt8(0); Asm->EOL("Extended Op");
3202 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3203 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3204 EmitReference("label", LabelID); Asm->EOL("Location label");
3206 // If change of source, then switch to the new source.
3207 if (Source != LineInfo.getSourceID()) {
3208 Source = LineInfo.getSourceID();
3209 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
3210 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
3213 // If change of line.
3214 if (Line != LineInfo.getLine()) {
3215 // Determine offset.
3216 int Offset = LineInfo.getLine() - Line;
3217 int Delta = Offset - MinLineDelta;
3220 Line = LineInfo.getLine();
3222 // If delta is small enough and in range...
3223 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3224 // ... then use fast opcode.
3225 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
3227 // ... otherwise use long hand.
3228 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
3229 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
3230 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3233 // Copy the previous row (different address or source)
3234 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3238 EmitEndOfLineMatrix(j + 1);
3241 if (SecSrcLinesSize == 0)
3242 // Because we're emitting a debug_line section, we still need a line
3243 // table. The linker and friends expect it to exist. If there's nothing to
3244 // put into it, emit an empty table.
3245 EmitEndOfLineMatrix(1);
3247 EmitLabel("line_end", 0);
3252 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
3254 void EmitCommonDebugFrame() {
3255 if (!TAI->doesDwarfRequireFrameSection())
3259 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3260 TargetFrameInfo::StackGrowsUp ?
3261 TD->getPointerSize() : -TD->getPointerSize();
3263 // Start the dwarf frame section.
3264 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3266 EmitLabel("debug_frame_common", 0);
3267 EmitDifference("debug_frame_common_end", 0,
3268 "debug_frame_common_begin", 0, true);
3269 Asm->EOL("Length of Common Information Entry");
3271 EmitLabel("debug_frame_common_begin", 0);
3272 Asm->EmitInt32((int)DW_CIE_ID);
3273 Asm->EOL("CIE Identifier Tag");
3274 Asm->EmitInt8(DW_CIE_VERSION);
3275 Asm->EOL("CIE Version");
3276 Asm->EmitString("");
3277 Asm->EOL("CIE Augmentation");
3278 Asm->EmitULEB128Bytes(1);
3279 Asm->EOL("CIE Code Alignment Factor");
3280 Asm->EmitSLEB128Bytes(stackGrowth);
3281 Asm->EOL("CIE Data Alignment Factor");
3282 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3283 Asm->EOL("CIE RA Column");
3285 std::vector<MachineMove> Moves;
3286 RI->getInitialFrameState(Moves);
3288 EmitFrameMoves(NULL, 0, Moves, false);
3290 Asm->EmitAlignment(2, 0, 0, false);
3291 EmitLabel("debug_frame_common_end", 0);
3296 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
3298 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3299 if (!TAI->doesDwarfRequireFrameSection())
3302 // Start the dwarf frame section.
3303 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3305 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
3306 "debug_frame_begin", DebugFrameInfo.Number, true);
3307 Asm->EOL("Length of Frame Information Entry");
3309 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
3311 EmitSectionOffset("debug_frame_common", "section_debug_frame",
3313 Asm->EOL("FDE CIE offset");
3315 EmitReference("func_begin", DebugFrameInfo.Number);
3316 Asm->EOL("FDE initial location");
3317 EmitDifference("func_end", DebugFrameInfo.Number,
3318 "func_begin", DebugFrameInfo.Number);
3319 Asm->EOL("FDE address range");
3321 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
3323 Asm->EmitAlignment(2, 0, 0, false);
3324 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
3329 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
3331 void EmitDebugPubNames() {
3332 // Start the dwarf pubnames section.
3333 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
3335 CompileUnit *Unit = GetBaseCompileUnit();
3337 EmitDifference("pubnames_end", Unit->getID(),
3338 "pubnames_begin", Unit->getID(), true);
3339 Asm->EOL("Length of Public Names Info");
3341 EmitLabel("pubnames_begin", Unit->getID());
3343 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
3345 EmitSectionOffset("info_begin", "section_info",
3346 Unit->getID(), 0, true, false);
3347 Asm->EOL("Offset of Compilation Unit Info");
3349 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
3350 Asm->EOL("Compilation Unit Length");
3352 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
3354 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
3357 const std::string &Name = GI->first;
3358 DIE * Entity = GI->second;
3360 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
3361 Asm->EmitString(Name); Asm->EOL("External Name");
3364 Asm->EmitInt32(0); Asm->EOL("End Mark");
3365 EmitLabel("pubnames_end", Unit->getID());
3370 /// EmitDebugStr - Emit visible names into a debug str section.
3372 void EmitDebugStr() {
3373 // Check to see if it is worth the effort.
3374 if (!StringPool.empty()) {
3375 // Start the dwarf str section.
3376 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
3378 // For each of strings in the string pool.
3379 for (unsigned StringID = 1, N = StringPool.size();
3380 StringID <= N; ++StringID) {
3381 // Emit a label for reference from debug information entries.
3382 EmitLabel("string", StringID);
3383 // Emit the string itself.
3384 const std::string &String = StringPool[StringID];
3385 Asm->EmitString(String); Asm->EOL();
3392 /// EmitDebugLoc - Emit visible names into a debug loc section.
3394 void EmitDebugLoc() {
3395 // Start the dwarf loc section.
3396 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
3401 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3403 void EmitDebugARanges() {
3404 // Start the dwarf aranges section.
3405 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
3409 CompileUnit *Unit = GetBaseCompileUnit();
3411 // Don't include size of length
3412 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
3414 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
3416 EmitReference("info_begin", Unit->getID());
3417 Asm->EOL("Offset of Compilation Unit Info");
3419 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
3421 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
3423 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
3424 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
3427 EmitReference("text_begin", 0); Asm->EOL("Address");
3428 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
3430 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
3431 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
3437 /// EmitDebugRanges - Emit visible names into a debug ranges section.
3439 void EmitDebugRanges() {
3440 // Start the dwarf ranges section.
3441 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
3446 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
3448 void EmitDebugMacInfo() {
3449 // Start the dwarf macinfo section.
3450 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
3455 /// ConstructCompileUnits - Create a compile unit DIEs.
3456 void ConstructCompileUnits() {
3457 std::string CUName = "llvm.dbg.compile_units";
3458 std::vector<GlobalVariable*> Result;
3459 getGlobalVariablesUsing(*M, CUName, Result);
3460 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3461 RE = Result.end(); RI != RE; ++RI) {
3462 DICompileUnit *DIUnit = new DICompileUnit(*RI);
3463 unsigned ID = RecordSource(DIUnit->getDirectory(),
3464 DIUnit->getFilename());
3466 DIE *Die = new DIE(DW_TAG_compile_unit);
3467 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
3468 DWLabel("section_line", 0), DWLabel("section_line", 0),
3470 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
3471 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
3472 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
3473 if (!DIUnit->getDirectory().empty())
3474 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
3476 CompileUnit *Unit = new CompileUnit(ID, Die);
3477 DW_CUs[DIUnit->getGV()] = Unit;
3481 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3483 void ConstructCompileUnitDIEs() {
3484 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3486 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3487 unsigned ID = MMI->RecordSource(CUW[i]);
3488 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3489 CompileUnits.push_back(Unit);
3493 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
3494 /// visible global variables.
3495 void ConstructGlobalVariableDIEs() {
3496 std::string GVName = "llvm.dbg.global_variables";
3497 std::vector<GlobalVariable*> Result;
3498 getGlobalVariablesUsing(*M, GVName, Result);
3499 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
3500 GVE = Result.end(); GVI != GVE; ++GVI) {
3501 DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
3502 CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
3504 // Check for pre-existence.
3505 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
3508 DIE *VariableDie = new DIE(DW_TAG_variable);
3509 AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
3510 const std::string &LinkageName = DI_GV->getLinkageName();
3511 if (!LinkageName.empty())
3512 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3514 AddType(DW_Unit, VariableDie, DI_GV->getType());
3516 if (!DI_GV->isLocalToUnit())
3517 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
3519 // Add source line info, if available.
3520 AddSourceLine(VariableDie, DI_GV);
3523 DIEBlock *Block = new DIEBlock();
3524 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3525 AddObjectLabel(Block, 0, DW_FORM_udata,
3526 Asm->getGlobalLinkName(DI_GV->getGV()));
3527 AddBlock(VariableDie, DW_AT_location, 0, Block);
3532 //Add to context owner.
3533 DW_Unit->getDie()->AddChild(VariableDie);
3535 //Expose as global. FIXME - need to check external flag.
3536 DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
3540 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3541 /// global variables.
3542 void ConstructGlobalDIEs() {
3543 std::vector<GlobalVariableDesc *> GlobalVariables;
3544 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3546 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3547 GlobalVariableDesc *GVD = GlobalVariables[i];
3548 NewGlobalVariable(GVD);
3552 /// ConstructSubprograms - Create DIEs for each of the externally visible
3554 void ConstructSubprograms() {
3556 std::string SPName = "llvm.dbg.subprograms";
3557 std::vector<GlobalVariable*> Result;
3558 getGlobalVariablesUsing(*M, SPName, Result);
3559 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3560 RE = Result.end(); RI != RE; ++RI) {
3562 DISubprogram *SP = new DISubprogram(*RI);
3563 CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
3565 // Check for pre-existence.
3566 DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
3569 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
3570 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
3571 const std::string &LinkageName = SP->getLinkageName();
3572 if (!LinkageName.empty())
3573 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3575 DIType SPTy = SP->getType();
3576 AddType(Unit, SubprogramDie, SPTy);
3577 if (!SP->isLocalToUnit())
3578 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
3579 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
3581 AddSourceLine(SubprogramDie, SP);
3583 Slot = SubprogramDie;
3584 //Add to context owner.
3585 Unit->getDie()->AddChild(SubprogramDie);
3587 Unit->AddGlobal(SP->getName(), SubprogramDie);
3591 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3593 void ConstructSubprogramDIEs() {
3594 std::vector<SubprogramDesc *> Subprograms;
3595 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3597 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3598 SubprogramDesc *SPD = Subprograms[i];
3604 //===--------------------------------------------------------------------===//
3605 // Main entry points.
3607 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3608 : Dwarf(OS, A, T, "dbg")
3610 , AbbreviationsSet(InitAbbreviationsSetSize)
3612 , ValuesSet(InitValuesSetSize)
3617 , SectionSourceLines()
3620 , RootDbgScope(NULL)
3623 virtual ~DwarfDebug() {
3624 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3625 delete CompileUnits[i];
3626 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3630 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3631 /// This is inovked by the target AsmPrinter.
3632 void SetDebugInfo() {
3633 // FIXME - Check if the module has debug info or not.
3634 // Create all the compile unit DIEs.
3635 ConstructCompileUnits();
3637 // Create DIEs for each of the externally visible global variables.
3638 ConstructGlobalVariableDIEs();
3640 // Create DIEs for each of the externally visible subprograms.
3641 ConstructSubprograms();
3643 // Prime section data.
3644 SectionMap.insert(TAI->getTextSection());
3646 // Print out .file directives to specify files for .loc directives. These
3647 // are printed out early so that they precede any .loc directives.
3648 if (TAI->hasDotLocAndDotFile()) {
3649 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
3650 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
3651 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
3652 assert(AppendOk && "Could not append filename to directory!");
3654 Asm->EmitFile(i, FullPath.toString());
3659 // Emit initial sections
3663 /// SetModuleInfo - Set machine module information when it's known that pass
3664 /// manager has created it. Set by the target AsmPrinter.
3665 void SetModuleInfo(MachineModuleInfo *mmi) {
3666 // Make sure initial declarations are made.
3667 if (!MMI && mmi->hasDebugInfo()) {
3671 // Create all the compile unit DIEs.
3672 ConstructCompileUnitDIEs();
3674 // Create DIEs for each of the externally visible global variables.
3675 ConstructGlobalDIEs();
3677 // Create DIEs for each of the externally visible subprograms.
3678 ConstructSubprogramDIEs();
3680 // Prime section data.
3681 SectionMap.insert(TAI->getTextSection());
3683 // Print out .file directives to specify files for .loc directives. These
3684 // are printed out early so that they precede any .loc directives.
3685 if (TAI->hasDotLocAndDotFile()) {
3686 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3687 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3688 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3689 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3690 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3691 assert(AppendOk && "Could not append filename to directory!");
3693 Asm->EmitFile(i, FullPath.toString());
3698 // Emit initial sections
3703 /// BeginModule - Emit all Dwarf sections that should come prior to the
3705 void BeginModule(Module *M) {
3709 /// EndModule - Emit all Dwarf sections that should come after the content.
3712 if (!ShouldEmitDwarf()) return;
3714 // Standard sections final addresses.
3715 Asm->SwitchToSection(TAI->getTextSection());
3716 EmitLabel("text_end", 0);
3717 Asm->SwitchToSection(TAI->getDataSection());
3718 EmitLabel("data_end", 0);
3720 // End text sections.
3721 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3722 Asm->SwitchToSection(SectionMap[i]);
3723 EmitLabel("section_end", i);
3726 // Emit common frame information.
3727 EmitCommonDebugFrame();
3729 // Emit function debug frame information
3730 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3731 E = DebugFrames.end(); I != E; ++I)
3732 EmitFunctionDebugFrame(*I);
3734 // Compute DIE offsets and sizes.
3737 // Emit all the DIEs into a debug info section
3740 // Corresponding abbreviations into a abbrev section.
3741 EmitAbbreviations();
3743 // Emit source line correspondence into a debug line section.
3746 // Emit info into a debug pubnames section.
3747 EmitDebugPubNames();
3749 // Emit info into a debug str section.
3752 // Emit info into a debug loc section.
3755 // Emit info into a debug aranges section.
3758 // Emit info into a debug ranges section.
3761 // Emit info into a debug macinfo section.
3765 /// BeginFunction - Gather pre-function debug information. Assumes being
3766 /// emitted immediately after the function entry point.
3767 void BeginFunction(MachineFunction *MF) {
3770 if (!ShouldEmitDwarf()) return;
3772 // Begin accumulating function debug information.
3773 MMI->BeginFunction(MF);
3775 // Assumes in correct section after the entry point.
3776 EmitLabel("func_begin", ++SubprogramCount);
3778 // Emit label for the implicitly defined dbg.stoppoint at the start of
3780 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3781 if (!LineInfos.empty()) {
3782 const SourceLineInfo &LineInfo = LineInfos[0];
3783 Asm->printLabel(LineInfo.getLabelID());
3787 /// EndFunction - Gather and emit post-function debug information.
3789 void EndFunction(MachineFunction *MF) {
3790 if (!ShouldEmitDwarf()) return;
3792 // Define end label for subprogram.
3793 EmitLabel("func_end", SubprogramCount);
3795 // Get function line info.
3796 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3798 if (!LineInfos.empty()) {
3799 // Get section line info.
3800 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3801 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3802 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3803 // Append the function info to section info.
3804 SectionLineInfos.insert(SectionLineInfos.end(),
3805 LineInfos.begin(), LineInfos.end());
3808 // Construct scopes for subprogram.
3809 if (MMI->getRootScope())
3810 ConstructRootScope(MMI->getRootScope());
3812 // FIXME: This is wrong. We are essentially getting past a problem with
3813 // debug information not being able to handle unreachable blocks that have
3814 // debug information in them. In particular, those unreachable blocks that
3815 // have "region end" info in them. That situation results in the "root
3816 // scope" not being created. If that's the case, then emit a "default"
3817 // scope, i.e., one that encompasses the whole function. This isn't
3818 // desirable. And a better way of handling this (and all of the debugging
3819 // information) needs to be explored.
3820 ConstructDefaultScope(MF);
3822 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3823 MMI->getFrameMoves()));
3827 //===----------------------------------------------------------------------===//
3828 /// DwarfException - Emits Dwarf exception handling directives.
3830 class DwarfException : public Dwarf {
3833 struct FunctionEHFrameInfo {
3836 unsigned PersonalityIndex;
3838 bool hasLandingPads;
3839 std::vector<MachineMove> Moves;
3840 const Function * function;
3842 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3844 const std::vector<MachineMove> &M,
3846 FnName(FN), Number(Num), PersonalityIndex(P),
3847 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3850 std::vector<FunctionEHFrameInfo> EHFrames;
3852 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3854 bool shouldEmitTable;
3856 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3857 /// should be emitted.
3858 bool shouldEmitMoves;
3860 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3861 /// should be emitted.
3862 bool shouldEmitTableModule;
3864 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3865 /// should be emitted.
3866 bool shouldEmitMovesModule;
3868 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3870 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3871 // Size and sign of stack growth.
3873 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3874 TargetFrameInfo::StackGrowsUp ?
3875 TD->getPointerSize() : -TD->getPointerSize();
3877 // Begin eh frame section.
3878 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3880 if (!TAI->doesRequireNonLocalEHFrameLabel())
3881 O << TAI->getEHGlobalPrefix();
3882 O << "EH_frame" << Index << ":\n";
3883 EmitLabel("section_eh_frame", Index);
3885 // Define base labels.
3886 EmitLabel("eh_frame_common", Index);
3888 // Define the eh frame length.
3889 EmitDifference("eh_frame_common_end", Index,
3890 "eh_frame_common_begin", Index, true);
3891 Asm->EOL("Length of Common Information Entry");
3894 EmitLabel("eh_frame_common_begin", Index);
3895 Asm->EmitInt32((int)0);
3896 Asm->EOL("CIE Identifier Tag");
3897 Asm->EmitInt8(DW_CIE_VERSION);
3898 Asm->EOL("CIE Version");
3900 // The personality presence indicates that language specific information
3901 // will show up in the eh frame.
3902 Asm->EmitString(Personality ? "zPLR" : "zR");
3903 Asm->EOL("CIE Augmentation");
3905 // Round out reader.
3906 Asm->EmitULEB128Bytes(1);
3907 Asm->EOL("CIE Code Alignment Factor");
3908 Asm->EmitSLEB128Bytes(stackGrowth);
3909 Asm->EOL("CIE Data Alignment Factor");
3910 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3911 Asm->EOL("CIE Return Address Column");
3913 // If there is a personality, we need to indicate the functions location.
3915 Asm->EmitULEB128Bytes(7);
3916 Asm->EOL("Augmentation Size");
3918 if (TAI->getNeedsIndirectEncoding()) {
3919 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3920 Asm->EOL("Personality (pcrel sdata4 indirect)");
3922 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3923 Asm->EOL("Personality (pcrel sdata4)");
3926 PrintRelDirective(true);
3927 O << TAI->getPersonalityPrefix();
3928 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3929 O << TAI->getPersonalitySuffix();
3930 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3931 O << "-" << TAI->getPCSymbol();
3932 Asm->EOL("Personality");
3934 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3935 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3937 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3938 Asm->EOL("FDE Encoding (pcrel sdata4)");
3940 Asm->EmitULEB128Bytes(1);
3941 Asm->EOL("Augmentation Size");
3943 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3944 Asm->EOL("FDE Encoding (pcrel sdata4)");
3947 // Indicate locations of general callee saved registers in frame.
3948 std::vector<MachineMove> Moves;
3949 RI->getInitialFrameState(Moves);
3950 EmitFrameMoves(NULL, 0, Moves, true);
3952 // On Darwin the linker honors the alignment of eh_frame, which means it
3953 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3954 // you get holes which confuse readers of eh_frame.
3955 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3957 EmitLabel("eh_frame_common_end", Index);
3962 /// EmitEHFrame - Emit function exception frame information.
3964 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3965 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3967 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3969 // Externally visible entry into the functions eh frame info.
3970 // If the corresponding function is static, this should not be
3971 // externally visible.
3972 if (linkage != Function::InternalLinkage) {
3973 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3974 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3977 // If corresponding function is weak definition, this should be too.
3978 if ((linkage == Function::WeakLinkage ||
3979 linkage == Function::LinkOnceLinkage) &&
3980 TAI->getWeakDefDirective())
3981 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3983 // If there are no calls then you can't unwind. This may mean we can
3984 // omit the EH Frame, but some environments do not handle weak absolute
3986 // If UnwindTablesMandatory is set we cannot do this optimization; the
3987 // unwind info is to be available for non-EH uses.
3988 if (!EHFrameInfo.hasCalls &&
3989 !UnwindTablesMandatory &&
3990 ((linkage != Function::WeakLinkage &&
3991 linkage != Function::LinkOnceLinkage) ||
3992 !TAI->getWeakDefDirective() ||
3993 TAI->getSupportsWeakOmittedEHFrame()))
3995 O << EHFrameInfo.FnName << " = 0\n";
3996 // This name has no connection to the function, so it might get
3997 // dead-stripped when the function is not, erroneously. Prohibit
3998 // dead-stripping unconditionally.
3999 if (const char *UsedDirective = TAI->getUsedDirective())
4000 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4002 O << EHFrameInfo.FnName << ":\n";
4005 EmitDifference("eh_frame_end", EHFrameInfo.Number,
4006 "eh_frame_begin", EHFrameInfo.Number, true);
4007 Asm->EOL("Length of Frame Information Entry");
4009 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
4011 if (TAI->doesRequireNonLocalEHFrameLabel()) {
4012 PrintRelDirective(true, true);
4013 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
4015 if (!TAI->isAbsoluteEHSectionOffsets())
4016 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
4018 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
4019 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
4023 Asm->EOL("FDE CIE offset");
4025 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
4026 Asm->EOL("FDE initial location");
4027 EmitDifference("eh_func_end", EHFrameInfo.Number,
4028 "eh_func_begin", EHFrameInfo.Number, true);
4029 Asm->EOL("FDE address range");
4031 // If there is a personality and landing pads then point to the language
4032 // specific data area in the exception table.
4033 if (EHFrameInfo.PersonalityIndex) {
4034 Asm->EmitULEB128Bytes(4);
4035 Asm->EOL("Augmentation size");
4037 if (EHFrameInfo.hasLandingPads)
4038 EmitReference("exception", EHFrameInfo.Number, true, true);
4040 Asm->EmitInt32((int)0);
4041 Asm->EOL("Language Specific Data Area");
4043 Asm->EmitULEB128Bytes(0);
4044 Asm->EOL("Augmentation size");
4047 // Indicate locations of function specific callee saved registers in
4049 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
4051 // On Darwin the linker honors the alignment of eh_frame, which means it
4052 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
4053 // you get holes which confuse readers of eh_frame.
4054 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
4056 EmitLabel("eh_frame_end", EHFrameInfo.Number);
4058 // If the function is marked used, this table should be also. We cannot
4059 // make the mark unconditional in this case, since retaining the table
4060 // also retains the function in this case, and there is code around
4061 // that depends on unused functions (calling undefined externals) being
4062 // dead-stripped to link correctly. Yes, there really is.
4063 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
4064 if (const char *UsedDirective = TAI->getUsedDirective())
4065 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4069 /// EmitExceptionTable - Emit landing pads and actions.
4071 /// The general organization of the table is complex, but the basic concepts
4072 /// are easy. First there is a header which describes the location and
4073 /// organization of the three components that follow.
4074 /// 1. The landing pad site information describes the range of code covered
4075 /// by the try. In our case it's an accumulation of the ranges covered
4076 /// by the invokes in the try. There is also a reference to the landing
4077 /// pad that handles the exception once processed. Finally an index into
4078 /// the actions table.
4079 /// 2. The action table, in our case, is composed of pairs of type ids
4080 /// and next action offset. Starting with the action index from the
4081 /// landing pad site, each type Id is checked for a match to the current
4082 /// exception. If it matches then the exception and type id are passed
4083 /// on to the landing pad. Otherwise the next action is looked up. This
4084 /// chain is terminated with a next action of zero. If no type id is
4085 /// found the the frame is unwound and handling continues.
4086 /// 3. Type id table contains references to all the C++ typeinfo for all
4087 /// catches in the function. This tables is reversed indexed base 1.
4089 /// SharedTypeIds - How many leading type ids two landing pads have in common.
4090 static unsigned SharedTypeIds(const LandingPadInfo *L,
4091 const LandingPadInfo *R) {
4092 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4093 unsigned LSize = LIds.size(), RSize = RIds.size();
4094 unsigned MinSize = LSize < RSize ? LSize : RSize;
4097 for (; Count != MinSize; ++Count)
4098 if (LIds[Count] != RIds[Count])
4104 /// PadLT - Order landing pads lexicographically by type id.
4105 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
4106 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4107 unsigned LSize = LIds.size(), RSize = RIds.size();
4108 unsigned MinSize = LSize < RSize ? LSize : RSize;
4110 for (unsigned i = 0; i != MinSize; ++i)
4111 if (LIds[i] != RIds[i])
4112 return LIds[i] < RIds[i];
4114 return LSize < RSize;
4118 static inline unsigned getEmptyKey() { return -1U; }
4119 static inline unsigned getTombstoneKey() { return -2U; }
4120 static unsigned getHashValue(const unsigned &Key) { return Key; }
4121 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
4122 static bool isPod() { return true; }
4125 /// ActionEntry - Structure describing an entry in the actions table.
4126 struct ActionEntry {
4127 int ValueForTypeID; // The value to write - may not be equal to the type id.
4129 struct ActionEntry *Previous;
4132 /// PadRange - Structure holding a try-range and the associated landing pad.
4134 // The index of the landing pad.
4136 // The index of the begin and end labels in the landing pad's label lists.
4137 unsigned RangeIndex;
4140 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
4142 /// CallSiteEntry - Structure describing an entry in the call-site table.
4143 struct CallSiteEntry {
4144 // The 'try-range' is BeginLabel .. EndLabel.
4145 unsigned BeginLabel; // zero indicates the start of the function.
4146 unsigned EndLabel; // zero indicates the end of the function.
4147 // The landing pad starts at PadLabel.
4148 unsigned PadLabel; // zero indicates that there is no landing pad.
4152 void EmitExceptionTable() {
4153 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
4154 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
4155 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
4156 if (PadInfos.empty()) return;
4158 // Sort the landing pads in order of their type ids. This is used to fold
4159 // duplicate actions.
4160 SmallVector<const LandingPadInfo *, 64> LandingPads;
4161 LandingPads.reserve(PadInfos.size());
4162 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
4163 LandingPads.push_back(&PadInfos[i]);
4164 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
4166 // Negative type ids index into FilterIds, positive type ids index into
4167 // TypeInfos. The value written for a positive type id is just the type
4168 // id itself. For a negative type id, however, the value written is the
4169 // (negative) byte offset of the corresponding FilterIds entry. The byte
4170 // offset is usually equal to the type id, because the FilterIds entries
4171 // are written using a variable width encoding which outputs one byte per
4172 // entry as long as the value written is not too large, but can differ.
4173 // This kind of complication does not occur for positive type ids because
4174 // type infos are output using a fixed width encoding.
4175 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
4176 SmallVector<int, 16> FilterOffsets;
4177 FilterOffsets.reserve(FilterIds.size());
4179 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
4180 E = FilterIds.end(); I != E; ++I) {
4181 FilterOffsets.push_back(Offset);
4182 Offset -= TargetAsmInfo::getULEB128Size(*I);
4185 // Compute the actions table and gather the first action index for each
4186 // landing pad site.
4187 SmallVector<ActionEntry, 32> Actions;
4188 SmallVector<unsigned, 64> FirstActions;
4189 FirstActions.reserve(LandingPads.size());
4191 int FirstAction = 0;
4192 unsigned SizeActions = 0;
4193 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4194 const LandingPadInfo *LP = LandingPads[i];
4195 const std::vector<int> &TypeIds = LP->TypeIds;
4196 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
4197 unsigned SizeSiteActions = 0;
4199 if (NumShared < TypeIds.size()) {
4200 unsigned SizeAction = 0;
4201 ActionEntry *PrevAction = 0;
4204 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
4205 assert(Actions.size());
4206 PrevAction = &Actions.back();
4207 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
4208 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4209 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
4211 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4212 SizeAction += -PrevAction->NextAction;
4213 PrevAction = PrevAction->Previous;
4217 // Compute the actions.
4218 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
4219 int TypeID = TypeIds[I];
4220 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
4221 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
4222 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
4224 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
4225 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
4226 SizeSiteActions += SizeAction;
4228 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4229 Actions.push_back(Action);
4231 PrevAction = &Actions.back();
4234 // Record the first action of the landing pad site.
4235 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4236 } // else identical - re-use previous FirstAction
4238 FirstActions.push_back(FirstAction);
4240 // Compute this sites contribution to size.
4241 SizeActions += SizeSiteActions;
4244 // Compute the call-site table. The entry for an invoke has a try-range
4245 // containing the call, a non-zero landing pad and an appropriate action.
4246 // The entry for an ordinary call has a try-range containing the call and
4247 // zero for the landing pad and the action. Calls marked 'nounwind' have
4248 // no entry and must not be contained in the try-range of any entry - they
4249 // form gaps in the table. Entries must be ordered by try-range address.
4250 SmallVector<CallSiteEntry, 64> CallSites;
4252 RangeMapType PadMap;
4253 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4254 // by try-range labels when lowered). Ordinary calls do not, so appropriate
4255 // try-ranges for them need be deduced.
4256 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4257 const LandingPadInfo *LandingPad = LandingPads[i];
4258 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4259 unsigned BeginLabel = LandingPad->BeginLabels[j];
4260 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4261 PadRange P = { i, j };
4262 PadMap[BeginLabel] = P;
4266 // The end label of the previous invoke or nounwind try-range.
4267 unsigned LastLabel = 0;
4269 // Whether there is a potentially throwing instruction (currently this means
4270 // an ordinary call) between the end of the previous try-range and now.
4271 bool SawPotentiallyThrowing = false;
4273 // Whether the last callsite entry was for an invoke.
4274 bool PreviousIsInvoke = false;
4276 // Visit all instructions in order of address.
4277 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4279 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4281 if (!MI->isLabel()) {
4282 SawPotentiallyThrowing |= MI->getDesc().isCall();
4286 unsigned BeginLabel = MI->getOperand(0).getImm();
4287 assert(BeginLabel && "Invalid label!");
4289 // End of the previous try-range?
4290 if (BeginLabel == LastLabel)
4291 SawPotentiallyThrowing = false;
4293 // Beginning of a new try-range?
4294 RangeMapType::iterator L = PadMap.find(BeginLabel);
4295 if (L == PadMap.end())
4296 // Nope, it was just some random label.
4299 PadRange P = L->second;
4300 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4302 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4303 "Inconsistent landing pad map!");
4305 // If some instruction between the previous try-range and this one may
4306 // throw, create a call-site entry with no landing pad for the region
4307 // between the try-ranges.
4308 if (SawPotentiallyThrowing) {
4309 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4310 CallSites.push_back(Site);
4311 PreviousIsInvoke = false;
4314 LastLabel = LandingPad->EndLabels[P.RangeIndex];
4315 assert(BeginLabel && LastLabel && "Invalid landing pad!");
4317 if (LandingPad->LandingPadLabel) {
4318 // This try-range is for an invoke.
4319 CallSiteEntry Site = {BeginLabel, LastLabel,
4320 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4322 // Try to merge with the previous call-site.
4323 if (PreviousIsInvoke) {
4324 CallSiteEntry &Prev = CallSites.back();
4325 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4326 // Extend the range of the previous entry.
4327 Prev.EndLabel = Site.EndLabel;
4332 // Otherwise, create a new call-site.
4333 CallSites.push_back(Site);
4334 PreviousIsInvoke = true;
4337 PreviousIsInvoke = false;
4341 // If some instruction between the previous try-range and the end of the
4342 // function may throw, create a call-site entry with no landing pad for the
4343 // region following the try-range.
4344 if (SawPotentiallyThrowing) {
4345 CallSiteEntry Site = {LastLabel, 0, 0, 0};
4346 CallSites.push_back(Site);
4352 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
4353 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4354 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4355 unsigned SizeSites = CallSites.size() * (SiteStartSize +
4358 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4359 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4362 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4363 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4365 unsigned TypeOffset = sizeof(int8_t) + // Call site format
4366 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4367 SizeSites + SizeActions + SizeTypes;
4369 unsigned TotalSize = sizeof(int8_t) + // LPStart format
4370 sizeof(int8_t) + // TType format
4371 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4374 unsigned SizeAlign = (4 - TotalSize) & 3;
4376 // Begin the exception table.
4377 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4378 Asm->EmitAlignment(2, 0, 0, false);
4379 O << "GCC_except_table" << SubprogramCount << ":\n";
4380 for (unsigned i = 0; i != SizeAlign; ++i) {
4382 Asm->EOL("Padding");
4384 EmitLabel("exception", SubprogramCount);
4387 Asm->EmitInt8(DW_EH_PE_omit);
4388 Asm->EOL("LPStart format (DW_EH_PE_omit)");
4389 Asm->EmitInt8(DW_EH_PE_absptr);
4390 Asm->EOL("TType format (DW_EH_PE_absptr)");
4391 Asm->EmitULEB128Bytes(TypeOffset);
4392 Asm->EOL("TType base offset");
4393 Asm->EmitInt8(DW_EH_PE_udata4);
4394 Asm->EOL("Call site format (DW_EH_PE_udata4)");
4395 Asm->EmitULEB128Bytes(SizeSites);
4396 Asm->EOL("Call-site table length");
4398 // Emit the landing pad site information.
4399 for (unsigned i = 0; i < CallSites.size(); ++i) {
4400 CallSiteEntry &S = CallSites[i];
4401 const char *BeginTag;
4402 unsigned BeginNumber;
4404 if (!S.BeginLabel) {
4405 BeginTag = "eh_func_begin";
4406 BeginNumber = SubprogramCount;
4409 BeginNumber = S.BeginLabel;
4412 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4414 Asm->EOL("Region start");
4417 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4420 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4422 Asm->EOL("Region length");
4427 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4429 Asm->EOL("Landing pad");
4431 Asm->EmitULEB128Bytes(S.Action);
4435 // Emit the actions.
4436 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4437 ActionEntry &Action = Actions[I];
4439 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4440 Asm->EOL("TypeInfo index");
4441 Asm->EmitSLEB128Bytes(Action.NextAction);
4442 Asm->EOL("Next action");
4445 // Emit the type ids.
4446 for (unsigned M = TypeInfos.size(); M; --M) {
4447 GlobalVariable *GV = TypeInfos[M - 1];
4449 PrintRelDirective();
4452 O << Asm->getGlobalLinkName(GV);
4456 Asm->EOL("TypeInfo");
4459 // Emit the filter typeids.
4460 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4461 unsigned TypeID = FilterIds[j];
4462 Asm->EmitULEB128Bytes(TypeID);
4463 Asm->EOL("Filter TypeInfo index");
4466 Asm->EmitAlignment(2, 0, 0, false);
4470 //===--------------------------------------------------------------------===//
4471 // Main entry points.
4473 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4474 : Dwarf(OS, A, T, "eh")
4475 , shouldEmitTable(false)
4476 , shouldEmitMoves(false)
4477 , shouldEmitTableModule(false)
4478 , shouldEmitMovesModule(false)
4481 virtual ~DwarfException() {}
4483 /// SetModuleInfo - Set machine module information when it's known that pass
4484 /// manager has created it. Set by the target AsmPrinter.
4485 void SetModuleInfo(MachineModuleInfo *mmi) {
4489 /// BeginModule - Emit all exception information that should come prior to the
4491 void BeginModule(Module *M) {
4495 /// EndModule - Emit all exception information that should come after the
4498 if (shouldEmitMovesModule || shouldEmitTableModule) {
4499 const std::vector<Function *> Personalities = MMI->getPersonalities();
4500 for (unsigned i =0; i < Personalities.size(); ++i)
4501 EmitCommonEHFrame(Personalities[i], i);
4503 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4504 E = EHFrames.end(); I != E; ++I)
4509 /// BeginFunction - Gather pre-function exception information. Assumes being
4510 /// emitted immediately after the function entry point.
4511 void BeginFunction(MachineFunction *MF) {
4513 shouldEmitTable = shouldEmitMoves = false;
4514 if (MMI && TAI->doesSupportExceptionHandling()) {
4516 // Map all labels and get rid of any dead landing pads.
4517 MMI->TidyLandingPads();
4518 // If any landing pads survive, we need an EH table.
4519 if (MMI->getLandingPads().size())
4520 shouldEmitTable = true;
4522 // See if we need frame move info.
4523 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4524 shouldEmitMoves = true;
4526 if (shouldEmitMoves || shouldEmitTable)
4527 // Assumes in correct section after the entry point.
4528 EmitLabel("eh_func_begin", ++SubprogramCount);
4530 shouldEmitTableModule |= shouldEmitTable;
4531 shouldEmitMovesModule |= shouldEmitMoves;
4534 /// EndFunction - Gather and emit post-function exception information.
4536 void EndFunction() {
4537 if (shouldEmitMoves || shouldEmitTable) {
4538 EmitLabel("eh_func_end", SubprogramCount);
4539 EmitExceptionTable();
4541 // Save EH frame information
4543 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4545 MMI->getPersonalityIndex(),
4546 MF->getFrameInfo()->hasCalls(),
4547 !MMI->getLandingPads().empty(),
4548 MMI->getFrameMoves(),
4549 MF->getFunction()));
4554 } // End of namespace llvm
4556 //===----------------------------------------------------------------------===//
4558 /// Emit - Print the abbreviation using the specified Dwarf writer.
4560 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4561 // Emit its Dwarf tag type.
4562 DD.getAsm()->EmitULEB128Bytes(Tag);
4563 DD.getAsm()->EOL(TagString(Tag));
4565 // Emit whether it has children DIEs.
4566 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4567 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4569 // For each attribute description.
4570 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4571 const DIEAbbrevData &AttrData = Data[i];
4573 // Emit attribute type.
4574 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4575 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4578 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4579 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4582 // Mark end of abbreviation.
4583 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4584 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4588 void DIEAbbrev::print(std::ostream &O) {
4589 O << "Abbreviation @"
4590 << std::hex << (intptr_t)this << std::dec
4594 << ChildrenString(ChildrenFlag)
4597 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4599 << AttributeString(Data[i].getAttribute())
4601 << FormEncodingString(Data[i].getForm())
4605 void DIEAbbrev::dump() { print(cerr); }
4608 //===----------------------------------------------------------------------===//
4611 void DIEValue::dump() {
4616 //===----------------------------------------------------------------------===//
4618 /// EmitValue - Emit integer of appropriate size.
4620 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4622 case DW_FORM_flag: // Fall thru
4623 case DW_FORM_ref1: // Fall thru
4624 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4625 case DW_FORM_ref2: // Fall thru
4626 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4627 case DW_FORM_ref4: // Fall thru
4628 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4629 case DW_FORM_ref8: // Fall thru
4630 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4631 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4632 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4633 default: assert(0 && "DIE Value form not supported yet"); break;
4637 /// SizeOf - Determine size of integer value in bytes.
4639 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4641 case DW_FORM_flag: // Fall thru
4642 case DW_FORM_ref1: // Fall thru
4643 case DW_FORM_data1: return sizeof(int8_t);
4644 case DW_FORM_ref2: // Fall thru
4645 case DW_FORM_data2: return sizeof(int16_t);
4646 case DW_FORM_ref4: // Fall thru
4647 case DW_FORM_data4: return sizeof(int32_t);
4648 case DW_FORM_ref8: // Fall thru
4649 case DW_FORM_data8: return sizeof(int64_t);
4650 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4651 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4652 default: assert(0 && "DIE Value form not supported yet"); break;
4657 //===----------------------------------------------------------------------===//
4659 /// EmitValue - Emit string value.
4661 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4662 DD.getAsm()->EmitString(String);
4665 //===----------------------------------------------------------------------===//
4667 /// EmitValue - Emit label value.
4669 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4670 bool IsSmall = Form == DW_FORM_data4;
4671 DD.EmitReference(Label, false, IsSmall);
4674 /// SizeOf - Determine size of label value in bytes.
4676 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4677 if (Form == DW_FORM_data4) return 4;
4678 return DD.getTargetData()->getPointerSize();
4681 //===----------------------------------------------------------------------===//
4683 /// EmitValue - Emit label value.
4685 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4686 bool IsSmall = Form == DW_FORM_data4;
4687 DD.EmitReference(Label, false, IsSmall);
4690 /// SizeOf - Determine size of label value in bytes.
4692 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4693 if (Form == DW_FORM_data4) return 4;
4694 return DD.getTargetData()->getPointerSize();
4697 //===----------------------------------------------------------------------===//
4699 /// EmitValue - Emit delta value.
4701 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4702 bool IsSmall = Form == DW_FORM_data4;
4703 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4704 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4707 /// SizeOf - Determine size of delta value in bytes.
4709 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4710 if (Form == DW_FORM_data4) return 4;
4711 return DD.getTargetData()->getPointerSize();
4714 //===----------------------------------------------------------------------===//
4716 /// EmitValue - Emit delta value.
4718 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4719 bool IsSmall = Form == DW_FORM_data4;
4720 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4723 /// SizeOf - Determine size of delta value in bytes.
4725 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4726 if (Form == DW_FORM_data4) return 4;
4727 return DD.getTargetData()->getPointerSize();
4730 //===----------------------------------------------------------------------===//
4732 /// EmitValue - Emit debug information entry offset.
4734 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4735 DD.getAsm()->EmitInt32(Entry->getOffset());
4738 //===----------------------------------------------------------------------===//
4740 /// ComputeSize - calculate the size of the block.
4742 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4744 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4746 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4747 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4753 /// EmitValue - Emit block data.
4755 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4757 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4758 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4759 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4760 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4761 default: assert(0 && "Improper form for block"); break;
4764 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4766 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4768 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4772 /// SizeOf - Determine size of block data in bytes.
4774 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4776 case DW_FORM_block1: return Size + sizeof(int8_t);
4777 case DW_FORM_block2: return Size + sizeof(int16_t);
4778 case DW_FORM_block4: return Size + sizeof(int32_t);
4779 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4780 default: assert(0 && "Improper form for block"); break;
4785 //===----------------------------------------------------------------------===//
4786 /// DIE Implementation
4789 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4793 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4795 void DIE::AddSiblingOffset() {
4796 DIEInteger *DI = new DIEInteger(0);
4797 Values.insert(Values.begin(), DI);
4798 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4801 /// Profile - Used to gather unique data for the value folding set.
4803 void DIE::Profile(FoldingSetNodeID &ID) {
4806 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4807 ID.AddPointer(Children[i]);
4809 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4810 ID.AddPointer(Values[j]);
4814 void DIE::print(std::ostream &O, unsigned IncIndent) {
4815 static unsigned IndentCount = 0;
4816 IndentCount += IncIndent;
4817 const std::string Indent(IndentCount, ' ');
4818 bool isBlock = Abbrev.getTag() == 0;
4823 << "0x" << std::hex << (intptr_t)this << std::dec
4824 << ", Offset: " << Offset
4825 << ", Size: " << Size
4829 << TagString(Abbrev.getTag())
4831 << ChildrenString(Abbrev.getChildrenFlag());
4833 O << "Size: " << Size;
4837 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4840 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4844 O << AttributeString(Data[i].getAttribute());
4846 O << "Blk[" << i << "]";
4849 << FormEncodingString(Data[i].getForm())
4851 Values[i]->print(O);
4856 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4857 Children[j]->print(O, 4);
4860 if (!isBlock) O << "\n";
4861 IndentCount -= IncIndent;
4869 //===----------------------------------------------------------------------===//
4870 /// DwarfWriter Implementation
4873 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4876 DwarfWriter::~DwarfWriter() {
4881 /// BeginModule - Emit all Dwarf sections that should come prior to the
4883 void DwarfWriter::BeginModule(Module *M,
4884 MachineModuleInfo *MMI,
4885 raw_ostream &OS, AsmPrinter *A,
4886 const TargetAsmInfo *T) {
4887 DE = new DwarfException(OS, A, T);
4888 DD = new DwarfDebug(OS, A, T);
4891 DD->SetModuleInfo(MMI);
4892 DE->SetModuleInfo(MMI);
4895 /// EndModule - Emit all Dwarf sections that should come after the content.
4897 void DwarfWriter::EndModule() {
4902 /// BeginFunction - Gather pre-function debug information. Assumes being
4903 /// emitted immediately after the function entry point.
4904 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4905 DE->BeginFunction(MF);
4906 DD->BeginFunction(MF);
4909 /// EndFunction - Gather and emit post-function debug information.
4911 void DwarfWriter::EndFunction(MachineFunction *MF) {
4912 DD->EndFunction(MF);
4915 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4916 // Clear function debug information.