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 *, 8> Scopes; // Scopes defined in scope.
1246 SmallVector<DbgVariable *, 32> 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 *, 8> &getScopes() { return Scopes; }
1260 SmallVector<DbgVariable *, 32> &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 // DbgLabelIDList - One entry per assigned label. Normally the entry is equal to
1345 // the list index(+1). If the entry is zero then the label has been deleted.
1346 // Any other value indicates the label has been deleted by is mapped to
1348 SmallVector<unsigned, 32> DbgLabelIDList;
1350 /// NextLabelID - Return the next unique label id.
1352 unsigned NextLabelID() {
1353 unsigned ID = (unsigned)DbgLabelIDList.size() + 1;
1354 DbgLabelIDList.push_back(ID);
1358 /// RemapLabel - Indicate that a label has been merged into another.
1360 void RemapLabel(unsigned OldLabelID, unsigned NewLabelID) {
1361 assert(0 < OldLabelID && OldLabelID <= DbgLabelIDList.size() &&
1362 "Old label ID out of range.");
1363 assert(NewLabelID <= DbgLabelIDList.size() &&
1364 "New label ID out of range.");
1365 DbgLabelIDList[OldLabelID - 1] = NewLabelID;
1368 /// MappedLabel - Find out the label's final ID. Zero indicates deletion.
1369 /// ID != Mapped ID indicates that the label was folded into another label.
1370 unsigned MappedLabel(unsigned LabelID) const {
1371 assert(LabelID <= DbgLabelIDList.size() && "Debug label ID out of range.");
1372 return LabelID ? DbgLabelIDList[LabelID - 1] : 0;
1375 struct FunctionDebugFrameInfo {
1377 std::vector<MachineMove> Moves;
1379 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1380 Number(Num), Moves(M) { }
1383 std::vector<FunctionDebugFrameInfo> DebugFrames;
1387 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1389 bool ShouldEmitDwarf() const { return shouldEmit; }
1391 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1393 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1394 // Profile the node so that we can make it unique.
1395 FoldingSetNodeID ID;
1398 // Check the set for priors.
1399 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1401 // If it's newly added.
1402 if (InSet == &Abbrev) {
1403 // Add to abbreviation list.
1404 Abbreviations.push_back(&Abbrev);
1405 // Assign the vector position + 1 as its number.
1406 Abbrev.setNumber(Abbreviations.size());
1408 // Assign existing abbreviation number.
1409 Abbrev.setNumber(InSet->getNumber());
1413 /// NewString - Add a string to the constant pool and returns a label.
1415 DWLabel NewString(const std::string &String) {
1416 unsigned StringID = StringPool.insert(String);
1417 return DWLabel("string", StringID);
1420 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1422 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1426 FoldingSetNodeID ID;
1427 DIEntry::Profile(ID, Entry);
1429 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1431 if (Value) return Value;
1433 Value = new DIEntry(Entry);
1434 ValuesSet.InsertNode(Value, Where);
1436 Value = new DIEntry(Entry);
1439 Values.push_back(Value);
1443 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1445 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1446 Value->Entry = Entry;
1447 // Add to values set if not already there. If it is, we merely have a
1448 // duplicate in the values list (no harm.)
1449 ValuesSet.GetOrInsertNode(Value);
1452 /// AddUInt - Add an unsigned integer attribute data and value.
1454 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1455 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1457 FoldingSetNodeID ID;
1458 DIEInteger::Profile(ID, Integer);
1460 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1462 Value = new DIEInteger(Integer);
1463 ValuesSet.InsertNode(Value, Where);
1464 Values.push_back(Value);
1467 Die->AddValue(Attribute, Form, Value);
1470 /// AddSInt - Add an signed integer attribute data and value.
1472 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1473 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1475 FoldingSetNodeID ID;
1476 DIEInteger::Profile(ID, (uint64_t)Integer);
1478 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1480 Value = new DIEInteger(Integer);
1481 ValuesSet.InsertNode(Value, Where);
1482 Values.push_back(Value);
1485 Die->AddValue(Attribute, Form, Value);
1488 /// AddString - Add a std::string attribute data and value.
1490 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1491 const std::string &String) {
1492 FoldingSetNodeID ID;
1493 DIEString::Profile(ID, String);
1495 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1497 Value = new DIEString(String);
1498 ValuesSet.InsertNode(Value, Where);
1499 Values.push_back(Value);
1502 Die->AddValue(Attribute, Form, Value);
1505 /// AddLabel - Add a Dwarf label attribute data and value.
1507 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1508 const DWLabel &Label) {
1509 FoldingSetNodeID ID;
1510 DIEDwarfLabel::Profile(ID, Label);
1512 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1514 Value = new DIEDwarfLabel(Label);
1515 ValuesSet.InsertNode(Value, Where);
1516 Values.push_back(Value);
1519 Die->AddValue(Attribute, Form, Value);
1522 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1524 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1525 const std::string &Label) {
1526 FoldingSetNodeID ID;
1527 DIEObjectLabel::Profile(ID, Label);
1529 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1531 Value = new DIEObjectLabel(Label);
1532 ValuesSet.InsertNode(Value, Where);
1533 Values.push_back(Value);
1536 Die->AddValue(Attribute, Form, Value);
1539 /// AddSectionOffset - Add a section offset label attribute data and value.
1541 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1542 const DWLabel &Label, const DWLabel &Section,
1543 bool isEH = false, bool useSet = true) {
1544 FoldingSetNodeID ID;
1545 DIESectionOffset::Profile(ID, Label, Section);
1547 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1549 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1550 ValuesSet.InsertNode(Value, Where);
1551 Values.push_back(Value);
1554 Die->AddValue(Attribute, Form, Value);
1557 /// AddDelta - Add a label delta attribute data and value.
1559 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1560 const DWLabel &Hi, const DWLabel &Lo) {
1561 FoldingSetNodeID ID;
1562 DIEDelta::Profile(ID, Hi, Lo);
1564 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1566 Value = new DIEDelta(Hi, Lo);
1567 ValuesSet.InsertNode(Value, Where);
1568 Values.push_back(Value);
1571 Die->AddValue(Attribute, Form, Value);
1574 /// AddDIEntry - Add a DIE attribute data and value.
1576 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1577 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1580 /// AddBlock - Add block data.
1582 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1583 Block->ComputeSize(*this);
1584 FoldingSetNodeID ID;
1587 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1590 ValuesSet.InsertNode(Value, Where);
1591 Values.push_back(Value);
1593 // Already exists, reuse the previous one.
1595 Block = cast<DIEBlock>(Value);
1598 Die->AddValue(Attribute, Block->BestForm(), Value);
1603 /// AddSourceLine - Add location information to specified debug information
1605 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1607 CompileUnit *FileUnit = FindCompileUnit(File);
1608 unsigned FileID = FileUnit->getID();
1609 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1610 AddUInt(Die, DW_AT_decl_line, 0, Line);
1614 /// AddSourceLine - Add location information to specified debug information
1616 void AddSourceLine(DIE *Die, DIVariable *V) {
1617 unsigned FileID = 0;
1618 unsigned Line = V->getLineNumber();
1619 if (V->getVersion() < DIDescriptor::Version7) {
1620 // Version6 or earlier. Use compile unit info to get file id.
1621 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1622 FileID = Unit->getID();
1624 // Version7 or newer, use filename and directory info from DIVariable
1626 unsigned DID = Directories.idFor(V->getDirectory());
1627 FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1629 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1630 AddUInt(Die, DW_AT_decl_line, 0, Line);
1633 /// AddSourceLine - Add location information to specified debug information
1635 void AddSourceLine(DIE *Die, DIGlobal *G) {
1636 unsigned FileID = 0;
1637 unsigned Line = G->getLineNumber();
1638 if (G->getVersion() < DIDescriptor::Version7) {
1639 // Version6 or earlier. Use compile unit info to get file id.
1640 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1641 FileID = Unit->getID();
1643 // Version7 or newer, use filename and directory info from DIGlobal
1645 unsigned DID = Directories.idFor(G->getDirectory());
1646 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1648 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1649 AddUInt(Die, DW_AT_decl_line, 0, Line);
1652 void AddSourceLine(DIE *Die, DIType *G) {
1653 unsigned FileID = 0;
1654 unsigned Line = G->getLineNumber();
1655 if (G->getVersion() < DIDescriptor::Version7) {
1656 // Version6 or earlier. Use compile unit info to get file id.
1657 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1658 FileID = Unit->getID();
1660 // Version7 or newer, use filename and directory info from DIGlobal
1662 unsigned DID = Directories.idFor(G->getDirectory());
1663 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1665 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1666 AddUInt(Die, DW_AT_decl_line, 0, Line);
1669 /// AddAddress - Add an address attribute to a die based on the location
1671 void AddAddress(DIE *Die, unsigned Attribute,
1672 const MachineLocation &Location) {
1673 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1674 DIEBlock *Block = new DIEBlock();
1676 if (Location.isReg()) {
1678 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1680 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1681 AddUInt(Block, 0, DW_FORM_udata, Reg);
1685 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1687 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1688 AddUInt(Block, 0, DW_FORM_udata, Reg);
1690 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1693 AddBlock(Die, Attribute, 0, Block);
1696 /// AddBasicType - Add a new basic type attribute to the specified entity.
1698 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1699 const std::string &Name,
1700 unsigned Encoding, unsigned Size) {
1702 DIE Buffer(DW_TAG_base_type);
1703 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1704 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1705 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1706 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1707 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1710 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1712 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1713 DIE Buffer(DW_TAG_pointer_type);
1714 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1715 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1716 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1717 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1720 /// AddType - Add a new type attribute to the specified entity.
1722 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1724 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1726 // Check for pre-existence.
1727 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1729 // If it exists then use the existing value.
1731 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1735 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1736 // FIXME - Not sure why programs and variables are coming through here.
1737 // Short cut for handling subprogram types (not really a TyDesc.)
1738 AddPointerType(Entity, Unit, SubprogramTy->getName());
1739 } else if (GlobalVariableDesc *GlobalTy =
1740 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1741 // FIXME - Not sure why programs and variables are coming through here.
1742 // Short cut for handling global variable types (not really a TyDesc.)
1743 AddPointerType(Entity, Unit, GlobalTy->getName());
1746 Slot = NewDIEntry();
1749 DIE Buffer(DW_TAG_base_type);
1750 ConstructType(Buffer, TyDesc, Unit);
1752 // Add debug information entry to entity and unit.
1753 DIE *Die = Unit->AddDie(Buffer);
1754 SetDIEntry(Slot, Die);
1755 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1760 /// AddType - Add a new type attribute to the specified entity.
1761 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1763 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1767 // Check for pre-existence.
1768 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1769 // If it exists then use the existing value.
1771 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1776 Slot = NewDIEntry();
1779 DIE Buffer(DW_TAG_base_type);
1780 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1781 ConstructTypeDIE(DW_Unit, Buffer, BT);
1782 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1783 ConstructTypeDIE(DW_Unit, Buffer, DT);
1784 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1785 ConstructTypeDIE(DW_Unit, Buffer, CT);
1787 // Add debug information entry to entity and unit.
1788 DIE *Die = DW_Unit->AddDie(Buffer);
1789 SetDIEntry(Slot, Die);
1790 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1793 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1794 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1797 // Get core information.
1798 const std::string &Name = BTy->getName();
1799 Buffer.setTag(DW_TAG_base_type);
1800 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1801 // Add name if not anonymous or intermediate type.
1803 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1804 uint64_t Size = BTy->getSizeInBits() >> 3;
1805 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1808 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1809 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1810 DIDerivedType *DTy) {
1812 // Get core information.
1813 const std::string &Name = DTy->getName();
1814 uint64_t Size = DTy->getSizeInBits() >> 3;
1815 unsigned Tag = DTy->getTag();
1816 // FIXME - Workaround for templates.
1817 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1820 // Map to main type, void will not have a type.
1821 DIType FromTy = DTy->getTypeDerivedFrom();
1822 AddType(DW_Unit, &Buffer, FromTy);
1824 // Add name if not anonymous or intermediate type.
1825 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1827 // Add size if non-zero (derived types might be zero-sized.)
1829 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1831 // Add source line info if available and TyDesc is not a forward
1833 // FIXME - Enable this. if (!DTy->isForwardDecl())
1834 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1837 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1838 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1839 DICompositeType *CTy) {
1841 // Get core information.
1842 const std::string &Name = CTy->getName();
1843 uint64_t Size = CTy->getSizeInBits() >> 3;
1844 unsigned Tag = CTy->getTag();
1846 case DW_TAG_vector_type:
1847 case DW_TAG_array_type:
1848 ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1850 //FIXME - Enable this.
1851 // case DW_TAG_enumeration_type:
1852 // DIArray Elements = CTy->getTypeArray();
1853 // // Add enumerators to enumeration type.
1854 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1855 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1857 case DW_TAG_subroutine_type:
1859 // Add prototype flag.
1860 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1861 DIArray Elements = CTy->getTypeArray();
1863 DIDescriptor RTy = Elements.getElement(0);
1864 if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1865 AddType(DW_Unit, &Buffer, *BT);
1866 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1867 AddType(DW_Unit, &Buffer, *DT);
1868 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1869 AddType(DW_Unit, &Buffer, *CT);
1871 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1873 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1874 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1875 DIDescriptor Ty = Elements.getElement(i);
1876 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1877 AddType(DW_Unit, &Buffer, *BT);
1878 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1879 AddType(DW_Unit, &Buffer, *DT);
1880 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1881 AddType(DW_Unit, &Buffer, *CT);
1882 Buffer.AddChild(Arg);
1886 case DW_TAG_structure_type:
1887 case DW_TAG_union_type:
1889 // Add elements to structure type.
1890 DIArray Elements = CTy->getTypeArray();
1891 // Add elements to structure type.
1892 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1893 DIDescriptor Element = Elements.getElement(i);
1894 if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1895 ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1896 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1897 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1898 else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1899 ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1907 // Add name if not anonymous or intermediate type.
1908 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1910 // Add size if non-zero (derived types might be zero-sized.)
1912 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1914 // Add zero size even if it is not a forward declaration.
1915 // FIXME - Enable this.
1916 // if (!CTy->isDefinition())
1917 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1919 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1922 // Add source line info if available and TyDesc is not a forward
1924 // FIXME - Enable this.
1925 // if (CTy->isForwardDecl())
1926 // AddSourceLine(&Buffer, *CTy);
1929 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1930 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1931 int64_t L = SR->getLo();
1932 int64_t H = SR->getHi();
1933 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1935 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1937 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1938 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1940 Buffer.AddChild(DW_Subrange);
1943 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1944 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1945 DICompositeType *CTy) {
1946 Buffer.setTag(DW_TAG_array_type);
1947 if (CTy->getTag() == DW_TAG_vector_type)
1948 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1950 DIArray Elements = CTy->getTypeArray();
1951 // FIXME - Enable this.
1952 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1954 // Construct an anonymous type for index type.
1955 DIE IdxBuffer(DW_TAG_base_type);
1956 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1957 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1958 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1960 // Add subranges to array type.
1961 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1962 DIDescriptor Element = Elements.getElement(i);
1963 if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1964 ConstructSubrangeDIE(Buffer, SR, IndexTy);
1968 /// ConstructEnumTypeDIE - Construct enum type DIE from
1970 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1971 DIE &Buffer, DIEnumerator *ETy) {
1973 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1974 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1975 int64_t Value = ETy->getEnumValue();
1976 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1977 Buffer.AddChild(Enumerator);
1980 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1981 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1982 DIE &Buffer, DIGlobalVariable *V) {
1984 DIE *VariableDie = new DIE(DW_TAG_variable);
1985 const std::string &LinkageName = V->getLinkageName();
1986 if (!LinkageName.empty())
1987 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1989 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1990 AddType(DW_Unit, VariableDie, V->getType());
1991 if (!V->isLocalToUnit())
1992 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1993 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1994 Buffer.AddChild(VariableDie);
1997 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1998 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1999 DIE &Buffer, DISubprogram *SP,
2000 bool IsConstructor = false) {
2001 DIE *Method = new DIE(DW_TAG_subprogram);
2002 AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
2003 const std::string &LinkageName = SP->getLinkageName();
2004 if (!LinkageName.empty())
2005 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
2006 // FIXME - Enable this. AddSourceLine(Method, SP);
2008 DICompositeType MTy = SP->getType();
2009 DIArray Args = MTy.getTypeArray();
2012 if (!IsConstructor) {
2013 DIDescriptor Ty = Args.getElement(0);
2014 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
2015 AddType(DW_Unit, Method, *BT);
2016 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
2017 AddType(DW_Unit, Method, *DT);
2018 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2019 AddType(DW_Unit, Method, *CT);
2023 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
2024 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2025 DIDescriptor Ty = Args.getElement(i);
2026 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
2027 AddType(DW_Unit, Method, *BT);
2028 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
2029 AddType(DW_Unit, Method, *DT);
2030 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2031 AddType(DW_Unit, Method, *CT);
2032 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
2033 Method->AddChild(Arg);
2036 if (!SP->isLocalToUnit())
2037 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2038 Buffer.AddChild(Method);
2041 /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
2042 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
2043 DIDerivedType *DTy) {
2044 unsigned Tag = DTy->getTag();
2045 DIE *MemberDie = new DIE(Tag);
2046 if (!DTy->getName().empty())
2047 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
2048 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
2050 DIType FromTy = DTy->getTypeDerivedFrom();
2051 AddType(DW_Unit, MemberDie, FromTy);
2053 uint64_t Size = DTy->getSizeInBits();
2054 uint64_t Offset = DTy->getOffsetInBits();
2056 // FIXME Handle bitfields
2059 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
2060 // Add computation for offset.
2061 DIEBlock *Block = new DIEBlock();
2062 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2063 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
2064 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
2066 // FIXME Handle DW_AT_accessibility.
2068 Buffer.AddChild(MemberDie);
2071 /// ConstructType - Adds all the required attributes to the type.
2073 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
2074 // Get core information.
2075 const std::string &Name = TyDesc->getName();
2076 uint64_t Size = TyDesc->getSize() >> 3;
2078 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
2079 // Fundamental types like int, float, bool
2080 Buffer.setTag(DW_TAG_base_type);
2081 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
2082 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
2084 unsigned Tag = DerivedTy->getTag();
2085 // FIXME - Workaround for templates.
2086 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
2087 // Pointers, typedefs et al.
2089 // Map to main type, void will not have a type.
2090 if (TypeDesc *FromTy = DerivedTy->getFromType())
2091 AddType(&Buffer, FromTy, Unit);
2092 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
2094 unsigned Tag = CompTy->getTag();
2096 // Set tag accordingly.
2097 if (Tag == DW_TAG_vector_type)
2098 Buffer.setTag(DW_TAG_array_type);
2102 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
2105 case DW_TAG_vector_type:
2106 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
2108 case DW_TAG_array_type: {
2109 // Add element type.
2110 if (TypeDesc *FromTy = CompTy->getFromType())
2111 AddType(&Buffer, FromTy, Unit);
2113 // Don't emit size attribute.
2116 // Construct an anonymous type for index type.
2117 DIE Buffer(DW_TAG_base_type);
2118 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
2119 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
2120 DIE *IndexTy = Unit->AddDie(Buffer);
2122 // Add subranges to array type.
2123 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2124 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
2125 int64_t Lo = SRD->getLo();
2126 int64_t Hi = SRD->getHi();
2127 DIE *Subrange = new DIE(DW_TAG_subrange_type);
2129 // If a range is available.
2131 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
2132 // Only add low if non-zero.
2133 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
2134 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
2137 Buffer.AddChild(Subrange);
2141 case DW_TAG_structure_type:
2142 case DW_TAG_union_type: {
2143 // Add elements to structure type.
2144 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2145 DebugInfoDesc *Element = Elements[i];
2147 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
2148 // Add field or base class.
2149 unsigned Tag = MemberDesc->getTag();
2151 // Extract the basic information.
2152 const std::string &Name = MemberDesc->getName();
2153 uint64_t Size = MemberDesc->getSize();
2154 uint64_t Align = MemberDesc->getAlign();
2155 uint64_t Offset = MemberDesc->getOffset();
2157 // Construct member debug information entry.
2158 DIE *Member = new DIE(Tag);
2160 // Add name if not "".
2162 AddString(Member, DW_AT_name, DW_FORM_string, Name);
2164 // Add location if available.
2165 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
2167 // Most of the time the field info is the same as the members.
2168 uint64_t FieldSize = Size;
2169 uint64_t FieldAlign = Align;
2170 uint64_t FieldOffset = Offset;
2172 // Set the member type.
2173 TypeDesc *FromTy = MemberDesc->getFromType();
2174 AddType(Member, FromTy, Unit);
2176 // Walk up typedefs until a real size is found.
2178 if (FromTy->getTag() != DW_TAG_typedef) {
2179 FieldSize = FromTy->getSize();
2180 FieldAlign = FromTy->getAlign();
2184 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
2187 // Unless we have a bit field.
2188 if (Tag == DW_TAG_member && FieldSize != Size) {
2189 // Construct the alignment mask.
2190 uint64_t AlignMask = ~(FieldAlign - 1);
2191 // Determine the high bit + 1 of the declared size.
2192 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
2193 // Work backwards to determine the base offset of the field.
2194 FieldOffset = HiMark - FieldSize;
2195 // Now normalize offset to the field.
2196 Offset -= FieldOffset;
2198 // Maybe we need to work from the other end.
2199 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
2201 // Add size and offset.
2202 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
2203 AddUInt(Member, DW_AT_bit_size, 0, Size);
2204 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
2207 // Add computation for offset.
2208 DIEBlock *Block = new DIEBlock();
2209 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2210 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
2211 AddBlock(Member, DW_AT_data_member_location, 0, Block);
2213 // Add accessibility (public default unless is base class.
2214 if (MemberDesc->isProtected()) {
2215 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
2216 } else if (MemberDesc->isPrivate()) {
2217 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
2218 } else if (Tag == DW_TAG_inheritance) {
2219 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
2222 Buffer.AddChild(Member);
2223 } else if (GlobalVariableDesc *StaticDesc =
2224 dyn_cast<GlobalVariableDesc>(Element)) {
2225 // Add static member.
2227 // Construct member debug information entry.
2228 DIE *Static = new DIE(DW_TAG_variable);
2230 // Add name and mangled name.
2231 const std::string &Name = StaticDesc->getName();
2232 const std::string &LinkageName = StaticDesc->getLinkageName();
2233 AddString(Static, DW_AT_name, DW_FORM_string, Name);
2234 if (!LinkageName.empty()) {
2235 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
2240 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
2243 if (TypeDesc *StaticTy = StaticDesc->getType())
2244 AddType(Static, StaticTy, Unit);
2247 if (!StaticDesc->isStatic())
2248 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
2249 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2251 Buffer.AddChild(Static);
2252 } else if (SubprogramDesc *MethodDesc =
2253 dyn_cast<SubprogramDesc>(Element)) {
2254 // Add member function.
2256 // Construct member debug information entry.
2257 DIE *Method = new DIE(DW_TAG_subprogram);
2259 // Add name and mangled name.
2260 const std::string &Name = MethodDesc->getName();
2261 const std::string &LinkageName = MethodDesc->getLinkageName();
2263 AddString(Method, DW_AT_name, DW_FORM_string, Name);
2264 bool IsCTor = TyDesc->getName() == Name;
2266 if (!LinkageName.empty()) {
2267 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2272 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2275 if (CompositeTypeDesc *MethodTy =
2276 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2277 // Get argument information.
2278 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2283 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2287 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2288 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2289 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2290 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2291 Method->AddChild(Arg);
2296 if (!MethodDesc->isStatic())
2297 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2298 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2300 Buffer.AddChild(Method);
2305 case DW_TAG_enumeration_type: {
2306 // Add enumerators to enumeration type.
2307 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2308 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2309 const std::string &Name = ED->getName();
2310 int64_t Value = ED->getValue();
2311 DIE *Enumerator = new DIE(DW_TAG_enumerator);
2312 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2313 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2314 Buffer.AddChild(Enumerator);
2319 case DW_TAG_subroutine_type: {
2320 // Add prototype flag.
2321 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2323 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2326 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2327 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2328 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2329 Buffer.AddChild(Arg);
2338 // Add name if not anonymous or intermediate type.
2339 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2341 // Add size if non-zero (derived types might be zero-sized.)
2343 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2344 else if (isa<CompositeTypeDesc>(TyDesc)) {
2345 // If TyDesc is a composite type, then add size even if it's zero unless
2346 // it's a forward declaration.
2347 if (TyDesc->isForwardDecl())
2348 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2350 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2353 // Add source line info if available and TyDesc is not a forward
2355 if (!TyDesc->isForwardDecl())
2356 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2359 /// NewCompileUnit - Create new compile unit and it's debug information entry.
2361 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2362 // Construct debug information entry.
2363 DIE *Die = new DIE(DW_TAG_compile_unit);
2364 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2365 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2366 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
2367 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
2368 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
2369 if (!UnitDesc->getDirectory().empty())
2370 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
2372 // Construct compile unit.
2373 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2375 // Add Unit to compile unit map.
2376 DescToUnitMap[UnitDesc] = Unit;
2381 /// GetBaseCompileUnit - Get the main compile unit.
2383 CompileUnit *GetBaseCompileUnit() const {
2384 CompileUnit *Unit = CompileUnits[0];
2385 assert(Unit && "Missing compile unit.");
2389 /// FindCompileUnit - Get the compile unit for the given descriptor.
2391 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2392 CompileUnit *Unit = DescToUnitMap[UnitDesc];
2393 assert(Unit && "Missing compile unit.");
2397 /// FindCompileUnit - Get the compile unit for the given descriptor.
2399 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
2400 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
2401 assert(DW_Unit && "Missing compile unit.");
2405 /// NewGlobalVariable - Add a new global variable DIE.
2407 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2408 // Get the compile unit context.
2409 CompileUnitDesc *UnitDesc =
2410 static_cast<CompileUnitDesc *>(GVD->getContext());
2411 CompileUnit *Unit = GetBaseCompileUnit();
2413 // Check for pre-existence.
2414 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2415 if (Slot) return Slot;
2417 // Get the global variable itself.
2418 GlobalVariable *GV = GVD->getGlobalVariable();
2420 const std::string &Name = GVD->getName();
2421 const std::string &FullName = GVD->getFullName();
2422 const std::string &LinkageName = GVD->getLinkageName();
2423 // Create the global's variable DIE.
2424 DIE *VariableDie = new DIE(DW_TAG_variable);
2425 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2426 if (!LinkageName.empty()) {
2427 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2430 AddType(VariableDie, GVD->getType(), Unit);
2431 if (!GVD->isStatic())
2432 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2434 // Add source line info if available.
2435 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2438 DIEBlock *Block = new DIEBlock();
2439 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2440 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2441 AddBlock(VariableDie, DW_AT_location, 0, Block);
2446 // Add to context owner.
2447 Unit->getDie()->AddChild(VariableDie);
2449 // Expose as global.
2450 // FIXME - need to check external flag.
2451 Unit->AddGlobal(FullName, VariableDie);
2456 /// NewSubprogram - Add a new subprogram DIE.
2458 DIE *NewSubprogram(SubprogramDesc *SPD) {
2459 // Get the compile unit context.
2460 CompileUnitDesc *UnitDesc =
2461 static_cast<CompileUnitDesc *>(SPD->getContext());
2462 CompileUnit *Unit = GetBaseCompileUnit();
2464 // Check for pre-existence.
2465 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2466 if (Slot) return Slot;
2468 // Gather the details (simplify add attribute code.)
2469 const std::string &Name = SPD->getName();
2470 const std::string &FullName = SPD->getFullName();
2471 const std::string &LinkageName = SPD->getLinkageName();
2473 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2474 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2475 if (!LinkageName.empty()) {
2476 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2479 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2480 if (!SPD->isStatic())
2481 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2482 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2484 // Add source line info if available.
2485 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2488 Slot = SubprogramDie;
2490 // Add to context owner.
2491 Unit->getDie()->AddChild(SubprogramDie);
2493 // Expose as global.
2494 Unit->AddGlobal(FullName, SubprogramDie);
2496 return SubprogramDie;
2499 /// NewScopeVariable - Create a new scope variable.
2501 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2502 // Get the descriptor.
2503 VariableDesc *VD = DV->getDesc();
2505 // Translate tag to proper Dwarf tag. The result variable is dropped for
2508 switch (VD->getTag()) {
2509 case DW_TAG_return_variable: return NULL;
2510 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2511 case DW_TAG_auto_variable: // fall thru
2512 default: Tag = DW_TAG_variable; break;
2515 // Define variable debug information entry.
2516 DIE *VariableDie = new DIE(Tag);
2517 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2519 // Add source line info if available.
2520 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2522 // Add variable type.
2523 AddType(VariableDie, VD->getType(), Unit);
2525 // Add variable address.
2526 MachineLocation Location;
2527 Location.set(RI->getFrameRegister(*MF),
2528 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2529 AddAddress(VariableDie, DW_AT_location, Location);
2534 /// NewScopeVariable - Create a new scope variable.
2536 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
2537 // Get the descriptor.
2538 DIVariable *VD = DV->getVariable();
2540 // Translate tag to proper Dwarf tag. The result variable is dropped for
2543 switch (VD->getTag()) {
2544 case DW_TAG_return_variable: return NULL;
2545 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2546 case DW_TAG_auto_variable: // fall thru
2547 default: Tag = DW_TAG_variable; break;
2550 // Define variable debug information entry.
2551 DIE *VariableDie = new DIE(Tag);
2552 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2554 // Add source line info if available.
2555 AddSourceLine(VariableDie, VD);
2557 // Add variable type.
2558 AddType(Unit, VariableDie, VD->getType());
2560 // Add variable address.
2561 MachineLocation Location;
2562 Location.set(RI->getFrameRegister(*MF),
2563 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2564 AddAddress(VariableDie, DW_AT_location, Location);
2569 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2570 CompileUnit *Unit = DW_CUs[V];
2571 assert (Unit && "Unable to find CompileUnit");
2572 unsigned ID = NextLabelID();
2573 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2577 unsigned getRecordSourceLineCount() {
2578 return Lines.size();
2581 unsigned RecordSource(const std::string &Directory,
2582 const std::string &File) {
2583 unsigned DID = Directories.insert(Directory);
2584 return SrcFiles.insert(SrcFileInfo(DID,File));
2587 /// RecordRegionStart - Indicate the start of a region.
2589 unsigned RecordRegionStart(GlobalVariable *V) {
2590 DbgScope *Scope = getOrCreateScope(V);
2591 unsigned ID = NextLabelID();
2592 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2596 /// RecordRegionEnd - Indicate the end of a region.
2598 unsigned RecordRegionEnd(GlobalVariable *V) {
2599 DbgScope *Scope = getOrCreateScope(V);
2600 unsigned ID = NextLabelID();
2601 Scope->setEndLabelID(ID);
2605 /// RecordVariable - Indicate the declaration of a local variable.
2607 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
2608 DbgScope *Scope = getOrCreateScope(GV);
2609 DIVariable *VD = new DIVariable(GV);
2610 DbgVariable *DV = new DbgVariable(VD, FrameIndex);
2611 Scope->AddVariable(DV);
2614 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2616 DbgScope *getOrCreateScope(GlobalVariable *V) {
2617 DbgScope *&Slot = DbgScopeMap[V];
2619 // FIXME - breaks down when the context is an inlined function.
2620 DIDescriptor ParentDesc;
2621 DIDescriptor *DB = new DIBlock(V);
2622 if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
2623 ParentDesc = Block->getContext();
2625 DbgScope *Parent = ParentDesc.isNull() ?
2626 NULL : getOrCreateScope(ParentDesc.getGV());
2627 Slot = new DbgScope(Parent, DB);
2629 Parent->AddScope(Slot);
2630 } else if (RootDbgScope) {
2631 // FIXME - Add inlined function scopes to the root so we can delete
2632 // them later. Long term, handle inlined functions properly.
2633 RootDbgScope->AddScope(Slot);
2635 // First function is top level function.
2636 RootDbgScope = Slot;
2642 /// ConstructDbgScope - Construct the components of a scope.
2644 void ConstructDbgScope(DbgScope *ParentScope,
2645 unsigned ParentStartID, unsigned ParentEndID,
2646 DIE *ParentDie, CompileUnit *Unit) {
2647 // Add variables to scope.
2648 SmallVector<DbgVariable *, 32> &Variables = ParentScope->getVariables();
2649 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2650 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2651 if (VariableDie) ParentDie->AddChild(VariableDie);
2654 // Add nested scopes.
2655 SmallVector<DbgScope *, 8> &Scopes = ParentScope->getScopes();
2656 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2657 // Define the Scope debug information entry.
2658 DbgScope *Scope = Scopes[j];
2659 // FIXME - Ignore inlined functions for the time being.
2660 if (!Scope->getParent()) continue;
2662 unsigned StartID = MappedLabel(Scope->getStartLabelID());
2663 unsigned EndID = MappedLabel(Scope->getEndLabelID());
2665 // Ignore empty scopes.
2666 if (StartID == EndID && StartID != 0) continue;
2667 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2669 if (StartID == ParentStartID && EndID == ParentEndID) {
2670 // Just add stuff to the parent scope.
2671 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2673 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2675 // Add the scope bounds.
2677 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2678 DWLabel("label", StartID));
2680 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2681 DWLabel("func_begin", SubprogramCount));
2684 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2685 DWLabel("label", EndID));
2687 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2688 DWLabel("func_end", SubprogramCount));
2691 // Add the scope contents.
2692 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2693 ParentDie->AddChild(ScopeDie);
2698 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2700 void ConstructRootDbgScope(DbgScope *RootScope) {
2701 // Exit if there is no root scope.
2702 if (!RootScope) return;
2704 // Get the subprogram debug information entry.
2705 DISubprogram *SPD = cast<DISubprogram>(RootScope->getDesc());
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));
2719 MachineLocation Location(RI->getFrameRegister(*MF));
2720 AddAddress(SPDie, DW_AT_frame_base, Location);
2722 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2725 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2727 void ConstructDefaultDbgScope(MachineFunction *MF) {
2728 // Find the correct subprogram descriptor.
2729 std::string SPName = "llvm.dbg.subprograms";
2730 std::vector<GlobalVariable*> Result;
2731 getGlobalVariablesUsing(*M, SPName, Result);
2732 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2733 E = Result.end(); I != E; ++I) {
2735 DISubprogram *SPD = new DISubprogram(*I);
2737 if (SPD->getName() == MF->getFunction()->getName()) {
2738 // Get the compile unit context.
2739 CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2741 // Get the subprogram die.
2742 DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2743 assert(SPDie && "Missing subprogram descriptor");
2745 // Add the function bounds.
2746 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2747 DWLabel("func_begin", SubprogramCount));
2748 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2749 DWLabel("func_end", SubprogramCount));
2751 MachineLocation Location(RI->getFrameRegister(*MF));
2752 AddAddress(SPDie, DW_AT_frame_base, Location);
2757 // FIXME: This is causing an abort because C++ mangled names are compared
2758 // with their unmangled counterparts. See PR2885. Don't do this assert.
2759 assert(0 && "Couldn't find DIE for machine function!");
2763 /// ConstructScope - Construct the components of a scope.
2765 void ConstructScope(DebugScope *ParentScope,
2766 unsigned ParentStartID, unsigned ParentEndID,
2767 DIE *ParentDie, CompileUnit *Unit) {
2768 // Add variables to scope.
2769 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2770 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2771 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2772 if (VariableDie) ParentDie->AddChild(VariableDie);
2775 // Add nested scopes.
2776 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2777 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2778 // Define the Scope debug information entry.
2779 DebugScope *Scope = Scopes[j];
2780 // FIXME - Ignore inlined functions for the time being.
2781 if (!Scope->getParent()) continue;
2783 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2784 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2786 // Ignore empty scopes.
2787 if (StartID == EndID && StartID != 0) continue;
2788 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2790 if (StartID == ParentStartID && EndID == ParentEndID) {
2791 // Just add stuff to the parent scope.
2792 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2794 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2796 // Add the scope bounds.
2798 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2799 DWLabel("label", StartID));
2801 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2802 DWLabel("func_begin", SubprogramCount));
2805 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2806 DWLabel("label", EndID));
2808 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2809 DWLabel("func_end", SubprogramCount));
2812 // Add the scope contents.
2813 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2814 ParentDie->AddChild(ScopeDie);
2819 /// ConstructRootScope - Construct the scope for the subprogram.
2821 void ConstructRootScope(DebugScope *RootScope) {
2822 // Exit if there is no root scope.
2823 if (!RootScope) return;
2825 // Get the subprogram debug information entry.
2826 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2828 // Get the compile unit context.
2829 CompileUnit *Unit = GetBaseCompileUnit();
2831 // Get the subprogram die.
2832 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2833 assert(SPDie && "Missing subprogram descriptor");
2835 // Add the function bounds.
2836 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2837 DWLabel("func_begin", SubprogramCount));
2838 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2839 DWLabel("func_end", SubprogramCount));
2840 MachineLocation Location(RI->getFrameRegister(*MF));
2841 AddAddress(SPDie, DW_AT_frame_base, Location);
2843 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2846 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2848 void ConstructDefaultScope(MachineFunction *MF) {
2849 // Find the correct subprogram descriptor.
2850 std::vector<SubprogramDesc *> Subprograms;
2851 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2853 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2854 SubprogramDesc *SPD = Subprograms[i];
2856 if (SPD->getName() == MF->getFunction()->getName()) {
2857 // Get the compile unit context.
2858 CompileUnit *Unit = GetBaseCompileUnit();
2860 // Get the subprogram die.
2861 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2862 assert(SPDie && "Missing subprogram descriptor");
2864 // Add the function bounds.
2865 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2866 DWLabel("func_begin", SubprogramCount));
2867 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2868 DWLabel("func_end", SubprogramCount));
2870 MachineLocation Location(RI->getFrameRegister(*MF));
2871 AddAddress(SPDie, DW_AT_frame_base, Location);
2876 // FIXME: This is causing an abort because C++ mangled names are compared
2877 // with their unmangled counterparts. See PR2885. Don't do this assert.
2878 assert(0 && "Couldn't find DIE for machine function!");
2882 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2883 /// tools to recognize the object file contains Dwarf information.
2884 void EmitInitial() {
2885 // Check to see if we already emitted intial headers.
2886 if (didInitial) return;
2889 // Dwarf sections base addresses.
2890 if (TAI->doesDwarfRequireFrameSection()) {
2891 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2892 EmitLabel("section_debug_frame", 0);
2894 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2895 EmitLabel("section_info", 0);
2896 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2897 EmitLabel("section_abbrev", 0);
2898 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2899 EmitLabel("section_aranges", 0);
2900 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2901 EmitLabel("section_macinfo", 0);
2902 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2903 EmitLabel("section_line", 0);
2904 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2905 EmitLabel("section_loc", 0);
2906 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2907 EmitLabel("section_pubnames", 0);
2908 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2909 EmitLabel("section_str", 0);
2910 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2911 EmitLabel("section_ranges", 0);
2913 Asm->SwitchToSection(TAI->getTextSection());
2914 EmitLabel("text_begin", 0);
2915 Asm->SwitchToSection(TAI->getDataSection());
2916 EmitLabel("data_begin", 0);
2919 /// EmitDIE - Recusively Emits a debug information entry.
2921 void EmitDIE(DIE *Die) {
2922 // Get the abbreviation for this DIE.
2923 unsigned AbbrevNumber = Die->getAbbrevNumber();
2924 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2928 // Emit the code (index) for the abbreviation.
2929 Asm->EmitULEB128Bytes(AbbrevNumber);
2932 Asm->EOL(std::string("Abbrev [" +
2933 utostr(AbbrevNumber) +
2934 "] 0x" + utohexstr(Die->getOffset()) +
2935 ":0x" + utohexstr(Die->getSize()) + " " +
2936 TagString(Abbrev->getTag())));
2940 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2941 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2943 // Emit the DIE attribute values.
2944 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2945 unsigned Attr = AbbrevData[i].getAttribute();
2946 unsigned Form = AbbrevData[i].getForm();
2947 assert(Form && "Too many attributes for DIE (check abbreviation)");
2950 case DW_AT_sibling: {
2951 Asm->EmitInt32(Die->SiblingOffset());
2955 // Emit an attribute using the defined form.
2956 Values[i]->EmitValue(*this, Form);
2961 Asm->EOL(AttributeString(Attr));
2964 // Emit the DIE children if any.
2965 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2966 const std::vector<DIE *> &Children = Die->getChildren();
2968 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2969 EmitDIE(Children[j]);
2972 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2976 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2978 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2979 // Get the children.
2980 const std::vector<DIE *> &Children = Die->getChildren();
2982 // If not last sibling and has children then add sibling offset attribute.
2983 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2985 // Record the abbreviation.
2986 AssignAbbrevNumber(Die->getAbbrev());
2988 // Get the abbreviation for this DIE.
2989 unsigned AbbrevNumber = Die->getAbbrevNumber();
2990 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2993 Die->setOffset(Offset);
2995 // Start the size with the size of abbreviation code.
2996 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2998 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2999 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3001 // Size the DIE attribute values.
3002 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3003 // Size attribute value.
3004 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
3007 // Size the DIE children if any.
3008 if (!Children.empty()) {
3009 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
3010 "Children flag not set");
3012 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3013 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
3016 // End of children marker.
3017 Offset += sizeof(int8_t);
3020 Die->setSize(Offset - Die->getOffset());
3024 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
3026 void SizeAndOffsets() {
3027 // Process base compile unit.
3028 CompileUnit *Unit = GetBaseCompileUnit();
3029 // Compute size of compile unit header
3030 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
3031 sizeof(int16_t) + // DWARF version number
3032 sizeof(int32_t) + // Offset Into Abbrev. Section
3033 sizeof(int8_t); // Pointer Size (in bytes)
3034 SizeAndOffsetDie(Unit->getDie(), Offset, true);
3037 /// EmitDebugInfo - Emit the debug info section.
3039 void EmitDebugInfo() {
3040 // Start debug info section.
3041 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
3043 CompileUnit *Unit = GetBaseCompileUnit();
3044 DIE *Die = Unit->getDie();
3045 // Emit the compile units header.
3046 EmitLabel("info_begin", Unit->getID());
3047 // Emit size of content not including length itself
3048 unsigned ContentSize = Die->getSize() +
3049 sizeof(int16_t) + // DWARF version number
3050 sizeof(int32_t) + // Offset Into Abbrev. Section
3051 sizeof(int8_t) + // Pointer Size (in bytes)
3052 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3054 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
3055 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3056 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
3057 Asm->EOL("Offset Into Abbrev. Section");
3058 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
3061 // FIXME - extra padding for gdb bug.
3062 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3063 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3064 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3065 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3066 EmitLabel("info_end", Unit->getID());
3071 /// EmitAbbreviations - Emit the abbreviation section.
3073 void EmitAbbreviations() const {
3074 // Check to see if it is worth the effort.
3075 if (!Abbreviations.empty()) {
3076 // Start the debug abbrev section.
3077 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
3079 EmitLabel("abbrev_begin", 0);
3081 // For each abbrevation.
3082 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3083 // Get abbreviation data
3084 const DIEAbbrev *Abbrev = Abbreviations[i];
3086 // Emit the abbrevations code (base 1 index.)
3087 Asm->EmitULEB128Bytes(Abbrev->getNumber());
3088 Asm->EOL("Abbreviation Code");
3090 // Emit the abbreviations data.
3091 Abbrev->Emit(*this);
3096 // Mark end of abbreviations.
3097 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
3099 EmitLabel("abbrev_end", 0);
3105 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
3106 /// the line matrix.
3108 void EmitEndOfLineMatrix(unsigned SectionEnd) {
3109 // Define last address of section.
3110 Asm->EmitInt8(0); Asm->EOL("Extended Op");
3111 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3112 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3113 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
3115 // Mark end of matrix.
3116 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
3117 Asm->EmitULEB128Bytes(1); Asm->EOL();
3118 Asm->EmitInt8(1); Asm->EOL();
3121 /// EmitDebugLines - Emit source line information.
3123 void EmitDebugLines() {
3124 // If the target is using .loc/.file, the assembler will be emitting the
3125 // .debug_line table automatically.
3126 if (TAI->hasDotLocAndDotFile())
3129 // Minimum line delta, thus ranging from -10..(255-10).
3130 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
3131 // Maximum line delta, thus ranging from -10..(255-10).
3132 const int MaxLineDelta = 255 + MinLineDelta;
3134 // Start the dwarf line section.
3135 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
3137 // Construct the section header.
3139 EmitDifference("line_end", 0, "line_begin", 0, true);
3140 Asm->EOL("Length of Source Line Info");
3141 EmitLabel("line_begin", 0);
3143 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3145 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
3146 Asm->EOL("Prolog Length");
3147 EmitLabel("line_prolog_begin", 0);
3149 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
3151 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
3153 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
3155 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
3157 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
3159 // Line number standard opcode encodings argument count
3160 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
3161 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
3162 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
3163 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
3164 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
3165 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
3166 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
3167 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
3168 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
3170 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3171 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3173 // Emit directories.
3174 for (unsigned DirectoryID = 1, NDID = Directories.size();
3175 DirectoryID <= NDID; ++DirectoryID) {
3176 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
3178 Asm->EmitInt8(0); Asm->EOL("End of directories");
3181 for (unsigned SourceID = 1, NSID = SourceFiles.size();
3182 SourceID <= NSID; ++SourceID) {
3183 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3184 Asm->EmitString(SourceFile.getName());
3186 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
3187 Asm->EOL("Directory #");
3188 Asm->EmitULEB128Bytes(0);
3189 Asm->EOL("Mod date");
3190 Asm->EmitULEB128Bytes(0);
3191 Asm->EOL("File size");
3193 Asm->EmitInt8(0); Asm->EOL("End of files");
3195 EmitLabel("line_prolog_end", 0);
3197 // A sequence for each text section.
3198 unsigned SecSrcLinesSize = SectionSourceLines.size();
3200 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3201 // Isolate current sections line info.
3202 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
3205 const Section* S = SectionMap[j + 1];
3206 Asm->EOL(std::string("Section ") + S->getName());
3210 // Dwarf assumes we start with first line of first source file.
3211 unsigned Source = 1;
3214 // Construct rows of the address, source, line, column matrix.
3215 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3216 const SourceLineInfo &LineInfo = LineInfos[i];
3217 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
3218 if (!LabelID) continue;
3220 unsigned SourceID = LineInfo.getSourceID();
3221 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3222 unsigned DirectoryID = SourceFile.getDirectoryID();
3224 Asm->EOL(Directories[DirectoryID]
3225 + SourceFile.getName()
3227 + utostr_32(LineInfo.getLine()));
3231 // Define the line address.
3232 Asm->EmitInt8(0); Asm->EOL("Extended Op");
3233 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3234 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3235 EmitReference("label", LabelID); Asm->EOL("Location label");
3237 // If change of source, then switch to the new source.
3238 if (Source != LineInfo.getSourceID()) {
3239 Source = LineInfo.getSourceID();
3240 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
3241 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
3244 // If change of line.
3245 if (Line != LineInfo.getLine()) {
3246 // Determine offset.
3247 int Offset = LineInfo.getLine() - Line;
3248 int Delta = Offset - MinLineDelta;
3251 Line = LineInfo.getLine();
3253 // If delta is small enough and in range...
3254 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3255 // ... then use fast opcode.
3256 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
3258 // ... otherwise use long hand.
3259 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
3260 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
3261 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3264 // Copy the previous row (different address or source)
3265 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3269 EmitEndOfLineMatrix(j + 1);
3272 if (SecSrcLinesSize == 0)
3273 // Because we're emitting a debug_line section, we still need a line
3274 // table. The linker and friends expect it to exist. If there's nothing to
3275 // put into it, emit an empty table.
3276 EmitEndOfLineMatrix(1);
3278 EmitLabel("line_end", 0);
3283 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
3285 void EmitCommonDebugFrame() {
3286 if (!TAI->doesDwarfRequireFrameSection())
3290 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3291 TargetFrameInfo::StackGrowsUp ?
3292 TD->getPointerSize() : -TD->getPointerSize();
3294 // Start the dwarf frame section.
3295 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3297 EmitLabel("debug_frame_common", 0);
3298 EmitDifference("debug_frame_common_end", 0,
3299 "debug_frame_common_begin", 0, true);
3300 Asm->EOL("Length of Common Information Entry");
3302 EmitLabel("debug_frame_common_begin", 0);
3303 Asm->EmitInt32((int)DW_CIE_ID);
3304 Asm->EOL("CIE Identifier Tag");
3305 Asm->EmitInt8(DW_CIE_VERSION);
3306 Asm->EOL("CIE Version");
3307 Asm->EmitString("");
3308 Asm->EOL("CIE Augmentation");
3309 Asm->EmitULEB128Bytes(1);
3310 Asm->EOL("CIE Code Alignment Factor");
3311 Asm->EmitSLEB128Bytes(stackGrowth);
3312 Asm->EOL("CIE Data Alignment Factor");
3313 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3314 Asm->EOL("CIE RA Column");
3316 std::vector<MachineMove> Moves;
3317 RI->getInitialFrameState(Moves);
3319 EmitFrameMoves(NULL, 0, Moves, false);
3321 Asm->EmitAlignment(2, 0, 0, false);
3322 EmitLabel("debug_frame_common_end", 0);
3327 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
3329 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3330 if (!TAI->doesDwarfRequireFrameSection())
3333 // Start the dwarf frame section.
3334 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3336 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
3337 "debug_frame_begin", DebugFrameInfo.Number, true);
3338 Asm->EOL("Length of Frame Information Entry");
3340 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
3342 EmitSectionOffset("debug_frame_common", "section_debug_frame",
3344 Asm->EOL("FDE CIE offset");
3346 EmitReference("func_begin", DebugFrameInfo.Number);
3347 Asm->EOL("FDE initial location");
3348 EmitDifference("func_end", DebugFrameInfo.Number,
3349 "func_begin", DebugFrameInfo.Number);
3350 Asm->EOL("FDE address range");
3352 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
3354 Asm->EmitAlignment(2, 0, 0, false);
3355 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
3360 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
3362 void EmitDebugPubNames() {
3363 // Start the dwarf pubnames section.
3364 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
3366 CompileUnit *Unit = GetBaseCompileUnit();
3368 EmitDifference("pubnames_end", Unit->getID(),
3369 "pubnames_begin", Unit->getID(), true);
3370 Asm->EOL("Length of Public Names Info");
3372 EmitLabel("pubnames_begin", Unit->getID());
3374 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
3376 EmitSectionOffset("info_begin", "section_info",
3377 Unit->getID(), 0, true, false);
3378 Asm->EOL("Offset of Compilation Unit Info");
3380 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
3381 Asm->EOL("Compilation Unit Length");
3383 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
3385 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
3388 const std::string &Name = GI->first;
3389 DIE * Entity = GI->second;
3391 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
3392 Asm->EmitString(Name); Asm->EOL("External Name");
3395 Asm->EmitInt32(0); Asm->EOL("End Mark");
3396 EmitLabel("pubnames_end", Unit->getID());
3401 /// EmitDebugStr - Emit visible names into a debug str section.
3403 void EmitDebugStr() {
3404 // Check to see if it is worth the effort.
3405 if (!StringPool.empty()) {
3406 // Start the dwarf str section.
3407 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
3409 // For each of strings in the string pool.
3410 for (unsigned StringID = 1, N = StringPool.size();
3411 StringID <= N; ++StringID) {
3412 // Emit a label for reference from debug information entries.
3413 EmitLabel("string", StringID);
3414 // Emit the string itself.
3415 const std::string &String = StringPool[StringID];
3416 Asm->EmitString(String); Asm->EOL();
3423 /// EmitDebugLoc - Emit visible names into a debug loc section.
3425 void EmitDebugLoc() {
3426 // Start the dwarf loc section.
3427 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
3432 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3434 void EmitDebugARanges() {
3435 // Start the dwarf aranges section.
3436 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
3440 CompileUnit *Unit = GetBaseCompileUnit();
3442 // Don't include size of length
3443 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
3445 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
3447 EmitReference("info_begin", Unit->getID());
3448 Asm->EOL("Offset of Compilation Unit Info");
3450 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
3452 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
3454 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
3455 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
3458 EmitReference("text_begin", 0); Asm->EOL("Address");
3459 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
3461 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
3462 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
3468 /// EmitDebugRanges - Emit visible names into a debug ranges section.
3470 void EmitDebugRanges() {
3471 // Start the dwarf ranges section.
3472 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
3477 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
3479 void EmitDebugMacInfo() {
3480 // Start the dwarf macinfo section.
3481 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
3486 /// ConstructCompileUnits - Create a compile unit DIEs.
3487 void ConstructCompileUnits() {
3488 std::string CUName = "llvm.dbg.compile_units";
3489 std::vector<GlobalVariable*> Result;
3490 getGlobalVariablesUsing(*M, CUName, Result);
3491 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3492 RE = Result.end(); RI != RE; ++RI) {
3493 DICompileUnit *DIUnit = new DICompileUnit(*RI);
3494 unsigned ID = RecordSource(DIUnit->getDirectory(),
3495 DIUnit->getFilename());
3497 DIE *Die = new DIE(DW_TAG_compile_unit);
3498 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
3499 DWLabel("section_line", 0), DWLabel("section_line", 0),
3501 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
3502 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
3503 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
3504 if (!DIUnit->getDirectory().empty())
3505 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
3507 CompileUnit *Unit = new CompileUnit(ID, Die);
3508 DW_CUs[DIUnit->getGV()] = Unit;
3512 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3514 void ConstructCompileUnitDIEs() {
3515 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3517 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3518 unsigned ID = MMI->RecordSource(CUW[i]);
3519 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3520 CompileUnits.push_back(Unit);
3524 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
3525 /// visible global variables.
3526 void ConstructGlobalVariableDIEs() {
3527 std::string GVName = "llvm.dbg.global_variables";
3528 std::vector<GlobalVariable*> Result;
3529 getGlobalVariablesUsing(*M, GVName, Result);
3530 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
3531 GVE = Result.end(); GVI != GVE; ++GVI) {
3532 DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
3533 CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
3535 // Check for pre-existence.
3536 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
3539 DIE *VariableDie = new DIE(DW_TAG_variable);
3540 AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
3541 const std::string &LinkageName = DI_GV->getLinkageName();
3542 if (!LinkageName.empty())
3543 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3545 AddType(DW_Unit, VariableDie, DI_GV->getType());
3547 if (!DI_GV->isLocalToUnit())
3548 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
3550 // Add source line info, if available.
3551 AddSourceLine(VariableDie, DI_GV);
3554 DIEBlock *Block = new DIEBlock();
3555 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3556 AddObjectLabel(Block, 0, DW_FORM_udata,
3557 Asm->getGlobalLinkName(DI_GV->getGV()));
3558 AddBlock(VariableDie, DW_AT_location, 0, Block);
3563 //Add to context owner.
3564 DW_Unit->getDie()->AddChild(VariableDie);
3566 //Expose as global. FIXME - need to check external flag.
3567 DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
3571 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3572 /// global variables.
3573 void ConstructGlobalDIEs() {
3574 std::vector<GlobalVariableDesc *> GlobalVariables;
3575 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3577 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3578 GlobalVariableDesc *GVD = GlobalVariables[i];
3579 NewGlobalVariable(GVD);
3583 /// ConstructSubprograms - Create DIEs for each of the externally visible
3585 void ConstructSubprograms() {
3587 std::string SPName = "llvm.dbg.subprograms";
3588 std::vector<GlobalVariable*> Result;
3589 getGlobalVariablesUsing(*M, SPName, Result);
3590 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3591 RE = Result.end(); RI != RE; ++RI) {
3593 DISubprogram *SP = new DISubprogram(*RI);
3594 CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
3596 // Check for pre-existence.
3597 DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
3600 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
3601 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
3602 const std::string &LinkageName = SP->getLinkageName();
3603 if (!LinkageName.empty())
3604 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3606 DIType SPTy = SP->getType();
3607 AddType(Unit, SubprogramDie, SPTy);
3608 if (!SP->isLocalToUnit())
3609 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
3610 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
3612 AddSourceLine(SubprogramDie, SP);
3614 Slot = SubprogramDie;
3615 //Add to context owner.
3616 Unit->getDie()->AddChild(SubprogramDie);
3618 Unit->AddGlobal(SP->getName(), SubprogramDie);
3622 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3624 void ConstructSubprogramDIEs() {
3625 std::vector<SubprogramDesc *> Subprograms;
3626 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3628 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3629 SubprogramDesc *SPD = Subprograms[i];
3635 //===--------------------------------------------------------------------===//
3636 // Main entry points.
3638 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3639 : Dwarf(OS, A, T, "dbg")
3641 , AbbreviationsSet(InitAbbreviationsSetSize)
3643 , ValuesSet(InitValuesSetSize)
3648 , SectionSourceLines()
3651 , RootDbgScope(NULL)
3654 virtual ~DwarfDebug() {
3655 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3656 delete CompileUnits[i];
3657 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3661 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3662 /// This is inovked by the target AsmPrinter.
3663 void SetDebugInfo() {
3664 // FIXME - Check if the module has debug info or not.
3665 // Create all the compile unit DIEs.
3666 ConstructCompileUnits();
3668 // Create DIEs for each of the externally visible global variables.
3669 ConstructGlobalVariableDIEs();
3671 // Create DIEs for each of the externally visible subprograms.
3672 ConstructSubprograms();
3674 // Prime section data.
3675 SectionMap.insert(TAI->getTextSection());
3677 // Print out .file directives to specify files for .loc directives. These
3678 // are printed out early so that they precede any .loc directives.
3679 if (TAI->hasDotLocAndDotFile()) {
3680 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
3681 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
3682 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
3683 assert(AppendOk && "Could not append filename to directory!");
3685 Asm->EmitFile(i, FullPath.toString());
3690 // Emit initial sections
3694 /// SetModuleInfo - Set machine module information when it's known that pass
3695 /// manager has created it. Set by the target AsmPrinter.
3696 void SetModuleInfo(MachineModuleInfo *mmi) {
3697 // Make sure initial declarations are made.
3698 if (!MMI && mmi->hasDebugInfo()) {
3702 // Create all the compile unit DIEs.
3703 ConstructCompileUnitDIEs();
3705 // Create DIEs for each of the externally visible global variables.
3706 ConstructGlobalDIEs();
3708 // Create DIEs for each of the externally visible subprograms.
3709 ConstructSubprogramDIEs();
3711 // Prime section data.
3712 SectionMap.insert(TAI->getTextSection());
3714 // Print out .file directives to specify files for .loc directives. These
3715 // are printed out early so that they precede any .loc directives.
3716 if (TAI->hasDotLocAndDotFile()) {
3717 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3718 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3719 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3720 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3721 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3722 assert(AppendOk && "Could not append filename to directory!");
3724 Asm->EmitFile(i, FullPath.toString());
3729 // Emit initial sections
3734 /// BeginModule - Emit all Dwarf sections that should come prior to the
3736 void BeginModule(Module *M) {
3740 /// EndModule - Emit all Dwarf sections that should come after the content.
3743 if (!ShouldEmitDwarf()) return;
3745 // Standard sections final addresses.
3746 Asm->SwitchToSection(TAI->getTextSection());
3747 EmitLabel("text_end", 0);
3748 Asm->SwitchToSection(TAI->getDataSection());
3749 EmitLabel("data_end", 0);
3751 // End text sections.
3752 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3753 Asm->SwitchToSection(SectionMap[i]);
3754 EmitLabel("section_end", i);
3757 // Emit common frame information.
3758 EmitCommonDebugFrame();
3760 // Emit function debug frame information
3761 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3762 E = DebugFrames.end(); I != E; ++I)
3763 EmitFunctionDebugFrame(*I);
3765 // Compute DIE offsets and sizes.
3768 // Emit all the DIEs into a debug info section
3771 // Corresponding abbreviations into a abbrev section.
3772 EmitAbbreviations();
3774 // Emit source line correspondence into a debug line section.
3777 // Emit info into a debug pubnames section.
3778 EmitDebugPubNames();
3780 // Emit info into a debug str section.
3783 // Emit info into a debug loc section.
3786 // Emit info into a debug aranges section.
3789 // Emit info into a debug ranges section.
3792 // Emit info into a debug macinfo section.
3796 /// BeginFunction - Gather pre-function debug information. Assumes being
3797 /// emitted immediately after the function entry point.
3798 void BeginFunction(MachineFunction *MF) {
3801 if (!ShouldEmitDwarf()) return;
3803 // Begin accumulating function debug information.
3804 MMI->BeginFunction(MF);
3806 // Assumes in correct section after the entry point.
3807 EmitLabel("func_begin", ++SubprogramCount);
3809 // Emit label for the implicitly defined dbg.stoppoint at the start of
3811 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3812 if (!LineInfos.empty()) {
3813 const SourceLineInfo &LineInfo = LineInfos[0];
3814 Asm->printLabel(LineInfo.getLabelID());
3818 /// EndFunction - Gather and emit post-function debug information.
3820 void EndFunction(MachineFunction *MF) {
3821 if (!ShouldEmitDwarf()) return;
3823 // Define end label for subprogram.
3824 EmitLabel("func_end", SubprogramCount);
3826 // Get function line info.
3827 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3829 if (!LineInfos.empty()) {
3830 // Get section line info.
3831 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3832 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3833 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3834 // Append the function info to section info.
3835 SectionLineInfos.insert(SectionLineInfos.end(),
3836 LineInfos.begin(), LineInfos.end());
3839 // Construct scopes for subprogram.
3840 if (MMI->getRootScope())
3841 ConstructRootScope(MMI->getRootScope());
3843 // FIXME: This is wrong. We are essentially getting past a problem with
3844 // debug information not being able to handle unreachable blocks that have
3845 // debug information in them. In particular, those unreachable blocks that
3846 // have "region end" info in them. That situation results in the "root
3847 // scope" not being created. If that's the case, then emit a "default"
3848 // scope, i.e., one that encompasses the whole function. This isn't
3849 // desirable. And a better way of handling this (and all of the debugging
3850 // information) needs to be explored.
3851 ConstructDefaultScope(MF);
3853 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3854 MMI->getFrameMoves()));
3858 //===----------------------------------------------------------------------===//
3859 /// DwarfException - Emits Dwarf exception handling directives.
3861 class DwarfException : public Dwarf {
3864 struct FunctionEHFrameInfo {
3867 unsigned PersonalityIndex;
3869 bool hasLandingPads;
3870 std::vector<MachineMove> Moves;
3871 const Function * function;
3873 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3875 const std::vector<MachineMove> &M,
3877 FnName(FN), Number(Num), PersonalityIndex(P),
3878 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3881 std::vector<FunctionEHFrameInfo> EHFrames;
3883 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3885 bool shouldEmitTable;
3887 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3888 /// should be emitted.
3889 bool shouldEmitMoves;
3891 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3892 /// should be emitted.
3893 bool shouldEmitTableModule;
3895 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3896 /// should be emitted.
3897 bool shouldEmitMovesModule;
3899 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3901 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3902 // Size and sign of stack growth.
3904 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3905 TargetFrameInfo::StackGrowsUp ?
3906 TD->getPointerSize() : -TD->getPointerSize();
3908 // Begin eh frame section.
3909 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3911 if (!TAI->doesRequireNonLocalEHFrameLabel())
3912 O << TAI->getEHGlobalPrefix();
3913 O << "EH_frame" << Index << ":\n";
3914 EmitLabel("section_eh_frame", Index);
3916 // Define base labels.
3917 EmitLabel("eh_frame_common", Index);
3919 // Define the eh frame length.
3920 EmitDifference("eh_frame_common_end", Index,
3921 "eh_frame_common_begin", Index, true);
3922 Asm->EOL("Length of Common Information Entry");
3925 EmitLabel("eh_frame_common_begin", Index);
3926 Asm->EmitInt32((int)0);
3927 Asm->EOL("CIE Identifier Tag");
3928 Asm->EmitInt8(DW_CIE_VERSION);
3929 Asm->EOL("CIE Version");
3931 // The personality presence indicates that language specific information
3932 // will show up in the eh frame.
3933 Asm->EmitString(Personality ? "zPLR" : "zR");
3934 Asm->EOL("CIE Augmentation");
3936 // Round out reader.
3937 Asm->EmitULEB128Bytes(1);
3938 Asm->EOL("CIE Code Alignment Factor");
3939 Asm->EmitSLEB128Bytes(stackGrowth);
3940 Asm->EOL("CIE Data Alignment Factor");
3941 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3942 Asm->EOL("CIE Return Address Column");
3944 // If there is a personality, we need to indicate the functions location.
3946 Asm->EmitULEB128Bytes(7);
3947 Asm->EOL("Augmentation Size");
3949 if (TAI->getNeedsIndirectEncoding()) {
3950 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3951 Asm->EOL("Personality (pcrel sdata4 indirect)");
3953 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3954 Asm->EOL("Personality (pcrel sdata4)");
3957 PrintRelDirective(true);
3958 O << TAI->getPersonalityPrefix();
3959 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3960 O << TAI->getPersonalitySuffix();
3961 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3962 O << "-" << TAI->getPCSymbol();
3963 Asm->EOL("Personality");
3965 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3966 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3968 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3969 Asm->EOL("FDE Encoding (pcrel sdata4)");
3971 Asm->EmitULEB128Bytes(1);
3972 Asm->EOL("Augmentation Size");
3974 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3975 Asm->EOL("FDE Encoding (pcrel sdata4)");
3978 // Indicate locations of general callee saved registers in frame.
3979 std::vector<MachineMove> Moves;
3980 RI->getInitialFrameState(Moves);
3981 EmitFrameMoves(NULL, 0, Moves, true);
3983 // On Darwin the linker honors the alignment of eh_frame, which means it
3984 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3985 // you get holes which confuse readers of eh_frame.
3986 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3988 EmitLabel("eh_frame_common_end", Index);
3993 /// EmitEHFrame - Emit function exception frame information.
3995 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3996 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3998 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
4000 // Externally visible entry into the functions eh frame info.
4001 // If the corresponding function is static, this should not be
4002 // externally visible.
4003 if (linkage != Function::InternalLinkage) {
4004 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
4005 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
4008 // If corresponding function is weak definition, this should be too.
4009 if ((linkage == Function::WeakLinkage ||
4010 linkage == Function::LinkOnceLinkage) &&
4011 TAI->getWeakDefDirective())
4012 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
4014 // If there are no calls then you can't unwind. This may mean we can
4015 // omit the EH Frame, but some environments do not handle weak absolute
4017 // If UnwindTablesMandatory is set we cannot do this optimization; the
4018 // unwind info is to be available for non-EH uses.
4019 if (!EHFrameInfo.hasCalls &&
4020 !UnwindTablesMandatory &&
4021 ((linkage != Function::WeakLinkage &&
4022 linkage != Function::LinkOnceLinkage) ||
4023 !TAI->getWeakDefDirective() ||
4024 TAI->getSupportsWeakOmittedEHFrame()))
4026 O << EHFrameInfo.FnName << " = 0\n";
4027 // This name has no connection to the function, so it might get
4028 // dead-stripped when the function is not, erroneously. Prohibit
4029 // dead-stripping unconditionally.
4030 if (const char *UsedDirective = TAI->getUsedDirective())
4031 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4033 O << EHFrameInfo.FnName << ":\n";
4036 EmitDifference("eh_frame_end", EHFrameInfo.Number,
4037 "eh_frame_begin", EHFrameInfo.Number, true);
4038 Asm->EOL("Length of Frame Information Entry");
4040 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
4042 if (TAI->doesRequireNonLocalEHFrameLabel()) {
4043 PrintRelDirective(true, true);
4044 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
4046 if (!TAI->isAbsoluteEHSectionOffsets())
4047 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
4049 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
4050 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
4054 Asm->EOL("FDE CIE offset");
4056 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
4057 Asm->EOL("FDE initial location");
4058 EmitDifference("eh_func_end", EHFrameInfo.Number,
4059 "eh_func_begin", EHFrameInfo.Number, true);
4060 Asm->EOL("FDE address range");
4062 // If there is a personality and landing pads then point to the language
4063 // specific data area in the exception table.
4064 if (EHFrameInfo.PersonalityIndex) {
4065 Asm->EmitULEB128Bytes(4);
4066 Asm->EOL("Augmentation size");
4068 if (EHFrameInfo.hasLandingPads)
4069 EmitReference("exception", EHFrameInfo.Number, true, true);
4071 Asm->EmitInt32((int)0);
4072 Asm->EOL("Language Specific Data Area");
4074 Asm->EmitULEB128Bytes(0);
4075 Asm->EOL("Augmentation size");
4078 // Indicate locations of function specific callee saved registers in
4080 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
4082 // On Darwin the linker honors the alignment of eh_frame, which means it
4083 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
4084 // you get holes which confuse readers of eh_frame.
4085 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
4087 EmitLabel("eh_frame_end", EHFrameInfo.Number);
4089 // If the function is marked used, this table should be also. We cannot
4090 // make the mark unconditional in this case, since retaining the table
4091 // also retains the function in this case, and there is code around
4092 // that depends on unused functions (calling undefined externals) being
4093 // dead-stripped to link correctly. Yes, there really is.
4094 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
4095 if (const char *UsedDirective = TAI->getUsedDirective())
4096 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4100 /// EmitExceptionTable - Emit landing pads and actions.
4102 /// The general organization of the table is complex, but the basic concepts
4103 /// are easy. First there is a header which describes the location and
4104 /// organization of the three components that follow.
4105 /// 1. The landing pad site information describes the range of code covered
4106 /// by the try. In our case it's an accumulation of the ranges covered
4107 /// by the invokes in the try. There is also a reference to the landing
4108 /// pad that handles the exception once processed. Finally an index into
4109 /// the actions table.
4110 /// 2. The action table, in our case, is composed of pairs of type ids
4111 /// and next action offset. Starting with the action index from the
4112 /// landing pad site, each type Id is checked for a match to the current
4113 /// exception. If it matches then the exception and type id are passed
4114 /// on to the landing pad. Otherwise the next action is looked up. This
4115 /// chain is terminated with a next action of zero. If no type id is
4116 /// found the the frame is unwound and handling continues.
4117 /// 3. Type id table contains references to all the C++ typeinfo for all
4118 /// catches in the function. This tables is reversed indexed base 1.
4120 /// SharedTypeIds - How many leading type ids two landing pads have in common.
4121 static unsigned SharedTypeIds(const LandingPadInfo *L,
4122 const LandingPadInfo *R) {
4123 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4124 unsigned LSize = LIds.size(), RSize = RIds.size();
4125 unsigned MinSize = LSize < RSize ? LSize : RSize;
4128 for (; Count != MinSize; ++Count)
4129 if (LIds[Count] != RIds[Count])
4135 /// PadLT - Order landing pads lexicographically by type id.
4136 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
4137 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4138 unsigned LSize = LIds.size(), RSize = RIds.size();
4139 unsigned MinSize = LSize < RSize ? LSize : RSize;
4141 for (unsigned i = 0; i != MinSize; ++i)
4142 if (LIds[i] != RIds[i])
4143 return LIds[i] < RIds[i];
4145 return LSize < RSize;
4149 static inline unsigned getEmptyKey() { return -1U; }
4150 static inline unsigned getTombstoneKey() { return -2U; }
4151 static unsigned getHashValue(const unsigned &Key) { return Key; }
4152 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
4153 static bool isPod() { return true; }
4156 /// ActionEntry - Structure describing an entry in the actions table.
4157 struct ActionEntry {
4158 int ValueForTypeID; // The value to write - may not be equal to the type id.
4160 struct ActionEntry *Previous;
4163 /// PadRange - Structure holding a try-range and the associated landing pad.
4165 // The index of the landing pad.
4167 // The index of the begin and end labels in the landing pad's label lists.
4168 unsigned RangeIndex;
4171 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
4173 /// CallSiteEntry - Structure describing an entry in the call-site table.
4174 struct CallSiteEntry {
4175 // The 'try-range' is BeginLabel .. EndLabel.
4176 unsigned BeginLabel; // zero indicates the start of the function.
4177 unsigned EndLabel; // zero indicates the end of the function.
4178 // The landing pad starts at PadLabel.
4179 unsigned PadLabel; // zero indicates that there is no landing pad.
4183 void EmitExceptionTable() {
4184 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
4185 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
4186 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
4187 if (PadInfos.empty()) return;
4189 // Sort the landing pads in order of their type ids. This is used to fold
4190 // duplicate actions.
4191 SmallVector<const LandingPadInfo *, 64> LandingPads;
4192 LandingPads.reserve(PadInfos.size());
4193 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
4194 LandingPads.push_back(&PadInfos[i]);
4195 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
4197 // Negative type ids index into FilterIds, positive type ids index into
4198 // TypeInfos. The value written for a positive type id is just the type
4199 // id itself. For a negative type id, however, the value written is the
4200 // (negative) byte offset of the corresponding FilterIds entry. The byte
4201 // offset is usually equal to the type id, because the FilterIds entries
4202 // are written using a variable width encoding which outputs one byte per
4203 // entry as long as the value written is not too large, but can differ.
4204 // This kind of complication does not occur for positive type ids because
4205 // type infos are output using a fixed width encoding.
4206 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
4207 SmallVector<int, 16> FilterOffsets;
4208 FilterOffsets.reserve(FilterIds.size());
4210 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
4211 E = FilterIds.end(); I != E; ++I) {
4212 FilterOffsets.push_back(Offset);
4213 Offset -= TargetAsmInfo::getULEB128Size(*I);
4216 // Compute the actions table and gather the first action index for each
4217 // landing pad site.
4218 SmallVector<ActionEntry, 32> Actions;
4219 SmallVector<unsigned, 64> FirstActions;
4220 FirstActions.reserve(LandingPads.size());
4222 int FirstAction = 0;
4223 unsigned SizeActions = 0;
4224 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4225 const LandingPadInfo *LP = LandingPads[i];
4226 const std::vector<int> &TypeIds = LP->TypeIds;
4227 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
4228 unsigned SizeSiteActions = 0;
4230 if (NumShared < TypeIds.size()) {
4231 unsigned SizeAction = 0;
4232 ActionEntry *PrevAction = 0;
4235 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
4236 assert(Actions.size());
4237 PrevAction = &Actions.back();
4238 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
4239 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4240 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
4242 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4243 SizeAction += -PrevAction->NextAction;
4244 PrevAction = PrevAction->Previous;
4248 // Compute the actions.
4249 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
4250 int TypeID = TypeIds[I];
4251 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
4252 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
4253 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
4255 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
4256 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
4257 SizeSiteActions += SizeAction;
4259 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4260 Actions.push_back(Action);
4262 PrevAction = &Actions.back();
4265 // Record the first action of the landing pad site.
4266 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4267 } // else identical - re-use previous FirstAction
4269 FirstActions.push_back(FirstAction);
4271 // Compute this sites contribution to size.
4272 SizeActions += SizeSiteActions;
4275 // Compute the call-site table. The entry for an invoke has a try-range
4276 // containing the call, a non-zero landing pad and an appropriate action.
4277 // The entry for an ordinary call has a try-range containing the call and
4278 // zero for the landing pad and the action. Calls marked 'nounwind' have
4279 // no entry and must not be contained in the try-range of any entry - they
4280 // form gaps in the table. Entries must be ordered by try-range address.
4281 SmallVector<CallSiteEntry, 64> CallSites;
4283 RangeMapType PadMap;
4284 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4285 // by try-range labels when lowered). Ordinary calls do not, so appropriate
4286 // try-ranges for them need be deduced.
4287 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4288 const LandingPadInfo *LandingPad = LandingPads[i];
4289 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4290 unsigned BeginLabel = LandingPad->BeginLabels[j];
4291 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4292 PadRange P = { i, j };
4293 PadMap[BeginLabel] = P;
4297 // The end label of the previous invoke or nounwind try-range.
4298 unsigned LastLabel = 0;
4300 // Whether there is a potentially throwing instruction (currently this means
4301 // an ordinary call) between the end of the previous try-range and now.
4302 bool SawPotentiallyThrowing = false;
4304 // Whether the last callsite entry was for an invoke.
4305 bool PreviousIsInvoke = false;
4307 // Visit all instructions in order of address.
4308 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4310 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4312 if (!MI->isLabel()) {
4313 SawPotentiallyThrowing |= MI->getDesc().isCall();
4317 unsigned BeginLabel = MI->getOperand(0).getImm();
4318 assert(BeginLabel && "Invalid label!");
4320 // End of the previous try-range?
4321 if (BeginLabel == LastLabel)
4322 SawPotentiallyThrowing = false;
4324 // Beginning of a new try-range?
4325 RangeMapType::iterator L = PadMap.find(BeginLabel);
4326 if (L == PadMap.end())
4327 // Nope, it was just some random label.
4330 PadRange P = L->second;
4331 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4333 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4334 "Inconsistent landing pad map!");
4336 // If some instruction between the previous try-range and this one may
4337 // throw, create a call-site entry with no landing pad for the region
4338 // between the try-ranges.
4339 if (SawPotentiallyThrowing) {
4340 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4341 CallSites.push_back(Site);
4342 PreviousIsInvoke = false;
4345 LastLabel = LandingPad->EndLabels[P.RangeIndex];
4346 assert(BeginLabel && LastLabel && "Invalid landing pad!");
4348 if (LandingPad->LandingPadLabel) {
4349 // This try-range is for an invoke.
4350 CallSiteEntry Site = {BeginLabel, LastLabel,
4351 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4353 // Try to merge with the previous call-site.
4354 if (PreviousIsInvoke) {
4355 CallSiteEntry &Prev = CallSites.back();
4356 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4357 // Extend the range of the previous entry.
4358 Prev.EndLabel = Site.EndLabel;
4363 // Otherwise, create a new call-site.
4364 CallSites.push_back(Site);
4365 PreviousIsInvoke = true;
4368 PreviousIsInvoke = false;
4372 // If some instruction between the previous try-range and the end of the
4373 // function may throw, create a call-site entry with no landing pad for the
4374 // region following the try-range.
4375 if (SawPotentiallyThrowing) {
4376 CallSiteEntry Site = {LastLabel, 0, 0, 0};
4377 CallSites.push_back(Site);
4383 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
4384 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4385 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4386 unsigned SizeSites = CallSites.size() * (SiteStartSize +
4389 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4390 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4393 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4394 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4396 unsigned TypeOffset = sizeof(int8_t) + // Call site format
4397 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4398 SizeSites + SizeActions + SizeTypes;
4400 unsigned TotalSize = sizeof(int8_t) + // LPStart format
4401 sizeof(int8_t) + // TType format
4402 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4405 unsigned SizeAlign = (4 - TotalSize) & 3;
4407 // Begin the exception table.
4408 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4409 Asm->EmitAlignment(2, 0, 0, false);
4410 O << "GCC_except_table" << SubprogramCount << ":\n";
4411 for (unsigned i = 0; i != SizeAlign; ++i) {
4413 Asm->EOL("Padding");
4415 EmitLabel("exception", SubprogramCount);
4418 Asm->EmitInt8(DW_EH_PE_omit);
4419 Asm->EOL("LPStart format (DW_EH_PE_omit)");
4420 Asm->EmitInt8(DW_EH_PE_absptr);
4421 Asm->EOL("TType format (DW_EH_PE_absptr)");
4422 Asm->EmitULEB128Bytes(TypeOffset);
4423 Asm->EOL("TType base offset");
4424 Asm->EmitInt8(DW_EH_PE_udata4);
4425 Asm->EOL("Call site format (DW_EH_PE_udata4)");
4426 Asm->EmitULEB128Bytes(SizeSites);
4427 Asm->EOL("Call-site table length");
4429 // Emit the landing pad site information.
4430 for (unsigned i = 0; i < CallSites.size(); ++i) {
4431 CallSiteEntry &S = CallSites[i];
4432 const char *BeginTag;
4433 unsigned BeginNumber;
4435 if (!S.BeginLabel) {
4436 BeginTag = "eh_func_begin";
4437 BeginNumber = SubprogramCount;
4440 BeginNumber = S.BeginLabel;
4443 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4445 Asm->EOL("Region start");
4448 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4451 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4453 Asm->EOL("Region length");
4458 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4460 Asm->EOL("Landing pad");
4462 Asm->EmitULEB128Bytes(S.Action);
4466 // Emit the actions.
4467 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4468 ActionEntry &Action = Actions[I];
4470 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4471 Asm->EOL("TypeInfo index");
4472 Asm->EmitSLEB128Bytes(Action.NextAction);
4473 Asm->EOL("Next action");
4476 // Emit the type ids.
4477 for (unsigned M = TypeInfos.size(); M; --M) {
4478 GlobalVariable *GV = TypeInfos[M - 1];
4480 PrintRelDirective();
4483 O << Asm->getGlobalLinkName(GV);
4487 Asm->EOL("TypeInfo");
4490 // Emit the filter typeids.
4491 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4492 unsigned TypeID = FilterIds[j];
4493 Asm->EmitULEB128Bytes(TypeID);
4494 Asm->EOL("Filter TypeInfo index");
4497 Asm->EmitAlignment(2, 0, 0, false);
4501 //===--------------------------------------------------------------------===//
4502 // Main entry points.
4504 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4505 : Dwarf(OS, A, T, "eh")
4506 , shouldEmitTable(false)
4507 , shouldEmitMoves(false)
4508 , shouldEmitTableModule(false)
4509 , shouldEmitMovesModule(false)
4512 virtual ~DwarfException() {}
4514 /// SetModuleInfo - Set machine module information when it's known that pass
4515 /// manager has created it. Set by the target AsmPrinter.
4516 void SetModuleInfo(MachineModuleInfo *mmi) {
4520 /// BeginModule - Emit all exception information that should come prior to the
4522 void BeginModule(Module *M) {
4526 /// EndModule - Emit all exception information that should come after the
4529 if (shouldEmitMovesModule || shouldEmitTableModule) {
4530 const std::vector<Function *> Personalities = MMI->getPersonalities();
4531 for (unsigned i =0; i < Personalities.size(); ++i)
4532 EmitCommonEHFrame(Personalities[i], i);
4534 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4535 E = EHFrames.end(); I != E; ++I)
4540 /// BeginFunction - Gather pre-function exception information. Assumes being
4541 /// emitted immediately after the function entry point.
4542 void BeginFunction(MachineFunction *MF) {
4544 shouldEmitTable = shouldEmitMoves = false;
4545 if (MMI && TAI->doesSupportExceptionHandling()) {
4547 // Map all labels and get rid of any dead landing pads.
4548 MMI->TidyLandingPads();
4549 // If any landing pads survive, we need an EH table.
4550 if (MMI->getLandingPads().size())
4551 shouldEmitTable = true;
4553 // See if we need frame move info.
4554 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4555 shouldEmitMoves = true;
4557 if (shouldEmitMoves || shouldEmitTable)
4558 // Assumes in correct section after the entry point.
4559 EmitLabel("eh_func_begin", ++SubprogramCount);
4561 shouldEmitTableModule |= shouldEmitTable;
4562 shouldEmitMovesModule |= shouldEmitMoves;
4565 /// EndFunction - Gather and emit post-function exception information.
4567 void EndFunction() {
4568 if (shouldEmitMoves || shouldEmitTable) {
4569 EmitLabel("eh_func_end", SubprogramCount);
4570 EmitExceptionTable();
4572 // Save EH frame information
4574 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4576 MMI->getPersonalityIndex(),
4577 MF->getFrameInfo()->hasCalls(),
4578 !MMI->getLandingPads().empty(),
4579 MMI->getFrameMoves(),
4580 MF->getFunction()));
4585 } // End of namespace llvm
4587 //===----------------------------------------------------------------------===//
4589 /// Emit - Print the abbreviation using the specified Dwarf writer.
4591 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4592 // Emit its Dwarf tag type.
4593 DD.getAsm()->EmitULEB128Bytes(Tag);
4594 DD.getAsm()->EOL(TagString(Tag));
4596 // Emit whether it has children DIEs.
4597 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4598 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4600 // For each attribute description.
4601 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4602 const DIEAbbrevData &AttrData = Data[i];
4604 // Emit attribute type.
4605 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4606 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4609 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4610 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4613 // Mark end of abbreviation.
4614 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4615 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4619 void DIEAbbrev::print(std::ostream &O) {
4620 O << "Abbreviation @"
4621 << std::hex << (intptr_t)this << std::dec
4625 << ChildrenString(ChildrenFlag)
4628 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4630 << AttributeString(Data[i].getAttribute())
4632 << FormEncodingString(Data[i].getForm())
4636 void DIEAbbrev::dump() { print(cerr); }
4639 //===----------------------------------------------------------------------===//
4642 void DIEValue::dump() {
4647 //===----------------------------------------------------------------------===//
4649 /// EmitValue - Emit integer of appropriate size.
4651 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4653 case DW_FORM_flag: // Fall thru
4654 case DW_FORM_ref1: // Fall thru
4655 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4656 case DW_FORM_ref2: // Fall thru
4657 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4658 case DW_FORM_ref4: // Fall thru
4659 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4660 case DW_FORM_ref8: // Fall thru
4661 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4662 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4663 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4664 default: assert(0 && "DIE Value form not supported yet"); break;
4668 /// SizeOf - Determine size of integer value in bytes.
4670 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4672 case DW_FORM_flag: // Fall thru
4673 case DW_FORM_ref1: // Fall thru
4674 case DW_FORM_data1: return sizeof(int8_t);
4675 case DW_FORM_ref2: // Fall thru
4676 case DW_FORM_data2: return sizeof(int16_t);
4677 case DW_FORM_ref4: // Fall thru
4678 case DW_FORM_data4: return sizeof(int32_t);
4679 case DW_FORM_ref8: // Fall thru
4680 case DW_FORM_data8: return sizeof(int64_t);
4681 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4682 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4683 default: assert(0 && "DIE Value form not supported yet"); break;
4688 //===----------------------------------------------------------------------===//
4690 /// EmitValue - Emit string value.
4692 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4693 DD.getAsm()->EmitString(String);
4696 //===----------------------------------------------------------------------===//
4698 /// EmitValue - Emit label value.
4700 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4701 bool IsSmall = Form == DW_FORM_data4;
4702 DD.EmitReference(Label, false, IsSmall);
4705 /// SizeOf - Determine size of label value in bytes.
4707 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4708 if (Form == DW_FORM_data4) return 4;
4709 return DD.getTargetData()->getPointerSize();
4712 //===----------------------------------------------------------------------===//
4714 /// EmitValue - Emit label value.
4716 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4717 bool IsSmall = Form == DW_FORM_data4;
4718 DD.EmitReference(Label, false, IsSmall);
4721 /// SizeOf - Determine size of label value in bytes.
4723 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4724 if (Form == DW_FORM_data4) return 4;
4725 return DD.getTargetData()->getPointerSize();
4728 //===----------------------------------------------------------------------===//
4730 /// EmitValue - Emit delta value.
4732 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4733 bool IsSmall = Form == DW_FORM_data4;
4734 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4735 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4738 /// SizeOf - Determine size of delta value in bytes.
4740 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4741 if (Form == DW_FORM_data4) return 4;
4742 return DD.getTargetData()->getPointerSize();
4745 //===----------------------------------------------------------------------===//
4747 /// EmitValue - Emit delta value.
4749 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4750 bool IsSmall = Form == DW_FORM_data4;
4751 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4754 /// SizeOf - Determine size of delta value in bytes.
4756 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4757 if (Form == DW_FORM_data4) return 4;
4758 return DD.getTargetData()->getPointerSize();
4761 //===----------------------------------------------------------------------===//
4763 /// EmitValue - Emit debug information entry offset.
4765 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4766 DD.getAsm()->EmitInt32(Entry->getOffset());
4769 //===----------------------------------------------------------------------===//
4771 /// ComputeSize - calculate the size of the block.
4773 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4775 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4777 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4778 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4784 /// EmitValue - Emit block data.
4786 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4788 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4789 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4790 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4791 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4792 default: assert(0 && "Improper form for block"); break;
4795 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4797 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4799 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4803 /// SizeOf - Determine size of block data in bytes.
4805 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4807 case DW_FORM_block1: return Size + sizeof(int8_t);
4808 case DW_FORM_block2: return Size + sizeof(int16_t);
4809 case DW_FORM_block4: return Size + sizeof(int32_t);
4810 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4811 default: assert(0 && "Improper form for block"); break;
4816 //===----------------------------------------------------------------------===//
4817 /// DIE Implementation
4820 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4824 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4826 void DIE::AddSiblingOffset() {
4827 DIEInteger *DI = new DIEInteger(0);
4828 Values.insert(Values.begin(), DI);
4829 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4832 /// Profile - Used to gather unique data for the value folding set.
4834 void DIE::Profile(FoldingSetNodeID &ID) {
4837 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4838 ID.AddPointer(Children[i]);
4840 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4841 ID.AddPointer(Values[j]);
4845 void DIE::print(std::ostream &O, unsigned IncIndent) {
4846 static unsigned IndentCount = 0;
4847 IndentCount += IncIndent;
4848 const std::string Indent(IndentCount, ' ');
4849 bool isBlock = Abbrev.getTag() == 0;
4854 << "0x" << std::hex << (intptr_t)this << std::dec
4855 << ", Offset: " << Offset
4856 << ", Size: " << Size
4860 << TagString(Abbrev.getTag())
4862 << ChildrenString(Abbrev.getChildrenFlag());
4864 O << "Size: " << Size;
4868 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4871 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4875 O << AttributeString(Data[i].getAttribute());
4877 O << "Blk[" << i << "]";
4880 << FormEncodingString(Data[i].getForm())
4882 Values[i]->print(O);
4887 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4888 Children[j]->print(O, 4);
4891 if (!isBlock) O << "\n";
4892 IndentCount -= IncIndent;
4900 //===----------------------------------------------------------------------===//
4901 /// DwarfWriter Implementation
4904 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4907 DwarfWriter::~DwarfWriter() {
4912 /// BeginModule - Emit all Dwarf sections that should come prior to the
4914 void DwarfWriter::BeginModule(Module *M,
4915 MachineModuleInfo *MMI,
4916 raw_ostream &OS, AsmPrinter *A,
4917 const TargetAsmInfo *T) {
4918 DE = new DwarfException(OS, A, T);
4919 DD = new DwarfDebug(OS, A, T);
4922 DD->SetModuleInfo(MMI);
4923 DE->SetModuleInfo(MMI);
4926 /// EndModule - Emit all Dwarf sections that should come after the content.
4928 void DwarfWriter::EndModule() {
4933 /// BeginFunction - Gather pre-function debug information. Assumes being
4934 /// emitted immediately after the function entry point.
4935 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4936 DE->BeginFunction(MF);
4937 DD->BeginFunction(MF);
4940 /// EndFunction - Gather and emit post-function debug information.
4942 void DwarfWriter::EndFunction(MachineFunction *MF) {
4943 DD->EndFunction(MF);
4946 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4947 // Clear function debug information.