1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
44 using namespace llvm::dwarf;
48 //===----------------------------------------------------------------------===//
50 /// Configuration values for initial hash set sizes (log2).
52 static const unsigned InitDiesSetSize = 9; // 512
53 static const unsigned InitAbbreviationsSetSize = 9; // 512
54 static const unsigned InitValuesSetSize = 9; // 512
56 //===----------------------------------------------------------------------===//
57 /// Forward declarations.
62 //===----------------------------------------------------------------------===//
63 /// DWLabel - Labels are used to track locations in the assembler file.
64 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
65 /// where the tag is a category of label (Ex. location) and number is a value
66 /// unique in that category.
69 /// Tag - Label category tag. Should always be a staticly declared C string.
73 /// Number - Value to make label unique.
77 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
79 void Profile(FoldingSetNodeID &ID) const {
80 ID.AddString(std::string(Tag));
81 ID.AddInteger(Number);
85 void print(std::ostream *O) const {
88 void print(std::ostream &O) const {
90 if (Number) O << Number;
95 //===----------------------------------------------------------------------===//
96 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
97 /// Dwarf abbreviation.
100 /// Attribute - Dwarf attribute code.
104 /// Form - Dwarf form code.
109 DIEAbbrevData(unsigned A, unsigned F)
115 unsigned getAttribute() const { return Attribute; }
116 unsigned getForm() const { return Form; }
118 /// Profile - Used to gather unique data for the abbreviation folding set.
120 void Profile(FoldingSetNodeID &ID)const {
121 ID.AddInteger(Attribute);
126 //===----------------------------------------------------------------------===//
127 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
128 /// information object.
129 class DIEAbbrev : public FoldingSetNode {
131 /// Tag - Dwarf tag code.
135 /// Unique number for node.
139 /// ChildrenFlag - Dwarf children flag.
141 unsigned ChildrenFlag;
143 /// Data - Raw data bytes for abbreviation.
145 SmallVector<DIEAbbrevData, 8> Data;
149 DIEAbbrev(unsigned T, unsigned C)
157 unsigned getTag() const { return Tag; }
158 unsigned getNumber() const { return Number; }
159 unsigned getChildrenFlag() const { return ChildrenFlag; }
160 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
161 void setTag(unsigned T) { Tag = T; }
162 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
163 void setNumber(unsigned N) { Number = N; }
165 /// AddAttribute - Adds another set of attribute information to the
167 void AddAttribute(unsigned Attribute, unsigned Form) {
168 Data.push_back(DIEAbbrevData(Attribute, Form));
171 /// AddFirstAttribute - Adds a set of attribute information to the front
172 /// of the abbreviation.
173 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
174 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
177 /// Profile - Used to gather unique data for the abbreviation folding set.
179 void Profile(FoldingSetNodeID &ID) {
181 ID.AddInteger(ChildrenFlag);
183 // For each attribute description.
184 for (unsigned i = 0, N = Data.size(); i < N; ++i)
188 /// Emit - Print the abbreviation using the specified Dwarf writer.
190 void Emit(const DwarfDebug &DD) const;
193 void print(std::ostream *O) {
196 void print(std::ostream &O);
201 //===----------------------------------------------------------------------===//
202 /// DIE - A structured debug information entry. Has an abbreviation which
203 /// describes it's organization.
204 class DIE : public FoldingSetNode {
206 /// Abbrev - Buffer for constructing abbreviation.
210 /// Offset - Offset in debug info section.
214 /// Size - Size of instance + children.
220 std::vector<DIE *> Children;
222 /// Attributes values.
224 SmallVector<DIEValue*, 32> Values;
227 explicit DIE(unsigned Tag)
228 : Abbrev(Tag, DW_CHILDREN_no)
237 DIEAbbrev &getAbbrev() { return Abbrev; }
238 unsigned getAbbrevNumber() const {
239 return Abbrev.getNumber();
241 unsigned getTag() const { return Abbrev.getTag(); }
242 unsigned getOffset() const { return Offset; }
243 unsigned getSize() const { return Size; }
244 const std::vector<DIE *> &getChildren() const { return Children; }
245 SmallVector<DIEValue*, 32> &getValues() { return Values; }
246 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
247 void setOffset(unsigned O) { Offset = O; }
248 void setSize(unsigned S) { Size = S; }
250 /// AddValue - Add a value and attributes to a DIE.
252 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
253 Abbrev.AddAttribute(Attribute, Form);
254 Values.push_back(Value);
257 /// SiblingOffset - Return the offset of the debug information entry's
259 unsigned SiblingOffset() const { return Offset + Size; }
261 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
263 void AddSiblingOffset();
265 /// AddChild - Add a child to the DIE.
267 void AddChild(DIE *Child) {
268 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
269 Children.push_back(Child);
272 /// Detach - Detaches objects connected to it after copying.
278 /// Profile - Used to gather unique data for the value folding set.
280 void Profile(FoldingSetNodeID &ID) ;
283 void print(std::ostream *O, unsigned IncIndent = 0) {
284 if (O) print(*O, IncIndent);
286 void print(std::ostream &O, unsigned IncIndent = 0);
291 //===----------------------------------------------------------------------===//
292 /// DIEValue - A debug information entry value.
294 class DIEValue : public FoldingSetNode {
307 /// Type - Type of data stored in the value.
311 explicit DIEValue(unsigned T)
314 virtual ~DIEValue() {}
317 unsigned getType() const { return Type; }
319 // Implement isa/cast/dyncast.
320 static bool classof(const DIEValue *) { return true; }
322 /// EmitValue - Emit value via the Dwarf writer.
324 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
326 /// SizeOf - Return the size of a value in bytes.
328 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
330 /// Profile - Used to gather unique data for the value folding set.
332 virtual void Profile(FoldingSetNodeID &ID) = 0;
335 void print(std::ostream *O) {
338 virtual void print(std::ostream &O) = 0;
343 //===----------------------------------------------------------------------===//
344 /// DWInteger - An integer value DIE.
346 class DIEInteger : public DIEValue {
351 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
353 // Implement isa/cast/dyncast.
354 static bool classof(const DIEInteger *) { return true; }
355 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
357 /// BestForm - Choose the best form for integer.
359 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
361 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
362 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
363 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
365 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
366 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
367 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
369 return DW_FORM_data8;
372 /// EmitValue - Emit integer of appropriate size.
374 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
376 /// SizeOf - Determine size of integer value in bytes.
378 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
380 /// Profile - Used to gather unique data for the value folding set.
382 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
383 ID.AddInteger(isInteger);
384 ID.AddInteger(Integer);
386 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
389 virtual void print(std::ostream &O) {
390 O << "Int: " << (int64_t)Integer
391 << " 0x" << std::hex << Integer << std::dec;
396 //===----------------------------------------------------------------------===//
397 /// DIEString - A string value DIE.
399 class DIEString : public DIEValue {
401 const std::string String;
403 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
405 // Implement isa/cast/dyncast.
406 static bool classof(const DIEString *) { return true; }
407 static bool classof(const DIEValue *S) { return S->Type == isString; }
409 /// EmitValue - Emit string value.
411 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
413 /// SizeOf - Determine size of string value in bytes.
415 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
416 return String.size() + sizeof(char); // sizeof('\0');
419 /// Profile - Used to gather unique data for the value folding set.
421 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
422 ID.AddInteger(isString);
423 ID.AddString(String);
425 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
428 virtual void print(std::ostream &O) {
429 O << "Str: \"" << String << "\"";
434 //===----------------------------------------------------------------------===//
435 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
437 class DIEDwarfLabel : public DIEValue {
442 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
444 // Implement isa/cast/dyncast.
445 static bool classof(const DIEDwarfLabel *) { return true; }
446 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
448 /// EmitValue - Emit label value.
450 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
452 /// SizeOf - Determine size of label value in bytes.
454 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
456 /// Profile - Used to gather unique data for the value folding set.
458 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
459 ID.AddInteger(isLabel);
462 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
465 virtual void print(std::ostream &O) {
473 //===----------------------------------------------------------------------===//
474 /// DIEObjectLabel - A label to an object in code or data.
476 class DIEObjectLabel : public DIEValue {
478 const std::string Label;
480 explicit DIEObjectLabel(const std::string &L)
481 : DIEValue(isAsIsLabel), Label(L) {}
483 // Implement isa/cast/dyncast.
484 static bool classof(const DIEObjectLabel *) { return true; }
485 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
487 /// EmitValue - Emit label value.
489 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
491 /// SizeOf - Determine size of label value in bytes.
493 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
495 /// Profile - Used to gather unique data for the value folding set.
497 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
498 ID.AddInteger(isAsIsLabel);
501 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
504 virtual void print(std::ostream &O) {
505 O << "Obj: " << Label;
510 //===----------------------------------------------------------------------===//
511 /// DIESectionOffset - A section offset DIE.
513 class DIESectionOffset : public DIEValue {
516 const DWLabel Section;
520 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
521 bool isEH = false, bool useSet = true)
522 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
523 IsEH(isEH), UseSet(useSet) {}
525 // Implement isa/cast/dyncast.
526 static bool classof(const DIESectionOffset *) { return true; }
527 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
529 /// EmitValue - Emit section offset.
531 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
533 /// SizeOf - Determine size of section offset value in bytes.
535 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
537 /// Profile - Used to gather unique data for the value folding set.
539 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
540 const DWLabel &Section) {
541 ID.AddInteger(isSectionOffset);
544 // IsEH and UseSet are specific to the Label/Section that we will emit
545 // the offset for; so Label/Section are enough for uniqueness.
547 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
550 virtual void print(std::ostream &O) {
555 O << "-" << IsEH << "-" << UseSet;
560 //===----------------------------------------------------------------------===//
561 /// DIEDelta - A simple label difference DIE.
563 class DIEDelta : public DIEValue {
565 const DWLabel LabelHi;
566 const DWLabel LabelLo;
568 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
569 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
571 // Implement isa/cast/dyncast.
572 static bool classof(const DIEDelta *) { return true; }
573 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
575 /// EmitValue - Emit delta value.
577 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
579 /// SizeOf - Determine size of delta value in bytes.
581 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
583 /// Profile - Used to gather unique data for the value folding set.
585 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
586 const DWLabel &LabelLo) {
587 ID.AddInteger(isDelta);
591 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
594 virtual void print(std::ostream &O) {
603 //===----------------------------------------------------------------------===//
604 /// DIEntry - A pointer to another debug information entry. An instance of this
605 /// class can also be used as a proxy for a debug information entry not yet
606 /// defined (ie. types.)
607 class DIEntry : public DIEValue {
611 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
613 // Implement isa/cast/dyncast.
614 static bool classof(const DIEntry *) { return true; }
615 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
617 /// EmitValue - Emit debug information entry offset.
619 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
621 /// SizeOf - Determine size of debug information entry in bytes.
623 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
624 return sizeof(int32_t);
627 /// Profile - Used to gather unique data for the value folding set.
629 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
630 ID.AddInteger(isEntry);
631 ID.AddPointer(Entry);
633 virtual void Profile(FoldingSetNodeID &ID) {
634 ID.AddInteger(isEntry);
637 ID.AddPointer(Entry);
644 virtual void print(std::ostream &O) {
645 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
650 //===----------------------------------------------------------------------===//
651 /// DIEBlock - A block of values. Primarily used for location expressions.
653 class DIEBlock : public DIEValue, public DIE {
655 unsigned Size; // Size in bytes excluding size header.
665 // Implement isa/cast/dyncast.
666 static bool classof(const DIEBlock *) { return true; }
667 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
669 /// ComputeSize - calculate the size of the block.
671 unsigned ComputeSize(DwarfDebug &DD);
673 /// BestForm - Choose the best form for data.
675 unsigned BestForm() const {
676 if ((unsigned char)Size == Size) return DW_FORM_block1;
677 if ((unsigned short)Size == Size) return DW_FORM_block2;
678 if ((unsigned int)Size == Size) return DW_FORM_block4;
679 return DW_FORM_block;
682 /// EmitValue - Emit block data.
684 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
686 /// SizeOf - Determine size of block data in bytes.
688 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
691 /// Profile - Used to gather unique data for the value folding set.
693 virtual void Profile(FoldingSetNodeID &ID) {
694 ID.AddInteger(isBlock);
699 virtual void print(std::ostream &O) {
706 //===----------------------------------------------------------------------===//
707 /// CompileUnit - This dwarf writer support class manages information associate
708 /// with a source file.
711 /// Desc - Compile unit debug descriptor.
713 CompileUnitDesc *Desc;
715 /// ID - File identifier for source.
719 /// Die - Compile unit debug information entry.
723 /// DescToDieMap - Tracks the mapping of unit level debug informaton
724 /// descriptors to debug information entries.
725 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
726 DenseMap<GlobalVariable *, DIE *> GVToDieMap;
728 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
729 /// descriptors to debug information entries using a DIEntry proxy.
730 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
731 DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
733 /// Globals - A map of globally visible named entities for this unit.
735 std::map<std::string, DIE *> Globals;
737 /// DiesSet - Used to uniquely define dies within the compile unit.
739 FoldingSet<DIE> DiesSet;
741 /// Dies - List of all dies in the compile unit.
743 std::vector<DIE *> Dies;
746 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
755 , DiesSet(InitDiesSetSize)
762 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
767 CompileUnitDesc *getDesc() const { return Desc; }
768 unsigned getID() const { return ID; }
769 DIE* getDie() const { return Die; }
770 std::map<std::string, DIE *> &getGlobals() { return Globals; }
772 /// hasContent - Return true if this compile unit has something to write out.
774 bool hasContent() const {
775 return !Die->getChildren().empty();
778 /// AddGlobal - Add a new global entity to the compile unit.
780 void AddGlobal(const std::string &Name, DIE *Die) {
784 /// getDieMapSlotFor - Returns the debug information entry map slot for the
785 /// specified debug descriptor.
786 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
787 return DescToDieMap[DID];
789 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
790 return GVToDieMap[GV];
793 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
794 /// specified debug descriptor.
795 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
796 return DescToDIEntryMap[DID];
798 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
799 return GVToDIEntryMap[GV];
802 /// AddDie - Adds or interns the DIE to the compile unit.
804 DIE *AddDie(DIE &Buffer) {
808 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
811 Die = new DIE(Buffer);
812 DiesSet.InsertNode(Die, Where);
813 this->Die->AddChild(Die);
821 //===----------------------------------------------------------------------===//
822 /// Dwarf - Emits general Dwarf directives.
828 //===--------------------------------------------------------------------===//
829 // Core attributes used by the Dwarf writer.
833 /// O - Stream to .s file.
837 /// Asm - Target of Dwarf emission.
841 /// TAI - Target asm information.
842 const TargetAsmInfo *TAI;
844 /// TD - Target data.
845 const TargetData *TD;
847 /// RI - Register Information.
848 const TargetRegisterInfo *RI;
850 /// M - Current module.
854 /// MF - Current machine function.
858 /// MMI - Collected machine module information.
860 MachineModuleInfo *MMI;
862 /// SubprogramCount - The running count of functions being compiled.
864 unsigned SubprogramCount;
866 /// Flavor - A unique string indicating what dwarf producer this is, used to
868 const char * const Flavor;
871 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
876 , TD(Asm->TM.getTargetData())
877 , RI(Asm->TM.getRegisterInfo())
889 //===--------------------------------------------------------------------===//
892 AsmPrinter *getAsm() const { return Asm; }
893 MachineModuleInfo *getMMI() const { return MMI; }
894 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
895 const TargetData *getTargetData() const { return TD; }
897 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
899 if (isInSection && TAI->getDwarfSectionOffsetDirective())
900 O << TAI->getDwarfSectionOffsetDirective();
901 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
902 O << TAI->getData32bitsDirective();
904 O << TAI->getData64bitsDirective();
907 /// PrintLabelName - Print label name in form used by Dwarf writer.
909 void PrintLabelName(DWLabel Label) const {
910 PrintLabelName(Label.Tag, Label.Number);
912 void PrintLabelName(const char *Tag, unsigned Number) const {
913 O << TAI->getPrivateGlobalPrefix() << Tag;
914 if (Number) O << Number;
917 void PrintLabelName(const char *Tag, unsigned Number,
918 const char *Suffix) const {
919 O << TAI->getPrivateGlobalPrefix() << Tag;
920 if (Number) O << Number;
924 /// EmitLabel - Emit location label for internal use by Dwarf.
926 void EmitLabel(DWLabel Label) const {
927 EmitLabel(Label.Tag, Label.Number);
929 void EmitLabel(const char *Tag, unsigned Number) const {
930 PrintLabelName(Tag, Number);
934 /// EmitReference - Emit a reference to a label.
936 void EmitReference(DWLabel Label, bool IsPCRelative = false,
937 bool Force32Bit = false) const {
938 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
940 void EmitReference(const char *Tag, unsigned Number,
941 bool IsPCRelative = false, bool Force32Bit = false) const {
942 PrintRelDirective(Force32Bit);
943 PrintLabelName(Tag, Number);
945 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
947 void EmitReference(const std::string &Name, bool IsPCRelative = false,
948 bool Force32Bit = false) const {
949 PrintRelDirective(Force32Bit);
953 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
956 /// EmitDifference - Emit the difference between two labels. Some
957 /// assemblers do not behave with absolute expressions with data directives,
958 /// so there is an option (needsSet) to use an intermediary set expression.
959 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
960 bool IsSmall = false) {
961 EmitDifference(LabelHi.Tag, LabelHi.Number,
962 LabelLo.Tag, LabelLo.Number,
965 void EmitDifference(const char *TagHi, unsigned NumberHi,
966 const char *TagLo, unsigned NumberLo,
967 bool IsSmall = false) {
968 if (TAI->needsSet()) {
970 PrintLabelName("set", SetCounter, Flavor);
972 PrintLabelName(TagHi, NumberHi);
974 PrintLabelName(TagLo, NumberLo);
977 PrintRelDirective(IsSmall);
978 PrintLabelName("set", SetCounter, Flavor);
981 PrintRelDirective(IsSmall);
983 PrintLabelName(TagHi, NumberHi);
985 PrintLabelName(TagLo, NumberLo);
989 void EmitSectionOffset(const char* Label, const char* Section,
990 unsigned LabelNumber, unsigned SectionNumber,
991 bool IsSmall = false, bool isEH = false,
992 bool useSet = true) {
993 bool printAbsolute = false;
995 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
997 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
999 if (TAI->needsSet() && useSet) {
1001 PrintLabelName("set", SetCounter, Flavor);
1003 PrintLabelName(Label, LabelNumber);
1005 if (!printAbsolute) {
1007 PrintLabelName(Section, SectionNumber);
1011 PrintRelDirective(IsSmall);
1013 PrintLabelName("set", SetCounter, Flavor);
1016 PrintRelDirective(IsSmall, true);
1018 PrintLabelName(Label, LabelNumber);
1020 if (!printAbsolute) {
1022 PrintLabelName(Section, SectionNumber);
1027 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1029 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1030 const std::vector<MachineMove> &Moves, bool isEH) {
1032 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1033 TargetFrameInfo::StackGrowsUp ?
1034 TD->getPointerSize() : -TD->getPointerSize();
1035 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1037 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1038 const MachineMove &Move = Moves[i];
1039 unsigned LabelID = Move.getLabelID();
1042 LabelID = MMI->MappedLabel(LabelID);
1044 // Throw out move if the label is invalid.
1045 if (!LabelID) continue;
1048 const MachineLocation &Dst = Move.getDestination();
1049 const MachineLocation &Src = Move.getSource();
1051 // Advance row if new location.
1052 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1053 Asm->EmitInt8(DW_CFA_advance_loc4);
1054 Asm->EOL("DW_CFA_advance_loc4");
1055 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1058 BaseLabelID = LabelID;
1059 BaseLabel = "label";
1063 // If advancing cfa.
1064 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1066 if (Src.getReg() == MachineLocation::VirtualFP) {
1067 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1068 Asm->EOL("DW_CFA_def_cfa_offset");
1070 Asm->EmitInt8(DW_CFA_def_cfa);
1071 Asm->EOL("DW_CFA_def_cfa");
1072 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1073 Asm->EOL("Register");
1076 int Offset = -Src.getOffset();
1078 Asm->EmitULEB128Bytes(Offset);
1081 assert(0 && "Machine move no supported yet.");
1083 } else if (Src.isReg() &&
1084 Src.getReg() == MachineLocation::VirtualFP) {
1086 Asm->EmitInt8(DW_CFA_def_cfa_register);
1087 Asm->EOL("DW_CFA_def_cfa_register");
1088 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1089 Asm->EOL("Register");
1091 assert(0 && "Machine move no supported yet.");
1094 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1095 int Offset = Dst.getOffset() / stackGrowth;
1098 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1099 Asm->EOL("DW_CFA_offset_extended_sf");
1100 Asm->EmitULEB128Bytes(Reg);
1102 Asm->EmitSLEB128Bytes(Offset);
1104 } else if (Reg < 64) {
1105 Asm->EmitInt8(DW_CFA_offset + Reg);
1107 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1110 Asm->EmitULEB128Bytes(Offset);
1113 Asm->EmitInt8(DW_CFA_offset_extended);
1114 Asm->EOL("DW_CFA_offset_extended");
1115 Asm->EmitULEB128Bytes(Reg);
1117 Asm->EmitULEB128Bytes(Offset);
1126 //===----------------------------------------------------------------------===//
1127 /// SrcFileInfo - This class is used to track source information.
1130 unsigned DirectoryID; // Directory ID number.
1131 std::string Name; // File name (not including directory.)
1133 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1136 unsigned getDirectoryID() const { return DirectoryID; }
1137 const std::string &getName() const { return Name; }
1139 /// operator== - Used by UniqueVector to locate entry.
1141 bool operator==(const SourceFileInfo &SI) const {
1142 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1145 /// operator< - Used by UniqueVector to locate entry.
1147 bool operator<(const SrcFileInfo &SI) const {
1148 return getDirectoryID() < SI.getDirectoryID() ||
1149 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1153 //===----------------------------------------------------------------------===//
1154 /// DwarfDebug - Emits Dwarf debug directives.
1156 class DwarfDebug : public Dwarf {
1159 //===--------------------------------------------------------------------===//
1160 // Attributes used to construct specific Dwarf sections.
1163 /// CompileUnits - All the compile units involved in this build. The index
1164 /// of each entry in this vector corresponds to the sources in MMI.
1165 std::vector<CompileUnit *> CompileUnits;
1166 DenseMap<GlobalVariable *, CompileUnit *> DW_CUs;
1168 /// AbbreviationsSet - Used to uniquely define abbreviations.
1170 FoldingSet<DIEAbbrev> AbbreviationsSet;
1172 /// Abbreviations - A list of all the unique abbreviations in use.
1174 std::vector<DIEAbbrev *> Abbreviations;
1176 /// ValuesSet - Used to uniquely define values.
1178 // Directories - Uniquing vector for directories.
1179 UniqueVector<std::string> Directories;
1181 // SourceFiles - Uniquing vector for source files.
1182 UniqueVector<SrcFileInfo> SrcFiles;
1184 FoldingSet<DIEValue> ValuesSet;
1186 /// Values - A list of all the unique values in use.
1188 std::vector<DIEValue *> Values;
1190 /// StringPool - A UniqueVector of strings used by indirect references.
1192 UniqueVector<std::string> StringPool;
1194 /// UnitMap - Map debug information descriptor to compile unit.
1196 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1198 /// SectionMap - Provides a unique id per text section.
1200 UniqueVector<const Section*> SectionMap;
1202 /// SectionSourceLines - Tracks line numbers per text section.
1204 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1206 /// didInitial - Flag to indicate if initial emission has been done.
1210 /// shouldEmit - Flag to indicate if debug information should be emitted.
1214 struct FunctionDebugFrameInfo {
1216 std::vector<MachineMove> Moves;
1218 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1219 Number(Num), Moves(M) { }
1222 std::vector<FunctionDebugFrameInfo> DebugFrames;
1226 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1228 bool ShouldEmitDwarf() const { return shouldEmit; }
1230 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1232 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1233 // Profile the node so that we can make it unique.
1234 FoldingSetNodeID ID;
1237 // Check the set for priors.
1238 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1240 // If it's newly added.
1241 if (InSet == &Abbrev) {
1242 // Add to abbreviation list.
1243 Abbreviations.push_back(&Abbrev);
1244 // Assign the vector position + 1 as its number.
1245 Abbrev.setNumber(Abbreviations.size());
1247 // Assign existing abbreviation number.
1248 Abbrev.setNumber(InSet->getNumber());
1252 /// NewString - Add a string to the constant pool and returns a label.
1254 DWLabel NewString(const std::string &String) {
1255 unsigned StringID = StringPool.insert(String);
1256 return DWLabel("string", StringID);
1259 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1261 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1265 FoldingSetNodeID ID;
1266 DIEntry::Profile(ID, Entry);
1268 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1270 if (Value) return Value;
1272 Value = new DIEntry(Entry);
1273 ValuesSet.InsertNode(Value, Where);
1275 Value = new DIEntry(Entry);
1278 Values.push_back(Value);
1282 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1284 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1285 Value->Entry = Entry;
1286 // Add to values set if not already there. If it is, we merely have a
1287 // duplicate in the values list (no harm.)
1288 ValuesSet.GetOrInsertNode(Value);
1291 /// AddUInt - Add an unsigned integer attribute data and value.
1293 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1294 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1296 FoldingSetNodeID ID;
1297 DIEInteger::Profile(ID, Integer);
1299 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1301 Value = new DIEInteger(Integer);
1302 ValuesSet.InsertNode(Value, Where);
1303 Values.push_back(Value);
1306 Die->AddValue(Attribute, Form, Value);
1309 /// AddSInt - Add an signed integer attribute data and value.
1311 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1312 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1314 FoldingSetNodeID ID;
1315 DIEInteger::Profile(ID, (uint64_t)Integer);
1317 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1319 Value = new DIEInteger(Integer);
1320 ValuesSet.InsertNode(Value, Where);
1321 Values.push_back(Value);
1324 Die->AddValue(Attribute, Form, Value);
1327 /// AddString - Add a std::string attribute data and value.
1329 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1330 const std::string &String) {
1331 FoldingSetNodeID ID;
1332 DIEString::Profile(ID, String);
1334 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1336 Value = new DIEString(String);
1337 ValuesSet.InsertNode(Value, Where);
1338 Values.push_back(Value);
1341 Die->AddValue(Attribute, Form, Value);
1344 /// AddLabel - Add a Dwarf label attribute data and value.
1346 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1347 const DWLabel &Label) {
1348 FoldingSetNodeID ID;
1349 DIEDwarfLabel::Profile(ID, Label);
1351 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1353 Value = new DIEDwarfLabel(Label);
1354 ValuesSet.InsertNode(Value, Where);
1355 Values.push_back(Value);
1358 Die->AddValue(Attribute, Form, Value);
1361 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1363 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1364 const std::string &Label) {
1365 FoldingSetNodeID ID;
1366 DIEObjectLabel::Profile(ID, Label);
1368 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1370 Value = new DIEObjectLabel(Label);
1371 ValuesSet.InsertNode(Value, Where);
1372 Values.push_back(Value);
1375 Die->AddValue(Attribute, Form, Value);
1378 /// AddSectionOffset - Add a section offset label attribute data and value.
1380 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1381 const DWLabel &Label, const DWLabel &Section,
1382 bool isEH = false, bool useSet = true) {
1383 FoldingSetNodeID ID;
1384 DIESectionOffset::Profile(ID, Label, Section);
1386 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1388 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1389 ValuesSet.InsertNode(Value, Where);
1390 Values.push_back(Value);
1393 Die->AddValue(Attribute, Form, Value);
1396 /// AddDelta - Add a label delta attribute data and value.
1398 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1399 const DWLabel &Hi, const DWLabel &Lo) {
1400 FoldingSetNodeID ID;
1401 DIEDelta::Profile(ID, Hi, Lo);
1403 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1405 Value = new DIEDelta(Hi, Lo);
1406 ValuesSet.InsertNode(Value, Where);
1407 Values.push_back(Value);
1410 Die->AddValue(Attribute, Form, Value);
1413 /// AddDIEntry - Add a DIE attribute data and value.
1415 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1416 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1419 /// AddBlock - Add block data.
1421 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1422 Block->ComputeSize(*this);
1423 FoldingSetNodeID ID;
1426 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1429 ValuesSet.InsertNode(Value, Where);
1430 Values.push_back(Value);
1432 // Already exists, reuse the previous one.
1434 Block = cast<DIEBlock>(Value);
1437 Die->AddValue(Attribute, Block->BestForm(), Value);
1442 /// AddSourceLine - Add location information to specified debug information
1444 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1446 CompileUnit *FileUnit = FindCompileUnit(File);
1447 unsigned FileID = FileUnit->getID();
1448 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1449 AddUInt(Die, DW_AT_decl_line, 0, Line);
1453 /// AddSourceLine - Add location information to specified debug information
1455 void AddSourceLine(DIE *Die, DIGlobal *G) {
1456 unsigned FileID = 0;
1457 unsigned Line = G->getLineNumber();
1458 if (G->getVersion() < DIDescriptor::Version7) {
1459 // Version6 or earlier. Use compile unit info to get file id.
1460 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1461 FileID = Unit->getID();
1463 // Version7 or newer, use filename and directory info from DIGlobal
1465 unsigned DID = Directories.idFor(G->getDirectory());
1466 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1468 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1469 AddUInt(Die, DW_AT_decl_line, 0, Line);
1472 void AddSourceLine(DIE *Die, DIType *G) {
1473 unsigned FileID = 0;
1474 unsigned Line = G->getLineNumber();
1475 if (G->getVersion() < DIDescriptor::Version7) {
1476 // Version6 or earlier. Use compile unit info to get file id.
1477 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1478 FileID = Unit->getID();
1480 // Version7 or newer, use filename and directory info from DIGlobal
1482 unsigned DID = Directories.idFor(G->getDirectory());
1483 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1485 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1486 AddUInt(Die, DW_AT_decl_line, 0, Line);
1489 /// AddAddress - Add an address attribute to a die based on the location
1491 void AddAddress(DIE *Die, unsigned Attribute,
1492 const MachineLocation &Location) {
1493 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1494 DIEBlock *Block = new DIEBlock();
1496 if (Location.isReg()) {
1498 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1500 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1501 AddUInt(Block, 0, DW_FORM_udata, Reg);
1505 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1507 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1508 AddUInt(Block, 0, DW_FORM_udata, Reg);
1510 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1513 AddBlock(Die, Attribute, 0, Block);
1516 /// AddBasicType - Add a new basic type attribute to the specified entity.
1518 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1519 const std::string &Name,
1520 unsigned Encoding, unsigned Size) {
1522 DIE Buffer(DW_TAG_base_type);
1523 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1524 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1525 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1526 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1527 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1530 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1532 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1533 DIE Buffer(DW_TAG_pointer_type);
1534 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1535 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1536 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1537 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1540 /// AddType - Add a new type attribute to the specified entity.
1542 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1544 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1546 // Check for pre-existence.
1547 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1549 // If it exists then use the existing value.
1551 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1555 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1556 // FIXME - Not sure why programs and variables are coming through here.
1557 // Short cut for handling subprogram types (not really a TyDesc.)
1558 AddPointerType(Entity, Unit, SubprogramTy->getName());
1559 } else if (GlobalVariableDesc *GlobalTy =
1560 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1561 // FIXME - Not sure why programs and variables are coming through here.
1562 // Short cut for handling global variable types (not really a TyDesc.)
1563 AddPointerType(Entity, Unit, GlobalTy->getName());
1566 Slot = NewDIEntry();
1569 DIE Buffer(DW_TAG_base_type);
1570 ConstructType(Buffer, TyDesc, Unit);
1572 // Add debug information entry to entity and unit.
1573 DIE *Die = Unit->AddDie(Buffer);
1574 SetDIEntry(Slot, Die);
1575 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1580 /// AddType - Add a new type attribute to the specified entity.
1581 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1583 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1587 // Check for pre-existence.
1588 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1589 // If it exists then use the existing value.
1591 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1596 Slot = NewDIEntry();
1599 DIE Buffer(DW_TAG_base_type);
1600 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1601 ConstructTypeDIE(DW_Unit, Buffer, BT);
1602 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1603 ConstructTypeDIE(DW_Unit, Buffer, DT);
1604 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1605 ConstructTypeDIE(DW_Unit, Buffer, CT);
1607 // Add debug information entry to entity and unit.
1608 DIE *Die = DW_Unit->AddDie(Buffer);
1609 SetDIEntry(Slot, Die);
1610 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1613 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1614 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1617 // Get core information.
1618 const std::string &Name = BTy->getName();
1619 Buffer.setTag(DW_TAG_base_type);
1620 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1621 // Add name if not anonymous or intermediate type.
1623 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1624 uint64_t Size = BTy->getSizeInBits() >> 3;
1625 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1628 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1629 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1630 DIDerivedType *DTy) {
1632 // Get core information.
1633 const std::string &Name = DTy->getName();
1634 uint64_t Size = DTy->getSizeInBits() >> 3;
1635 unsigned Tag = DTy->getTag();
1636 // FIXME - Workaround for templates.
1637 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1640 // Map to main type, void will not have a type.
1641 DIType FromTy = DTy->getTypeDerivedFrom();
1642 AddType(DW_Unit, &Buffer, FromTy);
1644 // Add name if not anonymous or intermediate type.
1645 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1647 // Add size if non-zero (derived types might be zero-sized.)
1649 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1651 // Add source line info if available and TyDesc is not a forward
1653 // FIXME - Enable this. if (!DTy->isForwardDecl())
1654 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1657 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1658 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1659 DICompositeType *CTy) {
1661 // Get core information.
1662 const std::string &Name = CTy->getName();
1663 uint64_t Size = CTy->getSizeInBits() >> 3;
1664 unsigned Tag = CTy->getTag();
1666 case DW_TAG_vector_type:
1667 case DW_TAG_array_type:
1668 ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1670 //FIXME - Enable this.
1671 // case DW_TAG_enumeration_type:
1672 // DIArray Elements = CTy->getTypeArray();
1673 // // Add enumerators to enumeration type.
1674 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1675 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1677 case DW_TAG_subroutine_type:
1679 // Add prototype flag.
1680 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1681 DIArray Elements = CTy->getTypeArray();
1683 DIDescriptor RTy = Elements.getElement(0);
1684 if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1685 AddType(DW_Unit, &Buffer, *BT);
1686 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1687 AddType(DW_Unit, &Buffer, *DT);
1688 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1689 AddType(DW_Unit, &Buffer, *CT);
1691 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1693 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1694 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1695 DIDescriptor Ty = Elements.getElement(i);
1696 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1697 AddType(DW_Unit, &Buffer, *BT);
1698 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1699 AddType(DW_Unit, &Buffer, *DT);
1700 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1701 AddType(DW_Unit, &Buffer, *CT);
1702 Buffer.AddChild(Arg);
1706 case DW_TAG_structure_type:
1707 case DW_TAG_union_type:
1709 // Add elements to structure type.
1710 DIArray Elements = CTy->getTypeArray();
1711 // Add elements to structure type.
1712 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1713 DIDescriptor Element = Elements.getElement(i);
1714 if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1715 ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1716 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1717 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1718 else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1719 ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1727 // Add name if not anonymous or intermediate type.
1728 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1730 // Add size if non-zero (derived types might be zero-sized.)
1732 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1734 // Add zero size even if it is not a forward declaration.
1735 // FIXME - Enable this.
1736 // if (!CTy->isDefinition())
1737 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1739 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1742 // Add source line info if available and TyDesc is not a forward
1744 // FIXME - Enable this.
1745 // if (CTy->isForwardDecl())
1746 // AddSourceLine(&Buffer, *CTy);
1749 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1750 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1751 int64_t L = SR->getLo();
1752 int64_t H = SR->getHi();
1753 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1755 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1757 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1758 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1760 Buffer.AddChild(DW_Subrange);
1763 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1764 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1765 DICompositeType *CTy) {
1766 Buffer.setTag(DW_TAG_array_type);
1767 if (CTy->getTag() == DW_TAG_vector_type)
1768 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1770 DIArray Elements = CTy->getTypeArray();
1771 // FIXME - Enable this.
1772 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1774 // Construct an anonymous type for index type.
1775 DIE IdxBuffer(DW_TAG_base_type);
1776 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1777 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1778 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1780 // Add subranges to array type.
1781 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1782 DIDescriptor Element = Elements.getElement(i);
1783 if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1784 ConstructSubrangeDIE(Buffer, SR, IndexTy);
1788 /// ConstructEnumTypeDIE - Construct enum type DIE from
1790 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1791 DIE &Buffer, DIEnumerator *ETy) {
1793 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1794 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1795 int64_t Value = ETy->getEnumValue();
1796 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1797 Buffer.AddChild(Enumerator);
1800 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1801 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1802 DIE &Buffer, DIGlobalVariable *V) {
1804 DIE *VariableDie = new DIE(DW_TAG_variable);
1805 const std::string &LinkageName = V->getLinkageName();
1806 if (!LinkageName.empty())
1807 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1809 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1810 AddType(DW_Unit, VariableDie, V->getType());
1811 if (!V->isLocalToUnit())
1812 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1813 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1814 Buffer.AddChild(VariableDie);
1817 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1818 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1819 DIE &Buffer, DISubprogram *SP,
1820 bool IsConstructor = false) {
1821 DIE *Method = new DIE(DW_TAG_subprogram);
1822 AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1823 const std::string &LinkageName = SP->getLinkageName();
1824 if (!LinkageName.empty())
1825 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1826 // FIXME - Enable this. AddSourceLine(Method, SP);
1828 DICompositeType MTy = SP->getType();
1829 DIArray Args = MTy.getTypeArray();
1832 if (!IsConstructor) {
1833 DIDescriptor Ty = Args.getElement(0);
1834 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1835 AddType(DW_Unit, Method, *BT);
1836 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1837 AddType(DW_Unit, Method, *DT);
1838 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1839 AddType(DW_Unit, Method, *CT);
1843 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1844 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1845 DIDescriptor Ty = Args.getElement(i);
1846 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1847 AddType(DW_Unit, Method, *BT);
1848 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1849 AddType(DW_Unit, Method, *DT);
1850 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1851 AddType(DW_Unit, Method, *CT);
1852 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1853 Method->AddChild(Arg);
1856 if (!SP->isLocalToUnit())
1857 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1858 Buffer.AddChild(Method);
1861 /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
1862 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1863 DIDerivedType *DTy) {
1864 unsigned Tag = DTy->getTag();
1865 DIE *MemberDie = new DIE(Tag);
1866 if (!DTy->getName().empty())
1867 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
1868 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
1870 DIType FromTy = DTy->getTypeDerivedFrom();
1871 AddType(DW_Unit, MemberDie, FromTy);
1873 uint64_t Size = DTy->getSizeInBits();
1874 uint64_t Offset = DTy->getOffsetInBits();
1876 // FIXME Handle bitfields
1879 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
1880 // Add computation for offset.
1881 DIEBlock *Block = new DIEBlock();
1882 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1883 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
1884 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1886 // FIXME Handle DW_AT_accessibility.
1888 Buffer.AddChild(MemberDie);
1891 /// ConstructType - Adds all the required attributes to the type.
1893 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1894 // Get core information.
1895 const std::string &Name = TyDesc->getName();
1896 uint64_t Size = TyDesc->getSize() >> 3;
1898 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1899 // Fundamental types like int, float, bool
1900 Buffer.setTag(DW_TAG_base_type);
1901 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1902 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1904 unsigned Tag = DerivedTy->getTag();
1905 // FIXME - Workaround for templates.
1906 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1907 // Pointers, typedefs et al.
1909 // Map to main type, void will not have a type.
1910 if (TypeDesc *FromTy = DerivedTy->getFromType())
1911 AddType(&Buffer, FromTy, Unit);
1912 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1914 unsigned Tag = CompTy->getTag();
1916 // Set tag accordingly.
1917 if (Tag == DW_TAG_vector_type)
1918 Buffer.setTag(DW_TAG_array_type);
1922 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1925 case DW_TAG_vector_type:
1926 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1928 case DW_TAG_array_type: {
1929 // Add element type.
1930 if (TypeDesc *FromTy = CompTy->getFromType())
1931 AddType(&Buffer, FromTy, Unit);
1933 // Don't emit size attribute.
1936 // Construct an anonymous type for index type.
1937 DIE Buffer(DW_TAG_base_type);
1938 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
1939 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1940 DIE *IndexTy = Unit->AddDie(Buffer);
1942 // Add subranges to array type.
1943 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1944 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1945 int64_t Lo = SRD->getLo();
1946 int64_t Hi = SRD->getHi();
1947 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1949 // If a range is available.
1951 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1952 // Only add low if non-zero.
1953 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1954 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1957 Buffer.AddChild(Subrange);
1961 case DW_TAG_structure_type:
1962 case DW_TAG_union_type: {
1963 // Add elements to structure type.
1964 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1965 DebugInfoDesc *Element = Elements[i];
1967 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1968 // Add field or base class.
1969 unsigned Tag = MemberDesc->getTag();
1971 // Extract the basic information.
1972 const std::string &Name = MemberDesc->getName();
1973 uint64_t Size = MemberDesc->getSize();
1974 uint64_t Align = MemberDesc->getAlign();
1975 uint64_t Offset = MemberDesc->getOffset();
1977 // Construct member debug information entry.
1978 DIE *Member = new DIE(Tag);
1980 // Add name if not "".
1982 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1984 // Add location if available.
1985 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1987 // Most of the time the field info is the same as the members.
1988 uint64_t FieldSize = Size;
1989 uint64_t FieldAlign = Align;
1990 uint64_t FieldOffset = Offset;
1992 // Set the member type.
1993 TypeDesc *FromTy = MemberDesc->getFromType();
1994 AddType(Member, FromTy, Unit);
1996 // Walk up typedefs until a real size is found.
1998 if (FromTy->getTag() != DW_TAG_typedef) {
1999 FieldSize = FromTy->getSize();
2000 FieldAlign = FromTy->getAlign();
2004 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
2007 // Unless we have a bit field.
2008 if (Tag == DW_TAG_member && FieldSize != Size) {
2009 // Construct the alignment mask.
2010 uint64_t AlignMask = ~(FieldAlign - 1);
2011 // Determine the high bit + 1 of the declared size.
2012 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
2013 // Work backwards to determine the base offset of the field.
2014 FieldOffset = HiMark - FieldSize;
2015 // Now normalize offset to the field.
2016 Offset -= FieldOffset;
2018 // Maybe we need to work from the other end.
2019 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
2021 // Add size and offset.
2022 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
2023 AddUInt(Member, DW_AT_bit_size, 0, Size);
2024 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
2027 // Add computation for offset.
2028 DIEBlock *Block = new DIEBlock();
2029 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2030 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
2031 AddBlock(Member, DW_AT_data_member_location, 0, Block);
2033 // Add accessibility (public default unless is base class.
2034 if (MemberDesc->isProtected()) {
2035 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
2036 } else if (MemberDesc->isPrivate()) {
2037 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
2038 } else if (Tag == DW_TAG_inheritance) {
2039 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
2042 Buffer.AddChild(Member);
2043 } else if (GlobalVariableDesc *StaticDesc =
2044 dyn_cast<GlobalVariableDesc>(Element)) {
2045 // Add static member.
2047 // Construct member debug information entry.
2048 DIE *Static = new DIE(DW_TAG_variable);
2050 // Add name and mangled name.
2051 const std::string &Name = StaticDesc->getName();
2052 const std::string &LinkageName = StaticDesc->getLinkageName();
2053 AddString(Static, DW_AT_name, DW_FORM_string, Name);
2054 if (!LinkageName.empty()) {
2055 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
2060 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
2063 if (TypeDesc *StaticTy = StaticDesc->getType())
2064 AddType(Static, StaticTy, Unit);
2067 if (!StaticDesc->isStatic())
2068 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
2069 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2071 Buffer.AddChild(Static);
2072 } else if (SubprogramDesc *MethodDesc =
2073 dyn_cast<SubprogramDesc>(Element)) {
2074 // Add member function.
2076 // Construct member debug information entry.
2077 DIE *Method = new DIE(DW_TAG_subprogram);
2079 // Add name and mangled name.
2080 const std::string &Name = MethodDesc->getName();
2081 const std::string &LinkageName = MethodDesc->getLinkageName();
2083 AddString(Method, DW_AT_name, DW_FORM_string, Name);
2084 bool IsCTor = TyDesc->getName() == Name;
2086 if (!LinkageName.empty()) {
2087 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2092 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2095 if (CompositeTypeDesc *MethodTy =
2096 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2097 // Get argument information.
2098 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2103 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2107 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2108 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2109 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2110 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2111 Method->AddChild(Arg);
2116 if (!MethodDesc->isStatic())
2117 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2118 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2120 Buffer.AddChild(Method);
2125 case DW_TAG_enumeration_type: {
2126 // Add enumerators to enumeration type.
2127 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2128 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2129 const std::string &Name = ED->getName();
2130 int64_t Value = ED->getValue();
2131 DIE *Enumerator = new DIE(DW_TAG_enumerator);
2132 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2133 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2134 Buffer.AddChild(Enumerator);
2139 case DW_TAG_subroutine_type: {
2140 // Add prototype flag.
2141 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2143 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2146 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2147 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2148 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2149 Buffer.AddChild(Arg);
2158 // Add name if not anonymous or intermediate type.
2159 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2161 // Add size if non-zero (derived types might be zero-sized.)
2163 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2164 else if (isa<CompositeTypeDesc>(TyDesc)) {
2165 // If TyDesc is a composite type, then add size even if it's zero unless
2166 // it's a forward declaration.
2167 if (TyDesc->isForwardDecl())
2168 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2170 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2173 // Add source line info if available and TyDesc is not a forward
2175 if (!TyDesc->isForwardDecl())
2176 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2179 /// NewCompileUnit - Create new compile unit and it's debug information entry.
2181 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2182 // Construct debug information entry.
2183 DIE *Die = new DIE(DW_TAG_compile_unit);
2184 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2185 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2186 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
2187 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
2188 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
2189 if (!UnitDesc->getDirectory().empty())
2190 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
2192 // Construct compile unit.
2193 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2195 // Add Unit to compile unit map.
2196 DescToUnitMap[UnitDesc] = Unit;
2201 /// GetBaseCompileUnit - Get the main compile unit.
2203 CompileUnit *GetBaseCompileUnit() const {
2204 CompileUnit *Unit = CompileUnits[0];
2205 assert(Unit && "Missing compile unit.");
2209 /// FindCompileUnit - Get the compile unit for the given descriptor.
2211 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2212 CompileUnit *Unit = DescToUnitMap[UnitDesc];
2213 assert(Unit && "Missing compile unit.");
2217 /// FindCompileUnit - Get the compile unit for the given descriptor.
2219 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
2220 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
2221 assert(DW_Unit && "Missing compile unit.");
2225 /// NewGlobalVariable - Add a new global variable DIE.
2227 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2228 // Get the compile unit context.
2229 CompileUnitDesc *UnitDesc =
2230 static_cast<CompileUnitDesc *>(GVD->getContext());
2231 CompileUnit *Unit = GetBaseCompileUnit();
2233 // Check for pre-existence.
2234 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2235 if (Slot) return Slot;
2237 // Get the global variable itself.
2238 GlobalVariable *GV = GVD->getGlobalVariable();
2240 const std::string &Name = GVD->getName();
2241 const std::string &FullName = GVD->getFullName();
2242 const std::string &LinkageName = GVD->getLinkageName();
2243 // Create the global's variable DIE.
2244 DIE *VariableDie = new DIE(DW_TAG_variable);
2245 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2246 if (!LinkageName.empty()) {
2247 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2250 AddType(VariableDie, GVD->getType(), Unit);
2251 if (!GVD->isStatic())
2252 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2254 // Add source line info if available.
2255 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2258 DIEBlock *Block = new DIEBlock();
2259 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2260 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2261 AddBlock(VariableDie, DW_AT_location, 0, Block);
2266 // Add to context owner.
2267 Unit->getDie()->AddChild(VariableDie);
2269 // Expose as global.
2270 // FIXME - need to check external flag.
2271 Unit->AddGlobal(FullName, VariableDie);
2276 /// NewSubprogram - Add a new subprogram DIE.
2278 DIE *NewSubprogram(SubprogramDesc *SPD) {
2279 // Get the compile unit context.
2280 CompileUnitDesc *UnitDesc =
2281 static_cast<CompileUnitDesc *>(SPD->getContext());
2282 CompileUnit *Unit = GetBaseCompileUnit();
2284 // Check for pre-existence.
2285 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2286 if (Slot) return Slot;
2288 // Gather the details (simplify add attribute code.)
2289 const std::string &Name = SPD->getName();
2290 const std::string &FullName = SPD->getFullName();
2291 const std::string &LinkageName = SPD->getLinkageName();
2293 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2294 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2295 if (!LinkageName.empty()) {
2296 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2299 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2300 if (!SPD->isStatic())
2301 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2302 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2304 // Add source line info if available.
2305 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2308 Slot = SubprogramDie;
2310 // Add to context owner.
2311 Unit->getDie()->AddChild(SubprogramDie);
2313 // Expose as global.
2314 Unit->AddGlobal(FullName, SubprogramDie);
2316 return SubprogramDie;
2319 /// NewScopeVariable - Create a new scope variable.
2321 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2322 // Get the descriptor.
2323 VariableDesc *VD = DV->getDesc();
2325 // Translate tag to proper Dwarf tag. The result variable is dropped for
2328 switch (VD->getTag()) {
2329 case DW_TAG_return_variable: return NULL;
2330 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2331 case DW_TAG_auto_variable: // fall thru
2332 default: Tag = DW_TAG_variable; break;
2335 // Define variable debug information entry.
2336 DIE *VariableDie = new DIE(Tag);
2337 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2339 // Add source line info if available.
2340 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2342 // Add variable type.
2343 AddType(VariableDie, VD->getType(), Unit);
2345 // Add variable address.
2346 MachineLocation Location;
2347 Location.set(RI->getFrameRegister(*MF),
2348 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2349 AddAddress(VariableDie, DW_AT_location, Location);
2354 /// ConstructScope - Construct the components of a scope.
2356 void ConstructScope(DebugScope *ParentScope,
2357 unsigned ParentStartID, unsigned ParentEndID,
2358 DIE *ParentDie, CompileUnit *Unit) {
2359 // Add variables to scope.
2360 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2361 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2362 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2363 if (VariableDie) ParentDie->AddChild(VariableDie);
2366 // Add nested scopes.
2367 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2368 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2369 // Define the Scope debug information entry.
2370 DebugScope *Scope = Scopes[j];
2371 // FIXME - Ignore inlined functions for the time being.
2372 if (!Scope->getParent()) continue;
2374 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2375 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2377 // Ignore empty scopes.
2378 if (StartID == EndID && StartID != 0) continue;
2379 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2381 if (StartID == ParentStartID && EndID == ParentEndID) {
2382 // Just add stuff to the parent scope.
2383 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2385 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2387 // Add the scope bounds.
2389 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2390 DWLabel("label", StartID));
2392 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2393 DWLabel("func_begin", SubprogramCount));
2396 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2397 DWLabel("label", EndID));
2399 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2400 DWLabel("func_end", SubprogramCount));
2403 // Add the scope contents.
2404 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2405 ParentDie->AddChild(ScopeDie);
2410 /// ConstructRootScope - Construct the scope for the subprogram.
2412 void ConstructRootScope(DebugScope *RootScope) {
2413 // Exit if there is no root scope.
2414 if (!RootScope) return;
2416 // Get the subprogram debug information entry.
2417 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2419 // Get the compile unit context.
2420 CompileUnit *Unit = GetBaseCompileUnit();
2422 // Get the subprogram die.
2423 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2424 assert(SPDie && "Missing subprogram descriptor");
2426 // Add the function bounds.
2427 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2428 DWLabel("func_begin", SubprogramCount));
2429 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2430 DWLabel("func_end", SubprogramCount));
2431 MachineLocation Location(RI->getFrameRegister(*MF));
2432 AddAddress(SPDie, DW_AT_frame_base, Location);
2434 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2437 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2439 void ConstructDefaultScope(MachineFunction *MF) {
2440 // Find the correct subprogram descriptor.
2441 std::vector<SubprogramDesc *> Subprograms;
2442 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2444 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2445 SubprogramDesc *SPD = Subprograms[i];
2447 if (SPD->getName() == MF->getFunction()->getName()) {
2448 // Get the compile unit context.
2449 CompileUnit *Unit = GetBaseCompileUnit();
2451 // Get the subprogram die.
2452 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2453 assert(SPDie && "Missing subprogram descriptor");
2455 // Add the function bounds.
2456 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2457 DWLabel("func_begin", SubprogramCount));
2458 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2459 DWLabel("func_end", SubprogramCount));
2461 MachineLocation Location(RI->getFrameRegister(*MF));
2462 AddAddress(SPDie, DW_AT_frame_base, Location);
2467 // FIXME: This is causing an abort because C++ mangled names are compared
2468 // with their unmangled counterparts. See PR2885. Don't do this assert.
2469 assert(0 && "Couldn't find DIE for machine function!");
2473 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2474 /// tools to recognize the object file contains Dwarf information.
2475 void EmitInitial() {
2476 // Check to see if we already emitted intial headers.
2477 if (didInitial) return;
2480 // Dwarf sections base addresses.
2481 if (TAI->doesDwarfRequireFrameSection()) {
2482 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2483 EmitLabel("section_debug_frame", 0);
2485 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2486 EmitLabel("section_info", 0);
2487 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2488 EmitLabel("section_abbrev", 0);
2489 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2490 EmitLabel("section_aranges", 0);
2491 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2492 EmitLabel("section_macinfo", 0);
2493 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2494 EmitLabel("section_line", 0);
2495 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2496 EmitLabel("section_loc", 0);
2497 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2498 EmitLabel("section_pubnames", 0);
2499 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2500 EmitLabel("section_str", 0);
2501 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2502 EmitLabel("section_ranges", 0);
2504 Asm->SwitchToSection(TAI->getTextSection());
2505 EmitLabel("text_begin", 0);
2506 Asm->SwitchToSection(TAI->getDataSection());
2507 EmitLabel("data_begin", 0);
2510 /// EmitDIE - Recusively Emits a debug information entry.
2512 void EmitDIE(DIE *Die) {
2513 // Get the abbreviation for this DIE.
2514 unsigned AbbrevNumber = Die->getAbbrevNumber();
2515 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2519 // Emit the code (index) for the abbreviation.
2520 Asm->EmitULEB128Bytes(AbbrevNumber);
2523 Asm->EOL(std::string("Abbrev [" +
2524 utostr(AbbrevNumber) +
2525 "] 0x" + utohexstr(Die->getOffset()) +
2526 ":0x" + utohexstr(Die->getSize()) + " " +
2527 TagString(Abbrev->getTag())));
2531 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2532 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2534 // Emit the DIE attribute values.
2535 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2536 unsigned Attr = AbbrevData[i].getAttribute();
2537 unsigned Form = AbbrevData[i].getForm();
2538 assert(Form && "Too many attributes for DIE (check abbreviation)");
2541 case DW_AT_sibling: {
2542 Asm->EmitInt32(Die->SiblingOffset());
2546 // Emit an attribute using the defined form.
2547 Values[i]->EmitValue(*this, Form);
2552 Asm->EOL(AttributeString(Attr));
2555 // Emit the DIE children if any.
2556 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2557 const std::vector<DIE *> &Children = Die->getChildren();
2559 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2560 EmitDIE(Children[j]);
2563 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2567 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2569 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2570 // Get the children.
2571 const std::vector<DIE *> &Children = Die->getChildren();
2573 // If not last sibling and has children then add sibling offset attribute.
2574 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2576 // Record the abbreviation.
2577 AssignAbbrevNumber(Die->getAbbrev());
2579 // Get the abbreviation for this DIE.
2580 unsigned AbbrevNumber = Die->getAbbrevNumber();
2581 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2584 Die->setOffset(Offset);
2586 // Start the size with the size of abbreviation code.
2587 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2589 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2590 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2592 // Size the DIE attribute values.
2593 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2594 // Size attribute value.
2595 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2598 // Size the DIE children if any.
2599 if (!Children.empty()) {
2600 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2601 "Children flag not set");
2603 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2604 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2607 // End of children marker.
2608 Offset += sizeof(int8_t);
2611 Die->setSize(Offset - Die->getOffset());
2615 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2617 void SizeAndOffsets() {
2618 // Process base compile unit.
2619 CompileUnit *Unit = GetBaseCompileUnit();
2620 // Compute size of compile unit header
2621 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2622 sizeof(int16_t) + // DWARF version number
2623 sizeof(int32_t) + // Offset Into Abbrev. Section
2624 sizeof(int8_t); // Pointer Size (in bytes)
2625 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2628 /// EmitDebugInfo - Emit the debug info section.
2630 void EmitDebugInfo() {
2631 // Start debug info section.
2632 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2634 CompileUnit *Unit = GetBaseCompileUnit();
2635 DIE *Die = Unit->getDie();
2636 // Emit the compile units header.
2637 EmitLabel("info_begin", Unit->getID());
2638 // Emit size of content not including length itself
2639 unsigned ContentSize = Die->getSize() +
2640 sizeof(int16_t) + // DWARF version number
2641 sizeof(int32_t) + // Offset Into Abbrev. Section
2642 sizeof(int8_t) + // Pointer Size (in bytes)
2643 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2645 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2646 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2647 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2648 Asm->EOL("Offset Into Abbrev. Section");
2649 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2652 // FIXME - extra padding for gdb bug.
2653 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2654 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2655 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2656 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2657 EmitLabel("info_end", Unit->getID());
2662 /// EmitAbbreviations - Emit the abbreviation section.
2664 void EmitAbbreviations() const {
2665 // Check to see if it is worth the effort.
2666 if (!Abbreviations.empty()) {
2667 // Start the debug abbrev section.
2668 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2670 EmitLabel("abbrev_begin", 0);
2672 // For each abbrevation.
2673 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2674 // Get abbreviation data
2675 const DIEAbbrev *Abbrev = Abbreviations[i];
2677 // Emit the abbrevations code (base 1 index.)
2678 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2679 Asm->EOL("Abbreviation Code");
2681 // Emit the abbreviations data.
2682 Abbrev->Emit(*this);
2687 // Mark end of abbreviations.
2688 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2690 EmitLabel("abbrev_end", 0);
2696 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2697 /// the line matrix.
2699 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2700 // Define last address of section.
2701 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2702 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2703 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2704 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2706 // Mark end of matrix.
2707 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2708 Asm->EmitULEB128Bytes(1); Asm->EOL();
2709 Asm->EmitInt8(1); Asm->EOL();
2712 /// EmitDebugLines - Emit source line information.
2714 void EmitDebugLines() {
2715 // If the target is using .loc/.file, the assembler will be emitting the
2716 // .debug_line table automatically.
2717 if (TAI->hasDotLocAndDotFile())
2720 // Minimum line delta, thus ranging from -10..(255-10).
2721 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2722 // Maximum line delta, thus ranging from -10..(255-10).
2723 const int MaxLineDelta = 255 + MinLineDelta;
2725 // Start the dwarf line section.
2726 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2728 // Construct the section header.
2730 EmitDifference("line_end", 0, "line_begin", 0, true);
2731 Asm->EOL("Length of Source Line Info");
2732 EmitLabel("line_begin", 0);
2734 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2736 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2737 Asm->EOL("Prolog Length");
2738 EmitLabel("line_prolog_begin", 0);
2740 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2742 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2744 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2746 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2748 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2750 // Line number standard opcode encodings argument count
2751 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2752 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2753 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2754 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2755 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2756 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2757 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2758 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2759 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2761 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2762 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2764 // Emit directories.
2765 for (unsigned DirectoryID = 1, NDID = Directories.size();
2766 DirectoryID <= NDID; ++DirectoryID) {
2767 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2769 Asm->EmitInt8(0); Asm->EOL("End of directories");
2772 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2773 SourceID <= NSID; ++SourceID) {
2774 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2775 Asm->EmitString(SourceFile.getName());
2777 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2778 Asm->EOL("Directory #");
2779 Asm->EmitULEB128Bytes(0);
2780 Asm->EOL("Mod date");
2781 Asm->EmitULEB128Bytes(0);
2782 Asm->EOL("File size");
2784 Asm->EmitInt8(0); Asm->EOL("End of files");
2786 EmitLabel("line_prolog_end", 0);
2788 // A sequence for each text section.
2789 unsigned SecSrcLinesSize = SectionSourceLines.size();
2791 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2792 // Isolate current sections line info.
2793 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2796 const Section* S = SectionMap[j + 1];
2797 Asm->EOL(std::string("Section ") + S->getName());
2801 // Dwarf assumes we start with first line of first source file.
2802 unsigned Source = 1;
2805 // Construct rows of the address, source, line, column matrix.
2806 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2807 const SourceLineInfo &LineInfo = LineInfos[i];
2808 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2809 if (!LabelID) continue;
2811 unsigned SourceID = LineInfo.getSourceID();
2812 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2813 unsigned DirectoryID = SourceFile.getDirectoryID();
2815 Asm->EOL(Directories[DirectoryID]
2816 + SourceFile.getName()
2818 + utostr_32(LineInfo.getLine()));
2822 // Define the line address.
2823 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2824 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2825 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2826 EmitReference("label", LabelID); Asm->EOL("Location label");
2828 // If change of source, then switch to the new source.
2829 if (Source != LineInfo.getSourceID()) {
2830 Source = LineInfo.getSourceID();
2831 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2832 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2835 // If change of line.
2836 if (Line != LineInfo.getLine()) {
2837 // Determine offset.
2838 int Offset = LineInfo.getLine() - Line;
2839 int Delta = Offset - MinLineDelta;
2842 Line = LineInfo.getLine();
2844 // If delta is small enough and in range...
2845 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2846 // ... then use fast opcode.
2847 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2849 // ... otherwise use long hand.
2850 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2851 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2852 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2855 // Copy the previous row (different address or source)
2856 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2860 EmitEndOfLineMatrix(j + 1);
2863 if (SecSrcLinesSize == 0)
2864 // Because we're emitting a debug_line section, we still need a line
2865 // table. The linker and friends expect it to exist. If there's nothing to
2866 // put into it, emit an empty table.
2867 EmitEndOfLineMatrix(1);
2869 EmitLabel("line_end", 0);
2874 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2876 void EmitCommonDebugFrame() {
2877 if (!TAI->doesDwarfRequireFrameSection())
2881 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2882 TargetFrameInfo::StackGrowsUp ?
2883 TD->getPointerSize() : -TD->getPointerSize();
2885 // Start the dwarf frame section.
2886 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2888 EmitLabel("debug_frame_common", 0);
2889 EmitDifference("debug_frame_common_end", 0,
2890 "debug_frame_common_begin", 0, true);
2891 Asm->EOL("Length of Common Information Entry");
2893 EmitLabel("debug_frame_common_begin", 0);
2894 Asm->EmitInt32((int)DW_CIE_ID);
2895 Asm->EOL("CIE Identifier Tag");
2896 Asm->EmitInt8(DW_CIE_VERSION);
2897 Asm->EOL("CIE Version");
2898 Asm->EmitString("");
2899 Asm->EOL("CIE Augmentation");
2900 Asm->EmitULEB128Bytes(1);
2901 Asm->EOL("CIE Code Alignment Factor");
2902 Asm->EmitSLEB128Bytes(stackGrowth);
2903 Asm->EOL("CIE Data Alignment Factor");
2904 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2905 Asm->EOL("CIE RA Column");
2907 std::vector<MachineMove> Moves;
2908 RI->getInitialFrameState(Moves);
2910 EmitFrameMoves(NULL, 0, Moves, false);
2912 Asm->EmitAlignment(2, 0, 0, false);
2913 EmitLabel("debug_frame_common_end", 0);
2918 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2920 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2921 if (!TAI->doesDwarfRequireFrameSection())
2924 // Start the dwarf frame section.
2925 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2927 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2928 "debug_frame_begin", DebugFrameInfo.Number, true);
2929 Asm->EOL("Length of Frame Information Entry");
2931 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2933 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2935 Asm->EOL("FDE CIE offset");
2937 EmitReference("func_begin", DebugFrameInfo.Number);
2938 Asm->EOL("FDE initial location");
2939 EmitDifference("func_end", DebugFrameInfo.Number,
2940 "func_begin", DebugFrameInfo.Number);
2941 Asm->EOL("FDE address range");
2943 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2945 Asm->EmitAlignment(2, 0, 0, false);
2946 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2951 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2953 void EmitDebugPubNames() {
2954 // Start the dwarf pubnames section.
2955 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2957 CompileUnit *Unit = GetBaseCompileUnit();
2959 EmitDifference("pubnames_end", Unit->getID(),
2960 "pubnames_begin", Unit->getID(), true);
2961 Asm->EOL("Length of Public Names Info");
2963 EmitLabel("pubnames_begin", Unit->getID());
2965 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2967 EmitSectionOffset("info_begin", "section_info",
2968 Unit->getID(), 0, true, false);
2969 Asm->EOL("Offset of Compilation Unit Info");
2971 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2972 Asm->EOL("Compilation Unit Length");
2974 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2976 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2979 const std::string &Name = GI->first;
2980 DIE * Entity = GI->second;
2982 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2983 Asm->EmitString(Name); Asm->EOL("External Name");
2986 Asm->EmitInt32(0); Asm->EOL("End Mark");
2987 EmitLabel("pubnames_end", Unit->getID());
2992 /// EmitDebugStr - Emit visible names into a debug str section.
2994 void EmitDebugStr() {
2995 // Check to see if it is worth the effort.
2996 if (!StringPool.empty()) {
2997 // Start the dwarf str section.
2998 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
3000 // For each of strings in the string pool.
3001 for (unsigned StringID = 1, N = StringPool.size();
3002 StringID <= N; ++StringID) {
3003 // Emit a label for reference from debug information entries.
3004 EmitLabel("string", StringID);
3005 // Emit the string itself.
3006 const std::string &String = StringPool[StringID];
3007 Asm->EmitString(String); Asm->EOL();
3014 /// EmitDebugLoc - Emit visible names into a debug loc section.
3016 void EmitDebugLoc() {
3017 // Start the dwarf loc section.
3018 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
3023 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3025 void EmitDebugARanges() {
3026 // Start the dwarf aranges section.
3027 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
3031 CompileUnit *Unit = GetBaseCompileUnit();
3033 // Don't include size of length
3034 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
3036 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
3038 EmitReference("info_begin", Unit->getID());
3039 Asm->EOL("Offset of Compilation Unit Info");
3041 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
3043 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
3045 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
3046 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
3049 EmitReference("text_begin", 0); Asm->EOL("Address");
3050 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
3052 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
3053 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
3059 /// EmitDebugRanges - Emit visible names into a debug ranges section.
3061 void EmitDebugRanges() {
3062 // Start the dwarf ranges section.
3063 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
3068 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
3070 void EmitDebugMacInfo() {
3071 // Start the dwarf macinfo section.
3072 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
3077 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3079 void ConstructCompileUnitDIEs() {
3080 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3082 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3083 unsigned ID = MMI->RecordSource(CUW[i]);
3084 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3085 CompileUnits.push_back(Unit);
3089 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3090 /// global variables.
3091 void ConstructGlobalDIEs() {
3092 std::vector<GlobalVariableDesc *> GlobalVariables;
3093 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3095 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3096 GlobalVariableDesc *GVD = GlobalVariables[i];
3097 NewGlobalVariable(GVD);
3101 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3103 void ConstructSubprogramDIEs() {
3104 std::vector<SubprogramDesc *> Subprograms;
3105 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3107 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3108 SubprogramDesc *SPD = Subprograms[i];
3114 //===--------------------------------------------------------------------===//
3115 // Main entry points.
3117 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3118 : Dwarf(OS, A, T, "dbg")
3120 , AbbreviationsSet(InitAbbreviationsSetSize)
3122 , ValuesSet(InitValuesSetSize)
3127 , SectionSourceLines()
3132 virtual ~DwarfDebug() {
3133 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3134 delete CompileUnits[i];
3135 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3139 /// SetModuleInfo - Set machine module information when it's known that pass
3140 /// manager has created it. Set by the target AsmPrinter.
3141 void SetModuleInfo(MachineModuleInfo *mmi) {
3142 // Make sure initial declarations are made.
3143 if (!MMI && mmi->hasDebugInfo()) {
3147 // Create all the compile unit DIEs.
3148 ConstructCompileUnitDIEs();
3150 // Create DIEs for each of the externally visible global variables.
3151 ConstructGlobalDIEs();
3153 // Create DIEs for each of the externally visible subprograms.
3154 ConstructSubprogramDIEs();
3156 // Prime section data.
3157 SectionMap.insert(TAI->getTextSection());
3159 // Print out .file directives to specify files for .loc directives. These
3160 // are printed out early so that they precede any .loc directives.
3161 if (TAI->hasDotLocAndDotFile()) {
3162 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3163 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3164 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3165 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3166 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3167 assert(AppendOk && "Could not append filename to directory!");
3169 Asm->EmitFile(i, FullPath.toString());
3174 // Emit initial sections
3179 /// BeginModule - Emit all Dwarf sections that should come prior to the
3181 void BeginModule(Module *M) {
3185 /// EndModule - Emit all Dwarf sections that should come after the content.
3188 if (!ShouldEmitDwarf()) return;
3190 // Standard sections final addresses.
3191 Asm->SwitchToSection(TAI->getTextSection());
3192 EmitLabel("text_end", 0);
3193 Asm->SwitchToSection(TAI->getDataSection());
3194 EmitLabel("data_end", 0);
3196 // End text sections.
3197 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3198 Asm->SwitchToSection(SectionMap[i]);
3199 EmitLabel("section_end", i);
3202 // Emit common frame information.
3203 EmitCommonDebugFrame();
3205 // Emit function debug frame information
3206 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3207 E = DebugFrames.end(); I != E; ++I)
3208 EmitFunctionDebugFrame(*I);
3210 // Compute DIE offsets and sizes.
3213 // Emit all the DIEs into a debug info section
3216 // Corresponding abbreviations into a abbrev section.
3217 EmitAbbreviations();
3219 // Emit source line correspondence into a debug line section.
3222 // Emit info into a debug pubnames section.
3223 EmitDebugPubNames();
3225 // Emit info into a debug str section.
3228 // Emit info into a debug loc section.
3231 // Emit info into a debug aranges section.
3234 // Emit info into a debug ranges section.
3237 // Emit info into a debug macinfo section.
3241 /// BeginFunction - Gather pre-function debug information. Assumes being
3242 /// emitted immediately after the function entry point.
3243 void BeginFunction(MachineFunction *MF) {
3246 if (!ShouldEmitDwarf()) return;
3248 // Begin accumulating function debug information.
3249 MMI->BeginFunction(MF);
3251 // Assumes in correct section after the entry point.
3252 EmitLabel("func_begin", ++SubprogramCount);
3254 // Emit label for the implicitly defined dbg.stoppoint at the start of
3256 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3257 if (!LineInfos.empty()) {
3258 const SourceLineInfo &LineInfo = LineInfos[0];
3259 Asm->printLabel(LineInfo.getLabelID());
3263 /// EndFunction - Gather and emit post-function debug information.
3265 void EndFunction(MachineFunction *MF) {
3266 if (!ShouldEmitDwarf()) return;
3268 // Define end label for subprogram.
3269 EmitLabel("func_end", SubprogramCount);
3271 // Get function line info.
3272 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3274 if (!LineInfos.empty()) {
3275 // Get section line info.
3276 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3277 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3278 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3279 // Append the function info to section info.
3280 SectionLineInfos.insert(SectionLineInfos.end(),
3281 LineInfos.begin(), LineInfos.end());
3284 // Construct scopes for subprogram.
3285 if (MMI->getRootScope())
3286 ConstructRootScope(MMI->getRootScope());
3288 // FIXME: This is wrong. We are essentially getting past a problem with
3289 // debug information not being able to handle unreachable blocks that have
3290 // debug information in them. In particular, those unreachable blocks that
3291 // have "region end" info in them. That situation results in the "root
3292 // scope" not being created. If that's the case, then emit a "default"
3293 // scope, i.e., one that encompasses the whole function. This isn't
3294 // desirable. And a better way of handling this (and all of the debugging
3295 // information) needs to be explored.
3296 ConstructDefaultScope(MF);
3298 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3299 MMI->getFrameMoves()));
3303 //===----------------------------------------------------------------------===//
3304 /// DwarfException - Emits Dwarf exception handling directives.
3306 class DwarfException : public Dwarf {
3309 struct FunctionEHFrameInfo {
3312 unsigned PersonalityIndex;
3314 bool hasLandingPads;
3315 std::vector<MachineMove> Moves;
3316 const Function * function;
3318 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3320 const std::vector<MachineMove> &M,
3322 FnName(FN), Number(Num), PersonalityIndex(P),
3323 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3326 std::vector<FunctionEHFrameInfo> EHFrames;
3328 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3330 bool shouldEmitTable;
3332 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3333 /// should be emitted.
3334 bool shouldEmitMoves;
3336 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3337 /// should be emitted.
3338 bool shouldEmitTableModule;
3340 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3341 /// should be emitted.
3342 bool shouldEmitMovesModule;
3344 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3346 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3347 // Size and sign of stack growth.
3349 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3350 TargetFrameInfo::StackGrowsUp ?
3351 TD->getPointerSize() : -TD->getPointerSize();
3353 // Begin eh frame section.
3354 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3356 if (!TAI->doesRequireNonLocalEHFrameLabel())
3357 O << TAI->getEHGlobalPrefix();
3358 O << "EH_frame" << Index << ":\n";
3359 EmitLabel("section_eh_frame", Index);
3361 // Define base labels.
3362 EmitLabel("eh_frame_common", Index);
3364 // Define the eh frame length.
3365 EmitDifference("eh_frame_common_end", Index,
3366 "eh_frame_common_begin", Index, true);
3367 Asm->EOL("Length of Common Information Entry");
3370 EmitLabel("eh_frame_common_begin", Index);
3371 Asm->EmitInt32((int)0);
3372 Asm->EOL("CIE Identifier Tag");
3373 Asm->EmitInt8(DW_CIE_VERSION);
3374 Asm->EOL("CIE Version");
3376 // The personality presence indicates that language specific information
3377 // will show up in the eh frame.
3378 Asm->EmitString(Personality ? "zPLR" : "zR");
3379 Asm->EOL("CIE Augmentation");
3381 // Round out reader.
3382 Asm->EmitULEB128Bytes(1);
3383 Asm->EOL("CIE Code Alignment Factor");
3384 Asm->EmitSLEB128Bytes(stackGrowth);
3385 Asm->EOL("CIE Data Alignment Factor");
3386 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3387 Asm->EOL("CIE Return Address Column");
3389 // If there is a personality, we need to indicate the functions location.
3391 Asm->EmitULEB128Bytes(7);
3392 Asm->EOL("Augmentation Size");
3394 if (TAI->getNeedsIndirectEncoding()) {
3395 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3396 Asm->EOL("Personality (pcrel sdata4 indirect)");
3398 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3399 Asm->EOL("Personality (pcrel sdata4)");
3402 PrintRelDirective(true);
3403 O << TAI->getPersonalityPrefix();
3404 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3405 O << TAI->getPersonalitySuffix();
3406 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3407 O << "-" << TAI->getPCSymbol();
3408 Asm->EOL("Personality");
3410 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3411 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3413 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3414 Asm->EOL("FDE Encoding (pcrel sdata4)");
3416 Asm->EmitULEB128Bytes(1);
3417 Asm->EOL("Augmentation Size");
3419 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3420 Asm->EOL("FDE Encoding (pcrel sdata4)");
3423 // Indicate locations of general callee saved registers in frame.
3424 std::vector<MachineMove> Moves;
3425 RI->getInitialFrameState(Moves);
3426 EmitFrameMoves(NULL, 0, Moves, true);
3428 // On Darwin the linker honors the alignment of eh_frame, which means it
3429 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3430 // you get holes which confuse readers of eh_frame.
3431 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3433 EmitLabel("eh_frame_common_end", Index);
3438 /// EmitEHFrame - Emit function exception frame information.
3440 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3441 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3443 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3445 // Externally visible entry into the functions eh frame info.
3446 // If the corresponding function is static, this should not be
3447 // externally visible.
3448 if (linkage != Function::InternalLinkage) {
3449 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3450 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3453 // If corresponding function is weak definition, this should be too.
3454 if ((linkage == Function::WeakLinkage ||
3455 linkage == Function::LinkOnceLinkage) &&
3456 TAI->getWeakDefDirective())
3457 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3459 // If there are no calls then you can't unwind. This may mean we can
3460 // omit the EH Frame, but some environments do not handle weak absolute
3462 // If UnwindTablesMandatory is set we cannot do this optimization; the
3463 // unwind info is to be available for non-EH uses.
3464 if (!EHFrameInfo.hasCalls &&
3465 !UnwindTablesMandatory &&
3466 ((linkage != Function::WeakLinkage &&
3467 linkage != Function::LinkOnceLinkage) ||
3468 !TAI->getWeakDefDirective() ||
3469 TAI->getSupportsWeakOmittedEHFrame()))
3471 O << EHFrameInfo.FnName << " = 0\n";
3472 // This name has no connection to the function, so it might get
3473 // dead-stripped when the function is not, erroneously. Prohibit
3474 // dead-stripping unconditionally.
3475 if (const char *UsedDirective = TAI->getUsedDirective())
3476 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3478 O << EHFrameInfo.FnName << ":\n";
3481 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3482 "eh_frame_begin", EHFrameInfo.Number, true);
3483 Asm->EOL("Length of Frame Information Entry");
3485 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3487 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3488 PrintRelDirective(true, true);
3489 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3491 if (!TAI->isAbsoluteEHSectionOffsets())
3492 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3494 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3495 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3499 Asm->EOL("FDE CIE offset");
3501 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
3502 Asm->EOL("FDE initial location");
3503 EmitDifference("eh_func_end", EHFrameInfo.Number,
3504 "eh_func_begin", EHFrameInfo.Number);
3505 Asm->EOL("FDE address range");
3507 // If there is a personality and landing pads then point to the language
3508 // specific data area in the exception table.
3509 if (EHFrameInfo.PersonalityIndex) {
3510 Asm->EmitULEB128Bytes(4);
3511 Asm->EOL("Augmentation size");
3513 if (EHFrameInfo.hasLandingPads)
3514 EmitReference("exception", EHFrameInfo.Number, true, true);
3516 Asm->EmitInt32((int)0);
3517 Asm->EOL("Language Specific Data Area");
3519 Asm->EmitULEB128Bytes(0);
3520 Asm->EOL("Augmentation size");
3523 // Indicate locations of function specific callee saved registers in
3525 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3527 // On Darwin the linker honors the alignment of eh_frame, which means it
3528 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3529 // you get holes which confuse readers of eh_frame.
3530 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3532 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3534 // If the function is marked used, this table should be also. We cannot
3535 // make the mark unconditional in this case, since retaining the table
3536 // also retains the function in this case, and there is code around
3537 // that depends on unused functions (calling undefined externals) being
3538 // dead-stripped to link correctly. Yes, there really is.
3539 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3540 if (const char *UsedDirective = TAI->getUsedDirective())
3541 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3545 /// EmitExceptionTable - Emit landing pads and actions.
3547 /// The general organization of the table is complex, but the basic concepts
3548 /// are easy. First there is a header which describes the location and
3549 /// organization of the three components that follow.
3550 /// 1. The landing pad site information describes the range of code covered
3551 /// by the try. In our case it's an accumulation of the ranges covered
3552 /// by the invokes in the try. There is also a reference to the landing
3553 /// pad that handles the exception once processed. Finally an index into
3554 /// the actions table.
3555 /// 2. The action table, in our case, is composed of pairs of type ids
3556 /// and next action offset. Starting with the action index from the
3557 /// landing pad site, each type Id is checked for a match to the current
3558 /// exception. If it matches then the exception and type id are passed
3559 /// on to the landing pad. Otherwise the next action is looked up. This
3560 /// chain is terminated with a next action of zero. If no type id is
3561 /// found the the frame is unwound and handling continues.
3562 /// 3. Type id table contains references to all the C++ typeinfo for all
3563 /// catches in the function. This tables is reversed indexed base 1.
3565 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3566 static unsigned SharedTypeIds(const LandingPadInfo *L,
3567 const LandingPadInfo *R) {
3568 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3569 unsigned LSize = LIds.size(), RSize = RIds.size();
3570 unsigned MinSize = LSize < RSize ? LSize : RSize;
3573 for (; Count != MinSize; ++Count)
3574 if (LIds[Count] != RIds[Count])
3580 /// PadLT - Order landing pads lexicographically by type id.
3581 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3582 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3583 unsigned LSize = LIds.size(), RSize = RIds.size();
3584 unsigned MinSize = LSize < RSize ? LSize : RSize;
3586 for (unsigned i = 0; i != MinSize; ++i)
3587 if (LIds[i] != RIds[i])
3588 return LIds[i] < RIds[i];
3590 return LSize < RSize;
3594 static inline unsigned getEmptyKey() { return -1U; }
3595 static inline unsigned getTombstoneKey() { return -2U; }
3596 static unsigned getHashValue(const unsigned &Key) { return Key; }
3597 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3598 static bool isPod() { return true; }
3601 /// ActionEntry - Structure describing an entry in the actions table.
3602 struct ActionEntry {
3603 int ValueForTypeID; // The value to write - may not be equal to the type id.
3605 struct ActionEntry *Previous;
3608 /// PadRange - Structure holding a try-range and the associated landing pad.
3610 // The index of the landing pad.
3612 // The index of the begin and end labels in the landing pad's label lists.
3613 unsigned RangeIndex;
3616 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3618 /// CallSiteEntry - Structure describing an entry in the call-site table.
3619 struct CallSiteEntry {
3620 // The 'try-range' is BeginLabel .. EndLabel.
3621 unsigned BeginLabel; // zero indicates the start of the function.
3622 unsigned EndLabel; // zero indicates the end of the function.
3623 // The landing pad starts at PadLabel.
3624 unsigned PadLabel; // zero indicates that there is no landing pad.
3628 void EmitExceptionTable() {
3629 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3630 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3631 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3632 if (PadInfos.empty()) return;
3634 // Sort the landing pads in order of their type ids. This is used to fold
3635 // duplicate actions.
3636 SmallVector<const LandingPadInfo *, 64> LandingPads;
3637 LandingPads.reserve(PadInfos.size());
3638 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3639 LandingPads.push_back(&PadInfos[i]);
3640 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3642 // Negative type ids index into FilterIds, positive type ids index into
3643 // TypeInfos. The value written for a positive type id is just the type
3644 // id itself. For a negative type id, however, the value written is the
3645 // (negative) byte offset of the corresponding FilterIds entry. The byte
3646 // offset is usually equal to the type id, because the FilterIds entries
3647 // are written using a variable width encoding which outputs one byte per
3648 // entry as long as the value written is not too large, but can differ.
3649 // This kind of complication does not occur for positive type ids because
3650 // type infos are output using a fixed width encoding.
3651 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3652 SmallVector<int, 16> FilterOffsets;
3653 FilterOffsets.reserve(FilterIds.size());
3655 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3656 E = FilterIds.end(); I != E; ++I) {
3657 FilterOffsets.push_back(Offset);
3658 Offset -= TargetAsmInfo::getULEB128Size(*I);
3661 // Compute the actions table and gather the first action index for each
3662 // landing pad site.
3663 SmallVector<ActionEntry, 32> Actions;
3664 SmallVector<unsigned, 64> FirstActions;
3665 FirstActions.reserve(LandingPads.size());
3667 int FirstAction = 0;
3668 unsigned SizeActions = 0;
3669 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3670 const LandingPadInfo *LP = LandingPads[i];
3671 const std::vector<int> &TypeIds = LP->TypeIds;
3672 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3673 unsigned SizeSiteActions = 0;
3675 if (NumShared < TypeIds.size()) {
3676 unsigned SizeAction = 0;
3677 ActionEntry *PrevAction = 0;
3680 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3681 assert(Actions.size());
3682 PrevAction = &Actions.back();
3683 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3684 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3685 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3687 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3688 SizeAction += -PrevAction->NextAction;
3689 PrevAction = PrevAction->Previous;
3693 // Compute the actions.
3694 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3695 int TypeID = TypeIds[I];
3696 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3697 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3698 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3700 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3701 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3702 SizeSiteActions += SizeAction;
3704 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3705 Actions.push_back(Action);
3707 PrevAction = &Actions.back();
3710 // Record the first action of the landing pad site.
3711 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3712 } // else identical - re-use previous FirstAction
3714 FirstActions.push_back(FirstAction);
3716 // Compute this sites contribution to size.
3717 SizeActions += SizeSiteActions;
3720 // Compute the call-site table. The entry for an invoke has a try-range
3721 // containing the call, a non-zero landing pad and an appropriate action.
3722 // The entry for an ordinary call has a try-range containing the call and
3723 // zero for the landing pad and the action. Calls marked 'nounwind' have
3724 // no entry and must not be contained in the try-range of any entry - they
3725 // form gaps in the table. Entries must be ordered by try-range address.
3726 SmallVector<CallSiteEntry, 64> CallSites;
3728 RangeMapType PadMap;
3729 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3730 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3731 // try-ranges for them need be deduced.
3732 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3733 const LandingPadInfo *LandingPad = LandingPads[i];
3734 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3735 unsigned BeginLabel = LandingPad->BeginLabels[j];
3736 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3737 PadRange P = { i, j };
3738 PadMap[BeginLabel] = P;
3742 // The end label of the previous invoke or nounwind try-range.
3743 unsigned LastLabel = 0;
3745 // Whether there is a potentially throwing instruction (currently this means
3746 // an ordinary call) between the end of the previous try-range and now.
3747 bool SawPotentiallyThrowing = false;
3749 // Whether the last callsite entry was for an invoke.
3750 bool PreviousIsInvoke = false;
3752 // Visit all instructions in order of address.
3753 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3755 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3757 if (!MI->isLabel()) {
3758 SawPotentiallyThrowing |= MI->getDesc().isCall();
3762 unsigned BeginLabel = MI->getOperand(0).getImm();
3763 assert(BeginLabel && "Invalid label!");
3765 // End of the previous try-range?
3766 if (BeginLabel == LastLabel)
3767 SawPotentiallyThrowing = false;
3769 // Beginning of a new try-range?
3770 RangeMapType::iterator L = PadMap.find(BeginLabel);
3771 if (L == PadMap.end())
3772 // Nope, it was just some random label.
3775 PadRange P = L->second;
3776 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3778 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3779 "Inconsistent landing pad map!");
3781 // If some instruction between the previous try-range and this one may
3782 // throw, create a call-site entry with no landing pad for the region
3783 // between the try-ranges.
3784 if (SawPotentiallyThrowing) {
3785 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3786 CallSites.push_back(Site);
3787 PreviousIsInvoke = false;
3790 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3791 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3793 if (LandingPad->LandingPadLabel) {
3794 // This try-range is for an invoke.
3795 CallSiteEntry Site = {BeginLabel, LastLabel,
3796 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3798 // Try to merge with the previous call-site.
3799 if (PreviousIsInvoke) {
3800 CallSiteEntry &Prev = CallSites.back();
3801 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3802 // Extend the range of the previous entry.
3803 Prev.EndLabel = Site.EndLabel;
3808 // Otherwise, create a new call-site.
3809 CallSites.push_back(Site);
3810 PreviousIsInvoke = true;
3813 PreviousIsInvoke = false;
3817 // If some instruction between the previous try-range and the end of the
3818 // function may throw, create a call-site entry with no landing pad for the
3819 // region following the try-range.
3820 if (SawPotentiallyThrowing) {
3821 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3822 CallSites.push_back(Site);
3828 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3829 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3830 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3831 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3834 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3835 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3838 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3839 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3841 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3842 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3843 SizeSites + SizeActions + SizeTypes;
3845 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3846 sizeof(int8_t) + // TType format
3847 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3850 unsigned SizeAlign = (4 - TotalSize) & 3;
3852 // Begin the exception table.
3853 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3854 Asm->EmitAlignment(2, 0, 0, false);
3855 O << "GCC_except_table" << SubprogramCount << ":\n";
3856 for (unsigned i = 0; i != SizeAlign; ++i) {
3858 Asm->EOL("Padding");
3860 EmitLabel("exception", SubprogramCount);
3863 Asm->EmitInt8(DW_EH_PE_omit);
3864 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3865 Asm->EmitInt8(DW_EH_PE_absptr);
3866 Asm->EOL("TType format (DW_EH_PE_absptr)");
3867 Asm->EmitULEB128Bytes(TypeOffset);
3868 Asm->EOL("TType base offset");
3869 Asm->EmitInt8(DW_EH_PE_udata4);
3870 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3871 Asm->EmitULEB128Bytes(SizeSites);
3872 Asm->EOL("Call-site table length");
3874 // Emit the landing pad site information.
3875 for (unsigned i = 0; i < CallSites.size(); ++i) {
3876 CallSiteEntry &S = CallSites[i];
3877 const char *BeginTag;
3878 unsigned BeginNumber;
3880 if (!S.BeginLabel) {
3881 BeginTag = "eh_func_begin";
3882 BeginNumber = SubprogramCount;
3885 BeginNumber = S.BeginLabel;
3888 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3890 Asm->EOL("Region start");
3893 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3896 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3898 Asm->EOL("Region length");
3903 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3905 Asm->EOL("Landing pad");
3907 Asm->EmitULEB128Bytes(S.Action);
3911 // Emit the actions.
3912 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3913 ActionEntry &Action = Actions[I];
3915 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3916 Asm->EOL("TypeInfo index");
3917 Asm->EmitSLEB128Bytes(Action.NextAction);
3918 Asm->EOL("Next action");
3921 // Emit the type ids.
3922 for (unsigned M = TypeInfos.size(); M; --M) {
3923 GlobalVariable *GV = TypeInfos[M - 1];
3925 PrintRelDirective();
3928 O << Asm->getGlobalLinkName(GV);
3932 Asm->EOL("TypeInfo");
3935 // Emit the filter typeids.
3936 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3937 unsigned TypeID = FilterIds[j];
3938 Asm->EmitULEB128Bytes(TypeID);
3939 Asm->EOL("Filter TypeInfo index");
3942 Asm->EmitAlignment(2, 0, 0, false);
3946 //===--------------------------------------------------------------------===//
3947 // Main entry points.
3949 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3950 : Dwarf(OS, A, T, "eh")
3951 , shouldEmitTable(false)
3952 , shouldEmitMoves(false)
3953 , shouldEmitTableModule(false)
3954 , shouldEmitMovesModule(false)
3957 virtual ~DwarfException() {}
3959 /// SetModuleInfo - Set machine module information when it's known that pass
3960 /// manager has created it. Set by the target AsmPrinter.
3961 void SetModuleInfo(MachineModuleInfo *mmi) {
3965 /// BeginModule - Emit all exception information that should come prior to the
3967 void BeginModule(Module *M) {
3971 /// EndModule - Emit all exception information that should come after the
3974 if (shouldEmitMovesModule || shouldEmitTableModule) {
3975 const std::vector<Function *> Personalities = MMI->getPersonalities();
3976 for (unsigned i =0; i < Personalities.size(); ++i)
3977 EmitCommonEHFrame(Personalities[i], i);
3979 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3980 E = EHFrames.end(); I != E; ++I)
3985 /// BeginFunction - Gather pre-function exception information. Assumes being
3986 /// emitted immediately after the function entry point.
3987 void BeginFunction(MachineFunction *MF) {
3989 shouldEmitTable = shouldEmitMoves = false;
3990 if (MMI && TAI->doesSupportExceptionHandling()) {
3992 // Map all labels and get rid of any dead landing pads.
3993 MMI->TidyLandingPads();
3994 // If any landing pads survive, we need an EH table.
3995 if (MMI->getLandingPads().size())
3996 shouldEmitTable = true;
3998 // See if we need frame move info.
3999 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4000 shouldEmitMoves = true;
4002 if (shouldEmitMoves || shouldEmitTable)
4003 // Assumes in correct section after the entry point.
4004 EmitLabel("eh_func_begin", ++SubprogramCount);
4006 shouldEmitTableModule |= shouldEmitTable;
4007 shouldEmitMovesModule |= shouldEmitMoves;
4010 /// EndFunction - Gather and emit post-function exception information.
4012 void EndFunction() {
4013 if (shouldEmitMoves || shouldEmitTable) {
4014 EmitLabel("eh_func_end", SubprogramCount);
4015 EmitExceptionTable();
4017 // Save EH frame information
4019 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4021 MMI->getPersonalityIndex(),
4022 MF->getFrameInfo()->hasCalls(),
4023 !MMI->getLandingPads().empty(),
4024 MMI->getFrameMoves(),
4025 MF->getFunction()));
4030 } // End of namespace llvm
4032 //===----------------------------------------------------------------------===//
4034 /// Emit - Print the abbreviation using the specified Dwarf writer.
4036 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4037 // Emit its Dwarf tag type.
4038 DD.getAsm()->EmitULEB128Bytes(Tag);
4039 DD.getAsm()->EOL(TagString(Tag));
4041 // Emit whether it has children DIEs.
4042 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4043 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4045 // For each attribute description.
4046 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4047 const DIEAbbrevData &AttrData = Data[i];
4049 // Emit attribute type.
4050 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4051 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4054 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4055 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4058 // Mark end of abbreviation.
4059 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4060 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4064 void DIEAbbrev::print(std::ostream &O) {
4065 O << "Abbreviation @"
4066 << std::hex << (intptr_t)this << std::dec
4070 << ChildrenString(ChildrenFlag)
4073 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4075 << AttributeString(Data[i].getAttribute())
4077 << FormEncodingString(Data[i].getForm())
4081 void DIEAbbrev::dump() { print(cerr); }
4084 //===----------------------------------------------------------------------===//
4087 void DIEValue::dump() {
4092 //===----------------------------------------------------------------------===//
4094 /// EmitValue - Emit integer of appropriate size.
4096 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4098 case DW_FORM_flag: // Fall thru
4099 case DW_FORM_ref1: // Fall thru
4100 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4101 case DW_FORM_ref2: // Fall thru
4102 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4103 case DW_FORM_ref4: // Fall thru
4104 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4105 case DW_FORM_ref8: // Fall thru
4106 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4107 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4108 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4109 default: assert(0 && "DIE Value form not supported yet"); break;
4113 /// SizeOf - Determine size of integer value in bytes.
4115 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4117 case DW_FORM_flag: // Fall thru
4118 case DW_FORM_ref1: // Fall thru
4119 case DW_FORM_data1: return sizeof(int8_t);
4120 case DW_FORM_ref2: // Fall thru
4121 case DW_FORM_data2: return sizeof(int16_t);
4122 case DW_FORM_ref4: // Fall thru
4123 case DW_FORM_data4: return sizeof(int32_t);
4124 case DW_FORM_ref8: // Fall thru
4125 case DW_FORM_data8: return sizeof(int64_t);
4126 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4127 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4128 default: assert(0 && "DIE Value form not supported yet"); break;
4133 //===----------------------------------------------------------------------===//
4135 /// EmitValue - Emit string value.
4137 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4138 DD.getAsm()->EmitString(String);
4141 //===----------------------------------------------------------------------===//
4143 /// EmitValue - Emit label value.
4145 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4146 bool IsSmall = Form == DW_FORM_data4;
4147 DD.EmitReference(Label, false, IsSmall);
4150 /// SizeOf - Determine size of label value in bytes.
4152 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4153 if (Form == DW_FORM_data4) return 4;
4154 return DD.getTargetData()->getPointerSize();
4157 //===----------------------------------------------------------------------===//
4159 /// EmitValue - Emit label value.
4161 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4162 bool IsSmall = Form == DW_FORM_data4;
4163 DD.EmitReference(Label, false, IsSmall);
4166 /// SizeOf - Determine size of label value in bytes.
4168 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4169 if (Form == DW_FORM_data4) return 4;
4170 return DD.getTargetData()->getPointerSize();
4173 //===----------------------------------------------------------------------===//
4175 /// EmitValue - Emit delta value.
4177 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4178 bool IsSmall = Form == DW_FORM_data4;
4179 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4180 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4183 /// SizeOf - Determine size of delta value in bytes.
4185 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4186 if (Form == DW_FORM_data4) return 4;
4187 return DD.getTargetData()->getPointerSize();
4190 //===----------------------------------------------------------------------===//
4192 /// EmitValue - Emit delta value.
4194 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4195 bool IsSmall = Form == DW_FORM_data4;
4196 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4199 /// SizeOf - Determine size of delta value in bytes.
4201 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4202 if (Form == DW_FORM_data4) return 4;
4203 return DD.getTargetData()->getPointerSize();
4206 //===----------------------------------------------------------------------===//
4208 /// EmitValue - Emit debug information entry offset.
4210 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4211 DD.getAsm()->EmitInt32(Entry->getOffset());
4214 //===----------------------------------------------------------------------===//
4216 /// ComputeSize - calculate the size of the block.
4218 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4220 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4222 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4223 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4229 /// EmitValue - Emit block data.
4231 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4233 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4234 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4235 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4236 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4237 default: assert(0 && "Improper form for block"); break;
4240 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4242 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4244 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4248 /// SizeOf - Determine size of block data in bytes.
4250 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4252 case DW_FORM_block1: return Size + sizeof(int8_t);
4253 case DW_FORM_block2: return Size + sizeof(int16_t);
4254 case DW_FORM_block4: return Size + sizeof(int32_t);
4255 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4256 default: assert(0 && "Improper form for block"); break;
4261 //===----------------------------------------------------------------------===//
4262 /// DIE Implementation
4265 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4269 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4271 void DIE::AddSiblingOffset() {
4272 DIEInteger *DI = new DIEInteger(0);
4273 Values.insert(Values.begin(), DI);
4274 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4277 /// Profile - Used to gather unique data for the value folding set.
4279 void DIE::Profile(FoldingSetNodeID &ID) {
4282 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4283 ID.AddPointer(Children[i]);
4285 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4286 ID.AddPointer(Values[j]);
4290 void DIE::print(std::ostream &O, unsigned IncIndent) {
4291 static unsigned IndentCount = 0;
4292 IndentCount += IncIndent;
4293 const std::string Indent(IndentCount, ' ');
4294 bool isBlock = Abbrev.getTag() == 0;
4299 << "0x" << std::hex << (intptr_t)this << std::dec
4300 << ", Offset: " << Offset
4301 << ", Size: " << Size
4305 << TagString(Abbrev.getTag())
4307 << ChildrenString(Abbrev.getChildrenFlag());
4309 O << "Size: " << Size;
4313 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4316 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4320 O << AttributeString(Data[i].getAttribute());
4322 O << "Blk[" << i << "]";
4325 << FormEncodingString(Data[i].getForm())
4327 Values[i]->print(O);
4332 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4333 Children[j]->print(O, 4);
4336 if (!isBlock) O << "\n";
4337 IndentCount -= IncIndent;
4345 //===----------------------------------------------------------------------===//
4346 /// DwarfWriter Implementation
4349 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
4350 const TargetAsmInfo *T) {
4351 DE = new DwarfException(OS, A, T);
4352 DD = new DwarfDebug(OS, A, T);
4355 DwarfWriter::~DwarfWriter() {
4360 /// SetModuleInfo - Set machine module info when it's known that pass manager
4361 /// has created it. Set by the target AsmPrinter.
4362 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
4363 DD->SetModuleInfo(MMI);
4364 DE->SetModuleInfo(MMI);
4367 /// BeginModule - Emit all Dwarf sections that should come prior to the
4369 void DwarfWriter::BeginModule(Module *M) {
4374 /// EndModule - Emit all Dwarf sections that should come after the content.
4376 void DwarfWriter::EndModule() {
4381 /// BeginFunction - Gather pre-function debug information. Assumes being
4382 /// emitted immediately after the function entry point.
4383 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4384 DE->BeginFunction(MF);
4385 DD->BeginFunction(MF);
4388 /// EndFunction - Gather and emit post-function debug information.
4390 void DwarfWriter::EndFunction(MachineFunction *MF) {
4391 DD->EndFunction(MF);
4394 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4395 // Clear function debug information.