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/Type.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;
48 //===----------------------------------------------------------------------===//
50 /// Configuration values for initial hash set sizes (log2).
52 static const unsigned InitDiesSetSize = 9; // 512
53 static const unsigned InitAbbreviationsSetSize = 9; // 512
54 static const unsigned InitValuesSetSize = 9; // 512
56 //===----------------------------------------------------------------------===//
57 /// Forward declarations.
62 //===----------------------------------------------------------------------===//
63 /// DWLabel - Labels are used to track locations in the assembler file.
64 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
65 /// where the tag is a category of label (Ex. location) and number is a value
66 /// unique in that category.
69 /// Tag - Label category tag. Should always be a staticly declared C string.
73 /// Number - Value to make label unique.
77 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
79 void Profile(FoldingSetNodeID &ID) const {
80 ID.AddString(std::string(Tag));
81 ID.AddInteger(Number);
85 void print(std::ostream *O) const {
88 void print(std::ostream &O) const {
90 if (Number) O << Number;
95 //===----------------------------------------------------------------------===//
96 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
97 /// Dwarf abbreviation.
100 /// Attribute - Dwarf attribute code.
104 /// Form - Dwarf form code.
109 DIEAbbrevData(unsigned A, unsigned F)
115 unsigned getAttribute() const { return Attribute; }
116 unsigned getForm() const { return Form; }
118 /// Profile - Used to gather unique data for the abbreviation folding set.
120 void Profile(FoldingSetNodeID &ID)const {
121 ID.AddInteger(Attribute);
126 //===----------------------------------------------------------------------===//
127 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
128 /// information object.
129 class DIEAbbrev : public FoldingSetNode {
131 /// Tag - Dwarf tag code.
135 /// Unique number for node.
139 /// ChildrenFlag - Dwarf children flag.
141 unsigned ChildrenFlag;
143 /// Data - Raw data bytes for abbreviation.
145 SmallVector<DIEAbbrevData, 8> Data;
149 DIEAbbrev(unsigned T, unsigned C)
157 unsigned getTag() const { return Tag; }
158 unsigned getNumber() const { return Number; }
159 unsigned getChildrenFlag() const { return ChildrenFlag; }
160 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
161 void setTag(unsigned T) { Tag = T; }
162 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
163 void setNumber(unsigned N) { Number = N; }
165 /// AddAttribute - Adds another set of attribute information to the
167 void AddAttribute(unsigned Attribute, unsigned Form) {
168 Data.push_back(DIEAbbrevData(Attribute, Form));
171 /// AddFirstAttribute - Adds a set of attribute information to the front
172 /// of the abbreviation.
173 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
174 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
177 /// Profile - Used to gather unique data for the abbreviation folding set.
179 void Profile(FoldingSetNodeID &ID) {
181 ID.AddInteger(ChildrenFlag);
183 // For each attribute description.
184 for (unsigned i = 0, N = Data.size(); i < N; ++i)
188 /// Emit - Print the abbreviation using the specified Dwarf writer.
190 void Emit(const DwarfDebug &DD) const;
193 void print(std::ostream *O) {
196 void print(std::ostream &O);
201 //===----------------------------------------------------------------------===//
202 /// DIE - A structured debug information entry. Has an abbreviation which
203 /// describes it's organization.
204 class DIE : public FoldingSetNode {
206 /// Abbrev - Buffer for constructing abbreviation.
210 /// Offset - Offset in debug info section.
214 /// Size - Size of instance + children.
220 std::vector<DIE *> Children;
222 /// Attributes values.
224 SmallVector<DIEValue*, 32> Values;
227 explicit DIE(unsigned Tag)
228 : Abbrev(Tag, DW_CHILDREN_no)
237 DIEAbbrev &getAbbrev() { return Abbrev; }
238 unsigned getAbbrevNumber() const {
239 return Abbrev.getNumber();
241 unsigned getTag() const { return Abbrev.getTag(); }
242 unsigned getOffset() const { return Offset; }
243 unsigned getSize() const { return Size; }
244 const std::vector<DIE *> &getChildren() const { return Children; }
245 SmallVector<DIEValue*, 32> &getValues() { return Values; }
246 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
247 void setOffset(unsigned O) { Offset = O; }
248 void setSize(unsigned S) { Size = S; }
250 /// AddValue - Add a value and attributes to a DIE.
252 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
253 Abbrev.AddAttribute(Attribute, Form);
254 Values.push_back(Value);
257 /// SiblingOffset - Return the offset of the debug information entry's
259 unsigned SiblingOffset() const { return Offset + Size; }
261 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
263 void AddSiblingOffset();
265 /// AddChild - Add a child to the DIE.
267 void AddChild(DIE *Child) {
268 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
269 Children.push_back(Child);
272 /// Detach - Detaches objects connected to it after copying.
278 /// Profile - Used to gather unique data for the value folding set.
280 void Profile(FoldingSetNodeID &ID) ;
283 void print(std::ostream *O, unsigned IncIndent = 0) {
284 if (O) print(*O, IncIndent);
286 void print(std::ostream &O, unsigned IncIndent = 0);
291 //===----------------------------------------------------------------------===//
292 /// DIEValue - A debug information entry value.
294 class DIEValue : public FoldingSetNode {
307 /// Type - Type of data stored in the value.
311 explicit DIEValue(unsigned T)
314 virtual ~DIEValue() {}
317 unsigned getType() const { return Type; }
319 // Implement isa/cast/dyncast.
320 static bool classof(const DIEValue *) { return true; }
322 /// EmitValue - Emit value via the Dwarf writer.
324 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
326 /// SizeOf - Return the size of a value in bytes.
328 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
330 /// Profile - Used to gather unique data for the value folding set.
332 virtual void Profile(FoldingSetNodeID &ID) = 0;
335 void print(std::ostream *O) {
338 virtual void print(std::ostream &O) = 0;
343 //===----------------------------------------------------------------------===//
344 /// DWInteger - An integer value DIE.
346 class DIEInteger : public DIEValue {
351 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
353 // Implement isa/cast/dyncast.
354 static bool classof(const DIEInteger *) { return true; }
355 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
357 /// BestForm - Choose the best form for integer.
359 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
361 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
362 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
363 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
365 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
366 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
367 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
369 return DW_FORM_data8;
372 /// EmitValue - Emit integer of appropriate size.
374 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
376 /// SizeOf - Determine size of integer value in bytes.
378 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
380 /// Profile - Used to gather unique data for the value folding set.
382 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
383 ID.AddInteger(isInteger);
384 ID.AddInteger(Integer);
386 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
389 virtual void print(std::ostream &O) {
390 O << "Int: " << (int64_t)Integer
391 << " 0x" << std::hex << Integer << std::dec;
396 //===----------------------------------------------------------------------===//
397 /// DIEString - A string value DIE.
399 class DIEString : public DIEValue {
401 const std::string String;
403 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
405 // Implement isa/cast/dyncast.
406 static bool classof(const DIEString *) { return true; }
407 static bool classof(const DIEValue *S) { return S->Type == isString; }
409 /// EmitValue - Emit string value.
411 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
413 /// SizeOf - Determine size of string value in bytes.
415 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
416 return String.size() + sizeof(char); // sizeof('\0');
419 /// Profile - Used to gather unique data for the value folding set.
421 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
422 ID.AddInteger(isString);
423 ID.AddString(String);
425 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
428 virtual void print(std::ostream &O) {
429 O << "Str: \"" << String << "\"";
434 //===----------------------------------------------------------------------===//
435 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
437 class DIEDwarfLabel : public DIEValue {
442 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
444 // Implement isa/cast/dyncast.
445 static bool classof(const DIEDwarfLabel *) { return true; }
446 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
448 /// EmitValue - Emit label value.
450 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
452 /// SizeOf - Determine size of label value in bytes.
454 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
456 /// Profile - Used to gather unique data for the value folding set.
458 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
459 ID.AddInteger(isLabel);
462 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
465 virtual void print(std::ostream &O) {
473 //===----------------------------------------------------------------------===//
474 /// DIEObjectLabel - A label to an object in code or data.
476 class DIEObjectLabel : public DIEValue {
478 const std::string Label;
480 explicit DIEObjectLabel(const std::string &L)
481 : DIEValue(isAsIsLabel), Label(L) {}
483 // Implement isa/cast/dyncast.
484 static bool classof(const DIEObjectLabel *) { return true; }
485 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
487 /// EmitValue - Emit label value.
489 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
491 /// SizeOf - Determine size of label value in bytes.
493 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
495 /// Profile - Used to gather unique data for the value folding set.
497 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
498 ID.AddInteger(isAsIsLabel);
501 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
504 virtual void print(std::ostream &O) {
505 O << "Obj: " << Label;
510 //===----------------------------------------------------------------------===//
511 /// DIESectionOffset - A section offset DIE.
513 class DIESectionOffset : public DIEValue {
516 const DWLabel Section;
520 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
521 bool isEH = false, bool useSet = true)
522 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
523 IsEH(isEH), UseSet(useSet) {}
525 // Implement isa/cast/dyncast.
526 static bool classof(const DIESectionOffset *) { return true; }
527 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
529 /// EmitValue - Emit section offset.
531 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
533 /// SizeOf - Determine size of section offset value in bytes.
535 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
537 /// Profile - Used to gather unique data for the value folding set.
539 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
540 const DWLabel &Section) {
541 ID.AddInteger(isSectionOffset);
544 // IsEH and UseSet are specific to the Label/Section that we will emit
545 // the offset for; so Label/Section are enough for uniqueness.
547 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
550 virtual void print(std::ostream &O) {
555 O << "-" << IsEH << "-" << UseSet;
560 //===----------------------------------------------------------------------===//
561 /// DIEDelta - A simple label difference DIE.
563 class DIEDelta : public DIEValue {
565 const DWLabel LabelHi;
566 const DWLabel LabelLo;
568 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
569 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
571 // Implement isa/cast/dyncast.
572 static bool classof(const DIEDelta *) { return true; }
573 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
575 /// EmitValue - Emit delta value.
577 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
579 /// SizeOf - Determine size of delta value in bytes.
581 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
583 /// Profile - Used to gather unique data for the value folding set.
585 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
586 const DWLabel &LabelLo) {
587 ID.AddInteger(isDelta);
591 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
594 virtual void print(std::ostream &O) {
603 //===----------------------------------------------------------------------===//
604 /// DIEntry - A pointer to another debug information entry. An instance of this
605 /// class can also be used as a proxy for a debug information entry not yet
606 /// defined (ie. types.)
607 class DIEntry : public DIEValue {
611 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
613 // Implement isa/cast/dyncast.
614 static bool classof(const DIEntry *) { return true; }
615 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
617 /// EmitValue - Emit debug information entry offset.
619 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
621 /// SizeOf - Determine size of debug information entry in bytes.
623 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
624 return sizeof(int32_t);
627 /// Profile - Used to gather unique data for the value folding set.
629 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
630 ID.AddInteger(isEntry);
631 ID.AddPointer(Entry);
633 virtual void Profile(FoldingSetNodeID &ID) {
634 ID.AddInteger(isEntry);
637 ID.AddPointer(Entry);
644 virtual void print(std::ostream &O) {
645 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
650 //===----------------------------------------------------------------------===//
651 /// DIEBlock - A block of values. Primarily used for location expressions.
653 class DIEBlock : public DIEValue, public DIE {
655 unsigned Size; // Size in bytes excluding size header.
665 // Implement isa/cast/dyncast.
666 static bool classof(const DIEBlock *) { return true; }
667 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
669 /// ComputeSize - calculate the size of the block.
671 unsigned ComputeSize(DwarfDebug &DD);
673 /// BestForm - Choose the best form for data.
675 unsigned BestForm() const {
676 if ((unsigned char)Size == Size) return DW_FORM_block1;
677 if ((unsigned short)Size == Size) return DW_FORM_block2;
678 if ((unsigned int)Size == Size) return DW_FORM_block4;
679 return DW_FORM_block;
682 /// EmitValue - Emit block data.
684 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
686 /// SizeOf - Determine size of block data in bytes.
688 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
691 /// Profile - Used to gather unique data for the value folding set.
693 virtual void Profile(FoldingSetNodeID &ID) {
694 ID.AddInteger(isBlock);
699 virtual void print(std::ostream &O) {
706 //===----------------------------------------------------------------------===//
707 /// CompileUnit - This dwarf writer support class manages information associate
708 /// with a source file.
711 /// Desc - Compile unit debug descriptor.
713 CompileUnitDesc *Desc;
715 /// ID - File identifier for source.
719 /// Die - Compile unit debug information entry.
723 /// DescToDieMap - Tracks the mapping of unit level debug informaton
724 /// descriptors to debug information entries.
725 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
726 DenseMap<GlobalVariable *, DIE *> GVToDieMap;
728 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
729 /// descriptors to debug information entries using a DIEntry proxy.
730 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
731 DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
733 /// Globals - A map of globally visible named entities for this unit.
735 std::map<std::string, DIE *> Globals;
737 /// DiesSet - Used to uniquely define dies within the compile unit.
739 FoldingSet<DIE> DiesSet;
741 /// Dies - List of all dies in the compile unit.
743 std::vector<DIE *> Dies;
746 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
755 , DiesSet(InitDiesSetSize)
762 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
767 CompileUnitDesc *getDesc() const { return Desc; }
768 unsigned getID() const { return ID; }
769 DIE* getDie() const { return Die; }
770 std::map<std::string, DIE *> &getGlobals() { return Globals; }
772 /// hasContent - Return true if this compile unit has something to write out.
774 bool hasContent() const {
775 return !Die->getChildren().empty();
778 /// AddGlobal - Add a new global entity to the compile unit.
780 void AddGlobal(const std::string &Name, DIE *Die) {
784 /// getDieMapSlotFor - Returns the debug information entry map slot for the
785 /// specified debug descriptor.
786 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
787 return DescToDieMap[DID];
789 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
790 return GVToDieMap[GV];
793 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
794 /// specified debug descriptor.
795 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
796 return DescToDIEntryMap[DID];
798 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
799 return GVToDIEntryMap[GV];
802 /// AddDie - Adds or interns the DIE to the compile unit.
804 DIE *AddDie(DIE &Buffer) {
808 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
811 Die = new DIE(Buffer);
812 DiesSet.InsertNode(Die, Where);
813 this->Die->AddChild(Die);
821 //===----------------------------------------------------------------------===//
822 /// Dwarf - Emits general Dwarf directives.
828 //===--------------------------------------------------------------------===//
829 // Core attributes used by the Dwarf writer.
833 /// O - Stream to .s file.
837 /// Asm - Target of Dwarf emission.
841 /// TAI - Target asm information.
842 const TargetAsmInfo *TAI;
844 /// TD - Target data.
845 const TargetData *TD;
847 /// RI - Register Information.
848 const TargetRegisterInfo *RI;
850 /// M - Current module.
854 /// MF - Current machine function.
858 /// MMI - Collected machine module information.
860 MachineModuleInfo *MMI;
862 /// SubprogramCount - The running count of functions being compiled.
864 unsigned SubprogramCount;
866 /// Flavor - A unique string indicating what dwarf producer this is, used to
868 const char * const Flavor;
871 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
876 , TD(Asm->TM.getTargetData())
877 , RI(Asm->TM.getRegisterInfo())
889 //===--------------------------------------------------------------------===//
892 AsmPrinter *getAsm() const { return Asm; }
893 MachineModuleInfo *getMMI() const { return MMI; }
894 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
895 const TargetData *getTargetData() const { return TD; }
897 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
899 if (isInSection && TAI->getDwarfSectionOffsetDirective())
900 O << TAI->getDwarfSectionOffsetDirective();
901 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
902 O << TAI->getData32bitsDirective();
904 O << TAI->getData64bitsDirective();
907 /// PrintLabelName - Print label name in form used by Dwarf writer.
909 void PrintLabelName(DWLabel Label) const {
910 PrintLabelName(Label.Tag, Label.Number);
912 void PrintLabelName(const char *Tag, unsigned Number) const {
913 O << TAI->getPrivateGlobalPrefix() << Tag;
914 if (Number) O << Number;
917 void PrintLabelName(const char *Tag, unsigned Number,
918 const char *Suffix) const {
919 O << TAI->getPrivateGlobalPrefix() << Tag;
920 if (Number) O << Number;
924 /// EmitLabel - Emit location label for internal use by Dwarf.
926 void EmitLabel(DWLabel Label) const {
927 EmitLabel(Label.Tag, Label.Number);
929 void EmitLabel(const char *Tag, unsigned Number) const {
930 PrintLabelName(Tag, Number);
934 /// EmitReference - Emit a reference to a label.
936 void EmitReference(DWLabel Label, bool IsPCRelative = false,
937 bool Force32Bit = false) const {
938 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
940 void EmitReference(const char *Tag, unsigned Number,
941 bool IsPCRelative = false, bool Force32Bit = false) const {
942 PrintRelDirective(Force32Bit);
943 PrintLabelName(Tag, Number);
945 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
947 void EmitReference(const std::string &Name, bool IsPCRelative = false,
948 bool Force32Bit = false) const {
949 PrintRelDirective(Force32Bit);
953 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
956 /// EmitDifference - Emit the difference between two labels. Some
957 /// assemblers do not behave with absolute expressions with data directives,
958 /// so there is an option (needsSet) to use an intermediary set expression.
959 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
960 bool IsSmall = false) {
961 EmitDifference(LabelHi.Tag, LabelHi.Number,
962 LabelLo.Tag, LabelLo.Number,
965 void EmitDifference(const char *TagHi, unsigned NumberHi,
966 const char *TagLo, unsigned NumberLo,
967 bool IsSmall = false) {
968 if (TAI->needsSet()) {
970 PrintLabelName("set", SetCounter, Flavor);
972 PrintLabelName(TagHi, NumberHi);
974 PrintLabelName(TagLo, NumberLo);
977 PrintRelDirective(IsSmall);
978 PrintLabelName("set", SetCounter, Flavor);
981 PrintRelDirective(IsSmall);
983 PrintLabelName(TagHi, NumberHi);
985 PrintLabelName(TagLo, NumberLo);
989 void EmitSectionOffset(const char* Label, const char* Section,
990 unsigned LabelNumber, unsigned SectionNumber,
991 bool IsSmall = false, bool isEH = false,
992 bool useSet = true) {
993 bool printAbsolute = false;
995 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
997 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
999 if (TAI->needsSet() && useSet) {
1001 PrintLabelName("set", SetCounter, Flavor);
1003 PrintLabelName(Label, LabelNumber);
1005 if (!printAbsolute) {
1007 PrintLabelName(Section, SectionNumber);
1011 PrintRelDirective(IsSmall);
1013 PrintLabelName("set", SetCounter, Flavor);
1016 PrintRelDirective(IsSmall, true);
1018 PrintLabelName(Label, LabelNumber);
1020 if (!printAbsolute) {
1022 PrintLabelName(Section, SectionNumber);
1027 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1029 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1030 const std::vector<MachineMove> &Moves, bool isEH) {
1032 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1033 TargetFrameInfo::StackGrowsUp ?
1034 TD->getPointerSize() : -TD->getPointerSize();
1035 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1037 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1038 const MachineMove &Move = Moves[i];
1039 unsigned LabelID = Move.getLabelID();
1042 LabelID = MMI->MappedLabel(LabelID);
1044 // Throw out move if the label is invalid.
1045 if (!LabelID) continue;
1048 const MachineLocation &Dst = Move.getDestination();
1049 const MachineLocation &Src = Move.getSource();
1051 // Advance row if new location.
1052 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1053 Asm->EmitInt8(DW_CFA_advance_loc4);
1054 Asm->EOL("DW_CFA_advance_loc4");
1055 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1058 BaseLabelID = LabelID;
1059 BaseLabel = "label";
1063 // If advancing cfa.
1064 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1066 if (Src.getReg() == MachineLocation::VirtualFP) {
1067 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1068 Asm->EOL("DW_CFA_def_cfa_offset");
1070 Asm->EmitInt8(DW_CFA_def_cfa);
1071 Asm->EOL("DW_CFA_def_cfa");
1072 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1073 Asm->EOL("Register");
1076 int Offset = -Src.getOffset();
1078 Asm->EmitULEB128Bytes(Offset);
1081 assert(0 && "Machine move no supported yet.");
1083 } else if (Src.isReg() &&
1084 Src.getReg() == MachineLocation::VirtualFP) {
1086 Asm->EmitInt8(DW_CFA_def_cfa_register);
1087 Asm->EOL("DW_CFA_def_cfa_register");
1088 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1089 Asm->EOL("Register");
1091 assert(0 && "Machine move no supported yet.");
1094 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1095 int Offset = Dst.getOffset() / stackGrowth;
1098 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1099 Asm->EOL("DW_CFA_offset_extended_sf");
1100 Asm->EmitULEB128Bytes(Reg);
1102 Asm->EmitSLEB128Bytes(Offset);
1104 } else if (Reg < 64) {
1105 Asm->EmitInt8(DW_CFA_offset + Reg);
1107 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1110 Asm->EmitULEB128Bytes(Offset);
1113 Asm->EmitInt8(DW_CFA_offset_extended);
1114 Asm->EOL("DW_CFA_offset_extended");
1115 Asm->EmitULEB128Bytes(Reg);
1117 Asm->EmitULEB128Bytes(Offset);
1126 //===----------------------------------------------------------------------===//
1127 /// DwarfDebug - Emits Dwarf debug directives.
1129 class DwarfDebug : public Dwarf {
1132 //===--------------------------------------------------------------------===//
1133 // Attributes used to construct specific Dwarf sections.
1136 /// CompileUnits - All the compile units involved in this build. The index
1137 /// of each entry in this vector corresponds to the sources in MMI.
1138 std::vector<CompileUnit *> CompileUnits;
1140 /// AbbreviationsSet - Used to uniquely define abbreviations.
1142 FoldingSet<DIEAbbrev> AbbreviationsSet;
1144 /// Abbreviations - A list of all the unique abbreviations in use.
1146 std::vector<DIEAbbrev *> Abbreviations;
1148 /// ValuesSet - Used to uniquely define values.
1150 FoldingSet<DIEValue> ValuesSet;
1152 /// Values - A list of all the unique values in use.
1154 std::vector<DIEValue *> Values;
1156 /// StringPool - A UniqueVector of strings used by indirect references.
1158 UniqueVector<std::string> StringPool;
1160 /// UnitMap - Map debug information descriptor to compile unit.
1162 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1164 /// SectionMap - Provides a unique id per text section.
1166 UniqueVector<const Section*> SectionMap;
1168 /// SectionSourceLines - Tracks line numbers per text section.
1170 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1172 /// didInitial - Flag to indicate if initial emission has been done.
1176 /// shouldEmit - Flag to indicate if debug information should be emitted.
1180 struct FunctionDebugFrameInfo {
1182 std::vector<MachineMove> Moves;
1184 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1185 Number(Num), Moves(M) { }
1188 std::vector<FunctionDebugFrameInfo> DebugFrames;
1192 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1194 bool ShouldEmitDwarf() const { return shouldEmit; }
1196 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1198 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1199 // Profile the node so that we can make it unique.
1200 FoldingSetNodeID ID;
1203 // Check the set for priors.
1204 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1206 // If it's newly added.
1207 if (InSet == &Abbrev) {
1208 // Add to abbreviation list.
1209 Abbreviations.push_back(&Abbrev);
1210 // Assign the vector position + 1 as its number.
1211 Abbrev.setNumber(Abbreviations.size());
1213 // Assign existing abbreviation number.
1214 Abbrev.setNumber(InSet->getNumber());
1218 /// NewString - Add a string to the constant pool and returns a label.
1220 DWLabel NewString(const std::string &String) {
1221 unsigned StringID = StringPool.insert(String);
1222 return DWLabel("string", StringID);
1225 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1227 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1231 FoldingSetNodeID ID;
1232 DIEntry::Profile(ID, Entry);
1234 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1236 if (Value) return Value;
1238 Value = new DIEntry(Entry);
1239 ValuesSet.InsertNode(Value, Where);
1241 Value = new DIEntry(Entry);
1244 Values.push_back(Value);
1248 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1250 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1251 Value->Entry = Entry;
1252 // Add to values set if not already there. If it is, we merely have a
1253 // duplicate in the values list (no harm.)
1254 ValuesSet.GetOrInsertNode(Value);
1257 /// AddUInt - Add an unsigned integer attribute data and value.
1259 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1260 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1262 FoldingSetNodeID ID;
1263 DIEInteger::Profile(ID, Integer);
1265 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1267 Value = new DIEInteger(Integer);
1268 ValuesSet.InsertNode(Value, Where);
1269 Values.push_back(Value);
1272 Die->AddValue(Attribute, Form, Value);
1275 /// AddSInt - Add an signed integer attribute data and value.
1277 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1278 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1280 FoldingSetNodeID ID;
1281 DIEInteger::Profile(ID, (uint64_t)Integer);
1283 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1285 Value = new DIEInteger(Integer);
1286 ValuesSet.InsertNode(Value, Where);
1287 Values.push_back(Value);
1290 Die->AddValue(Attribute, Form, Value);
1293 /// AddString - Add a std::string attribute data and value.
1295 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1296 const std::string &String) {
1297 FoldingSetNodeID ID;
1298 DIEString::Profile(ID, String);
1300 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1302 Value = new DIEString(String);
1303 ValuesSet.InsertNode(Value, Where);
1304 Values.push_back(Value);
1307 Die->AddValue(Attribute, Form, Value);
1310 /// AddLabel - Add a Dwarf label attribute data and value.
1312 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1313 const DWLabel &Label) {
1314 FoldingSetNodeID ID;
1315 DIEDwarfLabel::Profile(ID, Label);
1317 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1319 Value = new DIEDwarfLabel(Label);
1320 ValuesSet.InsertNode(Value, Where);
1321 Values.push_back(Value);
1324 Die->AddValue(Attribute, Form, Value);
1327 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1329 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1330 const std::string &Label) {
1331 FoldingSetNodeID ID;
1332 DIEObjectLabel::Profile(ID, Label);
1334 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1336 Value = new DIEObjectLabel(Label);
1337 ValuesSet.InsertNode(Value, Where);
1338 Values.push_back(Value);
1341 Die->AddValue(Attribute, Form, Value);
1344 /// AddSectionOffset - Add a section offset label attribute data and value.
1346 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1347 const DWLabel &Label, const DWLabel &Section,
1348 bool isEH = false, bool useSet = true) {
1349 FoldingSetNodeID ID;
1350 DIESectionOffset::Profile(ID, Label, Section);
1352 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1354 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1355 ValuesSet.InsertNode(Value, Where);
1356 Values.push_back(Value);
1359 Die->AddValue(Attribute, Form, Value);
1362 /// AddDelta - Add a label delta attribute data and value.
1364 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1365 const DWLabel &Hi, const DWLabel &Lo) {
1366 FoldingSetNodeID ID;
1367 DIEDelta::Profile(ID, Hi, Lo);
1369 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1371 Value = new DIEDelta(Hi, Lo);
1372 ValuesSet.InsertNode(Value, Where);
1373 Values.push_back(Value);
1376 Die->AddValue(Attribute, Form, Value);
1379 /// AddDIEntry - Add a DIE attribute data and value.
1381 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1382 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1385 /// AddBlock - Add block data.
1387 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1388 Block->ComputeSize(*this);
1389 FoldingSetNodeID ID;
1392 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1395 ValuesSet.InsertNode(Value, Where);
1396 Values.push_back(Value);
1398 // Already exists, reuse the previous one.
1400 Block = cast<DIEBlock>(Value);
1403 Die->AddValue(Attribute, Block->BestForm(), Value);
1408 /// AddSourceLine - Add location information to specified debug information
1410 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1412 CompileUnit *FileUnit = FindCompileUnit(File);
1413 unsigned FileID = FileUnit->getID();
1414 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1415 AddUInt(Die, DW_AT_decl_line, 0, Line);
1419 /// AddAddress - Add an address attribute to a die based on the location
1421 void AddAddress(DIE *Die, unsigned Attribute,
1422 const MachineLocation &Location) {
1423 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1424 DIEBlock *Block = new DIEBlock();
1426 if (Location.isReg()) {
1428 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1430 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1431 AddUInt(Block, 0, DW_FORM_udata, Reg);
1435 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1437 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1438 AddUInt(Block, 0, DW_FORM_udata, Reg);
1440 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1443 AddBlock(Die, Attribute, 0, Block);
1446 /// AddBasicType - Add a new basic type attribute to the specified entity.
1448 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1449 const std::string &Name,
1450 unsigned Encoding, unsigned Size) {
1452 DIE Buffer(DW_TAG_base_type);
1453 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1454 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1455 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1456 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1457 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1460 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1462 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1463 DIE Buffer(DW_TAG_pointer_type);
1464 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1465 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1466 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1467 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1470 /// AddType - Add a new type attribute to the specified entity.
1472 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1474 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1476 // Check for pre-existence.
1477 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1479 // If it exists then use the existing value.
1481 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1485 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1486 // FIXME - Not sure why programs and variables are coming through here.
1487 // Short cut for handling subprogram types (not really a TyDesc.)
1488 AddPointerType(Entity, Unit, SubprogramTy->getName());
1489 } else if (GlobalVariableDesc *GlobalTy =
1490 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1491 // FIXME - Not sure why programs and variables are coming through here.
1492 // Short cut for handling global variable types (not really a TyDesc.)
1493 AddPointerType(Entity, Unit, GlobalTy->getName());
1496 Slot = NewDIEntry();
1499 DIE Buffer(DW_TAG_base_type);
1500 ConstructType(Buffer, TyDesc, Unit);
1502 // Add debug information entry to entity and unit.
1503 DIE *Die = Unit->AddDie(Buffer);
1504 SetDIEntry(Slot, Die);
1505 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1510 /// AddType - Add a new type attribute to the specified entity.
1511 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1513 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1517 // Check for pre-existence.
1518 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1519 // If it exists then use the existing value.
1521 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1526 Slot = NewDIEntry();
1529 DIE Buffer(DW_TAG_base_type);
1530 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1531 ConstructTypeDIE(DW_Unit, Buffer, BT);
1532 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1533 ConstructTypeDIE(DW_Unit, Buffer, DT);
1534 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1535 ConstructTypeDIE(DW_Unit, Buffer, CT);
1537 // Add debug information entry to entity and unit.
1538 DIE *Die = DW_Unit->AddDie(Buffer);
1539 SetDIEntry(Slot, Die);
1540 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1543 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1544 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1547 // Get core information.
1548 const std::string &Name = BTy->getName();
1549 Buffer.setTag(DW_TAG_base_type);
1550 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1551 // Add name if not anonymous or intermediate type.
1553 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1554 uint64_t Size = BTy->getSizeInBits() >> 3;
1555 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1558 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1559 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1560 DIDerivedType *DTy) {
1562 // Get core information.
1563 const std::string &Name = DTy->getName();
1564 uint64_t Size = DTy->getSizeInBits() >> 3;
1565 unsigned Tag = DTy->getTag();
1566 // FIXME - Workaround for templates.
1567 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1570 // Map to main type, void will not have a type.
1571 DIType FromTy = DTy->getTypeDerivedFrom();
1572 AddType(DW_Unit, &Buffer, FromTy);
1574 // Add name if not anonymous or intermediate type.
1575 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1577 // Add size if non-zero (derived types might be zero-sized.)
1579 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1581 // Add source line info if available and TyDesc is not a forward
1583 // FIXME - Enable this. if (!DTy->isForwardDecl())
1584 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1587 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1588 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1589 DICompositeType *CTy) {
1591 // Get core information.
1592 const std::string &Name = CTy->getName();
1593 uint64_t Size = CTy->getSizeInBits() >> 3;
1594 unsigned Tag = CTy->getTag();
1596 case DW_TAG_vector_type:
1597 case DW_TAG_array_type:
1598 ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1600 //FIXME - Enable this.
1601 // case DW_TAG_enumeration_type:
1602 // DIArray Elements = CTy->getTypeArray();
1603 // // Add enumerators to enumeration type.
1604 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1605 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1607 case DW_TAG_subroutine_type:
1609 // Add prototype flag.
1610 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1611 DIArray Elements = CTy->getTypeArray();
1613 DIDescriptor RTy = Elements.getElement(0);
1614 if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1615 AddType(DW_Unit, &Buffer, *BT);
1616 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1617 AddType(DW_Unit, &Buffer, *DT);
1618 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1619 AddType(DW_Unit, &Buffer, *CT);
1621 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1623 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1624 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1625 DIDescriptor Ty = Elements.getElement(i);
1626 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1627 AddType(DW_Unit, &Buffer, *BT);
1628 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1629 AddType(DW_Unit, &Buffer, *DT);
1630 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1631 AddType(DW_Unit, &Buffer, *CT);
1632 Buffer.AddChild(Arg);
1636 case DW_TAG_structure_type:
1637 case DW_TAG_union_type:
1639 // Add elements to structure type.
1640 DIArray Elements = CTy->getTypeArray();
1641 // Add elements to structure type.
1642 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1643 DIDescriptor Element = Elements.getElement(i);
1644 if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1645 ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1646 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1647 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1648 else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1649 ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1657 // Add name if not anonymous or intermediate type.
1658 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1660 // Add size if non-zero (derived types might be zero-sized.)
1662 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1664 // Add zero size even if it is not a forward declaration.
1665 // FIXME - Enable this.
1666 // if (!CTy->isDefinition())
1667 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1669 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1672 // Add source line info if available and TyDesc is not a forward
1674 // FIXME - Enable this.
1675 // if (CTy->isForwardDecl())
1676 // AddSourceLine(&Buffer, *CTy);
1679 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1680 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1681 int64_t L = SR->getLo();
1682 int64_t H = SR->getHi();
1683 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1685 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1687 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1688 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1690 Buffer.AddChild(DW_Subrange);
1693 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1694 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1695 DICompositeType *CTy) {
1696 Buffer.setTag(DW_TAG_array_type);
1697 if (CTy->getTag() == DW_TAG_vector_type)
1698 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1700 DIArray Elements = CTy->getTypeArray();
1701 // FIXME - Enable this.
1702 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1704 // Construct an anonymous type for index type.
1705 DIE IdxBuffer(DW_TAG_base_type);
1706 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1707 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1708 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1710 // Add subranges to array type.
1711 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1712 DIDescriptor Element = Elements.getElement(i);
1713 if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1714 ConstructSubrangeDIE(Buffer, SR, IndexTy);
1718 /// ConstructEnumTypeDIE - Construct enum type DIE from
1720 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1721 DIE &Buffer, DIEnumerator *ETy) {
1723 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1724 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1725 int64_t Value = ETy->getEnumValue();
1726 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1727 Buffer.AddChild(Enumerator);
1730 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1731 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1732 DIE &Buffer, DIGlobalVariable *V) {
1734 DIE *VariableDie = new DIE(DW_TAG_variable);
1735 const std::string &LinkageName = V->getLinkageName();
1736 if (!LinkageName.empty())
1737 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1739 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1740 AddType(DW_Unit, VariableDie, V->getType());
1741 if (!V->isLocalToUnit())
1742 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1743 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1744 Buffer.AddChild(VariableDie);
1747 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1748 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1749 DIE &Buffer, DISubprogram *SP,
1750 bool IsConstructor = false) {
1751 DIE *Method = new DIE(DW_TAG_subprogram);
1752 AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1753 const std::string &LinkageName = SP->getLinkageName();
1754 if (!LinkageName.empty())
1755 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1756 // FIXME - Enable this. AddSourceLine(Method, SP);
1758 DICompositeType MTy = SP->getType();
1759 DIArray Args = MTy.getTypeArray();
1762 if (!IsConstructor) {
1763 DIDescriptor Ty = Args.getElement(0);
1764 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1765 AddType(DW_Unit, Method, *BT);
1766 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1767 AddType(DW_Unit, Method, *DT);
1768 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1769 AddType(DW_Unit, Method, *CT);
1773 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1774 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1775 DIDescriptor Ty = Args.getElement(i);
1776 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1777 AddType(DW_Unit, Method, *BT);
1778 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1779 AddType(DW_Unit, Method, *DT);
1780 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1781 AddType(DW_Unit, Method, *CT);
1782 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1783 Method->AddChild(Arg);
1786 if (!SP->isLocalToUnit())
1787 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1788 Buffer.AddChild(Method);
1791 /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
1792 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1793 DIDerivedType *DTy) {
1794 unsigned Tag = DTy->getTag();
1795 DIE *MemberDie = new DIE(Tag);
1796 if (!DTy->getName().empty())
1797 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
1798 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
1800 DIType FromTy = DTy->getTypeDerivedFrom();
1801 AddType(DW_Unit, MemberDie, FromTy);
1803 uint64_t Size = DTy->getSizeInBits();
1804 uint64_t Offset = DTy->getOffsetInBits();
1806 // FIXME Handle bitfields
1809 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
1810 // Add computation for offset.
1811 DIEBlock *Block = new DIEBlock();
1812 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1813 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
1814 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1816 // FIXME Handle DW_AT_accessibility.
1818 Buffer.AddChild(MemberDie);
1821 /// ConstructType - Adds all the required attributes to the type.
1823 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1824 // Get core information.
1825 const std::string &Name = TyDesc->getName();
1826 uint64_t Size = TyDesc->getSize() >> 3;
1828 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1829 // Fundamental types like int, float, bool
1830 Buffer.setTag(DW_TAG_base_type);
1831 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1832 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1834 unsigned Tag = DerivedTy->getTag();
1835 // FIXME - Workaround for templates.
1836 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1837 // Pointers, typedefs et al.
1839 // Map to main type, void will not have a type.
1840 if (TypeDesc *FromTy = DerivedTy->getFromType())
1841 AddType(&Buffer, FromTy, Unit);
1842 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1844 unsigned Tag = CompTy->getTag();
1846 // Set tag accordingly.
1847 if (Tag == DW_TAG_vector_type)
1848 Buffer.setTag(DW_TAG_array_type);
1852 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1855 case DW_TAG_vector_type:
1856 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1858 case DW_TAG_array_type: {
1859 // Add element type.
1860 if (TypeDesc *FromTy = CompTy->getFromType())
1861 AddType(&Buffer, FromTy, Unit);
1863 // Don't emit size attribute.
1866 // Construct an anonymous type for index type.
1867 DIE Buffer(DW_TAG_base_type);
1868 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
1869 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1870 DIE *IndexTy = Unit->AddDie(Buffer);
1872 // Add subranges to array type.
1873 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1874 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1875 int64_t Lo = SRD->getLo();
1876 int64_t Hi = SRD->getHi();
1877 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1879 // If a range is available.
1881 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1882 // Only add low if non-zero.
1883 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1884 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1887 Buffer.AddChild(Subrange);
1891 case DW_TAG_structure_type:
1892 case DW_TAG_union_type: {
1893 // Add elements to structure type.
1894 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1895 DebugInfoDesc *Element = Elements[i];
1897 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1898 // Add field or base class.
1899 unsigned Tag = MemberDesc->getTag();
1901 // Extract the basic information.
1902 const std::string &Name = MemberDesc->getName();
1903 uint64_t Size = MemberDesc->getSize();
1904 uint64_t Align = MemberDesc->getAlign();
1905 uint64_t Offset = MemberDesc->getOffset();
1907 // Construct member debug information entry.
1908 DIE *Member = new DIE(Tag);
1910 // Add name if not "".
1912 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1914 // Add location if available.
1915 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1917 // Most of the time the field info is the same as the members.
1918 uint64_t FieldSize = Size;
1919 uint64_t FieldAlign = Align;
1920 uint64_t FieldOffset = Offset;
1922 // Set the member type.
1923 TypeDesc *FromTy = MemberDesc->getFromType();
1924 AddType(Member, FromTy, Unit);
1926 // Walk up typedefs until a real size is found.
1928 if (FromTy->getTag() != DW_TAG_typedef) {
1929 FieldSize = FromTy->getSize();
1930 FieldAlign = FromTy->getAlign();
1934 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1937 // Unless we have a bit field.
1938 if (Tag == DW_TAG_member && FieldSize != Size) {
1939 // Construct the alignment mask.
1940 uint64_t AlignMask = ~(FieldAlign - 1);
1941 // Determine the high bit + 1 of the declared size.
1942 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1943 // Work backwards to determine the base offset of the field.
1944 FieldOffset = HiMark - FieldSize;
1945 // Now normalize offset to the field.
1946 Offset -= FieldOffset;
1948 // Maybe we need to work from the other end.
1949 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1951 // Add size and offset.
1952 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1953 AddUInt(Member, DW_AT_bit_size, 0, Size);
1954 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1957 // Add computation for offset.
1958 DIEBlock *Block = new DIEBlock();
1959 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1960 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1961 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1963 // Add accessibility (public default unless is base class.
1964 if (MemberDesc->isProtected()) {
1965 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1966 } else if (MemberDesc->isPrivate()) {
1967 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1968 } else if (Tag == DW_TAG_inheritance) {
1969 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1972 Buffer.AddChild(Member);
1973 } else if (GlobalVariableDesc *StaticDesc =
1974 dyn_cast<GlobalVariableDesc>(Element)) {
1975 // Add static member.
1977 // Construct member debug information entry.
1978 DIE *Static = new DIE(DW_TAG_variable);
1980 // Add name and mangled name.
1981 const std::string &Name = StaticDesc->getName();
1982 const std::string &LinkageName = StaticDesc->getLinkageName();
1983 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1984 if (!LinkageName.empty()) {
1985 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1990 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1993 if (TypeDesc *StaticTy = StaticDesc->getType())
1994 AddType(Static, StaticTy, Unit);
1997 if (!StaticDesc->isStatic())
1998 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1999 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2001 Buffer.AddChild(Static);
2002 } else if (SubprogramDesc *MethodDesc =
2003 dyn_cast<SubprogramDesc>(Element)) {
2004 // Add member function.
2006 // Construct member debug information entry.
2007 DIE *Method = new DIE(DW_TAG_subprogram);
2009 // Add name and mangled name.
2010 const std::string &Name = MethodDesc->getName();
2011 const std::string &LinkageName = MethodDesc->getLinkageName();
2013 AddString(Method, DW_AT_name, DW_FORM_string, Name);
2014 bool IsCTor = TyDesc->getName() == Name;
2016 if (!LinkageName.empty()) {
2017 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2022 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2025 if (CompositeTypeDesc *MethodTy =
2026 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2027 // Get argument information.
2028 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2033 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2037 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2038 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2039 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2040 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2041 Method->AddChild(Arg);
2046 if (!MethodDesc->isStatic())
2047 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2048 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2050 Buffer.AddChild(Method);
2055 case DW_TAG_enumeration_type: {
2056 // Add enumerators to enumeration type.
2057 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2058 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2059 const std::string &Name = ED->getName();
2060 int64_t Value = ED->getValue();
2061 DIE *Enumerator = new DIE(DW_TAG_enumerator);
2062 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2063 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2064 Buffer.AddChild(Enumerator);
2069 case DW_TAG_subroutine_type: {
2070 // Add prototype flag.
2071 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2073 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2076 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2077 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2078 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2079 Buffer.AddChild(Arg);
2088 // Add name if not anonymous or intermediate type.
2089 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2091 // Add size if non-zero (derived types might be zero-sized.)
2093 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2094 else if (isa<CompositeTypeDesc>(TyDesc)) {
2095 // If TyDesc is a composite type, then add size even if it's zero unless
2096 // it's a forward declaration.
2097 if (TyDesc->isForwardDecl())
2098 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2100 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2103 // Add source line info if available and TyDesc is not a forward
2105 if (!TyDesc->isForwardDecl())
2106 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2109 /// NewCompileUnit - Create new compile unit and it's debug information entry.
2111 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2112 // Construct debug information entry.
2113 DIE *Die = new DIE(DW_TAG_compile_unit);
2114 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2115 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2116 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
2117 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
2118 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
2119 if (!UnitDesc->getDirectory().empty())
2120 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
2122 // Construct compile unit.
2123 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2125 // Add Unit to compile unit map.
2126 DescToUnitMap[UnitDesc] = Unit;
2131 /// GetBaseCompileUnit - Get the main compile unit.
2133 CompileUnit *GetBaseCompileUnit() const {
2134 CompileUnit *Unit = CompileUnits[0];
2135 assert(Unit && "Missing compile unit.");
2139 /// FindCompileUnit - Get the compile unit for the given descriptor.
2141 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2142 CompileUnit *Unit = DescToUnitMap[UnitDesc];
2143 assert(Unit && "Missing compile unit.");
2147 /// NewGlobalVariable - Add a new global variable DIE.
2149 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2150 // Get the compile unit context.
2151 CompileUnitDesc *UnitDesc =
2152 static_cast<CompileUnitDesc *>(GVD->getContext());
2153 CompileUnit *Unit = GetBaseCompileUnit();
2155 // Check for pre-existence.
2156 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2157 if (Slot) return Slot;
2159 // Get the global variable itself.
2160 GlobalVariable *GV = GVD->getGlobalVariable();
2162 const std::string &Name = GVD->getName();
2163 const std::string &FullName = GVD->getFullName();
2164 const std::string &LinkageName = GVD->getLinkageName();
2165 // Create the global's variable DIE.
2166 DIE *VariableDie = new DIE(DW_TAG_variable);
2167 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2168 if (!LinkageName.empty()) {
2169 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2172 AddType(VariableDie, GVD->getType(), Unit);
2173 if (!GVD->isStatic())
2174 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2176 // Add source line info if available.
2177 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2180 DIEBlock *Block = new DIEBlock();
2181 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2182 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2183 AddBlock(VariableDie, DW_AT_location, 0, Block);
2188 // Add to context owner.
2189 Unit->getDie()->AddChild(VariableDie);
2191 // Expose as global.
2192 // FIXME - need to check external flag.
2193 Unit->AddGlobal(FullName, VariableDie);
2198 /// NewSubprogram - Add a new subprogram DIE.
2200 DIE *NewSubprogram(SubprogramDesc *SPD) {
2201 // Get the compile unit context.
2202 CompileUnitDesc *UnitDesc =
2203 static_cast<CompileUnitDesc *>(SPD->getContext());
2204 CompileUnit *Unit = GetBaseCompileUnit();
2206 // Check for pre-existence.
2207 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2208 if (Slot) return Slot;
2210 // Gather the details (simplify add attribute code.)
2211 const std::string &Name = SPD->getName();
2212 const std::string &FullName = SPD->getFullName();
2213 const std::string &LinkageName = SPD->getLinkageName();
2215 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2216 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2217 if (!LinkageName.empty()) {
2218 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2221 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2222 if (!SPD->isStatic())
2223 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2224 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2226 // Add source line info if available.
2227 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2230 Slot = SubprogramDie;
2232 // Add to context owner.
2233 Unit->getDie()->AddChild(SubprogramDie);
2235 // Expose as global.
2236 Unit->AddGlobal(FullName, SubprogramDie);
2238 return SubprogramDie;
2241 /// NewScopeVariable - Create a new scope variable.
2243 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2244 // Get the descriptor.
2245 VariableDesc *VD = DV->getDesc();
2247 // Translate tag to proper Dwarf tag. The result variable is dropped for
2250 switch (VD->getTag()) {
2251 case DW_TAG_return_variable: return NULL;
2252 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2253 case DW_TAG_auto_variable: // fall thru
2254 default: Tag = DW_TAG_variable; break;
2257 // Define variable debug information entry.
2258 DIE *VariableDie = new DIE(Tag);
2259 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2261 // Add source line info if available.
2262 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2264 // Add variable type.
2265 AddType(VariableDie, VD->getType(), Unit);
2267 // Add variable address.
2268 MachineLocation Location;
2269 Location.set(RI->getFrameRegister(*MF),
2270 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2271 AddAddress(VariableDie, DW_AT_location, Location);
2276 /// ConstructScope - Construct the components of a scope.
2278 void ConstructScope(DebugScope *ParentScope,
2279 unsigned ParentStartID, unsigned ParentEndID,
2280 DIE *ParentDie, CompileUnit *Unit) {
2281 // Add variables to scope.
2282 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2283 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2284 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2285 if (VariableDie) ParentDie->AddChild(VariableDie);
2288 // Add nested scopes.
2289 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2290 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2291 // Define the Scope debug information entry.
2292 DebugScope *Scope = Scopes[j];
2293 // FIXME - Ignore inlined functions for the time being.
2294 if (!Scope->getParent()) continue;
2296 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2297 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2299 // Ignore empty scopes.
2300 if (StartID == EndID && StartID != 0) continue;
2301 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2303 if (StartID == ParentStartID && EndID == ParentEndID) {
2304 // Just add stuff to the parent scope.
2305 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2307 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2309 // Add the scope bounds.
2311 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2312 DWLabel("label", StartID));
2314 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2315 DWLabel("func_begin", SubprogramCount));
2318 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2319 DWLabel("label", EndID));
2321 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2322 DWLabel("func_end", SubprogramCount));
2325 // Add the scope contents.
2326 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2327 ParentDie->AddChild(ScopeDie);
2332 /// ConstructRootScope - Construct the scope for the subprogram.
2334 void ConstructRootScope(DebugScope *RootScope) {
2335 // Exit if there is no root scope.
2336 if (!RootScope) return;
2338 // Get the subprogram debug information entry.
2339 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2341 // Get the compile unit context.
2342 CompileUnit *Unit = GetBaseCompileUnit();
2344 // Get the subprogram die.
2345 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2346 assert(SPDie && "Missing subprogram descriptor");
2348 // Add the function bounds.
2349 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2350 DWLabel("func_begin", SubprogramCount));
2351 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2352 DWLabel("func_end", SubprogramCount));
2353 MachineLocation Location(RI->getFrameRegister(*MF));
2354 AddAddress(SPDie, DW_AT_frame_base, Location);
2356 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2359 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2361 void ConstructDefaultScope(MachineFunction *MF) {
2362 // Find the correct subprogram descriptor.
2363 std::vector<SubprogramDesc *> Subprograms;
2364 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2366 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2367 SubprogramDesc *SPD = Subprograms[i];
2369 if (SPD->getName() == MF->getFunction()->getName()) {
2370 // Get the compile unit context.
2371 CompileUnit *Unit = GetBaseCompileUnit();
2373 // Get the subprogram die.
2374 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2375 assert(SPDie && "Missing subprogram descriptor");
2377 // Add the function bounds.
2378 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2379 DWLabel("func_begin", SubprogramCount));
2380 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2381 DWLabel("func_end", SubprogramCount));
2383 MachineLocation Location(RI->getFrameRegister(*MF));
2384 AddAddress(SPDie, DW_AT_frame_base, Location);
2389 // FIXME: This is causing an abort because C++ mangled names are compared
2390 // with their unmangled counterparts. See PR2885. Don't do this assert.
2391 assert(0 && "Couldn't find DIE for machine function!");
2395 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2396 /// tools to recognize the object file contains Dwarf information.
2397 void EmitInitial() {
2398 // Check to see if we already emitted intial headers.
2399 if (didInitial) return;
2402 // Dwarf sections base addresses.
2403 if (TAI->doesDwarfRequireFrameSection()) {
2404 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2405 EmitLabel("section_debug_frame", 0);
2407 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2408 EmitLabel("section_info", 0);
2409 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2410 EmitLabel("section_abbrev", 0);
2411 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2412 EmitLabel("section_aranges", 0);
2413 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2414 EmitLabel("section_macinfo", 0);
2415 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2416 EmitLabel("section_line", 0);
2417 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2418 EmitLabel("section_loc", 0);
2419 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2420 EmitLabel("section_pubnames", 0);
2421 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2422 EmitLabel("section_str", 0);
2423 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2424 EmitLabel("section_ranges", 0);
2426 Asm->SwitchToSection(TAI->getTextSection());
2427 EmitLabel("text_begin", 0);
2428 Asm->SwitchToSection(TAI->getDataSection());
2429 EmitLabel("data_begin", 0);
2432 /// EmitDIE - Recusively Emits a debug information entry.
2434 void EmitDIE(DIE *Die) {
2435 // Get the abbreviation for this DIE.
2436 unsigned AbbrevNumber = Die->getAbbrevNumber();
2437 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2441 // Emit the code (index) for the abbreviation.
2442 Asm->EmitULEB128Bytes(AbbrevNumber);
2445 Asm->EOL(std::string("Abbrev [" +
2446 utostr(AbbrevNumber) +
2447 "] 0x" + utohexstr(Die->getOffset()) +
2448 ":0x" + utohexstr(Die->getSize()) + " " +
2449 TagString(Abbrev->getTag())));
2453 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2454 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2456 // Emit the DIE attribute values.
2457 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2458 unsigned Attr = AbbrevData[i].getAttribute();
2459 unsigned Form = AbbrevData[i].getForm();
2460 assert(Form && "Too many attributes for DIE (check abbreviation)");
2463 case DW_AT_sibling: {
2464 Asm->EmitInt32(Die->SiblingOffset());
2468 // Emit an attribute using the defined form.
2469 Values[i]->EmitValue(*this, Form);
2474 Asm->EOL(AttributeString(Attr));
2477 // Emit the DIE children if any.
2478 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2479 const std::vector<DIE *> &Children = Die->getChildren();
2481 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2482 EmitDIE(Children[j]);
2485 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2489 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2491 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2492 // Get the children.
2493 const std::vector<DIE *> &Children = Die->getChildren();
2495 // If not last sibling and has children then add sibling offset attribute.
2496 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2498 // Record the abbreviation.
2499 AssignAbbrevNumber(Die->getAbbrev());
2501 // Get the abbreviation for this DIE.
2502 unsigned AbbrevNumber = Die->getAbbrevNumber();
2503 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2506 Die->setOffset(Offset);
2508 // Start the size with the size of abbreviation code.
2509 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2511 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2512 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2514 // Size the DIE attribute values.
2515 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2516 // Size attribute value.
2517 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2520 // Size the DIE children if any.
2521 if (!Children.empty()) {
2522 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2523 "Children flag not set");
2525 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2526 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2529 // End of children marker.
2530 Offset += sizeof(int8_t);
2533 Die->setSize(Offset - Die->getOffset());
2537 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2539 void SizeAndOffsets() {
2540 // Process base compile unit.
2541 CompileUnit *Unit = GetBaseCompileUnit();
2542 // Compute size of compile unit header
2543 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2544 sizeof(int16_t) + // DWARF version number
2545 sizeof(int32_t) + // Offset Into Abbrev. Section
2546 sizeof(int8_t); // Pointer Size (in bytes)
2547 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2550 /// EmitDebugInfo - Emit the debug info section.
2552 void EmitDebugInfo() {
2553 // Start debug info section.
2554 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2556 CompileUnit *Unit = GetBaseCompileUnit();
2557 DIE *Die = Unit->getDie();
2558 // Emit the compile units header.
2559 EmitLabel("info_begin", Unit->getID());
2560 // Emit size of content not including length itself
2561 unsigned ContentSize = Die->getSize() +
2562 sizeof(int16_t) + // DWARF version number
2563 sizeof(int32_t) + // Offset Into Abbrev. Section
2564 sizeof(int8_t) + // Pointer Size (in bytes)
2565 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2567 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2568 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2569 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2570 Asm->EOL("Offset Into Abbrev. Section");
2571 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2574 // FIXME - extra padding for gdb bug.
2575 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2576 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2577 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2578 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2579 EmitLabel("info_end", Unit->getID());
2584 /// EmitAbbreviations - Emit the abbreviation section.
2586 void EmitAbbreviations() const {
2587 // Check to see if it is worth the effort.
2588 if (!Abbreviations.empty()) {
2589 // Start the debug abbrev section.
2590 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2592 EmitLabel("abbrev_begin", 0);
2594 // For each abbrevation.
2595 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2596 // Get abbreviation data
2597 const DIEAbbrev *Abbrev = Abbreviations[i];
2599 // Emit the abbrevations code (base 1 index.)
2600 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2601 Asm->EOL("Abbreviation Code");
2603 // Emit the abbreviations data.
2604 Abbrev->Emit(*this);
2609 // Mark end of abbreviations.
2610 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2612 EmitLabel("abbrev_end", 0);
2618 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2619 /// the line matrix.
2621 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2622 // Define last address of section.
2623 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2624 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2625 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2626 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2628 // Mark end of matrix.
2629 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2630 Asm->EmitULEB128Bytes(1); Asm->EOL();
2631 Asm->EmitInt8(1); Asm->EOL();
2634 /// EmitDebugLines - Emit source line information.
2636 void EmitDebugLines() {
2637 // If the target is using .loc/.file, the assembler will be emitting the
2638 // .debug_line table automatically.
2639 if (TAI->hasDotLocAndDotFile())
2642 // Minimum line delta, thus ranging from -10..(255-10).
2643 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2644 // Maximum line delta, thus ranging from -10..(255-10).
2645 const int MaxLineDelta = 255 + MinLineDelta;
2647 // Start the dwarf line section.
2648 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2650 // Construct the section header.
2652 EmitDifference("line_end", 0, "line_begin", 0, true);
2653 Asm->EOL("Length of Source Line Info");
2654 EmitLabel("line_begin", 0);
2656 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2658 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2659 Asm->EOL("Prolog Length");
2660 EmitLabel("line_prolog_begin", 0);
2662 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2664 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2666 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2668 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2670 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2672 // Line number standard opcode encodings argument count
2673 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2674 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2675 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2676 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2677 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2678 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2679 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2680 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2681 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2683 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2684 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2686 // Emit directories.
2687 for (unsigned DirectoryID = 1, NDID = Directories.size();
2688 DirectoryID <= NDID; ++DirectoryID) {
2689 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2691 Asm->EmitInt8(0); Asm->EOL("End of directories");
2694 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2695 SourceID <= NSID; ++SourceID) {
2696 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2697 Asm->EmitString(SourceFile.getName());
2699 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2700 Asm->EOL("Directory #");
2701 Asm->EmitULEB128Bytes(0);
2702 Asm->EOL("Mod date");
2703 Asm->EmitULEB128Bytes(0);
2704 Asm->EOL("File size");
2706 Asm->EmitInt8(0); Asm->EOL("End of files");
2708 EmitLabel("line_prolog_end", 0);
2710 // A sequence for each text section.
2711 unsigned SecSrcLinesSize = SectionSourceLines.size();
2713 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2714 // Isolate current sections line info.
2715 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2718 const Section* S = SectionMap[j + 1];
2719 Asm->EOL(std::string("Section ") + S->getName());
2723 // Dwarf assumes we start with first line of first source file.
2724 unsigned Source = 1;
2727 // Construct rows of the address, source, line, column matrix.
2728 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2729 const SourceLineInfo &LineInfo = LineInfos[i];
2730 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2731 if (!LabelID) continue;
2733 unsigned SourceID = LineInfo.getSourceID();
2734 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2735 unsigned DirectoryID = SourceFile.getDirectoryID();
2737 Asm->EOL(Directories[DirectoryID]
2738 + SourceFile.getName()
2740 + utostr_32(LineInfo.getLine()));
2744 // Define the line address.
2745 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2746 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2747 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2748 EmitReference("label", LabelID); Asm->EOL("Location label");
2750 // If change of source, then switch to the new source.
2751 if (Source != LineInfo.getSourceID()) {
2752 Source = LineInfo.getSourceID();
2753 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2754 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2757 // If change of line.
2758 if (Line != LineInfo.getLine()) {
2759 // Determine offset.
2760 int Offset = LineInfo.getLine() - Line;
2761 int Delta = Offset - MinLineDelta;
2764 Line = LineInfo.getLine();
2766 // If delta is small enough and in range...
2767 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2768 // ... then use fast opcode.
2769 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2771 // ... otherwise use long hand.
2772 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2773 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2774 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2777 // Copy the previous row (different address or source)
2778 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2782 EmitEndOfLineMatrix(j + 1);
2785 if (SecSrcLinesSize == 0)
2786 // Because we're emitting a debug_line section, we still need a line
2787 // table. The linker and friends expect it to exist. If there's nothing to
2788 // put into it, emit an empty table.
2789 EmitEndOfLineMatrix(1);
2791 EmitLabel("line_end", 0);
2796 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2798 void EmitCommonDebugFrame() {
2799 if (!TAI->doesDwarfRequireFrameSection())
2803 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2804 TargetFrameInfo::StackGrowsUp ?
2805 TD->getPointerSize() : -TD->getPointerSize();
2807 // Start the dwarf frame section.
2808 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2810 EmitLabel("debug_frame_common", 0);
2811 EmitDifference("debug_frame_common_end", 0,
2812 "debug_frame_common_begin", 0, true);
2813 Asm->EOL("Length of Common Information Entry");
2815 EmitLabel("debug_frame_common_begin", 0);
2816 Asm->EmitInt32((int)DW_CIE_ID);
2817 Asm->EOL("CIE Identifier Tag");
2818 Asm->EmitInt8(DW_CIE_VERSION);
2819 Asm->EOL("CIE Version");
2820 Asm->EmitString("");
2821 Asm->EOL("CIE Augmentation");
2822 Asm->EmitULEB128Bytes(1);
2823 Asm->EOL("CIE Code Alignment Factor");
2824 Asm->EmitSLEB128Bytes(stackGrowth);
2825 Asm->EOL("CIE Data Alignment Factor");
2826 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2827 Asm->EOL("CIE RA Column");
2829 std::vector<MachineMove> Moves;
2830 RI->getInitialFrameState(Moves);
2832 EmitFrameMoves(NULL, 0, Moves, false);
2834 Asm->EmitAlignment(2, 0, 0, false);
2835 EmitLabel("debug_frame_common_end", 0);
2840 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2842 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2843 if (!TAI->doesDwarfRequireFrameSection())
2846 // Start the dwarf frame section.
2847 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2849 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2850 "debug_frame_begin", DebugFrameInfo.Number, true);
2851 Asm->EOL("Length of Frame Information Entry");
2853 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2855 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2857 Asm->EOL("FDE CIE offset");
2859 EmitReference("func_begin", DebugFrameInfo.Number);
2860 Asm->EOL("FDE initial location");
2861 EmitDifference("func_end", DebugFrameInfo.Number,
2862 "func_begin", DebugFrameInfo.Number);
2863 Asm->EOL("FDE address range");
2865 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2867 Asm->EmitAlignment(2, 0, 0, false);
2868 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2873 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2875 void EmitDebugPubNames() {
2876 // Start the dwarf pubnames section.
2877 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2879 CompileUnit *Unit = GetBaseCompileUnit();
2881 EmitDifference("pubnames_end", Unit->getID(),
2882 "pubnames_begin", Unit->getID(), true);
2883 Asm->EOL("Length of Public Names Info");
2885 EmitLabel("pubnames_begin", Unit->getID());
2887 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2889 EmitSectionOffset("info_begin", "section_info",
2890 Unit->getID(), 0, true, false);
2891 Asm->EOL("Offset of Compilation Unit Info");
2893 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2894 Asm->EOL("Compilation Unit Length");
2896 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2898 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2901 const std::string &Name = GI->first;
2902 DIE * Entity = GI->second;
2904 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2905 Asm->EmitString(Name); Asm->EOL("External Name");
2908 Asm->EmitInt32(0); Asm->EOL("End Mark");
2909 EmitLabel("pubnames_end", Unit->getID());
2914 /// EmitDebugStr - Emit visible names into a debug str section.
2916 void EmitDebugStr() {
2917 // Check to see if it is worth the effort.
2918 if (!StringPool.empty()) {
2919 // Start the dwarf str section.
2920 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2922 // For each of strings in the string pool.
2923 for (unsigned StringID = 1, N = StringPool.size();
2924 StringID <= N; ++StringID) {
2925 // Emit a label for reference from debug information entries.
2926 EmitLabel("string", StringID);
2927 // Emit the string itself.
2928 const std::string &String = StringPool[StringID];
2929 Asm->EmitString(String); Asm->EOL();
2936 /// EmitDebugLoc - Emit visible names into a debug loc section.
2938 void EmitDebugLoc() {
2939 // Start the dwarf loc section.
2940 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2945 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2947 void EmitDebugARanges() {
2948 // Start the dwarf aranges section.
2949 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2953 CompileUnit *Unit = GetBaseCompileUnit();
2955 // Don't include size of length
2956 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2958 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2960 EmitReference("info_begin", Unit->getID());
2961 Asm->EOL("Offset of Compilation Unit Info");
2963 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2965 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2967 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2968 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2971 EmitReference("text_begin", 0); Asm->EOL("Address");
2972 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2974 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2975 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2981 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2983 void EmitDebugRanges() {
2984 // Start the dwarf ranges section.
2985 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2990 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2992 void EmitDebugMacInfo() {
2993 // Start the dwarf macinfo section.
2994 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2999 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3001 void ConstructCompileUnitDIEs() {
3002 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3004 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3005 unsigned ID = MMI->RecordSource(CUW[i]);
3006 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3007 CompileUnits.push_back(Unit);
3011 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3012 /// global variables.
3013 void ConstructGlobalDIEs() {
3014 std::vector<GlobalVariableDesc *> GlobalVariables;
3015 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3017 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3018 GlobalVariableDesc *GVD = GlobalVariables[i];
3019 NewGlobalVariable(GVD);
3023 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3025 void ConstructSubprogramDIEs() {
3026 std::vector<SubprogramDesc *> Subprograms;
3027 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3029 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3030 SubprogramDesc *SPD = Subprograms[i];
3036 //===--------------------------------------------------------------------===//
3037 // Main entry points.
3039 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3040 : Dwarf(OS, A, T, "dbg")
3042 , AbbreviationsSet(InitAbbreviationsSetSize)
3044 , ValuesSet(InitValuesSetSize)
3049 , SectionSourceLines()
3054 virtual ~DwarfDebug() {
3055 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3056 delete CompileUnits[i];
3057 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3061 /// SetModuleInfo - Set machine module information when it's known that pass
3062 /// manager has created it. Set by the target AsmPrinter.
3063 void SetModuleInfo(MachineModuleInfo *mmi) {
3064 // Make sure initial declarations are made.
3065 if (!MMI && mmi->hasDebugInfo()) {
3069 // Create all the compile unit DIEs.
3070 ConstructCompileUnitDIEs();
3072 // Create DIEs for each of the externally visible global variables.
3073 ConstructGlobalDIEs();
3075 // Create DIEs for each of the externally visible subprograms.
3076 ConstructSubprogramDIEs();
3078 // Prime section data.
3079 SectionMap.insert(TAI->getTextSection());
3081 // Print out .file directives to specify files for .loc directives. These
3082 // are printed out early so that they precede any .loc directives.
3083 if (TAI->hasDotLocAndDotFile()) {
3084 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3085 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3086 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3087 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3088 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3089 assert(AppendOk && "Could not append filename to directory!");
3091 Asm->EmitFile(i, FullPath.toString());
3096 // Emit initial sections
3101 /// BeginModule - Emit all Dwarf sections that should come prior to the
3103 void BeginModule(Module *M) {
3107 /// EndModule - Emit all Dwarf sections that should come after the content.
3110 if (!ShouldEmitDwarf()) return;
3112 // Standard sections final addresses.
3113 Asm->SwitchToSection(TAI->getTextSection());
3114 EmitLabel("text_end", 0);
3115 Asm->SwitchToSection(TAI->getDataSection());
3116 EmitLabel("data_end", 0);
3118 // End text sections.
3119 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3120 Asm->SwitchToSection(SectionMap[i]);
3121 EmitLabel("section_end", i);
3124 // Emit common frame information.
3125 EmitCommonDebugFrame();
3127 // Emit function debug frame information
3128 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3129 E = DebugFrames.end(); I != E; ++I)
3130 EmitFunctionDebugFrame(*I);
3132 // Compute DIE offsets and sizes.
3135 // Emit all the DIEs into a debug info section
3138 // Corresponding abbreviations into a abbrev section.
3139 EmitAbbreviations();
3141 // Emit source line correspondence into a debug line section.
3144 // Emit info into a debug pubnames section.
3145 EmitDebugPubNames();
3147 // Emit info into a debug str section.
3150 // Emit info into a debug loc section.
3153 // Emit info into a debug aranges section.
3156 // Emit info into a debug ranges section.
3159 // Emit info into a debug macinfo section.
3163 /// BeginFunction - Gather pre-function debug information. Assumes being
3164 /// emitted immediately after the function entry point.
3165 void BeginFunction(MachineFunction *MF) {
3168 if (!ShouldEmitDwarf()) return;
3170 // Begin accumulating function debug information.
3171 MMI->BeginFunction(MF);
3173 // Assumes in correct section after the entry point.
3174 EmitLabel("func_begin", ++SubprogramCount);
3176 // Emit label for the implicitly defined dbg.stoppoint at the start of
3178 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3179 if (!LineInfos.empty()) {
3180 const SourceLineInfo &LineInfo = LineInfos[0];
3181 Asm->printLabel(LineInfo.getLabelID());
3185 /// EndFunction - Gather and emit post-function debug information.
3187 void EndFunction(MachineFunction *MF) {
3188 if (!ShouldEmitDwarf()) return;
3190 // Define end label for subprogram.
3191 EmitLabel("func_end", SubprogramCount);
3193 // Get function line info.
3194 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3196 if (!LineInfos.empty()) {
3197 // Get section line info.
3198 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3199 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3200 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3201 // Append the function info to section info.
3202 SectionLineInfos.insert(SectionLineInfos.end(),
3203 LineInfos.begin(), LineInfos.end());
3206 // Construct scopes for subprogram.
3207 if (MMI->getRootScope())
3208 ConstructRootScope(MMI->getRootScope());
3210 // FIXME: This is wrong. We are essentially getting past a problem with
3211 // debug information not being able to handle unreachable blocks that have
3212 // debug information in them. In particular, those unreachable blocks that
3213 // have "region end" info in them. That situation results in the "root
3214 // scope" not being created. If that's the case, then emit a "default"
3215 // scope, i.e., one that encompasses the whole function. This isn't
3216 // desirable. And a better way of handling this (and all of the debugging
3217 // information) needs to be explored.
3218 ConstructDefaultScope(MF);
3220 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3221 MMI->getFrameMoves()));
3225 //===----------------------------------------------------------------------===//
3226 /// DwarfException - Emits Dwarf exception handling directives.
3228 class DwarfException : public Dwarf {
3231 struct FunctionEHFrameInfo {
3234 unsigned PersonalityIndex;
3236 bool hasLandingPads;
3237 std::vector<MachineMove> Moves;
3238 const Function * function;
3240 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3242 const std::vector<MachineMove> &M,
3244 FnName(FN), Number(Num), PersonalityIndex(P),
3245 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3248 std::vector<FunctionEHFrameInfo> EHFrames;
3250 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3252 bool shouldEmitTable;
3254 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3255 /// should be emitted.
3256 bool shouldEmitMoves;
3258 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3259 /// should be emitted.
3260 bool shouldEmitTableModule;
3262 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3263 /// should be emitted.
3264 bool shouldEmitMovesModule;
3266 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3268 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3269 // Size and sign of stack growth.
3271 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3272 TargetFrameInfo::StackGrowsUp ?
3273 TD->getPointerSize() : -TD->getPointerSize();
3275 // Begin eh frame section.
3276 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3278 if (!TAI->doesRequireNonLocalEHFrameLabel())
3279 O << TAI->getEHGlobalPrefix();
3280 O << "EH_frame" << Index << ":\n";
3281 EmitLabel("section_eh_frame", Index);
3283 // Define base labels.
3284 EmitLabel("eh_frame_common", Index);
3286 // Define the eh frame length.
3287 EmitDifference("eh_frame_common_end", Index,
3288 "eh_frame_common_begin", Index, true);
3289 Asm->EOL("Length of Common Information Entry");
3292 EmitLabel("eh_frame_common_begin", Index);
3293 Asm->EmitInt32((int)0);
3294 Asm->EOL("CIE Identifier Tag");
3295 Asm->EmitInt8(DW_CIE_VERSION);
3296 Asm->EOL("CIE Version");
3298 // The personality presence indicates that language specific information
3299 // will show up in the eh frame.
3300 Asm->EmitString(Personality ? "zPLR" : "zR");
3301 Asm->EOL("CIE Augmentation");
3303 // Round out reader.
3304 Asm->EmitULEB128Bytes(1);
3305 Asm->EOL("CIE Code Alignment Factor");
3306 Asm->EmitSLEB128Bytes(stackGrowth);
3307 Asm->EOL("CIE Data Alignment Factor");
3308 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3309 Asm->EOL("CIE Return Address Column");
3311 // If there is a personality, we need to indicate the functions location.
3313 Asm->EmitULEB128Bytes(7);
3314 Asm->EOL("Augmentation Size");
3316 if (TAI->getNeedsIndirectEncoding()) {
3317 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3318 Asm->EOL("Personality (pcrel sdata4 indirect)");
3320 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3321 Asm->EOL("Personality (pcrel sdata4)");
3324 PrintRelDirective(true);
3325 O << TAI->getPersonalityPrefix();
3326 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3327 O << TAI->getPersonalitySuffix();
3328 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3329 O << "-" << TAI->getPCSymbol();
3330 Asm->EOL("Personality");
3332 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3333 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3335 if (TAI->doesFDEEncodingRequireSData4()) {
3336 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3337 Asm->EOL("FDE Encoding (pcrel sdata4)");
3339 Asm->EmitInt8(DW_EH_PE_pcrel);
3340 Asm->EOL("FDE Encoding (pcrel)");
3343 Asm->EmitULEB128Bytes(1);
3344 Asm->EOL("Augmentation Size");
3346 if (TAI->doesFDEEncodingRequireSData4()) {
3347 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3348 Asm->EOL("FDE Encoding (pcrel sdata4)");
3350 Asm->EmitInt8(DW_EH_PE_pcrel);
3351 Asm->EOL("FDE Encoding (pcrel)");
3355 // Indicate locations of general callee saved registers in frame.
3356 std::vector<MachineMove> Moves;
3357 RI->getInitialFrameState(Moves);
3358 EmitFrameMoves(NULL, 0, Moves, true);
3360 // On Darwin the linker honors the alignment of eh_frame, which means it
3361 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3362 // you get holes which confuse readers of eh_frame.
3363 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3365 EmitLabel("eh_frame_common_end", Index);
3370 /// EmitEHFrame - Emit function exception frame information.
3372 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3373 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3375 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3377 // Externally visible entry into the functions eh frame info.
3378 // If the corresponding function is static, this should not be
3379 // externally visible.
3380 if (linkage != Function::InternalLinkage) {
3381 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3382 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3385 // If corresponding function is weak definition, this should be too.
3386 if ((linkage == Function::WeakLinkage ||
3387 linkage == Function::LinkOnceLinkage) &&
3388 TAI->getWeakDefDirective())
3389 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3391 // If there are no calls then you can't unwind. This may mean we can
3392 // omit the EH Frame, but some environments do not handle weak absolute
3394 // If UnwindTablesMandatory is set we cannot do this optimization; the
3395 // unwind info is to be available for non-EH uses.
3396 if (!EHFrameInfo.hasCalls &&
3397 !UnwindTablesMandatory &&
3398 ((linkage != Function::WeakLinkage &&
3399 linkage != Function::LinkOnceLinkage) ||
3400 !TAI->getWeakDefDirective() ||
3401 TAI->getSupportsWeakOmittedEHFrame()))
3403 O << EHFrameInfo.FnName << " = 0\n";
3404 // This name has no connection to the function, so it might get
3405 // dead-stripped when the function is not, erroneously. Prohibit
3406 // dead-stripping unconditionally.
3407 if (const char *UsedDirective = TAI->getUsedDirective())
3408 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3410 O << EHFrameInfo.FnName << ":\n";
3413 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3414 "eh_frame_begin", EHFrameInfo.Number, true);
3415 Asm->EOL("Length of Frame Information Entry");
3417 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3419 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3420 PrintRelDirective(true, true);
3421 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3423 if (!TAI->isAbsoluteEHSectionOffsets())
3424 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3426 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3427 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3431 Asm->EOL("FDE CIE offset");
3433 EmitReference("eh_func_begin", EHFrameInfo.Number, true,
3434 TAI->doesRequire32BitFDEReference());
3435 Asm->EOL("FDE initial location");
3436 EmitDifference("eh_func_end", EHFrameInfo.Number,
3437 "eh_func_begin", EHFrameInfo.Number,
3438 TAI->doesRequire32BitFDEReference());
3439 Asm->EOL("FDE address range");
3441 // If there is a personality and landing pads then point to the language
3442 // specific data area in the exception table.
3443 if (EHFrameInfo.PersonalityIndex) {
3444 Asm->EmitULEB128Bytes(4);
3445 Asm->EOL("Augmentation size");
3447 if (EHFrameInfo.hasLandingPads)
3448 EmitReference("exception", EHFrameInfo.Number, true, true);
3450 Asm->EmitInt32((int)0);
3451 Asm->EOL("Language Specific Data Area");
3453 Asm->EmitULEB128Bytes(0);
3454 Asm->EOL("Augmentation size");
3457 // Indicate locations of function specific callee saved registers in
3459 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3461 // On Darwin the linker honors the alignment of eh_frame, which means it
3462 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3463 // you get holes which confuse readers of eh_frame.
3464 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3466 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3468 // If the function is marked used, this table should be also. We cannot
3469 // make the mark unconditional in this case, since retaining the table
3470 // also retains the function in this case, and there is code around
3471 // that depends on unused functions (calling undefined externals) being
3472 // dead-stripped to link correctly. Yes, there really is.
3473 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3474 if (const char *UsedDirective = TAI->getUsedDirective())
3475 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3479 /// EmitExceptionTable - Emit landing pads and actions.
3481 /// The general organization of the table is complex, but the basic concepts
3482 /// are easy. First there is a header which describes the location and
3483 /// organization of the three components that follow.
3484 /// 1. The landing pad site information describes the range of code covered
3485 /// by the try. In our case it's an accumulation of the ranges covered
3486 /// by the invokes in the try. There is also a reference to the landing
3487 /// pad that handles the exception once processed. Finally an index into
3488 /// the actions table.
3489 /// 2. The action table, in our case, is composed of pairs of type ids
3490 /// and next action offset. Starting with the action index from the
3491 /// landing pad site, each type Id is checked for a match to the current
3492 /// exception. If it matches then the exception and type id are passed
3493 /// on to the landing pad. Otherwise the next action is looked up. This
3494 /// chain is terminated with a next action of zero. If no type id is
3495 /// found the the frame is unwound and handling continues.
3496 /// 3. Type id table contains references to all the C++ typeinfo for all
3497 /// catches in the function. This tables is reversed indexed base 1.
3499 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3500 static unsigned SharedTypeIds(const LandingPadInfo *L,
3501 const LandingPadInfo *R) {
3502 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3503 unsigned LSize = LIds.size(), RSize = RIds.size();
3504 unsigned MinSize = LSize < RSize ? LSize : RSize;
3507 for (; Count != MinSize; ++Count)
3508 if (LIds[Count] != RIds[Count])
3514 /// PadLT - Order landing pads lexicographically by type id.
3515 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3516 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3517 unsigned LSize = LIds.size(), RSize = RIds.size();
3518 unsigned MinSize = LSize < RSize ? LSize : RSize;
3520 for (unsigned i = 0; i != MinSize; ++i)
3521 if (LIds[i] != RIds[i])
3522 return LIds[i] < RIds[i];
3524 return LSize < RSize;
3528 static inline unsigned getEmptyKey() { return -1U; }
3529 static inline unsigned getTombstoneKey() { return -2U; }
3530 static unsigned getHashValue(const unsigned &Key) { return Key; }
3531 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3532 static bool isPod() { return true; }
3535 /// ActionEntry - Structure describing an entry in the actions table.
3536 struct ActionEntry {
3537 int ValueForTypeID; // The value to write - may not be equal to the type id.
3539 struct ActionEntry *Previous;
3542 /// PadRange - Structure holding a try-range and the associated landing pad.
3544 // The index of the landing pad.
3546 // The index of the begin and end labels in the landing pad's label lists.
3547 unsigned RangeIndex;
3550 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3552 /// CallSiteEntry - Structure describing an entry in the call-site table.
3553 struct CallSiteEntry {
3554 // The 'try-range' is BeginLabel .. EndLabel.
3555 unsigned BeginLabel; // zero indicates the start of the function.
3556 unsigned EndLabel; // zero indicates the end of the function.
3557 // The landing pad starts at PadLabel.
3558 unsigned PadLabel; // zero indicates that there is no landing pad.
3562 void EmitExceptionTable() {
3563 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3564 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3565 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3566 if (PadInfos.empty()) return;
3568 // Sort the landing pads in order of their type ids. This is used to fold
3569 // duplicate actions.
3570 SmallVector<const LandingPadInfo *, 64> LandingPads;
3571 LandingPads.reserve(PadInfos.size());
3572 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3573 LandingPads.push_back(&PadInfos[i]);
3574 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3576 // Negative type ids index into FilterIds, positive type ids index into
3577 // TypeInfos. The value written for a positive type id is just the type
3578 // id itself. For a negative type id, however, the value written is the
3579 // (negative) byte offset of the corresponding FilterIds entry. The byte
3580 // offset is usually equal to the type id, because the FilterIds entries
3581 // are written using a variable width encoding which outputs one byte per
3582 // entry as long as the value written is not too large, but can differ.
3583 // This kind of complication does not occur for positive type ids because
3584 // type infos are output using a fixed width encoding.
3585 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3586 SmallVector<int, 16> FilterOffsets;
3587 FilterOffsets.reserve(FilterIds.size());
3589 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3590 E = FilterIds.end(); I != E; ++I) {
3591 FilterOffsets.push_back(Offset);
3592 Offset -= TargetAsmInfo::getULEB128Size(*I);
3595 // Compute the actions table and gather the first action index for each
3596 // landing pad site.
3597 SmallVector<ActionEntry, 32> Actions;
3598 SmallVector<unsigned, 64> FirstActions;
3599 FirstActions.reserve(LandingPads.size());
3601 int FirstAction = 0;
3602 unsigned SizeActions = 0;
3603 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3604 const LandingPadInfo *LP = LandingPads[i];
3605 const std::vector<int> &TypeIds = LP->TypeIds;
3606 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3607 unsigned SizeSiteActions = 0;
3609 if (NumShared < TypeIds.size()) {
3610 unsigned SizeAction = 0;
3611 ActionEntry *PrevAction = 0;
3614 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3615 assert(Actions.size());
3616 PrevAction = &Actions.back();
3617 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3618 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3619 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3621 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3622 SizeAction += -PrevAction->NextAction;
3623 PrevAction = PrevAction->Previous;
3627 // Compute the actions.
3628 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3629 int TypeID = TypeIds[I];
3630 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3631 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3632 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3634 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3635 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3636 SizeSiteActions += SizeAction;
3638 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3639 Actions.push_back(Action);
3641 PrevAction = &Actions.back();
3644 // Record the first action of the landing pad site.
3645 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3646 } // else identical - re-use previous FirstAction
3648 FirstActions.push_back(FirstAction);
3650 // Compute this sites contribution to size.
3651 SizeActions += SizeSiteActions;
3654 // Compute the call-site table. The entry for an invoke has a try-range
3655 // containing the call, a non-zero landing pad and an appropriate action.
3656 // The entry for an ordinary call has a try-range containing the call and
3657 // zero for the landing pad and the action. Calls marked 'nounwind' have
3658 // no entry and must not be contained in the try-range of any entry - they
3659 // form gaps in the table. Entries must be ordered by try-range address.
3660 SmallVector<CallSiteEntry, 64> CallSites;
3662 RangeMapType PadMap;
3663 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3664 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3665 // try-ranges for them need be deduced.
3666 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3667 const LandingPadInfo *LandingPad = LandingPads[i];
3668 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3669 unsigned BeginLabel = LandingPad->BeginLabels[j];
3670 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3671 PadRange P = { i, j };
3672 PadMap[BeginLabel] = P;
3676 // The end label of the previous invoke or nounwind try-range.
3677 unsigned LastLabel = 0;
3679 // Whether there is a potentially throwing instruction (currently this means
3680 // an ordinary call) between the end of the previous try-range and now.
3681 bool SawPotentiallyThrowing = false;
3683 // Whether the last callsite entry was for an invoke.
3684 bool PreviousIsInvoke = false;
3686 // Visit all instructions in order of address.
3687 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3689 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3691 if (!MI->isLabel()) {
3692 SawPotentiallyThrowing |= MI->getDesc().isCall();
3696 unsigned BeginLabel = MI->getOperand(0).getImm();
3697 assert(BeginLabel && "Invalid label!");
3699 // End of the previous try-range?
3700 if (BeginLabel == LastLabel)
3701 SawPotentiallyThrowing = false;
3703 // Beginning of a new try-range?
3704 RangeMapType::iterator L = PadMap.find(BeginLabel);
3705 if (L == PadMap.end())
3706 // Nope, it was just some random label.
3709 PadRange P = L->second;
3710 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3712 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3713 "Inconsistent landing pad map!");
3715 // If some instruction between the previous try-range and this one may
3716 // throw, create a call-site entry with no landing pad for the region
3717 // between the try-ranges.
3718 if (SawPotentiallyThrowing) {
3719 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3720 CallSites.push_back(Site);
3721 PreviousIsInvoke = false;
3724 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3725 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3727 if (LandingPad->LandingPadLabel) {
3728 // This try-range is for an invoke.
3729 CallSiteEntry Site = {BeginLabel, LastLabel,
3730 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3732 // Try to merge with the previous call-site.
3733 if (PreviousIsInvoke) {
3734 CallSiteEntry &Prev = CallSites.back();
3735 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3736 // Extend the range of the previous entry.
3737 Prev.EndLabel = Site.EndLabel;
3742 // Otherwise, create a new call-site.
3743 CallSites.push_back(Site);
3744 PreviousIsInvoke = true;
3747 PreviousIsInvoke = false;
3751 // If some instruction between the previous try-range and the end of the
3752 // function may throw, create a call-site entry with no landing pad for the
3753 // region following the try-range.
3754 if (SawPotentiallyThrowing) {
3755 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3756 CallSites.push_back(Site);
3762 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3763 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3764 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3765 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3768 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3769 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3772 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3773 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3775 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3776 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3777 SizeSites + SizeActions + SizeTypes;
3779 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3780 sizeof(int8_t) + // TType format
3781 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3784 unsigned SizeAlign = (4 - TotalSize) & 3;
3786 // Begin the exception table.
3787 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3788 Asm->EmitAlignment(2, 0, 0, false);
3789 O << "GCC_except_table" << SubprogramCount << ":\n";
3790 for (unsigned i = 0; i != SizeAlign; ++i) {
3792 Asm->EOL("Padding");
3794 EmitLabel("exception", SubprogramCount);
3797 Asm->EmitInt8(DW_EH_PE_omit);
3798 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3799 Asm->EmitInt8(DW_EH_PE_absptr);
3800 Asm->EOL("TType format (DW_EH_PE_absptr)");
3801 Asm->EmitULEB128Bytes(TypeOffset);
3802 Asm->EOL("TType base offset");
3803 Asm->EmitInt8(DW_EH_PE_udata4);
3804 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3805 Asm->EmitULEB128Bytes(SizeSites);
3806 Asm->EOL("Call-site table length");
3808 // Emit the landing pad site information.
3809 for (unsigned i = 0; i < CallSites.size(); ++i) {
3810 CallSiteEntry &S = CallSites[i];
3811 const char *BeginTag;
3812 unsigned BeginNumber;
3814 if (!S.BeginLabel) {
3815 BeginTag = "eh_func_begin";
3816 BeginNumber = SubprogramCount;
3819 BeginNumber = S.BeginLabel;
3822 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3824 Asm->EOL("Region start");
3827 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3830 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3832 Asm->EOL("Region length");
3837 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3839 Asm->EOL("Landing pad");
3841 Asm->EmitULEB128Bytes(S.Action);
3845 // Emit the actions.
3846 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3847 ActionEntry &Action = Actions[I];
3849 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3850 Asm->EOL("TypeInfo index");
3851 Asm->EmitSLEB128Bytes(Action.NextAction);
3852 Asm->EOL("Next action");
3855 // Emit the type ids.
3856 for (unsigned M = TypeInfos.size(); M; --M) {
3857 GlobalVariable *GV = TypeInfos[M - 1];
3859 PrintRelDirective();
3862 O << Asm->getGlobalLinkName(GV);
3866 Asm->EOL("TypeInfo");
3869 // Emit the filter typeids.
3870 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3871 unsigned TypeID = FilterIds[j];
3872 Asm->EmitULEB128Bytes(TypeID);
3873 Asm->EOL("Filter TypeInfo index");
3876 Asm->EmitAlignment(2, 0, 0, false);
3880 //===--------------------------------------------------------------------===//
3881 // Main entry points.
3883 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3884 : Dwarf(OS, A, T, "eh")
3885 , shouldEmitTable(false)
3886 , shouldEmitMoves(false)
3887 , shouldEmitTableModule(false)
3888 , shouldEmitMovesModule(false)
3891 virtual ~DwarfException() {}
3893 /// SetModuleInfo - Set machine module information when it's known that pass
3894 /// manager has created it. Set by the target AsmPrinter.
3895 void SetModuleInfo(MachineModuleInfo *mmi) {
3899 /// BeginModule - Emit all exception information that should come prior to the
3901 void BeginModule(Module *M) {
3905 /// EndModule - Emit all exception information that should come after the
3908 if (shouldEmitMovesModule || shouldEmitTableModule) {
3909 const std::vector<Function *> Personalities = MMI->getPersonalities();
3910 for (unsigned i =0; i < Personalities.size(); ++i)
3911 EmitCommonEHFrame(Personalities[i], i);
3913 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3914 E = EHFrames.end(); I != E; ++I)
3919 /// BeginFunction - Gather pre-function exception information. Assumes being
3920 /// emitted immediately after the function entry point.
3921 void BeginFunction(MachineFunction *MF) {
3923 shouldEmitTable = shouldEmitMoves = false;
3924 if (MMI && TAI->doesSupportExceptionHandling()) {
3926 // Map all labels and get rid of any dead landing pads.
3927 MMI->TidyLandingPads();
3928 // If any landing pads survive, we need an EH table.
3929 if (MMI->getLandingPads().size())
3930 shouldEmitTable = true;
3932 // See if we need frame move info.
3933 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3934 shouldEmitMoves = true;
3936 if (shouldEmitMoves || shouldEmitTable)
3937 // Assumes in correct section after the entry point.
3938 EmitLabel("eh_func_begin", ++SubprogramCount);
3940 shouldEmitTableModule |= shouldEmitTable;
3941 shouldEmitMovesModule |= shouldEmitMoves;
3944 /// EndFunction - Gather and emit post-function exception information.
3946 void EndFunction() {
3947 if (shouldEmitMoves || shouldEmitTable) {
3948 EmitLabel("eh_func_end", SubprogramCount);
3949 EmitExceptionTable();
3951 // Save EH frame information
3953 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3955 MMI->getPersonalityIndex(),
3956 MF->getFrameInfo()->hasCalls(),
3957 !MMI->getLandingPads().empty(),
3958 MMI->getFrameMoves(),
3959 MF->getFunction()));
3964 } // End of namespace llvm
3966 //===----------------------------------------------------------------------===//
3968 /// Emit - Print the abbreviation using the specified Dwarf writer.
3970 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3971 // Emit its Dwarf tag type.
3972 DD.getAsm()->EmitULEB128Bytes(Tag);
3973 DD.getAsm()->EOL(TagString(Tag));
3975 // Emit whether it has children DIEs.
3976 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3977 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3979 // For each attribute description.
3980 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3981 const DIEAbbrevData &AttrData = Data[i];
3983 // Emit attribute type.
3984 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3985 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3988 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3989 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3992 // Mark end of abbreviation.
3993 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3994 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3998 void DIEAbbrev::print(std::ostream &O) {
3999 O << "Abbreviation @"
4000 << std::hex << (intptr_t)this << std::dec
4004 << ChildrenString(ChildrenFlag)
4007 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4009 << AttributeString(Data[i].getAttribute())
4011 << FormEncodingString(Data[i].getForm())
4015 void DIEAbbrev::dump() { print(cerr); }
4018 //===----------------------------------------------------------------------===//
4021 void DIEValue::dump() {
4026 //===----------------------------------------------------------------------===//
4028 /// EmitValue - Emit integer of appropriate size.
4030 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4032 case DW_FORM_flag: // Fall thru
4033 case DW_FORM_ref1: // Fall thru
4034 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4035 case DW_FORM_ref2: // Fall thru
4036 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4037 case DW_FORM_ref4: // Fall thru
4038 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4039 case DW_FORM_ref8: // Fall thru
4040 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4041 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4042 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4043 default: assert(0 && "DIE Value form not supported yet"); break;
4047 /// SizeOf - Determine size of integer value in bytes.
4049 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4051 case DW_FORM_flag: // Fall thru
4052 case DW_FORM_ref1: // Fall thru
4053 case DW_FORM_data1: return sizeof(int8_t);
4054 case DW_FORM_ref2: // Fall thru
4055 case DW_FORM_data2: return sizeof(int16_t);
4056 case DW_FORM_ref4: // Fall thru
4057 case DW_FORM_data4: return sizeof(int32_t);
4058 case DW_FORM_ref8: // Fall thru
4059 case DW_FORM_data8: return sizeof(int64_t);
4060 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4061 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4062 default: assert(0 && "DIE Value form not supported yet"); break;
4067 //===----------------------------------------------------------------------===//
4069 /// EmitValue - Emit string value.
4071 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4072 DD.getAsm()->EmitString(String);
4075 //===----------------------------------------------------------------------===//
4077 /// EmitValue - Emit label value.
4079 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4080 bool IsSmall = Form == DW_FORM_data4;
4081 DD.EmitReference(Label, false, IsSmall);
4084 /// SizeOf - Determine size of label value in bytes.
4086 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4087 if (Form == DW_FORM_data4) return 4;
4088 return DD.getTargetData()->getPointerSize();
4091 //===----------------------------------------------------------------------===//
4093 /// EmitValue - Emit label value.
4095 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4096 bool IsSmall = Form == DW_FORM_data4;
4097 DD.EmitReference(Label, false, IsSmall);
4100 /// SizeOf - Determine size of label value in bytes.
4102 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4103 if (Form == DW_FORM_data4) return 4;
4104 return DD.getTargetData()->getPointerSize();
4107 //===----------------------------------------------------------------------===//
4109 /// EmitValue - Emit delta value.
4111 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4112 bool IsSmall = Form == DW_FORM_data4;
4113 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4114 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4117 /// SizeOf - Determine size of delta value in bytes.
4119 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4120 if (Form == DW_FORM_data4) return 4;
4121 return DD.getTargetData()->getPointerSize();
4124 //===----------------------------------------------------------------------===//
4126 /// EmitValue - Emit delta value.
4128 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4129 bool IsSmall = Form == DW_FORM_data4;
4130 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4133 /// SizeOf - Determine size of delta value in bytes.
4135 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4136 if (Form == DW_FORM_data4) return 4;
4137 return DD.getTargetData()->getPointerSize();
4140 //===----------------------------------------------------------------------===//
4142 /// EmitValue - Emit debug information entry offset.
4144 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4145 DD.getAsm()->EmitInt32(Entry->getOffset());
4148 //===----------------------------------------------------------------------===//
4150 /// ComputeSize - calculate the size of the block.
4152 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4154 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4156 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4157 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4163 /// EmitValue - Emit block data.
4165 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4167 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4168 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4169 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4170 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4171 default: assert(0 && "Improper form for block"); break;
4174 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4176 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4178 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4182 /// SizeOf - Determine size of block data in bytes.
4184 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4186 case DW_FORM_block1: return Size + sizeof(int8_t);
4187 case DW_FORM_block2: return Size + sizeof(int16_t);
4188 case DW_FORM_block4: return Size + sizeof(int32_t);
4189 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4190 default: assert(0 && "Improper form for block"); break;
4195 //===----------------------------------------------------------------------===//
4196 /// DIE Implementation
4199 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4203 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4205 void DIE::AddSiblingOffset() {
4206 DIEInteger *DI = new DIEInteger(0);
4207 Values.insert(Values.begin(), DI);
4208 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4211 /// Profile - Used to gather unique data for the value folding set.
4213 void DIE::Profile(FoldingSetNodeID &ID) {
4216 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4217 ID.AddPointer(Children[i]);
4219 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4220 ID.AddPointer(Values[j]);
4224 void DIE::print(std::ostream &O, unsigned IncIndent) {
4225 static unsigned IndentCount = 0;
4226 IndentCount += IncIndent;
4227 const std::string Indent(IndentCount, ' ');
4228 bool isBlock = Abbrev.getTag() == 0;
4233 << "0x" << std::hex << (intptr_t)this << std::dec
4234 << ", Offset: " << Offset
4235 << ", Size: " << Size
4239 << TagString(Abbrev.getTag())
4241 << ChildrenString(Abbrev.getChildrenFlag());
4243 O << "Size: " << Size;
4247 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4250 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4254 O << AttributeString(Data[i].getAttribute());
4256 O << "Blk[" << i << "]";
4259 << FormEncodingString(Data[i].getForm())
4261 Values[i]->print(O);
4266 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4267 Children[j]->print(O, 4);
4270 if (!isBlock) O << "\n";
4271 IndentCount -= IncIndent;
4279 //===----------------------------------------------------------------------===//
4280 /// DwarfWriter Implementation
4283 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
4284 const TargetAsmInfo *T) {
4285 DE = new DwarfException(OS, A, T);
4286 DD = new DwarfDebug(OS, A, T);
4289 DwarfWriter::~DwarfWriter() {
4294 /// SetModuleInfo - Set machine module info when it's known that pass manager
4295 /// has created it. Set by the target AsmPrinter.
4296 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
4297 DD->SetModuleInfo(MMI);
4298 DE->SetModuleInfo(MMI);
4301 /// BeginModule - Emit all Dwarf sections that should come prior to the
4303 void DwarfWriter::BeginModule(Module *M) {
4308 /// EndModule - Emit all Dwarf sections that should come after the content.
4310 void DwarfWriter::EndModule() {
4315 /// BeginFunction - Gather pre-function debug information. Assumes being
4316 /// emitted immediately after the function entry point.
4317 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4318 DE->BeginFunction(MF);
4319 DD->BeginFunction(MF);
4322 /// EndFunction - Gather and emit post-function debug information.
4324 void DwarfWriter::EndFunction(MachineFunction *MF) {
4325 DD->EndFunction(MF);
4328 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4329 // Clear function debug information.