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;
727 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
728 /// descriptors to debug information entries using a DIEntry proxy.
729 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
731 /// Globals - A map of globally visible named entities for this unit.
733 std::map<std::string, DIE *> Globals;
735 /// DiesSet - Used to uniquely define dies within the compile unit.
737 FoldingSet<DIE> DiesSet;
739 /// Dies - List of all dies in the compile unit.
741 std::vector<DIE *> Dies;
744 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
751 , DiesSet(InitDiesSetSize)
758 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
763 CompileUnitDesc *getDesc() const { return Desc; }
764 unsigned getID() const { return ID; }
765 DIE* getDie() const { return Die; }
766 std::map<std::string, DIE *> &getGlobals() { return Globals; }
768 /// hasContent - Return true if this compile unit has something to write out.
770 bool hasContent() const {
771 return !Die->getChildren().empty();
774 /// AddGlobal - Add a new global entity to the compile unit.
776 void AddGlobal(const std::string &Name, DIE *Die) {
780 /// getDieMapSlotFor - Returns the debug information entry map slot for the
781 /// specified debug descriptor.
782 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
783 return DescToDieMap[DID];
786 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
787 /// specified debug descriptor.
788 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
789 return DescToDIEntryMap[DID];
792 /// AddDie - Adds or interns the DIE to the compile unit.
794 DIE *AddDie(DIE &Buffer) {
798 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
801 Die = new DIE(Buffer);
802 DiesSet.InsertNode(Die, Where);
803 this->Die->AddChild(Die);
811 //===----------------------------------------------------------------------===//
812 /// Dwarf - Emits general Dwarf directives.
818 //===--------------------------------------------------------------------===//
819 // Core attributes used by the Dwarf writer.
823 /// O - Stream to .s file.
827 /// Asm - Target of Dwarf emission.
831 /// TAI - Target asm information.
832 const TargetAsmInfo *TAI;
834 /// TD - Target data.
835 const TargetData *TD;
837 /// RI - Register Information.
838 const TargetRegisterInfo *RI;
840 /// M - Current module.
844 /// MF - Current machine function.
848 /// MMI - Collected machine module information.
850 MachineModuleInfo *MMI;
852 /// SubprogramCount - The running count of functions being compiled.
854 unsigned SubprogramCount;
856 /// Flavor - A unique string indicating what dwarf producer this is, used to
858 const char * const Flavor;
861 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
866 , TD(Asm->TM.getTargetData())
867 , RI(Asm->TM.getRegisterInfo())
879 //===--------------------------------------------------------------------===//
882 AsmPrinter *getAsm() const { return Asm; }
883 MachineModuleInfo *getMMI() const { return MMI; }
884 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
885 const TargetData *getTargetData() const { return TD; }
887 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
889 if (isInSection && TAI->getDwarfSectionOffsetDirective())
890 O << TAI->getDwarfSectionOffsetDirective();
891 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
892 O << TAI->getData32bitsDirective();
894 O << TAI->getData64bitsDirective();
897 /// PrintLabelName - Print label name in form used by Dwarf writer.
899 void PrintLabelName(DWLabel Label) const {
900 PrintLabelName(Label.Tag, Label.Number);
902 void PrintLabelName(const char *Tag, unsigned Number) const {
903 O << TAI->getPrivateGlobalPrefix() << Tag;
904 if (Number) O << Number;
907 void PrintLabelName(const char *Tag, unsigned Number,
908 const char *Suffix) const {
909 O << TAI->getPrivateGlobalPrefix() << Tag;
910 if (Number) O << Number;
914 /// EmitLabel - Emit location label for internal use by Dwarf.
916 void EmitLabel(DWLabel Label) const {
917 EmitLabel(Label.Tag, Label.Number);
919 void EmitLabel(const char *Tag, unsigned Number) const {
920 PrintLabelName(Tag, Number);
924 /// EmitReference - Emit a reference to a label.
926 void EmitReference(DWLabel Label, bool IsPCRelative = false,
927 bool Force32Bit = false) const {
928 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
930 void EmitReference(const char *Tag, unsigned Number,
931 bool IsPCRelative = false, bool Force32Bit = false) const {
932 PrintRelDirective(Force32Bit);
933 PrintLabelName(Tag, Number);
935 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
937 void EmitReference(const std::string &Name, bool IsPCRelative = false,
938 bool Force32Bit = false) const {
939 PrintRelDirective(Force32Bit);
943 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
946 /// EmitDifference - Emit the difference between two labels. Some
947 /// assemblers do not behave with absolute expressions with data directives,
948 /// so there is an option (needsSet) to use an intermediary set expression.
949 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
950 bool IsSmall = false) {
951 EmitDifference(LabelHi.Tag, LabelHi.Number,
952 LabelLo.Tag, LabelLo.Number,
955 void EmitDifference(const char *TagHi, unsigned NumberHi,
956 const char *TagLo, unsigned NumberLo,
957 bool IsSmall = false) {
958 if (TAI->needsSet()) {
960 PrintLabelName("set", SetCounter, Flavor);
962 PrintLabelName(TagHi, NumberHi);
964 PrintLabelName(TagLo, NumberLo);
967 PrintRelDirective(IsSmall);
968 PrintLabelName("set", SetCounter, Flavor);
971 PrintRelDirective(IsSmall);
973 PrintLabelName(TagHi, NumberHi);
975 PrintLabelName(TagLo, NumberLo);
979 void EmitSectionOffset(const char* Label, const char* Section,
980 unsigned LabelNumber, unsigned SectionNumber,
981 bool IsSmall = false, bool isEH = false,
982 bool useSet = true) {
983 bool printAbsolute = false;
985 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
987 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
989 if (TAI->needsSet() && useSet) {
991 PrintLabelName("set", SetCounter, Flavor);
993 PrintLabelName(Label, LabelNumber);
995 if (!printAbsolute) {
997 PrintLabelName(Section, SectionNumber);
1001 PrintRelDirective(IsSmall);
1003 PrintLabelName("set", SetCounter, Flavor);
1006 PrintRelDirective(IsSmall, true);
1008 PrintLabelName(Label, LabelNumber);
1010 if (!printAbsolute) {
1012 PrintLabelName(Section, SectionNumber);
1017 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1019 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1020 const std::vector<MachineMove> &Moves, bool isEH) {
1022 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1023 TargetFrameInfo::StackGrowsUp ?
1024 TD->getPointerSize() : -TD->getPointerSize();
1025 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1027 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1028 const MachineMove &Move = Moves[i];
1029 unsigned LabelID = Move.getLabelID();
1032 LabelID = MMI->MappedLabel(LabelID);
1034 // Throw out move if the label is invalid.
1035 if (!LabelID) continue;
1038 const MachineLocation &Dst = Move.getDestination();
1039 const MachineLocation &Src = Move.getSource();
1041 // Advance row if new location.
1042 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1043 Asm->EmitInt8(DW_CFA_advance_loc4);
1044 Asm->EOL("DW_CFA_advance_loc4");
1045 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1048 BaseLabelID = LabelID;
1049 BaseLabel = "label";
1053 // If advancing cfa.
1054 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1056 if (Src.getReg() == MachineLocation::VirtualFP) {
1057 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1058 Asm->EOL("DW_CFA_def_cfa_offset");
1060 Asm->EmitInt8(DW_CFA_def_cfa);
1061 Asm->EOL("DW_CFA_def_cfa");
1062 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1063 Asm->EOL("Register");
1066 int Offset = -Src.getOffset();
1068 Asm->EmitULEB128Bytes(Offset);
1071 assert(0 && "Machine move no supported yet.");
1073 } else if (Src.isReg() &&
1074 Src.getReg() == MachineLocation::VirtualFP) {
1076 Asm->EmitInt8(DW_CFA_def_cfa_register);
1077 Asm->EOL("DW_CFA_def_cfa_register");
1078 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1079 Asm->EOL("Register");
1081 assert(0 && "Machine move no supported yet.");
1084 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1085 int Offset = Dst.getOffset() / stackGrowth;
1088 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1089 Asm->EOL("DW_CFA_offset_extended_sf");
1090 Asm->EmitULEB128Bytes(Reg);
1092 Asm->EmitSLEB128Bytes(Offset);
1094 } else if (Reg < 64) {
1095 Asm->EmitInt8(DW_CFA_offset + Reg);
1097 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1100 Asm->EmitULEB128Bytes(Offset);
1103 Asm->EmitInt8(DW_CFA_offset_extended);
1104 Asm->EOL("DW_CFA_offset_extended");
1105 Asm->EmitULEB128Bytes(Reg);
1107 Asm->EmitULEB128Bytes(Offset);
1116 //===----------------------------------------------------------------------===//
1117 /// DwarfDebug - Emits Dwarf debug directives.
1119 class DwarfDebug : public Dwarf {
1122 //===--------------------------------------------------------------------===//
1123 // Attributes used to construct specific Dwarf sections.
1126 /// CompileUnits - All the compile units involved in this build. The index
1127 /// of each entry in this vector corresponds to the sources in MMI.
1128 std::vector<CompileUnit *> CompileUnits;
1130 /// AbbreviationsSet - Used to uniquely define abbreviations.
1132 FoldingSet<DIEAbbrev> AbbreviationsSet;
1134 /// Abbreviations - A list of all the unique abbreviations in use.
1136 std::vector<DIEAbbrev *> Abbreviations;
1138 /// ValuesSet - Used to uniquely define values.
1140 FoldingSet<DIEValue> ValuesSet;
1142 /// Values - A list of all the unique values in use.
1144 std::vector<DIEValue *> Values;
1146 /// StringPool - A UniqueVector of strings used by indirect references.
1148 UniqueVector<std::string> StringPool;
1150 /// UnitMap - Map debug information descriptor to compile unit.
1152 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1154 /// SectionMap - Provides a unique id per text section.
1156 UniqueVector<const Section*> SectionMap;
1158 /// SectionSourceLines - Tracks line numbers per text section.
1160 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1162 /// didInitial - Flag to indicate if initial emission has been done.
1166 /// shouldEmit - Flag to indicate if debug information should be emitted.
1170 struct FunctionDebugFrameInfo {
1172 std::vector<MachineMove> Moves;
1174 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1175 Number(Num), Moves(M) { }
1178 std::vector<FunctionDebugFrameInfo> DebugFrames;
1182 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1184 bool ShouldEmitDwarf() const { return shouldEmit; }
1186 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1188 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1189 // Profile the node so that we can make it unique.
1190 FoldingSetNodeID ID;
1193 // Check the set for priors.
1194 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1196 // If it's newly added.
1197 if (InSet == &Abbrev) {
1198 // Add to abbreviation list.
1199 Abbreviations.push_back(&Abbrev);
1200 // Assign the vector position + 1 as its number.
1201 Abbrev.setNumber(Abbreviations.size());
1203 // Assign existing abbreviation number.
1204 Abbrev.setNumber(InSet->getNumber());
1208 /// NewString - Add a string to the constant pool and returns a label.
1210 DWLabel NewString(const std::string &String) {
1211 unsigned StringID = StringPool.insert(String);
1212 return DWLabel("string", StringID);
1215 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1217 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1221 FoldingSetNodeID ID;
1222 DIEntry::Profile(ID, Entry);
1224 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1226 if (Value) return Value;
1228 Value = new DIEntry(Entry);
1229 ValuesSet.InsertNode(Value, Where);
1231 Value = new DIEntry(Entry);
1234 Values.push_back(Value);
1238 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1240 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1241 Value->Entry = Entry;
1242 // Add to values set if not already there. If it is, we merely have a
1243 // duplicate in the values list (no harm.)
1244 ValuesSet.GetOrInsertNode(Value);
1247 /// AddUInt - Add an unsigned integer attribute data and value.
1249 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1250 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1252 FoldingSetNodeID ID;
1253 DIEInteger::Profile(ID, Integer);
1255 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1257 Value = new DIEInteger(Integer);
1258 ValuesSet.InsertNode(Value, Where);
1259 Values.push_back(Value);
1262 Die->AddValue(Attribute, Form, Value);
1265 /// AddSInt - Add an signed integer attribute data and value.
1267 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1268 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1270 FoldingSetNodeID ID;
1271 DIEInteger::Profile(ID, (uint64_t)Integer);
1273 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1275 Value = new DIEInteger(Integer);
1276 ValuesSet.InsertNode(Value, Where);
1277 Values.push_back(Value);
1280 Die->AddValue(Attribute, Form, Value);
1283 /// AddString - Add a std::string attribute data and value.
1285 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1286 const std::string &String) {
1287 FoldingSetNodeID ID;
1288 DIEString::Profile(ID, String);
1290 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1292 Value = new DIEString(String);
1293 ValuesSet.InsertNode(Value, Where);
1294 Values.push_back(Value);
1297 Die->AddValue(Attribute, Form, Value);
1300 /// AddLabel - Add a Dwarf label attribute data and value.
1302 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1303 const DWLabel &Label) {
1304 FoldingSetNodeID ID;
1305 DIEDwarfLabel::Profile(ID, Label);
1307 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1309 Value = new DIEDwarfLabel(Label);
1310 ValuesSet.InsertNode(Value, Where);
1311 Values.push_back(Value);
1314 Die->AddValue(Attribute, Form, Value);
1317 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1319 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1320 const std::string &Label) {
1321 FoldingSetNodeID ID;
1322 DIEObjectLabel::Profile(ID, Label);
1324 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1326 Value = new DIEObjectLabel(Label);
1327 ValuesSet.InsertNode(Value, Where);
1328 Values.push_back(Value);
1331 Die->AddValue(Attribute, Form, Value);
1334 /// AddSectionOffset - Add a section offset label attribute data and value.
1336 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1337 const DWLabel &Label, const DWLabel &Section,
1338 bool isEH = false, bool useSet = true) {
1339 FoldingSetNodeID ID;
1340 DIESectionOffset::Profile(ID, Label, Section);
1342 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1344 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1345 ValuesSet.InsertNode(Value, Where);
1346 Values.push_back(Value);
1349 Die->AddValue(Attribute, Form, Value);
1352 /// AddDelta - Add a label delta attribute data and value.
1354 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1355 const DWLabel &Hi, const DWLabel &Lo) {
1356 FoldingSetNodeID ID;
1357 DIEDelta::Profile(ID, Hi, Lo);
1359 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1361 Value = new DIEDelta(Hi, Lo);
1362 ValuesSet.InsertNode(Value, Where);
1363 Values.push_back(Value);
1366 Die->AddValue(Attribute, Form, Value);
1369 /// AddDIEntry - Add a DIE attribute data and value.
1371 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1372 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1375 /// AddBlock - Add block data.
1377 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1378 Block->ComputeSize(*this);
1379 FoldingSetNodeID ID;
1382 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1385 ValuesSet.InsertNode(Value, Where);
1386 Values.push_back(Value);
1388 // Already exists, reuse the previous one.
1390 Block = cast<DIEBlock>(Value);
1393 Die->AddValue(Attribute, Block->BestForm(), Value);
1398 /// AddSourceLine - Add location information to specified debug information
1400 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1402 CompileUnit *FileUnit = FindCompileUnit(File);
1403 unsigned FileID = FileUnit->getID();
1404 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1405 AddUInt(Die, DW_AT_decl_line, 0, Line);
1409 /// AddAddress - Add an address attribute to a die based on the location
1411 void AddAddress(DIE *Die, unsigned Attribute,
1412 const MachineLocation &Location) {
1413 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1414 DIEBlock *Block = new DIEBlock();
1416 if (Location.isReg()) {
1418 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1420 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1421 AddUInt(Block, 0, DW_FORM_udata, Reg);
1425 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1427 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1428 AddUInt(Block, 0, DW_FORM_udata, Reg);
1430 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1433 AddBlock(Die, Attribute, 0, Block);
1436 /// AddBasicType - Add a new basic type attribute to the specified entity.
1438 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1439 const std::string &Name,
1440 unsigned Encoding, unsigned Size) {
1442 DIE Buffer(DW_TAG_base_type);
1443 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1444 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1445 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1446 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1447 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1450 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1452 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1453 DIE Buffer(DW_TAG_pointer_type);
1454 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1455 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1456 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1457 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1460 /// AddType - Add a new type attribute to the specified entity.
1462 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1464 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1466 // Check for pre-existence.
1467 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1469 // If it exists then use the existing value.
1471 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1475 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1476 // FIXME - Not sure why programs and variables are coming through here.
1477 // Short cut for handling subprogram types (not really a TyDesc.)
1478 AddPointerType(Entity, Unit, SubprogramTy->getName());
1479 } else if (GlobalVariableDesc *GlobalTy =
1480 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1481 // FIXME - Not sure why programs and variables are coming through here.
1482 // Short cut for handling global variable types (not really a TyDesc.)
1483 AddPointerType(Entity, Unit, GlobalTy->getName());
1486 Slot = NewDIEntry();
1489 DIE Buffer(DW_TAG_base_type);
1490 ConstructType(Buffer, TyDesc, Unit);
1492 // Add debug information entry to entity and unit.
1493 DIE *Die = Unit->AddDie(Buffer);
1494 SetDIEntry(Slot, Die);
1495 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1500 /// ConstructType - Construct basic type die from DIBasicType.
1501 void ConstructType(CompileUnit *DW_Unit, DIE &Buffer,
1504 // Get core information.
1505 const std::string &Name = BTy->getName();
1506 Buffer.setTag(DW_TAG_base_type);
1507 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1508 // Add name if not anonymous or intermediate type.
1510 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1511 uint64_t Size = BTy->getSizeInBits() >> 3;
1512 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1515 /// ConstructType - Construct derived type die from DIDerivedType.
1516 void ConstructType(CompileUnit *DW_Unit, DIE &Buffer,
1517 DIDerivedType *DTy) {
1519 // Get core information.
1520 const std::string &Name = DTy->getName();
1521 uint64_t Size = DTy->getSizeInBits() >> 3;
1522 unsigned Tag = DTy->getTag();
1523 // FIXME - Workaround for templates.
1524 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1527 // Map to main type, void will not have a type.
1528 DIType FromTy = DTy->getTypeDerivedFrom();
1529 // FIXME - Enable this. AddType(&Buffer, FromTy, DW_Unit);
1531 // Add name if not anonymous or intermediate type.
1532 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1534 // Add size if non-zero (derived types might be zero-sized.)
1536 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1538 // Add source line info if available and TyDesc is not a forward
1540 // FIXME - Enable this. if (!DTy->isForwardDecl())
1541 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1544 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1545 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1546 int64_t L = SR->getLo();
1547 int64_t H = SR->getHi();
1548 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1550 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1552 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1553 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1555 Buffer.AddChild(DW_Subrange);
1558 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1559 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1560 DICompositeType *CTy) {
1561 Buffer.setTag(DW_TAG_array_type);
1562 if (CTy->getTag() == DW_TAG_vector_type)
1563 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1565 DIArray Elements = CTy->getTypeArray();
1566 // FIXME - Enable this.
1567 // AddType(&Buffer, CTy->getTypeDerivedFrom(), DW_Unit);
1569 // Construct an anonymous type for index type.
1570 DIE IdxBuffer(DW_TAG_base_type);
1571 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1572 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1573 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1575 // Add subranges to array type.
1576 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1577 DISubrange Element = Elements.getElement(i);
1578 ConstructSubrangeDIE(Buffer, &Element, IndexTy);
1583 /// ConstructType - Adds all the required attributes to the type.
1585 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1586 // Get core information.
1587 const std::string &Name = TyDesc->getName();
1588 uint64_t Size = TyDesc->getSize() >> 3;
1590 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1591 // Fundamental types like int, float, bool
1592 Buffer.setTag(DW_TAG_base_type);
1593 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1594 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1596 unsigned Tag = DerivedTy->getTag();
1597 // FIXME - Workaround for templates.
1598 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1599 // Pointers, typedefs et al.
1601 // Map to main type, void will not have a type.
1602 if (TypeDesc *FromTy = DerivedTy->getFromType())
1603 AddType(&Buffer, FromTy, Unit);
1604 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1606 unsigned Tag = CompTy->getTag();
1608 // Set tag accordingly.
1609 if (Tag == DW_TAG_vector_type)
1610 Buffer.setTag(DW_TAG_array_type);
1614 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1617 case DW_TAG_vector_type:
1618 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1620 case DW_TAG_array_type: {
1621 // Add element type.
1622 if (TypeDesc *FromTy = CompTy->getFromType())
1623 AddType(&Buffer, FromTy, Unit);
1625 // Don't emit size attribute.
1628 // Construct an anonymous type for index type.
1629 DIE Buffer(DW_TAG_base_type);
1630 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
1631 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1632 DIE *IndexTy = Unit->AddDie(Buffer);
1634 // Add subranges to array type.
1635 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1636 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1637 int64_t Lo = SRD->getLo();
1638 int64_t Hi = SRD->getHi();
1639 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1641 // If a range is available.
1643 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1644 // Only add low if non-zero.
1645 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1646 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1649 Buffer.AddChild(Subrange);
1653 case DW_TAG_structure_type:
1654 case DW_TAG_union_type: {
1655 // Add elements to structure type.
1656 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1657 DebugInfoDesc *Element = Elements[i];
1659 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1660 // Add field or base class.
1661 unsigned Tag = MemberDesc->getTag();
1663 // Extract the basic information.
1664 const std::string &Name = MemberDesc->getName();
1665 uint64_t Size = MemberDesc->getSize();
1666 uint64_t Align = MemberDesc->getAlign();
1667 uint64_t Offset = MemberDesc->getOffset();
1669 // Construct member debug information entry.
1670 DIE *Member = new DIE(Tag);
1672 // Add name if not "".
1674 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1676 // Add location if available.
1677 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1679 // Most of the time the field info is the same as the members.
1680 uint64_t FieldSize = Size;
1681 uint64_t FieldAlign = Align;
1682 uint64_t FieldOffset = Offset;
1684 // Set the member type.
1685 TypeDesc *FromTy = MemberDesc->getFromType();
1686 AddType(Member, FromTy, Unit);
1688 // Walk up typedefs until a real size is found.
1690 if (FromTy->getTag() != DW_TAG_typedef) {
1691 FieldSize = FromTy->getSize();
1692 FieldAlign = FromTy->getAlign();
1696 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1699 // Unless we have a bit field.
1700 if (Tag == DW_TAG_member && FieldSize != Size) {
1701 // Construct the alignment mask.
1702 uint64_t AlignMask = ~(FieldAlign - 1);
1703 // Determine the high bit + 1 of the declared size.
1704 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1705 // Work backwards to determine the base offset of the field.
1706 FieldOffset = HiMark - FieldSize;
1707 // Now normalize offset to the field.
1708 Offset -= FieldOffset;
1710 // Maybe we need to work from the other end.
1711 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1713 // Add size and offset.
1714 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1715 AddUInt(Member, DW_AT_bit_size, 0, Size);
1716 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1719 // Add computation for offset.
1720 DIEBlock *Block = new DIEBlock();
1721 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1722 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1723 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1725 // Add accessibility (public default unless is base class.
1726 if (MemberDesc->isProtected()) {
1727 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1728 } else if (MemberDesc->isPrivate()) {
1729 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1730 } else if (Tag == DW_TAG_inheritance) {
1731 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1734 Buffer.AddChild(Member);
1735 } else if (GlobalVariableDesc *StaticDesc =
1736 dyn_cast<GlobalVariableDesc>(Element)) {
1737 // Add static member.
1739 // Construct member debug information entry.
1740 DIE *Static = new DIE(DW_TAG_variable);
1742 // Add name and mangled name.
1743 const std::string &Name = StaticDesc->getName();
1744 const std::string &LinkageName = StaticDesc->getLinkageName();
1745 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1746 if (!LinkageName.empty()) {
1747 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1752 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1755 if (TypeDesc *StaticTy = StaticDesc->getType())
1756 AddType(Static, StaticTy, Unit);
1759 if (!StaticDesc->isStatic())
1760 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1761 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1763 Buffer.AddChild(Static);
1764 } else if (SubprogramDesc *MethodDesc =
1765 dyn_cast<SubprogramDesc>(Element)) {
1766 // Add member function.
1768 // Construct member debug information entry.
1769 DIE *Method = new DIE(DW_TAG_subprogram);
1771 // Add name and mangled name.
1772 const std::string &Name = MethodDesc->getName();
1773 const std::string &LinkageName = MethodDesc->getLinkageName();
1775 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1776 bool IsCTor = TyDesc->getName() == Name;
1778 if (!LinkageName.empty()) {
1779 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1784 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1787 if (CompositeTypeDesc *MethodTy =
1788 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1789 // Get argument information.
1790 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1795 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1799 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
1800 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1801 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1802 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1803 Method->AddChild(Arg);
1808 if (!MethodDesc->isStatic())
1809 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1810 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1812 Buffer.AddChild(Method);
1817 case DW_TAG_enumeration_type: {
1818 // Add enumerators to enumeration type.
1819 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1820 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1821 const std::string &Name = ED->getName();
1822 int64_t Value = ED->getValue();
1823 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1824 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1825 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1826 Buffer.AddChild(Enumerator);
1831 case DW_TAG_subroutine_type: {
1832 // Add prototype flag.
1833 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1835 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1838 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
1839 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1840 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1841 Buffer.AddChild(Arg);
1850 // Add name if not anonymous or intermediate type.
1851 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1853 // Add size if non-zero (derived types might be zero-sized.)
1855 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1856 else if (isa<CompositeTypeDesc>(TyDesc)) {
1857 // If TyDesc is a composite type, then add size even if it's zero unless
1858 // it's a forward declaration.
1859 if (TyDesc->isForwardDecl())
1860 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1862 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1865 // Add source line info if available and TyDesc is not a forward
1867 if (!TyDesc->isForwardDecl())
1868 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1871 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1873 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1874 // Construct debug information entry.
1875 DIE *Die = new DIE(DW_TAG_compile_unit);
1876 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
1877 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
1878 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1879 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1880 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1881 if (!UnitDesc->getDirectory().empty())
1882 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1884 // Construct compile unit.
1885 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1887 // Add Unit to compile unit map.
1888 DescToUnitMap[UnitDesc] = Unit;
1893 /// GetBaseCompileUnit - Get the main compile unit.
1895 CompileUnit *GetBaseCompileUnit() const {
1896 CompileUnit *Unit = CompileUnits[0];
1897 assert(Unit && "Missing compile unit.");
1901 /// FindCompileUnit - Get the compile unit for the given descriptor.
1903 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1904 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1905 assert(Unit && "Missing compile unit.");
1909 /// NewGlobalVariable - Add a new global variable DIE.
1911 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1912 // Get the compile unit context.
1913 CompileUnitDesc *UnitDesc =
1914 static_cast<CompileUnitDesc *>(GVD->getContext());
1915 CompileUnit *Unit = GetBaseCompileUnit();
1917 // Check for pre-existence.
1918 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1919 if (Slot) return Slot;
1921 // Get the global variable itself.
1922 GlobalVariable *GV = GVD->getGlobalVariable();
1924 const std::string &Name = GVD->getName();
1925 const std::string &FullName = GVD->getFullName();
1926 const std::string &LinkageName = GVD->getLinkageName();
1927 // Create the global's variable DIE.
1928 DIE *VariableDie = new DIE(DW_TAG_variable);
1929 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1930 if (!LinkageName.empty()) {
1931 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1934 AddType(VariableDie, GVD->getType(), Unit);
1935 if (!GVD->isStatic())
1936 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1938 // Add source line info if available.
1939 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1942 DIEBlock *Block = new DIEBlock();
1943 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1944 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1945 AddBlock(VariableDie, DW_AT_location, 0, Block);
1950 // Add to context owner.
1951 Unit->getDie()->AddChild(VariableDie);
1953 // Expose as global.
1954 // FIXME - need to check external flag.
1955 Unit->AddGlobal(FullName, VariableDie);
1960 /// NewSubprogram - Add a new subprogram DIE.
1962 DIE *NewSubprogram(SubprogramDesc *SPD) {
1963 // Get the compile unit context.
1964 CompileUnitDesc *UnitDesc =
1965 static_cast<CompileUnitDesc *>(SPD->getContext());
1966 CompileUnit *Unit = GetBaseCompileUnit();
1968 // Check for pre-existence.
1969 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1970 if (Slot) return Slot;
1972 // Gather the details (simplify add attribute code.)
1973 const std::string &Name = SPD->getName();
1974 const std::string &FullName = SPD->getFullName();
1975 const std::string &LinkageName = SPD->getLinkageName();
1977 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1978 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1979 if (!LinkageName.empty()) {
1980 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1983 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1984 if (!SPD->isStatic())
1985 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1986 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1988 // Add source line info if available.
1989 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1992 Slot = SubprogramDie;
1994 // Add to context owner.
1995 Unit->getDie()->AddChild(SubprogramDie);
1997 // Expose as global.
1998 Unit->AddGlobal(FullName, SubprogramDie);
2000 return SubprogramDie;
2003 /// NewScopeVariable - Create a new scope variable.
2005 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2006 // Get the descriptor.
2007 VariableDesc *VD = DV->getDesc();
2009 // Translate tag to proper Dwarf tag. The result variable is dropped for
2012 switch (VD->getTag()) {
2013 case DW_TAG_return_variable: return NULL;
2014 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2015 case DW_TAG_auto_variable: // fall thru
2016 default: Tag = DW_TAG_variable; break;
2019 // Define variable debug information entry.
2020 DIE *VariableDie = new DIE(Tag);
2021 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2023 // Add source line info if available.
2024 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2026 // Add variable type.
2027 AddType(VariableDie, VD->getType(), Unit);
2029 // Add variable address.
2030 MachineLocation Location;
2031 Location.set(RI->getFrameRegister(*MF),
2032 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2033 AddAddress(VariableDie, DW_AT_location, Location);
2038 /// ConstructScope - Construct the components of a scope.
2040 void ConstructScope(DebugScope *ParentScope,
2041 unsigned ParentStartID, unsigned ParentEndID,
2042 DIE *ParentDie, CompileUnit *Unit) {
2043 // Add variables to scope.
2044 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2045 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2046 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2047 if (VariableDie) ParentDie->AddChild(VariableDie);
2050 // Add nested scopes.
2051 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2052 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2053 // Define the Scope debug information entry.
2054 DebugScope *Scope = Scopes[j];
2055 // FIXME - Ignore inlined functions for the time being.
2056 if (!Scope->getParent()) continue;
2058 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2059 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2061 // Ignore empty scopes.
2062 if (StartID == EndID && StartID != 0) continue;
2063 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2065 if (StartID == ParentStartID && EndID == ParentEndID) {
2066 // Just add stuff to the parent scope.
2067 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2069 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2071 // Add the scope bounds.
2073 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2074 DWLabel("label", StartID));
2076 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2077 DWLabel("func_begin", SubprogramCount));
2080 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2081 DWLabel("label", EndID));
2083 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2084 DWLabel("func_end", SubprogramCount));
2087 // Add the scope contents.
2088 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2089 ParentDie->AddChild(ScopeDie);
2094 /// ConstructRootScope - Construct the scope for the subprogram.
2096 void ConstructRootScope(DebugScope *RootScope) {
2097 // Exit if there is no root scope.
2098 if (!RootScope) return;
2100 // Get the subprogram debug information entry.
2101 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2103 // Get the compile unit context.
2104 CompileUnit *Unit = GetBaseCompileUnit();
2106 // Get the subprogram die.
2107 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2108 assert(SPDie && "Missing subprogram descriptor");
2110 // Add the function bounds.
2111 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2112 DWLabel("func_begin", SubprogramCount));
2113 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2114 DWLabel("func_end", SubprogramCount));
2115 MachineLocation Location(RI->getFrameRegister(*MF));
2116 AddAddress(SPDie, DW_AT_frame_base, Location);
2118 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2121 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2123 void ConstructDefaultScope(MachineFunction *MF) {
2124 // Find the correct subprogram descriptor.
2125 std::vector<SubprogramDesc *> Subprograms;
2126 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2128 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2129 SubprogramDesc *SPD = Subprograms[i];
2131 if (SPD->getName() == MF->getFunction()->getName()) {
2132 // Get the compile unit context.
2133 CompileUnit *Unit = GetBaseCompileUnit();
2135 // Get the subprogram die.
2136 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2137 assert(SPDie && "Missing subprogram descriptor");
2139 // Add the function bounds.
2140 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2141 DWLabel("func_begin", SubprogramCount));
2142 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2143 DWLabel("func_end", SubprogramCount));
2145 MachineLocation Location(RI->getFrameRegister(*MF));
2146 AddAddress(SPDie, DW_AT_frame_base, Location);
2151 // FIXME: This is causing an abort because C++ mangled names are compared
2152 // with their unmangled counterparts. See PR2885. Don't do this assert.
2153 assert(0 && "Couldn't find DIE for machine function!");
2157 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2158 /// tools to recognize the object file contains Dwarf information.
2159 void EmitInitial() {
2160 // Check to see if we already emitted intial headers.
2161 if (didInitial) return;
2164 // Dwarf sections base addresses.
2165 if (TAI->doesDwarfRequireFrameSection()) {
2166 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2167 EmitLabel("section_debug_frame", 0);
2169 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2170 EmitLabel("section_info", 0);
2171 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2172 EmitLabel("section_abbrev", 0);
2173 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2174 EmitLabel("section_aranges", 0);
2175 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2176 EmitLabel("section_macinfo", 0);
2177 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2178 EmitLabel("section_line", 0);
2179 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2180 EmitLabel("section_loc", 0);
2181 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2182 EmitLabel("section_pubnames", 0);
2183 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2184 EmitLabel("section_str", 0);
2185 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2186 EmitLabel("section_ranges", 0);
2188 Asm->SwitchToSection(TAI->getTextSection());
2189 EmitLabel("text_begin", 0);
2190 Asm->SwitchToSection(TAI->getDataSection());
2191 EmitLabel("data_begin", 0);
2194 /// EmitDIE - Recusively Emits a debug information entry.
2196 void EmitDIE(DIE *Die) {
2197 // Get the abbreviation for this DIE.
2198 unsigned AbbrevNumber = Die->getAbbrevNumber();
2199 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2203 // Emit the code (index) for the abbreviation.
2204 Asm->EmitULEB128Bytes(AbbrevNumber);
2207 Asm->EOL(std::string("Abbrev [" +
2208 utostr(AbbrevNumber) +
2209 "] 0x" + utohexstr(Die->getOffset()) +
2210 ":0x" + utohexstr(Die->getSize()) + " " +
2211 TagString(Abbrev->getTag())));
2215 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2216 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2218 // Emit the DIE attribute values.
2219 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2220 unsigned Attr = AbbrevData[i].getAttribute();
2221 unsigned Form = AbbrevData[i].getForm();
2222 assert(Form && "Too many attributes for DIE (check abbreviation)");
2225 case DW_AT_sibling: {
2226 Asm->EmitInt32(Die->SiblingOffset());
2230 // Emit an attribute using the defined form.
2231 Values[i]->EmitValue(*this, Form);
2236 Asm->EOL(AttributeString(Attr));
2239 // Emit the DIE children if any.
2240 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2241 const std::vector<DIE *> &Children = Die->getChildren();
2243 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2244 EmitDIE(Children[j]);
2247 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2251 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2253 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2254 // Get the children.
2255 const std::vector<DIE *> &Children = Die->getChildren();
2257 // If not last sibling and has children then add sibling offset attribute.
2258 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2260 // Record the abbreviation.
2261 AssignAbbrevNumber(Die->getAbbrev());
2263 // Get the abbreviation for this DIE.
2264 unsigned AbbrevNumber = Die->getAbbrevNumber();
2265 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2268 Die->setOffset(Offset);
2270 // Start the size with the size of abbreviation code.
2271 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2273 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2274 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2276 // Size the DIE attribute values.
2277 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2278 // Size attribute value.
2279 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2282 // Size the DIE children if any.
2283 if (!Children.empty()) {
2284 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2285 "Children flag not set");
2287 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2288 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2291 // End of children marker.
2292 Offset += sizeof(int8_t);
2295 Die->setSize(Offset - Die->getOffset());
2299 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2301 void SizeAndOffsets() {
2302 // Process base compile unit.
2303 CompileUnit *Unit = GetBaseCompileUnit();
2304 // Compute size of compile unit header
2305 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2306 sizeof(int16_t) + // DWARF version number
2307 sizeof(int32_t) + // Offset Into Abbrev. Section
2308 sizeof(int8_t); // Pointer Size (in bytes)
2309 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2312 /// EmitDebugInfo - Emit the debug info section.
2314 void EmitDebugInfo() {
2315 // Start debug info section.
2316 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2318 CompileUnit *Unit = GetBaseCompileUnit();
2319 DIE *Die = Unit->getDie();
2320 // Emit the compile units header.
2321 EmitLabel("info_begin", Unit->getID());
2322 // Emit size of content not including length itself
2323 unsigned ContentSize = Die->getSize() +
2324 sizeof(int16_t) + // DWARF version number
2325 sizeof(int32_t) + // Offset Into Abbrev. Section
2326 sizeof(int8_t) + // Pointer Size (in bytes)
2327 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2329 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2330 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2331 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2332 Asm->EOL("Offset Into Abbrev. Section");
2333 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2336 // FIXME - extra padding for gdb bug.
2337 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2338 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2339 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2340 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2341 EmitLabel("info_end", Unit->getID());
2346 /// EmitAbbreviations - Emit the abbreviation section.
2348 void EmitAbbreviations() const {
2349 // Check to see if it is worth the effort.
2350 if (!Abbreviations.empty()) {
2351 // Start the debug abbrev section.
2352 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2354 EmitLabel("abbrev_begin", 0);
2356 // For each abbrevation.
2357 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2358 // Get abbreviation data
2359 const DIEAbbrev *Abbrev = Abbreviations[i];
2361 // Emit the abbrevations code (base 1 index.)
2362 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2363 Asm->EOL("Abbreviation Code");
2365 // Emit the abbreviations data.
2366 Abbrev->Emit(*this);
2371 // Mark end of abbreviations.
2372 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2374 EmitLabel("abbrev_end", 0);
2380 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2381 /// the line matrix.
2383 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2384 // Define last address of section.
2385 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2386 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2387 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2388 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2390 // Mark end of matrix.
2391 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2392 Asm->EmitULEB128Bytes(1); Asm->EOL();
2393 Asm->EmitInt8(1); Asm->EOL();
2396 /// EmitDebugLines - Emit source line information.
2398 void EmitDebugLines() {
2399 // If the target is using .loc/.file, the assembler will be emitting the
2400 // .debug_line table automatically.
2401 if (TAI->hasDotLocAndDotFile())
2404 // Minimum line delta, thus ranging from -10..(255-10).
2405 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2406 // Maximum line delta, thus ranging from -10..(255-10).
2407 const int MaxLineDelta = 255 + MinLineDelta;
2409 // Start the dwarf line section.
2410 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2412 // Construct the section header.
2414 EmitDifference("line_end", 0, "line_begin", 0, true);
2415 Asm->EOL("Length of Source Line Info");
2416 EmitLabel("line_begin", 0);
2418 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2420 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2421 Asm->EOL("Prolog Length");
2422 EmitLabel("line_prolog_begin", 0);
2424 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2426 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2428 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2430 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2432 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2434 // Line number standard opcode encodings argument count
2435 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2436 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2437 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2438 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2439 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2440 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2441 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2442 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2443 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2445 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2446 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2448 // Emit directories.
2449 for (unsigned DirectoryID = 1, NDID = Directories.size();
2450 DirectoryID <= NDID; ++DirectoryID) {
2451 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2453 Asm->EmitInt8(0); Asm->EOL("End of directories");
2456 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2457 SourceID <= NSID; ++SourceID) {
2458 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2459 Asm->EmitString(SourceFile.getName());
2461 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2462 Asm->EOL("Directory #");
2463 Asm->EmitULEB128Bytes(0);
2464 Asm->EOL("Mod date");
2465 Asm->EmitULEB128Bytes(0);
2466 Asm->EOL("File size");
2468 Asm->EmitInt8(0); Asm->EOL("End of files");
2470 EmitLabel("line_prolog_end", 0);
2472 // A sequence for each text section.
2473 unsigned SecSrcLinesSize = SectionSourceLines.size();
2475 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2476 // Isolate current sections line info.
2477 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2480 const Section* S = SectionMap[j + 1];
2481 Asm->EOL(std::string("Section ") + S->getName());
2485 // Dwarf assumes we start with first line of first source file.
2486 unsigned Source = 1;
2489 // Construct rows of the address, source, line, column matrix.
2490 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2491 const SourceLineInfo &LineInfo = LineInfos[i];
2492 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2493 if (!LabelID) continue;
2495 unsigned SourceID = LineInfo.getSourceID();
2496 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2497 unsigned DirectoryID = SourceFile.getDirectoryID();
2499 Asm->EOL(Directories[DirectoryID]
2500 + SourceFile.getName()
2502 + utostr_32(LineInfo.getLine()));
2506 // Define the line address.
2507 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2508 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2509 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2510 EmitReference("label", LabelID); Asm->EOL("Location label");
2512 // If change of source, then switch to the new source.
2513 if (Source != LineInfo.getSourceID()) {
2514 Source = LineInfo.getSourceID();
2515 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2516 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2519 // If change of line.
2520 if (Line != LineInfo.getLine()) {
2521 // Determine offset.
2522 int Offset = LineInfo.getLine() - Line;
2523 int Delta = Offset - MinLineDelta;
2526 Line = LineInfo.getLine();
2528 // If delta is small enough and in range...
2529 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2530 // ... then use fast opcode.
2531 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2533 // ... otherwise use long hand.
2534 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2535 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2536 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2539 // Copy the previous row (different address or source)
2540 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2544 EmitEndOfLineMatrix(j + 1);
2547 if (SecSrcLinesSize == 0)
2548 // Because we're emitting a debug_line section, we still need a line
2549 // table. The linker and friends expect it to exist. If there's nothing to
2550 // put into it, emit an empty table.
2551 EmitEndOfLineMatrix(1);
2553 EmitLabel("line_end", 0);
2558 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2560 void EmitCommonDebugFrame() {
2561 if (!TAI->doesDwarfRequireFrameSection())
2565 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2566 TargetFrameInfo::StackGrowsUp ?
2567 TD->getPointerSize() : -TD->getPointerSize();
2569 // Start the dwarf frame section.
2570 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2572 EmitLabel("debug_frame_common", 0);
2573 EmitDifference("debug_frame_common_end", 0,
2574 "debug_frame_common_begin", 0, true);
2575 Asm->EOL("Length of Common Information Entry");
2577 EmitLabel("debug_frame_common_begin", 0);
2578 Asm->EmitInt32((int)DW_CIE_ID);
2579 Asm->EOL("CIE Identifier Tag");
2580 Asm->EmitInt8(DW_CIE_VERSION);
2581 Asm->EOL("CIE Version");
2582 Asm->EmitString("");
2583 Asm->EOL("CIE Augmentation");
2584 Asm->EmitULEB128Bytes(1);
2585 Asm->EOL("CIE Code Alignment Factor");
2586 Asm->EmitSLEB128Bytes(stackGrowth);
2587 Asm->EOL("CIE Data Alignment Factor");
2588 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2589 Asm->EOL("CIE RA Column");
2591 std::vector<MachineMove> Moves;
2592 RI->getInitialFrameState(Moves);
2594 EmitFrameMoves(NULL, 0, Moves, false);
2596 Asm->EmitAlignment(2, 0, 0, false);
2597 EmitLabel("debug_frame_common_end", 0);
2602 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2604 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2605 if (!TAI->doesDwarfRequireFrameSection())
2608 // Start the dwarf frame section.
2609 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2611 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2612 "debug_frame_begin", DebugFrameInfo.Number, true);
2613 Asm->EOL("Length of Frame Information Entry");
2615 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2617 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2619 Asm->EOL("FDE CIE offset");
2621 EmitReference("func_begin", DebugFrameInfo.Number);
2622 Asm->EOL("FDE initial location");
2623 EmitDifference("func_end", DebugFrameInfo.Number,
2624 "func_begin", DebugFrameInfo.Number);
2625 Asm->EOL("FDE address range");
2627 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2629 Asm->EmitAlignment(2, 0, 0, false);
2630 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2635 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2637 void EmitDebugPubNames() {
2638 // Start the dwarf pubnames section.
2639 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2641 CompileUnit *Unit = GetBaseCompileUnit();
2643 EmitDifference("pubnames_end", Unit->getID(),
2644 "pubnames_begin", Unit->getID(), true);
2645 Asm->EOL("Length of Public Names Info");
2647 EmitLabel("pubnames_begin", Unit->getID());
2649 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2651 EmitSectionOffset("info_begin", "section_info",
2652 Unit->getID(), 0, true, false);
2653 Asm->EOL("Offset of Compilation Unit Info");
2655 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2656 Asm->EOL("Compilation Unit Length");
2658 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2660 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2663 const std::string &Name = GI->first;
2664 DIE * Entity = GI->second;
2666 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2667 Asm->EmitString(Name); Asm->EOL("External Name");
2670 Asm->EmitInt32(0); Asm->EOL("End Mark");
2671 EmitLabel("pubnames_end", Unit->getID());
2676 /// EmitDebugStr - Emit visible names into a debug str section.
2678 void EmitDebugStr() {
2679 // Check to see if it is worth the effort.
2680 if (!StringPool.empty()) {
2681 // Start the dwarf str section.
2682 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2684 // For each of strings in the string pool.
2685 for (unsigned StringID = 1, N = StringPool.size();
2686 StringID <= N; ++StringID) {
2687 // Emit a label for reference from debug information entries.
2688 EmitLabel("string", StringID);
2689 // Emit the string itself.
2690 const std::string &String = StringPool[StringID];
2691 Asm->EmitString(String); Asm->EOL();
2698 /// EmitDebugLoc - Emit visible names into a debug loc section.
2700 void EmitDebugLoc() {
2701 // Start the dwarf loc section.
2702 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2707 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2709 void EmitDebugARanges() {
2710 // Start the dwarf aranges section.
2711 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2715 CompileUnit *Unit = GetBaseCompileUnit();
2717 // Don't include size of length
2718 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2720 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2722 EmitReference("info_begin", Unit->getID());
2723 Asm->EOL("Offset of Compilation Unit Info");
2725 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2727 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2729 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2730 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2733 EmitReference("text_begin", 0); Asm->EOL("Address");
2734 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2736 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2737 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2743 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2745 void EmitDebugRanges() {
2746 // Start the dwarf ranges section.
2747 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2752 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2754 void EmitDebugMacInfo() {
2755 // Start the dwarf macinfo section.
2756 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2761 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2763 void ConstructCompileUnitDIEs() {
2764 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2766 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2767 unsigned ID = MMI->RecordSource(CUW[i]);
2768 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2769 CompileUnits.push_back(Unit);
2773 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2774 /// global variables.
2775 void ConstructGlobalDIEs() {
2776 std::vector<GlobalVariableDesc *> GlobalVariables;
2777 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
2779 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2780 GlobalVariableDesc *GVD = GlobalVariables[i];
2781 NewGlobalVariable(GVD);
2785 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2787 void ConstructSubprogramDIEs() {
2788 std::vector<SubprogramDesc *> Subprograms;
2789 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2791 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2792 SubprogramDesc *SPD = Subprograms[i];
2798 //===--------------------------------------------------------------------===//
2799 // Main entry points.
2801 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2802 : Dwarf(OS, A, T, "dbg")
2804 , AbbreviationsSet(InitAbbreviationsSetSize)
2806 , ValuesSet(InitValuesSetSize)
2811 , SectionSourceLines()
2816 virtual ~DwarfDebug() {
2817 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2818 delete CompileUnits[i];
2819 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2823 /// SetModuleInfo - Set machine module information when it's known that pass
2824 /// manager has created it. Set by the target AsmPrinter.
2825 void SetModuleInfo(MachineModuleInfo *mmi) {
2826 // Make sure initial declarations are made.
2827 if (!MMI && mmi->hasDebugInfo()) {
2831 // Create all the compile unit DIEs.
2832 ConstructCompileUnitDIEs();
2834 // Create DIEs for each of the externally visible global variables.
2835 ConstructGlobalDIEs();
2837 // Create DIEs for each of the externally visible subprograms.
2838 ConstructSubprogramDIEs();
2840 // Prime section data.
2841 SectionMap.insert(TAI->getTextSection());
2843 // Print out .file directives to specify files for .loc directives. These
2844 // are printed out early so that they precede any .loc directives.
2845 if (TAI->hasDotLocAndDotFile()) {
2846 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2847 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2848 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2849 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2850 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2851 assert(AppendOk && "Could not append filename to directory!");
2853 Asm->EmitFile(i, FullPath.toString());
2858 // Emit initial sections
2863 /// BeginModule - Emit all Dwarf sections that should come prior to the
2865 void BeginModule(Module *M) {
2869 /// EndModule - Emit all Dwarf sections that should come after the content.
2872 if (!ShouldEmitDwarf()) return;
2874 // Standard sections final addresses.
2875 Asm->SwitchToSection(TAI->getTextSection());
2876 EmitLabel("text_end", 0);
2877 Asm->SwitchToSection(TAI->getDataSection());
2878 EmitLabel("data_end", 0);
2880 // End text sections.
2881 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2882 Asm->SwitchToSection(SectionMap[i]);
2883 EmitLabel("section_end", i);
2886 // Emit common frame information.
2887 EmitCommonDebugFrame();
2889 // Emit function debug frame information
2890 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2891 E = DebugFrames.end(); I != E; ++I)
2892 EmitFunctionDebugFrame(*I);
2894 // Compute DIE offsets and sizes.
2897 // Emit all the DIEs into a debug info section
2900 // Corresponding abbreviations into a abbrev section.
2901 EmitAbbreviations();
2903 // Emit source line correspondence into a debug line section.
2906 // Emit info into a debug pubnames section.
2907 EmitDebugPubNames();
2909 // Emit info into a debug str section.
2912 // Emit info into a debug loc section.
2915 // Emit info into a debug aranges section.
2918 // Emit info into a debug ranges section.
2921 // Emit info into a debug macinfo section.
2925 /// BeginFunction - Gather pre-function debug information. Assumes being
2926 /// emitted immediately after the function entry point.
2927 void BeginFunction(MachineFunction *MF) {
2930 if (!ShouldEmitDwarf()) return;
2932 // Begin accumulating function debug information.
2933 MMI->BeginFunction(MF);
2935 // Assumes in correct section after the entry point.
2936 EmitLabel("func_begin", ++SubprogramCount);
2938 // Emit label for the implicitly defined dbg.stoppoint at the start of
2940 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2941 if (!LineInfos.empty()) {
2942 const SourceLineInfo &LineInfo = LineInfos[0];
2943 Asm->printLabel(LineInfo.getLabelID());
2947 /// EndFunction - Gather and emit post-function debug information.
2949 void EndFunction(MachineFunction *MF) {
2950 if (!ShouldEmitDwarf()) return;
2952 // Define end label for subprogram.
2953 EmitLabel("func_end", SubprogramCount);
2955 // Get function line info.
2956 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2958 if (!LineInfos.empty()) {
2959 // Get section line info.
2960 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2961 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2962 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2963 // Append the function info to section info.
2964 SectionLineInfos.insert(SectionLineInfos.end(),
2965 LineInfos.begin(), LineInfos.end());
2968 // Construct scopes for subprogram.
2969 if (MMI->getRootScope())
2970 ConstructRootScope(MMI->getRootScope());
2972 // FIXME: This is wrong. We are essentially getting past a problem with
2973 // debug information not being able to handle unreachable blocks that have
2974 // debug information in them. In particular, those unreachable blocks that
2975 // have "region end" info in them. That situation results in the "root
2976 // scope" not being created. If that's the case, then emit a "default"
2977 // scope, i.e., one that encompasses the whole function. This isn't
2978 // desirable. And a better way of handling this (and all of the debugging
2979 // information) needs to be explored.
2980 ConstructDefaultScope(MF);
2982 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2983 MMI->getFrameMoves()));
2987 //===----------------------------------------------------------------------===//
2988 /// DwarfException - Emits Dwarf exception handling directives.
2990 class DwarfException : public Dwarf {
2993 struct FunctionEHFrameInfo {
2996 unsigned PersonalityIndex;
2998 bool hasLandingPads;
2999 std::vector<MachineMove> Moves;
3000 const Function * function;
3002 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3004 const std::vector<MachineMove> &M,
3006 FnName(FN), Number(Num), PersonalityIndex(P),
3007 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3010 std::vector<FunctionEHFrameInfo> EHFrames;
3012 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3014 bool shouldEmitTable;
3016 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3017 /// should be emitted.
3018 bool shouldEmitMoves;
3020 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3021 /// should be emitted.
3022 bool shouldEmitTableModule;
3024 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3025 /// should be emitted.
3026 bool shouldEmitMovesModule;
3028 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3030 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3031 // Size and sign of stack growth.
3033 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3034 TargetFrameInfo::StackGrowsUp ?
3035 TD->getPointerSize() : -TD->getPointerSize();
3037 // Begin eh frame section.
3038 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3040 if (!TAI->doesRequireNonLocalEHFrameLabel())
3041 O << TAI->getEHGlobalPrefix();
3042 O << "EH_frame" << Index << ":\n";
3043 EmitLabel("section_eh_frame", Index);
3045 // Define base labels.
3046 EmitLabel("eh_frame_common", Index);
3048 // Define the eh frame length.
3049 EmitDifference("eh_frame_common_end", Index,
3050 "eh_frame_common_begin", Index, true);
3051 Asm->EOL("Length of Common Information Entry");
3054 EmitLabel("eh_frame_common_begin", Index);
3055 Asm->EmitInt32((int)0);
3056 Asm->EOL("CIE Identifier Tag");
3057 Asm->EmitInt8(DW_CIE_VERSION);
3058 Asm->EOL("CIE Version");
3060 // The personality presence indicates that language specific information
3061 // will show up in the eh frame.
3062 Asm->EmitString(Personality ? "zPLR" : "zR");
3063 Asm->EOL("CIE Augmentation");
3065 // Round out reader.
3066 Asm->EmitULEB128Bytes(1);
3067 Asm->EOL("CIE Code Alignment Factor");
3068 Asm->EmitSLEB128Bytes(stackGrowth);
3069 Asm->EOL("CIE Data Alignment Factor");
3070 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3071 Asm->EOL("CIE Return Address Column");
3073 // If there is a personality, we need to indicate the functions location.
3075 Asm->EmitULEB128Bytes(7);
3076 Asm->EOL("Augmentation Size");
3078 if (TAI->getNeedsIndirectEncoding()) {
3079 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3080 Asm->EOL("Personality (pcrel sdata4 indirect)");
3082 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3083 Asm->EOL("Personality (pcrel sdata4)");
3086 PrintRelDirective(true);
3087 O << TAI->getPersonalityPrefix();
3088 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3089 O << TAI->getPersonalitySuffix();
3090 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3091 O << "-" << TAI->getPCSymbol();
3092 Asm->EOL("Personality");
3094 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3095 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3097 if (TAI->doesFDEEncodingRequireSData4()) {
3098 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3099 Asm->EOL("FDE Encoding (pcrel sdata4)");
3101 Asm->EmitInt8(DW_EH_PE_pcrel);
3102 Asm->EOL("FDE Encoding (pcrel)");
3105 Asm->EmitULEB128Bytes(1);
3106 Asm->EOL("Augmentation Size");
3108 if (TAI->doesFDEEncodingRequireSData4()) {
3109 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3110 Asm->EOL("FDE Encoding (pcrel sdata4)");
3112 Asm->EmitInt8(DW_EH_PE_pcrel);
3113 Asm->EOL("FDE Encoding (pcrel)");
3117 // Indicate locations of general callee saved registers in frame.
3118 std::vector<MachineMove> Moves;
3119 RI->getInitialFrameState(Moves);
3120 EmitFrameMoves(NULL, 0, Moves, true);
3122 // On Darwin the linker honors the alignment of eh_frame, which means it
3123 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3124 // you get holes which confuse readers of eh_frame.
3125 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3127 EmitLabel("eh_frame_common_end", Index);
3132 /// EmitEHFrame - Emit function exception frame information.
3134 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3135 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3137 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3139 // Externally visible entry into the functions eh frame info.
3140 // If the corresponding function is static, this should not be
3141 // externally visible.
3142 if (linkage != Function::InternalLinkage) {
3143 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3144 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3147 // If corresponding function is weak definition, this should be too.
3148 if ((linkage == Function::WeakLinkage ||
3149 linkage == Function::LinkOnceLinkage) &&
3150 TAI->getWeakDefDirective())
3151 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3153 // If there are no calls then you can't unwind. This may mean we can
3154 // omit the EH Frame, but some environments do not handle weak absolute
3156 // If UnwindTablesMandatory is set we cannot do this optimization; the
3157 // unwind info is to be available for non-EH uses.
3158 if (!EHFrameInfo.hasCalls &&
3159 !UnwindTablesMandatory &&
3160 ((linkage != Function::WeakLinkage &&
3161 linkage != Function::LinkOnceLinkage) ||
3162 !TAI->getWeakDefDirective() ||
3163 TAI->getSupportsWeakOmittedEHFrame()))
3165 O << EHFrameInfo.FnName << " = 0\n";
3166 // This name has no connection to the function, so it might get
3167 // dead-stripped when the function is not, erroneously. Prohibit
3168 // dead-stripping unconditionally.
3169 if (const char *UsedDirective = TAI->getUsedDirective())
3170 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3172 O << EHFrameInfo.FnName << ":\n";
3175 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3176 "eh_frame_begin", EHFrameInfo.Number, true);
3177 Asm->EOL("Length of Frame Information Entry");
3179 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3181 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3182 PrintRelDirective(true, true);
3183 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3185 if (!TAI->isAbsoluteEHSectionOffsets())
3186 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3188 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3189 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3193 Asm->EOL("FDE CIE offset");
3195 EmitReference("eh_func_begin", EHFrameInfo.Number, true,
3196 TAI->doesRequire32BitFDEReference());
3197 Asm->EOL("FDE initial location");
3198 EmitDifference("eh_func_end", EHFrameInfo.Number,
3199 "eh_func_begin", EHFrameInfo.Number,
3200 TAI->doesRequire32BitFDEReference());
3201 Asm->EOL("FDE address range");
3203 // If there is a personality and landing pads then point to the language
3204 // specific data area in the exception table.
3205 if (EHFrameInfo.PersonalityIndex) {
3206 Asm->EmitULEB128Bytes(4);
3207 Asm->EOL("Augmentation size");
3209 if (EHFrameInfo.hasLandingPads)
3210 EmitReference("exception", EHFrameInfo.Number, true, true);
3212 Asm->EmitInt32((int)0);
3213 Asm->EOL("Language Specific Data Area");
3215 Asm->EmitULEB128Bytes(0);
3216 Asm->EOL("Augmentation size");
3219 // Indicate locations of function specific callee saved registers in
3221 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3223 // On Darwin the linker honors the alignment of eh_frame, which means it
3224 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3225 // you get holes which confuse readers of eh_frame.
3226 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3228 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3230 // If the function is marked used, this table should be also. We cannot
3231 // make the mark unconditional in this case, since retaining the table
3232 // also retains the function in this case, and there is code around
3233 // that depends on unused functions (calling undefined externals) being
3234 // dead-stripped to link correctly. Yes, there really is.
3235 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3236 if (const char *UsedDirective = TAI->getUsedDirective())
3237 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3241 /// EmitExceptionTable - Emit landing pads and actions.
3243 /// The general organization of the table is complex, but the basic concepts
3244 /// are easy. First there is a header which describes the location and
3245 /// organization of the three components that follow.
3246 /// 1. The landing pad site information describes the range of code covered
3247 /// by the try. In our case it's an accumulation of the ranges covered
3248 /// by the invokes in the try. There is also a reference to the landing
3249 /// pad that handles the exception once processed. Finally an index into
3250 /// the actions table.
3251 /// 2. The action table, in our case, is composed of pairs of type ids
3252 /// and next action offset. Starting with the action index from the
3253 /// landing pad site, each type Id is checked for a match to the current
3254 /// exception. If it matches then the exception and type id are passed
3255 /// on to the landing pad. Otherwise the next action is looked up. This
3256 /// chain is terminated with a next action of zero. If no type id is
3257 /// found the the frame is unwound and handling continues.
3258 /// 3. Type id table contains references to all the C++ typeinfo for all
3259 /// catches in the function. This tables is reversed indexed base 1.
3261 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3262 static unsigned SharedTypeIds(const LandingPadInfo *L,
3263 const LandingPadInfo *R) {
3264 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3265 unsigned LSize = LIds.size(), RSize = RIds.size();
3266 unsigned MinSize = LSize < RSize ? LSize : RSize;
3269 for (; Count != MinSize; ++Count)
3270 if (LIds[Count] != RIds[Count])
3276 /// PadLT - Order landing pads lexicographically by type id.
3277 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3278 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3279 unsigned LSize = LIds.size(), RSize = RIds.size();
3280 unsigned MinSize = LSize < RSize ? LSize : RSize;
3282 for (unsigned i = 0; i != MinSize; ++i)
3283 if (LIds[i] != RIds[i])
3284 return LIds[i] < RIds[i];
3286 return LSize < RSize;
3290 static inline unsigned getEmptyKey() { return -1U; }
3291 static inline unsigned getTombstoneKey() { return -2U; }
3292 static unsigned getHashValue(const unsigned &Key) { return Key; }
3293 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3294 static bool isPod() { return true; }
3297 /// ActionEntry - Structure describing an entry in the actions table.
3298 struct ActionEntry {
3299 int ValueForTypeID; // The value to write - may not be equal to the type id.
3301 struct ActionEntry *Previous;
3304 /// PadRange - Structure holding a try-range and the associated landing pad.
3306 // The index of the landing pad.
3308 // The index of the begin and end labels in the landing pad's label lists.
3309 unsigned RangeIndex;
3312 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3314 /// CallSiteEntry - Structure describing an entry in the call-site table.
3315 struct CallSiteEntry {
3316 // The 'try-range' is BeginLabel .. EndLabel.
3317 unsigned BeginLabel; // zero indicates the start of the function.
3318 unsigned EndLabel; // zero indicates the end of the function.
3319 // The landing pad starts at PadLabel.
3320 unsigned PadLabel; // zero indicates that there is no landing pad.
3324 void EmitExceptionTable() {
3325 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3326 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3327 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3328 if (PadInfos.empty()) return;
3330 // Sort the landing pads in order of their type ids. This is used to fold
3331 // duplicate actions.
3332 SmallVector<const LandingPadInfo *, 64> LandingPads;
3333 LandingPads.reserve(PadInfos.size());
3334 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3335 LandingPads.push_back(&PadInfos[i]);
3336 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3338 // Negative type ids index into FilterIds, positive type ids index into
3339 // TypeInfos. The value written for a positive type id is just the type
3340 // id itself. For a negative type id, however, the value written is the
3341 // (negative) byte offset of the corresponding FilterIds entry. The byte
3342 // offset is usually equal to the type id, because the FilterIds entries
3343 // are written using a variable width encoding which outputs one byte per
3344 // entry as long as the value written is not too large, but can differ.
3345 // This kind of complication does not occur for positive type ids because
3346 // type infos are output using a fixed width encoding.
3347 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3348 SmallVector<int, 16> FilterOffsets;
3349 FilterOffsets.reserve(FilterIds.size());
3351 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3352 E = FilterIds.end(); I != E; ++I) {
3353 FilterOffsets.push_back(Offset);
3354 Offset -= TargetAsmInfo::getULEB128Size(*I);
3357 // Compute the actions table and gather the first action index for each
3358 // landing pad site.
3359 SmallVector<ActionEntry, 32> Actions;
3360 SmallVector<unsigned, 64> FirstActions;
3361 FirstActions.reserve(LandingPads.size());
3363 int FirstAction = 0;
3364 unsigned SizeActions = 0;
3365 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3366 const LandingPadInfo *LP = LandingPads[i];
3367 const std::vector<int> &TypeIds = LP->TypeIds;
3368 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3369 unsigned SizeSiteActions = 0;
3371 if (NumShared < TypeIds.size()) {
3372 unsigned SizeAction = 0;
3373 ActionEntry *PrevAction = 0;
3376 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3377 assert(Actions.size());
3378 PrevAction = &Actions.back();
3379 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3380 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3381 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3383 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3384 SizeAction += -PrevAction->NextAction;
3385 PrevAction = PrevAction->Previous;
3389 // Compute the actions.
3390 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3391 int TypeID = TypeIds[I];
3392 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3393 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3394 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3396 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3397 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3398 SizeSiteActions += SizeAction;
3400 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3401 Actions.push_back(Action);
3403 PrevAction = &Actions.back();
3406 // Record the first action of the landing pad site.
3407 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3408 } // else identical - re-use previous FirstAction
3410 FirstActions.push_back(FirstAction);
3412 // Compute this sites contribution to size.
3413 SizeActions += SizeSiteActions;
3416 // Compute the call-site table. The entry for an invoke has a try-range
3417 // containing the call, a non-zero landing pad and an appropriate action.
3418 // The entry for an ordinary call has a try-range containing the call and
3419 // zero for the landing pad and the action. Calls marked 'nounwind' have
3420 // no entry and must not be contained in the try-range of any entry - they
3421 // form gaps in the table. Entries must be ordered by try-range address.
3422 SmallVector<CallSiteEntry, 64> CallSites;
3424 RangeMapType PadMap;
3425 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3426 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3427 // try-ranges for them need be deduced.
3428 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3429 const LandingPadInfo *LandingPad = LandingPads[i];
3430 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3431 unsigned BeginLabel = LandingPad->BeginLabels[j];
3432 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3433 PadRange P = { i, j };
3434 PadMap[BeginLabel] = P;
3438 // The end label of the previous invoke or nounwind try-range.
3439 unsigned LastLabel = 0;
3441 // Whether there is a potentially throwing instruction (currently this means
3442 // an ordinary call) between the end of the previous try-range and now.
3443 bool SawPotentiallyThrowing = false;
3445 // Whether the last callsite entry was for an invoke.
3446 bool PreviousIsInvoke = false;
3448 // Visit all instructions in order of address.
3449 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3451 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3453 if (!MI->isLabel()) {
3454 SawPotentiallyThrowing |= MI->getDesc().isCall();
3458 unsigned BeginLabel = MI->getOperand(0).getImm();
3459 assert(BeginLabel && "Invalid label!");
3461 // End of the previous try-range?
3462 if (BeginLabel == LastLabel)
3463 SawPotentiallyThrowing = false;
3465 // Beginning of a new try-range?
3466 RangeMapType::iterator L = PadMap.find(BeginLabel);
3467 if (L == PadMap.end())
3468 // Nope, it was just some random label.
3471 PadRange P = L->second;
3472 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3474 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3475 "Inconsistent landing pad map!");
3477 // If some instruction between the previous try-range and this one may
3478 // throw, create a call-site entry with no landing pad for the region
3479 // between the try-ranges.
3480 if (SawPotentiallyThrowing) {
3481 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3482 CallSites.push_back(Site);
3483 PreviousIsInvoke = false;
3486 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3487 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3489 if (LandingPad->LandingPadLabel) {
3490 // This try-range is for an invoke.
3491 CallSiteEntry Site = {BeginLabel, LastLabel,
3492 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3494 // Try to merge with the previous call-site.
3495 if (PreviousIsInvoke) {
3496 CallSiteEntry &Prev = CallSites.back();
3497 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3498 // Extend the range of the previous entry.
3499 Prev.EndLabel = Site.EndLabel;
3504 // Otherwise, create a new call-site.
3505 CallSites.push_back(Site);
3506 PreviousIsInvoke = true;
3509 PreviousIsInvoke = false;
3513 // If some instruction between the previous try-range and the end of the
3514 // function may throw, create a call-site entry with no landing pad for the
3515 // region following the try-range.
3516 if (SawPotentiallyThrowing) {
3517 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3518 CallSites.push_back(Site);
3524 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3525 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3526 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3527 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3530 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3531 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3534 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3535 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3537 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3538 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3539 SizeSites + SizeActions + SizeTypes;
3541 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3542 sizeof(int8_t) + // TType format
3543 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3546 unsigned SizeAlign = (4 - TotalSize) & 3;
3548 // Begin the exception table.
3549 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3550 Asm->EmitAlignment(2, 0, 0, false);
3551 O << "GCC_except_table" << SubprogramCount << ":\n";
3552 for (unsigned i = 0; i != SizeAlign; ++i) {
3554 Asm->EOL("Padding");
3556 EmitLabel("exception", SubprogramCount);
3559 Asm->EmitInt8(DW_EH_PE_omit);
3560 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3561 Asm->EmitInt8(DW_EH_PE_absptr);
3562 Asm->EOL("TType format (DW_EH_PE_absptr)");
3563 Asm->EmitULEB128Bytes(TypeOffset);
3564 Asm->EOL("TType base offset");
3565 Asm->EmitInt8(DW_EH_PE_udata4);
3566 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3567 Asm->EmitULEB128Bytes(SizeSites);
3568 Asm->EOL("Call-site table length");
3570 // Emit the landing pad site information.
3571 for (unsigned i = 0; i < CallSites.size(); ++i) {
3572 CallSiteEntry &S = CallSites[i];
3573 const char *BeginTag;
3574 unsigned BeginNumber;
3576 if (!S.BeginLabel) {
3577 BeginTag = "eh_func_begin";
3578 BeginNumber = SubprogramCount;
3581 BeginNumber = S.BeginLabel;
3584 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3586 Asm->EOL("Region start");
3589 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3592 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3594 Asm->EOL("Region length");
3599 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3601 Asm->EOL("Landing pad");
3603 Asm->EmitULEB128Bytes(S.Action);
3607 // Emit the actions.
3608 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3609 ActionEntry &Action = Actions[I];
3611 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3612 Asm->EOL("TypeInfo index");
3613 Asm->EmitSLEB128Bytes(Action.NextAction);
3614 Asm->EOL("Next action");
3617 // Emit the type ids.
3618 for (unsigned M = TypeInfos.size(); M; --M) {
3619 GlobalVariable *GV = TypeInfos[M - 1];
3621 PrintRelDirective();
3624 O << Asm->getGlobalLinkName(GV);
3628 Asm->EOL("TypeInfo");
3631 // Emit the filter typeids.
3632 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3633 unsigned TypeID = FilterIds[j];
3634 Asm->EmitULEB128Bytes(TypeID);
3635 Asm->EOL("Filter TypeInfo index");
3638 Asm->EmitAlignment(2, 0, 0, false);
3642 //===--------------------------------------------------------------------===//
3643 // Main entry points.
3645 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3646 : Dwarf(OS, A, T, "eh")
3647 , shouldEmitTable(false)
3648 , shouldEmitMoves(false)
3649 , shouldEmitTableModule(false)
3650 , shouldEmitMovesModule(false)
3653 virtual ~DwarfException() {}
3655 /// SetModuleInfo - Set machine module information when it's known that pass
3656 /// manager has created it. Set by the target AsmPrinter.
3657 void SetModuleInfo(MachineModuleInfo *mmi) {
3661 /// BeginModule - Emit all exception information that should come prior to the
3663 void BeginModule(Module *M) {
3667 /// EndModule - Emit all exception information that should come after the
3670 if (shouldEmitMovesModule || shouldEmitTableModule) {
3671 const std::vector<Function *> Personalities = MMI->getPersonalities();
3672 for (unsigned i =0; i < Personalities.size(); ++i)
3673 EmitCommonEHFrame(Personalities[i], i);
3675 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3676 E = EHFrames.end(); I != E; ++I)
3681 /// BeginFunction - Gather pre-function exception information. Assumes being
3682 /// emitted immediately after the function entry point.
3683 void BeginFunction(MachineFunction *MF) {
3685 shouldEmitTable = shouldEmitMoves = false;
3686 if (MMI && TAI->doesSupportExceptionHandling()) {
3688 // Map all labels and get rid of any dead landing pads.
3689 MMI->TidyLandingPads();
3690 // If any landing pads survive, we need an EH table.
3691 if (MMI->getLandingPads().size())
3692 shouldEmitTable = true;
3694 // See if we need frame move info.
3695 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3696 shouldEmitMoves = true;
3698 if (shouldEmitMoves || shouldEmitTable)
3699 // Assumes in correct section after the entry point.
3700 EmitLabel("eh_func_begin", ++SubprogramCount);
3702 shouldEmitTableModule |= shouldEmitTable;
3703 shouldEmitMovesModule |= shouldEmitMoves;
3706 /// EndFunction - Gather and emit post-function exception information.
3708 void EndFunction() {
3709 if (shouldEmitMoves || shouldEmitTable) {
3710 EmitLabel("eh_func_end", SubprogramCount);
3711 EmitExceptionTable();
3713 // Save EH frame information
3715 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3717 MMI->getPersonalityIndex(),
3718 MF->getFrameInfo()->hasCalls(),
3719 !MMI->getLandingPads().empty(),
3720 MMI->getFrameMoves(),
3721 MF->getFunction()));
3726 } // End of namespace llvm
3728 //===----------------------------------------------------------------------===//
3730 /// Emit - Print the abbreviation using the specified Dwarf writer.
3732 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3733 // Emit its Dwarf tag type.
3734 DD.getAsm()->EmitULEB128Bytes(Tag);
3735 DD.getAsm()->EOL(TagString(Tag));
3737 // Emit whether it has children DIEs.
3738 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3739 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3741 // For each attribute description.
3742 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3743 const DIEAbbrevData &AttrData = Data[i];
3745 // Emit attribute type.
3746 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3747 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3750 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3751 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3754 // Mark end of abbreviation.
3755 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3756 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3760 void DIEAbbrev::print(std::ostream &O) {
3761 O << "Abbreviation @"
3762 << std::hex << (intptr_t)this << std::dec
3766 << ChildrenString(ChildrenFlag)
3769 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3771 << AttributeString(Data[i].getAttribute())
3773 << FormEncodingString(Data[i].getForm())
3777 void DIEAbbrev::dump() { print(cerr); }
3780 //===----------------------------------------------------------------------===//
3783 void DIEValue::dump() {
3788 //===----------------------------------------------------------------------===//
3790 /// EmitValue - Emit integer of appropriate size.
3792 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3794 case DW_FORM_flag: // Fall thru
3795 case DW_FORM_ref1: // Fall thru
3796 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3797 case DW_FORM_ref2: // Fall thru
3798 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3799 case DW_FORM_ref4: // Fall thru
3800 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3801 case DW_FORM_ref8: // Fall thru
3802 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3803 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3804 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3805 default: assert(0 && "DIE Value form not supported yet"); break;
3809 /// SizeOf - Determine size of integer value in bytes.
3811 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3813 case DW_FORM_flag: // Fall thru
3814 case DW_FORM_ref1: // Fall thru
3815 case DW_FORM_data1: return sizeof(int8_t);
3816 case DW_FORM_ref2: // Fall thru
3817 case DW_FORM_data2: return sizeof(int16_t);
3818 case DW_FORM_ref4: // Fall thru
3819 case DW_FORM_data4: return sizeof(int32_t);
3820 case DW_FORM_ref8: // Fall thru
3821 case DW_FORM_data8: return sizeof(int64_t);
3822 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
3823 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
3824 default: assert(0 && "DIE Value form not supported yet"); break;
3829 //===----------------------------------------------------------------------===//
3831 /// EmitValue - Emit string value.
3833 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3834 DD.getAsm()->EmitString(String);
3837 //===----------------------------------------------------------------------===//
3839 /// EmitValue - Emit label value.
3841 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3842 bool IsSmall = Form == DW_FORM_data4;
3843 DD.EmitReference(Label, false, IsSmall);
3846 /// SizeOf - Determine size of label value in bytes.
3848 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3849 if (Form == DW_FORM_data4) return 4;
3850 return DD.getTargetData()->getPointerSize();
3853 //===----------------------------------------------------------------------===//
3855 /// EmitValue - Emit label value.
3857 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3858 bool IsSmall = Form == DW_FORM_data4;
3859 DD.EmitReference(Label, false, IsSmall);
3862 /// SizeOf - Determine size of label value in bytes.
3864 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3865 if (Form == DW_FORM_data4) return 4;
3866 return DD.getTargetData()->getPointerSize();
3869 //===----------------------------------------------------------------------===//
3871 /// EmitValue - Emit delta value.
3873 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
3874 bool IsSmall = Form == DW_FORM_data4;
3875 DD.EmitSectionOffset(Label.Tag, Section.Tag,
3876 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
3879 /// SizeOf - Determine size of delta value in bytes.
3881 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3882 if (Form == DW_FORM_data4) return 4;
3883 return DD.getTargetData()->getPointerSize();
3886 //===----------------------------------------------------------------------===//
3888 /// EmitValue - Emit delta value.
3890 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3891 bool IsSmall = Form == DW_FORM_data4;
3892 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3895 /// SizeOf - Determine size of delta value in bytes.
3897 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3898 if (Form == DW_FORM_data4) return 4;
3899 return DD.getTargetData()->getPointerSize();
3902 //===----------------------------------------------------------------------===//
3904 /// EmitValue - Emit debug information entry offset.
3906 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3907 DD.getAsm()->EmitInt32(Entry->getOffset());
3910 //===----------------------------------------------------------------------===//
3912 /// ComputeSize - calculate the size of the block.
3914 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3916 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3918 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3919 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3925 /// EmitValue - Emit block data.
3927 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3929 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3930 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3931 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3932 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3933 default: assert(0 && "Improper form for block"); break;
3936 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3938 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3940 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3944 /// SizeOf - Determine size of block data in bytes.
3946 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3948 case DW_FORM_block1: return Size + sizeof(int8_t);
3949 case DW_FORM_block2: return Size + sizeof(int16_t);
3950 case DW_FORM_block4: return Size + sizeof(int32_t);
3951 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
3952 default: assert(0 && "Improper form for block"); break;
3957 //===----------------------------------------------------------------------===//
3958 /// DIE Implementation
3961 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3965 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3967 void DIE::AddSiblingOffset() {
3968 DIEInteger *DI = new DIEInteger(0);
3969 Values.insert(Values.begin(), DI);
3970 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3973 /// Profile - Used to gather unique data for the value folding set.
3975 void DIE::Profile(FoldingSetNodeID &ID) {
3978 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3979 ID.AddPointer(Children[i]);
3981 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3982 ID.AddPointer(Values[j]);
3986 void DIE::print(std::ostream &O, unsigned IncIndent) {
3987 static unsigned IndentCount = 0;
3988 IndentCount += IncIndent;
3989 const std::string Indent(IndentCount, ' ');
3990 bool isBlock = Abbrev.getTag() == 0;
3995 << "0x" << std::hex << (intptr_t)this << std::dec
3996 << ", Offset: " << Offset
3997 << ", Size: " << Size
4001 << TagString(Abbrev.getTag())
4003 << ChildrenString(Abbrev.getChildrenFlag());
4005 O << "Size: " << Size;
4009 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4012 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4016 O << AttributeString(Data[i].getAttribute());
4018 O << "Blk[" << i << "]";
4021 << FormEncodingString(Data[i].getForm())
4023 Values[i]->print(O);
4028 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4029 Children[j]->print(O, 4);
4032 if (!isBlock) O << "\n";
4033 IndentCount -= IncIndent;
4041 //===----------------------------------------------------------------------===//
4042 /// DwarfWriter Implementation
4045 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
4046 const TargetAsmInfo *T) {
4047 DE = new DwarfException(OS, A, T);
4048 DD = new DwarfDebug(OS, A, T);
4051 DwarfWriter::~DwarfWriter() {
4056 /// SetModuleInfo - Set machine module info when it's known that pass manager
4057 /// has created it. Set by the target AsmPrinter.
4058 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
4059 DD->SetModuleInfo(MMI);
4060 DE->SetModuleInfo(MMI);
4063 /// BeginModule - Emit all Dwarf sections that should come prior to the
4065 void DwarfWriter::BeginModule(Module *M) {
4070 /// EndModule - Emit all Dwarf sections that should come after the content.
4072 void DwarfWriter::EndModule() {
4077 /// BeginFunction - Gather pre-function debug information. Assumes being
4078 /// emitted immediately after the function entry point.
4079 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4080 DE->BeginFunction(MF);
4081 DD->BeginFunction(MF);
4084 /// EndFunction - Gather and emit post-function debug information.
4086 void DwarfWriter::EndFunction(MachineFunction *MF) {
4087 DD->EndFunction(MF);
4090 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4091 // Clear function debug information.