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/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/System/Path.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm::dwarf;
46 //===----------------------------------------------------------------------===//
48 /// Configuration values for initial hash set sizes (log2).
50 static const unsigned InitDiesSetSize = 9; // 512
51 static const unsigned InitAbbreviationsSetSize = 9; // 512
52 static const unsigned InitValuesSetSize = 9; // 512
54 //===----------------------------------------------------------------------===//
55 /// Forward declarations.
60 //===----------------------------------------------------------------------===//
61 /// DWLabel - Labels are used to track locations in the assembler file.
62 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
63 /// where the tag is a category of label (Ex. location) and number is a value
64 /// unique in that category.
67 /// Tag - Label category tag. Should always be a staticly declared C string.
71 /// Number - Value to make label unique.
75 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
77 void Profile(FoldingSetNodeID &ID) const {
78 ID.AddString(std::string(Tag));
79 ID.AddInteger(Number);
83 void print(std::ostream *O) const {
86 void print(std::ostream &O) const {
88 if (Number) O << Number;
93 //===----------------------------------------------------------------------===//
94 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
95 /// Dwarf abbreviation.
98 /// Attribute - Dwarf attribute code.
102 /// Form - Dwarf form code.
107 DIEAbbrevData(unsigned A, unsigned F)
113 unsigned getAttribute() const { return Attribute; }
114 unsigned getForm() const { return Form; }
116 /// Profile - Used to gather unique data for the abbreviation folding set.
118 void Profile(FoldingSetNodeID &ID)const {
119 ID.AddInteger(Attribute);
124 //===----------------------------------------------------------------------===//
125 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
126 /// information object.
127 class DIEAbbrev : public FoldingSetNode {
129 /// Tag - Dwarf tag code.
133 /// Unique number for node.
137 /// ChildrenFlag - Dwarf children flag.
139 unsigned ChildrenFlag;
141 /// Data - Raw data bytes for abbreviation.
143 std::vector<DIEAbbrevData> Data;
147 DIEAbbrev(unsigned T, unsigned C)
155 unsigned getTag() const { return Tag; }
156 unsigned getNumber() const { return Number; }
157 unsigned getChildrenFlag() const { return ChildrenFlag; }
158 const std::vector<DIEAbbrevData> &getData() const { return Data; }
159 void setTag(unsigned T) { Tag = T; }
160 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
161 void setNumber(unsigned N) { Number = N; }
163 /// AddAttribute - Adds another set of attribute information to the
165 void AddAttribute(unsigned Attribute, unsigned Form) {
166 Data.push_back(DIEAbbrevData(Attribute, Form));
169 /// AddFirstAttribute - Adds a set of attribute information to the front
170 /// of the abbreviation.
171 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
172 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
175 /// Profile - Used to gather unique data for the abbreviation folding set.
177 void Profile(FoldingSetNodeID &ID) {
179 ID.AddInteger(ChildrenFlag);
181 // For each attribute description.
182 for (unsigned i = 0, N = Data.size(); i < N; ++i)
186 /// Emit - Print the abbreviation using the specified Dwarf writer.
188 void Emit(const DwarfDebug &DD) const;
191 void print(std::ostream *O) {
194 void print(std::ostream &O);
199 //===----------------------------------------------------------------------===//
200 /// DIE - A structured debug information entry. Has an abbreviation which
201 /// describes it's organization.
202 class DIE : public FoldingSetNode {
204 /// Abbrev - Buffer for constructing abbreviation.
208 /// Offset - Offset in debug info section.
212 /// Size - Size of instance + children.
218 std::vector<DIE *> Children;
220 /// Attributes values.
222 std::vector<DIEValue *> Values;
225 explicit DIE(unsigned Tag)
226 : Abbrev(Tag, DW_CHILDREN_no)
235 DIEAbbrev &getAbbrev() { return Abbrev; }
236 unsigned getAbbrevNumber() const {
237 return Abbrev.getNumber();
239 unsigned getTag() const { return Abbrev.getTag(); }
240 unsigned getOffset() const { return Offset; }
241 unsigned getSize() const { return Size; }
242 const std::vector<DIE *> &getChildren() const { return Children; }
243 std::vector<DIEValue *> &getValues() { return Values; }
244 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
245 void setOffset(unsigned O) { Offset = O; }
246 void setSize(unsigned S) { Size = S; }
248 /// AddValue - Add a value and attributes to a DIE.
250 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
251 Abbrev.AddAttribute(Attribute, Form);
252 Values.push_back(Value);
255 /// SiblingOffset - Return the offset of the debug information entry's
257 unsigned SiblingOffset() const { return Offset + Size; }
259 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
261 void AddSiblingOffset();
263 /// AddChild - Add a child to the DIE.
265 void AddChild(DIE *Child) {
266 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
267 Children.push_back(Child);
270 /// Detach - Detaches objects connected to it after copying.
276 /// Profile - Used to gather unique data for the value folding set.
278 void Profile(FoldingSetNodeID &ID) ;
281 void print(std::ostream *O, unsigned IncIndent = 0) {
282 if (O) print(*O, IncIndent);
284 void print(std::ostream &O, unsigned IncIndent = 0);
289 //===----------------------------------------------------------------------===//
290 /// DIEValue - A debug information entry value.
292 class DIEValue : public FoldingSetNode {
304 /// Type - Type of data stored in the value.
308 explicit DIEValue(unsigned T)
311 virtual ~DIEValue() {}
314 unsigned getType() const { return Type; }
316 // Implement isa/cast/dyncast.
317 static bool classof(const DIEValue *) { return true; }
319 /// EmitValue - Emit value via the Dwarf writer.
321 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
323 /// SizeOf - Return the size of a value in bytes.
325 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
327 /// Profile - Used to gather unique data for the value folding set.
329 virtual void Profile(FoldingSetNodeID &ID) = 0;
332 void print(std::ostream *O) {
335 virtual void print(std::ostream &O) = 0;
340 //===----------------------------------------------------------------------===//
341 /// DWInteger - An integer value DIE.
343 class DIEInteger : public DIEValue {
348 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
350 // Implement isa/cast/dyncast.
351 static bool classof(const DIEInteger *) { return true; }
352 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
354 /// BestForm - Choose the best form for integer.
356 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
358 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
359 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
360 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
362 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
363 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
364 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
366 return DW_FORM_data8;
369 /// EmitValue - Emit integer of appropriate size.
371 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
373 /// SizeOf - Determine size of integer value in bytes.
375 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
377 /// Profile - Used to gather unique data for the value folding set.
379 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
380 ID.AddInteger(isInteger);
381 ID.AddInteger(Integer);
383 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
386 virtual void print(std::ostream &O) {
387 O << "Int: " << (int64_t)Integer
388 << " 0x" << std::hex << Integer << std::dec;
393 //===----------------------------------------------------------------------===//
394 /// DIEString - A string value DIE.
396 class DIEString : public DIEValue {
398 const std::string String;
400 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
402 // Implement isa/cast/dyncast.
403 static bool classof(const DIEString *) { return true; }
404 static bool classof(const DIEValue *S) { return S->Type == isString; }
406 /// EmitValue - Emit string value.
408 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
410 /// SizeOf - Determine size of string value in bytes.
412 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
413 return String.size() + sizeof(char); // sizeof('\0');
416 /// Profile - Used to gather unique data for the value folding set.
418 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
419 ID.AddInteger(isString);
420 ID.AddString(String);
422 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
425 virtual void print(std::ostream &O) {
426 O << "Str: \"" << String << "\"";
431 //===----------------------------------------------------------------------===//
432 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
434 class DIEDwarfLabel : public DIEValue {
439 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
441 // Implement isa/cast/dyncast.
442 static bool classof(const DIEDwarfLabel *) { return true; }
443 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
445 /// EmitValue - Emit label value.
447 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
449 /// SizeOf - Determine size of label value in bytes.
451 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
453 /// Profile - Used to gather unique data for the value folding set.
455 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
456 ID.AddInteger(isLabel);
459 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
462 virtual void print(std::ostream &O) {
470 //===----------------------------------------------------------------------===//
471 /// DIEObjectLabel - A label to an object in code or data.
473 class DIEObjectLabel : public DIEValue {
475 const std::string Label;
477 explicit DIEObjectLabel(const std::string &L)
478 : DIEValue(isAsIsLabel), Label(L) {}
480 // Implement isa/cast/dyncast.
481 static bool classof(const DIEObjectLabel *) { return true; }
482 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
484 /// EmitValue - Emit label value.
486 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
488 /// SizeOf - Determine size of label value in bytes.
490 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
492 /// Profile - Used to gather unique data for the value folding set.
494 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
495 ID.AddInteger(isAsIsLabel);
498 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
501 virtual void print(std::ostream &O) {
502 O << "Obj: " << Label;
507 //===----------------------------------------------------------------------===//
508 /// DIEDelta - A simple label difference DIE.
510 class DIEDelta : public DIEValue {
512 const DWLabel LabelHi;
513 const DWLabel LabelLo;
515 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
516 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
518 // Implement isa/cast/dyncast.
519 static bool classof(const DIEDelta *) { return true; }
520 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
522 /// EmitValue - Emit delta value.
524 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
526 /// SizeOf - Determine size of delta value in bytes.
528 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
530 /// Profile - Used to gather unique data for the value folding set.
532 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
533 const DWLabel &LabelLo) {
534 ID.AddInteger(isDelta);
538 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
541 virtual void print(std::ostream &O) {
550 //===----------------------------------------------------------------------===//
551 /// DIEntry - A pointer to another debug information entry. An instance of this
552 /// class can also be used as a proxy for a debug information entry not yet
553 /// defined (ie. types.)
554 class DIEntry : public DIEValue {
558 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
560 // Implement isa/cast/dyncast.
561 static bool classof(const DIEntry *) { return true; }
562 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
564 /// EmitValue - Emit debug information entry offset.
566 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
568 /// SizeOf - Determine size of debug information entry in bytes.
570 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
571 return sizeof(int32_t);
574 /// Profile - Used to gather unique data for the value folding set.
576 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
577 ID.AddInteger(isEntry);
578 ID.AddPointer(Entry);
580 virtual void Profile(FoldingSetNodeID &ID) {
581 ID.AddInteger(isEntry);
584 ID.AddPointer(Entry);
591 virtual void print(std::ostream &O) {
592 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
597 //===----------------------------------------------------------------------===//
598 /// DIEBlock - A block of values. Primarily used for location expressions.
600 class DIEBlock : public DIEValue, public DIE {
602 unsigned Size; // Size in bytes excluding size header.
612 // Implement isa/cast/dyncast.
613 static bool classof(const DIEBlock *) { return true; }
614 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
616 /// ComputeSize - calculate the size of the block.
618 unsigned ComputeSize(DwarfDebug &DD);
620 /// BestForm - Choose the best form for data.
622 unsigned BestForm() const {
623 if ((unsigned char)Size == Size) return DW_FORM_block1;
624 if ((unsigned short)Size == Size) return DW_FORM_block2;
625 if ((unsigned int)Size == Size) return DW_FORM_block4;
626 return DW_FORM_block;
629 /// EmitValue - Emit block data.
631 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
633 /// SizeOf - Determine size of block data in bytes.
635 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
638 /// Profile - Used to gather unique data for the value folding set.
640 virtual void Profile(FoldingSetNodeID &ID) {
641 ID.AddInteger(isBlock);
646 virtual void print(std::ostream &O) {
653 //===----------------------------------------------------------------------===//
654 /// CompileUnit - This dwarf writer support class manages information associate
655 /// with a source file.
658 /// Desc - Compile unit debug descriptor.
660 CompileUnitDesc *Desc;
662 /// ID - File identifier for source.
666 /// Die - Compile unit debug information entry.
670 /// DescToDieMap - Tracks the mapping of unit level debug informaton
671 /// descriptors to debug information entries.
672 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
674 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
675 /// descriptors to debug information entries using a DIEntry proxy.
676 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
678 /// Globals - A map of globally visible named entities for this unit.
680 std::map<std::string, DIE *> Globals;
682 /// DiesSet - Used to uniquely define dies within the compile unit.
684 FoldingSet<DIE> DiesSet;
686 /// Dies - List of all dies in the compile unit.
688 std::vector<DIE *> Dies;
691 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
698 , DiesSet(InitDiesSetSize)
705 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
710 CompileUnitDesc *getDesc() const { return Desc; }
711 unsigned getID() const { return ID; }
712 DIE* getDie() const { return Die; }
713 std::map<std::string, DIE *> &getGlobals() { return Globals; }
715 /// hasContent - Return true if this compile unit has something to write out.
717 bool hasContent() const {
718 return !Die->getChildren().empty();
721 /// AddGlobal - Add a new global entity to the compile unit.
723 void AddGlobal(const std::string &Name, DIE *Die) {
727 /// getDieMapSlotFor - Returns the debug information entry map slot for the
728 /// specified debug descriptor.
729 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
730 return DescToDieMap[DID];
733 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
734 /// specified debug descriptor.
735 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
736 return DescToDIEntryMap[DID];
739 /// AddDie - Adds or interns the DIE to the compile unit.
741 DIE *AddDie(DIE &Buffer) {
745 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
748 Die = new DIE(Buffer);
749 DiesSet.InsertNode(Die, Where);
750 this->Die->AddChild(Die);
758 //===----------------------------------------------------------------------===//
759 /// Dwarf - Emits general Dwarf directives.
765 //===--------------------------------------------------------------------===//
766 // Core attributes used by the Dwarf writer.
770 /// O - Stream to .s file.
774 /// Asm - Target of Dwarf emission.
778 /// TAI - Target Asm Printer.
779 const TargetAsmInfo *TAI;
781 /// TD - Target data.
782 const TargetData *TD;
784 /// RI - Register Information.
785 const TargetRegisterInfo *RI;
787 /// M - Current module.
791 /// MF - Current machine function.
795 /// MMI - Collected machine module information.
797 MachineModuleInfo *MMI;
799 /// SubprogramCount - The running count of functions being compiled.
801 unsigned SubprogramCount;
803 /// Flavor - A unique string indicating what dwarf producer this is, used to
805 const char * const Flavor;
808 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
813 , TD(Asm->TM.getTargetData())
814 , RI(Asm->TM.getRegisterInfo())
826 //===--------------------------------------------------------------------===//
829 AsmPrinter *getAsm() const { return Asm; }
830 MachineModuleInfo *getMMI() const { return MMI; }
831 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
832 const TargetData *getTargetData() const { return TD; }
834 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
836 if (isInSection && TAI->getDwarfSectionOffsetDirective())
837 O << TAI->getDwarfSectionOffsetDirective();
838 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
839 O << TAI->getData32bitsDirective();
841 O << TAI->getData64bitsDirective();
844 /// PrintLabelName - Print label name in form used by Dwarf writer.
846 void PrintLabelName(DWLabel Label) const {
847 PrintLabelName(Label.Tag, Label.Number);
849 void PrintLabelName(const char *Tag, unsigned Number) const {
850 O << TAI->getPrivateGlobalPrefix() << Tag;
851 if (Number) O << Number;
854 void PrintLabelName(const char *Tag, unsigned Number,
855 const char *Suffix) const {
856 O << TAI->getPrivateGlobalPrefix() << Tag;
857 if (Number) O << Number;
861 /// EmitLabel - Emit location label for internal use by Dwarf.
863 void EmitLabel(DWLabel Label) const {
864 EmitLabel(Label.Tag, Label.Number);
866 void EmitLabel(const char *Tag, unsigned Number) const {
867 PrintLabelName(Tag, Number);
871 /// EmitReference - Emit a reference to a label.
873 void EmitReference(DWLabel Label, bool IsPCRelative = false,
874 bool Force32Bit = false) const {
875 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
877 void EmitReference(const char *Tag, unsigned Number,
878 bool IsPCRelative = false, bool Force32Bit = false) const {
879 PrintRelDirective(Force32Bit);
880 PrintLabelName(Tag, Number);
882 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
884 void EmitReference(const std::string &Name, bool IsPCRelative = false,
885 bool Force32Bit = false) const {
886 PrintRelDirective(Force32Bit);
890 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
893 /// EmitDifference - Emit the difference between two labels. Some
894 /// assemblers do not behave with absolute expressions with data directives,
895 /// so there is an option (needsSet) to use an intermediary set expression.
896 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
897 bool IsSmall = false) {
898 EmitDifference(LabelHi.Tag, LabelHi.Number,
899 LabelLo.Tag, LabelLo.Number,
902 void EmitDifference(const char *TagHi, unsigned NumberHi,
903 const char *TagLo, unsigned NumberLo,
904 bool IsSmall = false) {
905 if (TAI->needsSet()) {
907 PrintLabelName("set", SetCounter, Flavor);
909 PrintLabelName(TagHi, NumberHi);
911 PrintLabelName(TagLo, NumberLo);
914 PrintRelDirective(IsSmall);
915 PrintLabelName("set", SetCounter, Flavor);
918 PrintRelDirective(IsSmall);
920 PrintLabelName(TagHi, NumberHi);
922 PrintLabelName(TagLo, NumberLo);
926 void EmitSectionOffset(const char* Label, const char* Section,
927 unsigned LabelNumber, unsigned SectionNumber,
928 bool IsSmall = false, bool isEH = false) {
929 bool printAbsolute = false;
930 if (TAI->needsSet()) {
932 PrintLabelName("set", SetCounter, Flavor);
934 PrintLabelName(Label, LabelNumber);
937 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
939 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
941 if (!printAbsolute) {
943 PrintLabelName(Section, SectionNumber);
947 PrintRelDirective(IsSmall);
949 PrintLabelName("set", SetCounter, Flavor);
952 PrintRelDirective(IsSmall, true);
954 PrintLabelName(Label, LabelNumber);
957 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
959 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
961 if (!printAbsolute) {
963 PrintLabelName(Section, SectionNumber);
968 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
970 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
971 const std::vector<MachineMove> &Moves, bool isEH) {
973 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
974 TargetFrameInfo::StackGrowsUp ?
975 TD->getPointerSize() : -TD->getPointerSize();
976 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
978 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
979 const MachineMove &Move = Moves[i];
980 unsigned LabelID = Move.getLabelID();
983 LabelID = MMI->MappedLabel(LabelID);
985 // Throw out move if the label is invalid.
986 if (!LabelID) continue;
989 const MachineLocation &Dst = Move.getDestination();
990 const MachineLocation &Src = Move.getSource();
992 // Advance row if new location.
993 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
994 Asm->EmitInt8(DW_CFA_advance_loc4);
995 Asm->EOL("DW_CFA_advance_loc4");
996 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
999 BaseLabelID = LabelID;
1000 BaseLabel = "label";
1004 // If advancing cfa.
1005 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1006 if (!Src.isRegister()) {
1007 if (Src.getRegister() == MachineLocation::VirtualFP) {
1008 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1009 Asm->EOL("DW_CFA_def_cfa_offset");
1011 Asm->EmitInt8(DW_CFA_def_cfa);
1012 Asm->EOL("DW_CFA_def_cfa");
1013 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister(), isEH));
1014 Asm->EOL("Register");
1017 int Offset = -Src.getOffset();
1019 Asm->EmitULEB128Bytes(Offset);
1022 assert(0 && "Machine move no supported yet.");
1024 } else if (Src.isRegister() &&
1025 Src.getRegister() == MachineLocation::VirtualFP) {
1026 if (Dst.isRegister()) {
1027 Asm->EmitInt8(DW_CFA_def_cfa_register);
1028 Asm->EOL("DW_CFA_def_cfa_register");
1029 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister(), isEH));
1030 Asm->EOL("Register");
1032 assert(0 && "Machine move no supported yet.");
1035 unsigned Reg = RI->getDwarfRegNum(Src.getRegister(), isEH);
1036 int Offset = Dst.getOffset() / stackGrowth;
1039 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1040 Asm->EOL("DW_CFA_offset_extended_sf");
1041 Asm->EmitULEB128Bytes(Reg);
1043 Asm->EmitSLEB128Bytes(Offset);
1045 } else if (Reg < 64) {
1046 Asm->EmitInt8(DW_CFA_offset + Reg);
1047 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1048 Asm->EmitULEB128Bytes(Offset);
1051 Asm->EmitInt8(DW_CFA_offset_extended);
1052 Asm->EOL("DW_CFA_offset_extended");
1053 Asm->EmitULEB128Bytes(Reg);
1055 Asm->EmitULEB128Bytes(Offset);
1064 //===----------------------------------------------------------------------===//
1065 /// DwarfDebug - Emits Dwarf debug directives.
1067 class DwarfDebug : public Dwarf {
1070 //===--------------------------------------------------------------------===//
1071 // Attributes used to construct specific Dwarf sections.
1074 /// CompileUnits - All the compile units involved in this build. The index
1075 /// of each entry in this vector corresponds to the sources in MMI.
1076 std::vector<CompileUnit *> CompileUnits;
1078 /// AbbreviationsSet - Used to uniquely define abbreviations.
1080 FoldingSet<DIEAbbrev> AbbreviationsSet;
1082 /// Abbreviations - A list of all the unique abbreviations in use.
1084 std::vector<DIEAbbrev *> Abbreviations;
1086 /// ValuesSet - Used to uniquely define values.
1088 FoldingSet<DIEValue> ValuesSet;
1090 /// Values - A list of all the unique values in use.
1092 std::vector<DIEValue *> Values;
1094 /// StringPool - A UniqueVector of strings used by indirect references.
1096 UniqueVector<std::string> StringPool;
1098 /// UnitMap - Map debug information descriptor to compile unit.
1100 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1102 /// SectionMap - Provides a unique id per text section.
1104 UniqueVector<std::string> SectionMap;
1106 /// SectionSourceLines - Tracks line numbers per text section.
1108 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1110 /// didInitial - Flag to indicate if initial emission has been done.
1114 /// shouldEmit - Flag to indicate if debug information should be emitted.
1118 struct FunctionDebugFrameInfo {
1120 std::vector<MachineMove> Moves;
1122 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1123 Number(Num), Moves(M) { }
1126 std::vector<FunctionDebugFrameInfo> DebugFrames;
1130 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1132 bool ShouldEmitDwarf() const { return shouldEmit; }
1134 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1136 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1137 // Profile the node so that we can make it unique.
1138 FoldingSetNodeID ID;
1141 // Check the set for priors.
1142 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1144 // If it's newly added.
1145 if (InSet == &Abbrev) {
1146 // Add to abbreviation list.
1147 Abbreviations.push_back(&Abbrev);
1148 // Assign the vector position + 1 as its number.
1149 Abbrev.setNumber(Abbreviations.size());
1151 // Assign existing abbreviation number.
1152 Abbrev.setNumber(InSet->getNumber());
1156 /// NewString - Add a string to the constant pool and returns a label.
1158 DWLabel NewString(const std::string &String) {
1159 unsigned StringID = StringPool.insert(String);
1160 return DWLabel("string", StringID);
1163 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1165 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1169 FoldingSetNodeID ID;
1170 DIEntry::Profile(ID, Entry);
1172 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1174 if (Value) return Value;
1176 Value = new DIEntry(Entry);
1177 ValuesSet.InsertNode(Value, Where);
1179 Value = new DIEntry(Entry);
1182 Values.push_back(Value);
1186 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1188 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1189 Value->Entry = Entry;
1190 // Add to values set if not already there. If it is, we merely have a
1191 // duplicate in the values list (no harm.)
1192 ValuesSet.GetOrInsertNode(Value);
1195 /// AddUInt - Add an unsigned integer attribute data and value.
1197 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1198 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1200 FoldingSetNodeID ID;
1201 DIEInteger::Profile(ID, Integer);
1203 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1205 Value = new DIEInteger(Integer);
1206 ValuesSet.InsertNode(Value, Where);
1207 Values.push_back(Value);
1210 Die->AddValue(Attribute, Form, Value);
1213 /// AddSInt - Add an signed integer attribute data and value.
1215 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1216 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1218 FoldingSetNodeID ID;
1219 DIEInteger::Profile(ID, (uint64_t)Integer);
1221 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1223 Value = new DIEInteger(Integer);
1224 ValuesSet.InsertNode(Value, Where);
1225 Values.push_back(Value);
1228 Die->AddValue(Attribute, Form, Value);
1231 /// AddString - Add a std::string attribute data and value.
1233 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1234 const std::string &String) {
1235 FoldingSetNodeID ID;
1236 DIEString::Profile(ID, String);
1238 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1240 Value = new DIEString(String);
1241 ValuesSet.InsertNode(Value, Where);
1242 Values.push_back(Value);
1245 Die->AddValue(Attribute, Form, Value);
1248 /// AddLabel - Add a Dwarf label attribute data and value.
1250 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1251 const DWLabel &Label) {
1252 FoldingSetNodeID ID;
1253 DIEDwarfLabel::Profile(ID, Label);
1255 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1257 Value = new DIEDwarfLabel(Label);
1258 ValuesSet.InsertNode(Value, Where);
1259 Values.push_back(Value);
1262 Die->AddValue(Attribute, Form, Value);
1265 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1267 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1268 const std::string &Label) {
1269 FoldingSetNodeID ID;
1270 DIEObjectLabel::Profile(ID, Label);
1272 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1274 Value = new DIEObjectLabel(Label);
1275 ValuesSet.InsertNode(Value, Where);
1276 Values.push_back(Value);
1279 Die->AddValue(Attribute, Form, Value);
1282 /// AddDelta - Add a label delta attribute data and value.
1284 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1285 const DWLabel &Hi, const DWLabel &Lo) {
1286 FoldingSetNodeID ID;
1287 DIEDelta::Profile(ID, Hi, Lo);
1289 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1291 Value = new DIEDelta(Hi, Lo);
1292 ValuesSet.InsertNode(Value, Where);
1293 Values.push_back(Value);
1296 Die->AddValue(Attribute, Form, Value);
1299 /// AddDIEntry - Add a DIE attribute data and value.
1301 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1302 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1305 /// AddBlock - Add block data.
1307 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1308 Block->ComputeSize(*this);
1309 FoldingSetNodeID ID;
1312 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1315 ValuesSet.InsertNode(Value, Where);
1316 Values.push_back(Value);
1318 // Already exists, reuse the previous one.
1320 Block = cast<DIEBlock>(Value);
1323 Die->AddValue(Attribute, Block->BestForm(), Value);
1328 /// AddSourceLine - Add location information to specified debug information
1330 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1332 CompileUnit *FileUnit = FindCompileUnit(File);
1333 unsigned FileID = FileUnit->getID();
1334 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1335 AddUInt(Die, DW_AT_decl_line, 0, Line);
1339 /// AddAddress - Add an address attribute to a die based on the location
1341 void AddAddress(DIE *Die, unsigned Attribute,
1342 const MachineLocation &Location) {
1343 unsigned Reg = RI->getDwarfRegNum(Location.getRegister(), false);
1344 DIEBlock *Block = new DIEBlock();
1346 if (Location.isRegister()) {
1348 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1350 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1351 AddUInt(Block, 0, DW_FORM_udata, Reg);
1355 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1357 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1358 AddUInt(Block, 0, DW_FORM_udata, Reg);
1360 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1363 AddBlock(Die, Attribute, 0, Block);
1366 /// AddBasicType - Add a new basic type attribute to the specified entity.
1368 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1369 const std::string &Name,
1370 unsigned Encoding, unsigned Size) {
1371 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1372 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1375 /// ConstructBasicType - Construct a new basic type.
1377 DIE *ConstructBasicType(CompileUnit *Unit,
1378 const std::string &Name,
1379 unsigned Encoding, unsigned Size) {
1380 DIE Buffer(DW_TAG_base_type);
1381 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1382 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1383 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1384 return Unit->AddDie(Buffer);
1387 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1389 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1390 DIE *Die = ConstructPointerType(Unit, Name);
1391 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1394 /// ConstructPointerType - Construct a new pointer type.
1396 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1397 DIE Buffer(DW_TAG_pointer_type);
1398 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1399 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1400 return Unit->AddDie(Buffer);
1403 /// AddType - Add a new type attribute to the specified entity.
1405 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1407 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1409 // Check for pre-existence.
1410 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1412 // If it exists then use the existing value.
1414 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1418 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1419 // FIXME - Not sure why programs and variables are coming through here.
1420 // Short cut for handling subprogram types (not really a TyDesc.)
1421 AddPointerType(Entity, Unit, SubprogramTy->getName());
1422 } else if (GlobalVariableDesc *GlobalTy =
1423 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1424 // FIXME - Not sure why programs and variables are coming through here.
1425 // Short cut for handling global variable types (not really a TyDesc.)
1426 AddPointerType(Entity, Unit, GlobalTy->getName());
1429 Slot = NewDIEntry();
1432 DIE Buffer(DW_TAG_base_type);
1433 ConstructType(Buffer, TyDesc, Unit);
1435 // Add debug information entry to entity and unit.
1436 DIE *Die = Unit->AddDie(Buffer);
1437 SetDIEntry(Slot, Die);
1438 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1443 /// ConstructType - Adds all the required attributes to the type.
1445 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1446 // Get core information.
1447 const std::string &Name = TyDesc->getName();
1448 uint64_t Size = TyDesc->getSize() >> 3;
1450 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1451 // Fundamental types like int, float, bool
1452 Buffer.setTag(DW_TAG_base_type);
1453 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1454 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1456 unsigned Tag = DerivedTy->getTag();
1457 // FIXME - Workaround for templates.
1458 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1459 // Pointers, typedefs et al.
1461 // Map to main type, void will not have a type.
1462 if (TypeDesc *FromTy = DerivedTy->getFromType())
1463 AddType(&Buffer, FromTy, Unit);
1464 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1466 unsigned Tag = CompTy->getTag();
1468 // Set tag accordingly.
1469 if (Tag == DW_TAG_vector_type)
1470 Buffer.setTag(DW_TAG_array_type);
1474 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1477 case DW_TAG_vector_type:
1478 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1480 case DW_TAG_array_type: {
1481 // Add element type.
1482 if (TypeDesc *FromTy = CompTy->getFromType())
1483 AddType(&Buffer, FromTy, Unit);
1485 // Don't emit size attribute.
1488 // Construct an anonymous type for index type.
1489 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1492 // Add subranges to array type.
1493 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1494 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1495 int64_t Lo = SRD->getLo();
1496 int64_t Hi = SRD->getHi();
1497 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1499 // If a range is available.
1501 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1502 // Only add low if non-zero.
1503 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1504 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1507 Buffer.AddChild(Subrange);
1511 case DW_TAG_structure_type:
1512 case DW_TAG_union_type: {
1513 // Add elements to structure type.
1514 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1515 DebugInfoDesc *Element = Elements[i];
1517 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1518 // Add field or base class.
1520 unsigned Tag = MemberDesc->getTag();
1522 // Extract the basic information.
1523 const std::string &Name = MemberDesc->getName();
1524 uint64_t Size = MemberDesc->getSize();
1525 uint64_t Align = MemberDesc->getAlign();
1526 uint64_t Offset = MemberDesc->getOffset();
1528 // Construct member debug information entry.
1529 DIE *Member = new DIE(Tag);
1531 // Add name if not "".
1533 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1534 // Add location if available.
1535 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1537 // Most of the time the field info is the same as the members.
1538 uint64_t FieldSize = Size;
1539 uint64_t FieldAlign = Align;
1540 uint64_t FieldOffset = Offset;
1542 // Set the member type.
1543 TypeDesc *FromTy = MemberDesc->getFromType();
1544 AddType(Member, FromTy, Unit);
1546 // Walk up typedefs until a real size is found.
1548 if (FromTy->getTag() != DW_TAG_typedef) {
1549 FieldSize = FromTy->getSize();
1550 FieldAlign = FromTy->getSize();
1554 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1557 // Unless we have a bit field.
1558 if (Tag == DW_TAG_member && FieldSize != Size) {
1559 // Construct the alignment mask.
1560 uint64_t AlignMask = ~(FieldAlign - 1);
1561 // Determine the high bit + 1 of the declared size.
1562 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1563 // Work backwards to determine the base offset of the field.
1564 FieldOffset = HiMark - FieldSize;
1565 // Now normalize offset to the field.
1566 Offset -= FieldOffset;
1568 // Maybe we need to work from the other end.
1569 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1571 // Add size and offset.
1572 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1573 AddUInt(Member, DW_AT_bit_size, 0, Size);
1574 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1577 // Add computation for offset.
1578 DIEBlock *Block = new DIEBlock();
1579 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1580 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1581 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1583 // Add accessibility (public default unless is base class.
1584 if (MemberDesc->isProtected()) {
1585 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1586 } else if (MemberDesc->isPrivate()) {
1587 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1588 } else if (Tag == DW_TAG_inheritance) {
1589 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1592 Buffer.AddChild(Member);
1593 } else if (GlobalVariableDesc *StaticDesc =
1594 dyn_cast<GlobalVariableDesc>(Element)) {
1595 // Add static member.
1597 // Construct member debug information entry.
1598 DIE *Static = new DIE(DW_TAG_variable);
1600 // Add name and mangled name.
1601 const std::string &Name = StaticDesc->getName();
1602 const std::string &LinkageName = StaticDesc->getLinkageName();
1603 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1604 if (!LinkageName.empty()) {
1605 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1610 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1613 if (TypeDesc *StaticTy = StaticDesc->getType())
1614 AddType(Static, StaticTy, Unit);
1617 if (!StaticDesc->isStatic())
1618 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1619 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1621 Buffer.AddChild(Static);
1622 } else if (SubprogramDesc *MethodDesc =
1623 dyn_cast<SubprogramDesc>(Element)) {
1624 // Add member function.
1626 // Construct member debug information entry.
1627 DIE *Method = new DIE(DW_TAG_subprogram);
1629 // Add name and mangled name.
1630 const std::string &Name = MethodDesc->getName();
1631 const std::string &LinkageName = MethodDesc->getLinkageName();
1633 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1634 bool IsCTor = TyDesc->getName() == Name;
1636 if (!LinkageName.empty()) {
1637 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1642 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1645 if (CompositeTypeDesc *MethodTy =
1646 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1647 // Get argument information.
1648 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1653 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1657 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1658 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1659 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1660 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1661 Method->AddChild(Arg);
1666 if (!MethodDesc->isStatic())
1667 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1668 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1670 Buffer.AddChild(Method);
1675 case DW_TAG_enumeration_type: {
1676 // Add enumerators to enumeration type.
1677 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1678 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1679 const std::string &Name = ED->getName();
1680 int64_t Value = ED->getValue();
1681 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1682 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1683 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1684 Buffer.AddChild(Enumerator);
1689 case DW_TAG_subroutine_type: {
1690 // Add prototype flag.
1691 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1693 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1696 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1697 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1698 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1699 Buffer.AddChild(Arg);
1708 // Add size if non-zero (derived types don't have a size.)
1709 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1710 // Add name if not anonymous or intermediate type.
1711 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1712 // Add source line info if available.
1713 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1716 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1718 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1719 // Construct debug information entry.
1720 DIE *Die = new DIE(DW_TAG_compile_unit);
1721 if (TAI->isAbsoluteDebugSectionOffsets())
1722 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1724 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1725 DWLabel("section_line", 0));
1726 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1727 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1728 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1729 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1731 // Construct compile unit.
1732 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1734 // Add Unit to compile unit map.
1735 DescToUnitMap[UnitDesc] = Unit;
1740 /// GetBaseCompileUnit - Get the main compile unit.
1742 CompileUnit *GetBaseCompileUnit() const {
1743 CompileUnit *Unit = CompileUnits[0];
1744 assert(Unit && "Missing compile unit.");
1748 /// FindCompileUnit - Get the compile unit for the given descriptor.
1750 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1751 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1752 assert(Unit && "Missing compile unit.");
1756 /// NewGlobalVariable - Add a new global variable DIE.
1758 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1759 // Get the compile unit context.
1760 CompileUnitDesc *UnitDesc =
1761 static_cast<CompileUnitDesc *>(GVD->getContext());
1762 CompileUnit *Unit = GetBaseCompileUnit();
1764 // Check for pre-existence.
1765 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1766 if (Slot) return Slot;
1768 // Get the global variable itself.
1769 GlobalVariable *GV = GVD->getGlobalVariable();
1771 const std::string &Name = GVD->getName();
1772 const std::string &FullName = GVD->getFullName();
1773 const std::string &LinkageName = GVD->getLinkageName();
1774 // Create the global's variable DIE.
1775 DIE *VariableDie = new DIE(DW_TAG_variable);
1776 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1777 if (!LinkageName.empty()) {
1778 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1781 AddType(VariableDie, GVD->getType(), Unit);
1782 if (!GVD->isStatic())
1783 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1785 // Add source line info if available.
1786 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1789 DIEBlock *Block = new DIEBlock();
1790 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1791 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1792 AddBlock(VariableDie, DW_AT_location, 0, Block);
1797 // Add to context owner.
1798 Unit->getDie()->AddChild(VariableDie);
1800 // Expose as global.
1801 // FIXME - need to check external flag.
1802 Unit->AddGlobal(FullName, VariableDie);
1807 /// NewSubprogram - Add a new subprogram DIE.
1809 DIE *NewSubprogram(SubprogramDesc *SPD) {
1810 // Get the compile unit context.
1811 CompileUnitDesc *UnitDesc =
1812 static_cast<CompileUnitDesc *>(SPD->getContext());
1813 CompileUnit *Unit = GetBaseCompileUnit();
1815 // Check for pre-existence.
1816 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1817 if (Slot) return Slot;
1819 // Gather the details (simplify add attribute code.)
1820 const std::string &Name = SPD->getName();
1821 const std::string &FullName = SPD->getFullName();
1822 const std::string &LinkageName = SPD->getLinkageName();
1824 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1825 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1826 if (!LinkageName.empty()) {
1827 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1830 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1831 if (!SPD->isStatic())
1832 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1833 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1835 // Add source line info if available.
1836 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1839 Slot = SubprogramDie;
1841 // Add to context owner.
1842 Unit->getDie()->AddChild(SubprogramDie);
1844 // Expose as global.
1845 Unit->AddGlobal(FullName, SubprogramDie);
1847 return SubprogramDie;
1850 /// NewScopeVariable - Create a new scope variable.
1852 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1853 // Get the descriptor.
1854 VariableDesc *VD = DV->getDesc();
1856 // Translate tag to proper Dwarf tag. The result variable is dropped for
1859 switch (VD->getTag()) {
1860 case DW_TAG_return_variable: return NULL;
1861 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1862 case DW_TAG_auto_variable: // fall thru
1863 default: Tag = DW_TAG_variable; break;
1866 // Define variable debug information entry.
1867 DIE *VariableDie = new DIE(Tag);
1868 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1870 // Add source line info if available.
1871 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1873 // Add variable type.
1874 AddType(VariableDie, VD->getType(), Unit);
1876 // Add variable address.
1877 MachineLocation Location;
1878 Location.set(RI->getFrameRegister(*MF),
1879 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1880 AddAddress(VariableDie, DW_AT_location, Location);
1885 /// ConstructScope - Construct the components of a scope.
1887 void ConstructScope(DebugScope *ParentScope,
1888 unsigned ParentStartID, unsigned ParentEndID,
1889 DIE *ParentDie, CompileUnit *Unit) {
1890 // Add variables to scope.
1891 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1892 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1893 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1894 if (VariableDie) ParentDie->AddChild(VariableDie);
1897 // Add nested scopes.
1898 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1899 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1900 // Define the Scope debug information entry.
1901 DebugScope *Scope = Scopes[j];
1902 // FIXME - Ignore inlined functions for the time being.
1903 if (!Scope->getParent()) continue;
1905 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1906 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1908 // Ignore empty scopes.
1909 if (StartID == EndID && StartID != 0) continue;
1910 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1912 if (StartID == ParentStartID && EndID == ParentEndID) {
1913 // Just add stuff to the parent scope.
1914 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1916 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1918 // Add the scope bounds.
1920 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1921 DWLabel("label", StartID));
1923 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1924 DWLabel("func_begin", SubprogramCount));
1927 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1928 DWLabel("label", EndID));
1930 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1931 DWLabel("func_end", SubprogramCount));
1934 // Add the scope contents.
1935 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1936 ParentDie->AddChild(ScopeDie);
1941 /// ConstructRootScope - Construct the scope for the subprogram.
1943 void ConstructRootScope(DebugScope *RootScope) {
1944 // Exit if there is no root scope.
1945 if (!RootScope) return;
1947 // Get the subprogram debug information entry.
1948 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1950 // Get the compile unit context.
1951 CompileUnit *Unit = GetBaseCompileUnit();
1953 // Get the subprogram die.
1954 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1955 assert(SPDie && "Missing subprogram descriptor");
1957 // Add the function bounds.
1958 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1959 DWLabel("func_begin", SubprogramCount));
1960 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1961 DWLabel("func_end", SubprogramCount));
1962 MachineLocation Location(RI->getFrameRegister(*MF));
1963 AddAddress(SPDie, DW_AT_frame_base, Location);
1965 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1968 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1969 /// tools to recognize the object file contains Dwarf information.
1970 void EmitInitial() {
1971 // Check to see if we already emitted intial headers.
1972 if (didInitial) return;
1975 // Dwarf sections base addresses.
1976 if (TAI->doesDwarfRequireFrameSection()) {
1977 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1978 EmitLabel("section_debug_frame", 0);
1980 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1981 EmitLabel("section_info", 0);
1982 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1983 EmitLabel("section_abbrev", 0);
1984 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1985 EmitLabel("section_aranges", 0);
1986 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1987 EmitLabel("section_macinfo", 0);
1988 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1989 EmitLabel("section_line", 0);
1990 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1991 EmitLabel("section_loc", 0);
1992 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1993 EmitLabel("section_pubnames", 0);
1994 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1995 EmitLabel("section_str", 0);
1996 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1997 EmitLabel("section_ranges", 0);
1999 Asm->SwitchToTextSection(TAI->getTextSection());
2000 EmitLabel("text_begin", 0);
2001 Asm->SwitchToDataSection(TAI->getDataSection());
2002 EmitLabel("data_begin", 0);
2005 /// EmitDIE - Recusively Emits a debug information entry.
2007 void EmitDIE(DIE *Die) {
2008 // Get the abbreviation for this DIE.
2009 unsigned AbbrevNumber = Die->getAbbrevNumber();
2010 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2014 // Emit the code (index) for the abbreviation.
2015 Asm->EmitULEB128Bytes(AbbrevNumber);
2016 Asm->EOL(std::string("Abbrev [" +
2017 utostr(AbbrevNumber) +
2018 "] 0x" + utohexstr(Die->getOffset()) +
2019 ":0x" + utohexstr(Die->getSize()) + " " +
2020 TagString(Abbrev->getTag())));
2022 std::vector<DIEValue *> &Values = Die->getValues();
2023 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2025 // Emit the DIE attribute values.
2026 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2027 unsigned Attr = AbbrevData[i].getAttribute();
2028 unsigned Form = AbbrevData[i].getForm();
2029 assert(Form && "Too many attributes for DIE (check abbreviation)");
2032 case DW_AT_sibling: {
2033 Asm->EmitInt32(Die->SiblingOffset());
2037 // Emit an attribute using the defined form.
2038 Values[i]->EmitValue(*this, Form);
2043 Asm->EOL(AttributeString(Attr));
2046 // Emit the DIE children if any.
2047 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2048 const std::vector<DIE *> &Children = Die->getChildren();
2050 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2051 EmitDIE(Children[j]);
2054 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2058 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2060 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2061 // Get the children.
2062 const std::vector<DIE *> &Children = Die->getChildren();
2064 // If not last sibling and has children then add sibling offset attribute.
2065 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2067 // Record the abbreviation.
2068 AssignAbbrevNumber(Die->getAbbrev());
2070 // Get the abbreviation for this DIE.
2071 unsigned AbbrevNumber = Die->getAbbrevNumber();
2072 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2075 Die->setOffset(Offset);
2077 // Start the size with the size of abbreviation code.
2078 Offset += Asm->SizeULEB128(AbbrevNumber);
2080 const std::vector<DIEValue *> &Values = Die->getValues();
2081 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2083 // Size the DIE attribute values.
2084 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2085 // Size attribute value.
2086 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2089 // Size the DIE children if any.
2090 if (!Children.empty()) {
2091 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2092 "Children flag not set");
2094 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2095 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2098 // End of children marker.
2099 Offset += sizeof(int8_t);
2102 Die->setSize(Offset - Die->getOffset());
2106 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2108 void SizeAndOffsets() {
2109 // Process base compile unit.
2110 CompileUnit *Unit = GetBaseCompileUnit();
2111 // Compute size of compile unit header
2112 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2113 sizeof(int16_t) + // DWARF version number
2114 sizeof(int32_t) + // Offset Into Abbrev. Section
2115 sizeof(int8_t); // Pointer Size (in bytes)
2116 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2119 /// EmitDebugInfo - Emit the debug info section.
2121 void EmitDebugInfo() {
2122 // Start debug info section.
2123 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2125 CompileUnit *Unit = GetBaseCompileUnit();
2126 DIE *Die = Unit->getDie();
2127 // Emit the compile units header.
2128 EmitLabel("info_begin", Unit->getID());
2129 // Emit size of content not including length itself
2130 unsigned ContentSize = Die->getSize() +
2131 sizeof(int16_t) + // DWARF version number
2132 sizeof(int32_t) + // Offset Into Abbrev. Section
2133 sizeof(int8_t) + // Pointer Size (in bytes)
2134 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2136 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2137 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2138 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2139 Asm->EOL("Offset Into Abbrev. Section");
2140 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2143 // FIXME - extra padding for gdb bug.
2144 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2145 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2146 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2147 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2148 EmitLabel("info_end", Unit->getID());
2153 /// EmitAbbreviations - Emit the abbreviation section.
2155 void EmitAbbreviations() const {
2156 // Check to see if it is worth the effort.
2157 if (!Abbreviations.empty()) {
2158 // Start the debug abbrev section.
2159 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2161 EmitLabel("abbrev_begin", 0);
2163 // For each abbrevation.
2164 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2165 // Get abbreviation data
2166 const DIEAbbrev *Abbrev = Abbreviations[i];
2168 // Emit the abbrevations code (base 1 index.)
2169 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2170 Asm->EOL("Abbreviation Code");
2172 // Emit the abbreviations data.
2173 Abbrev->Emit(*this);
2178 // Mark end of abbreviations.
2179 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2181 EmitLabel("abbrev_end", 0);
2187 /// EmitDebugLines - Emit source line information.
2189 void EmitDebugLines() {
2190 // If there are no lines to emit (such as when we're using .loc directives
2191 // to emit .debug_line information) don't emit a .debug_line header.
2192 if (SectionSourceLines.empty())
2195 // Minimum line delta, thus ranging from -10..(255-10).
2196 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2197 // Maximum line delta, thus ranging from -10..(255-10).
2198 const int MaxLineDelta = 255 + MinLineDelta;
2200 // Start the dwarf line section.
2201 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2203 // Construct the section header.
2205 EmitDifference("line_end", 0, "line_begin", 0, true);
2206 Asm->EOL("Length of Source Line Info");
2207 EmitLabel("line_begin", 0);
2209 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2211 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2212 Asm->EOL("Prolog Length");
2213 EmitLabel("line_prolog_begin", 0);
2215 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2217 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2219 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2221 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2223 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2225 // Line number standard opcode encodings argument count
2226 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2227 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2228 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2229 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2230 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2231 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2232 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2233 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2234 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2236 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2237 const UniqueVector<SourceFileInfo>
2238 &SourceFiles = MMI->getSourceFiles();
2240 // Emit directories.
2241 for (unsigned DirectoryID = 1, NDID = Directories.size();
2242 DirectoryID <= NDID; ++DirectoryID) {
2243 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2245 Asm->EmitInt8(0); Asm->EOL("End of directories");
2248 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2249 SourceID <= NSID; ++SourceID) {
2250 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2251 Asm->EmitString(SourceFile.getName());
2253 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2254 Asm->EOL("Directory #");
2255 Asm->EmitULEB128Bytes(0);
2256 Asm->EOL("Mod date");
2257 Asm->EmitULEB128Bytes(0);
2258 Asm->EOL("File size");
2260 Asm->EmitInt8(0); Asm->EOL("End of files");
2262 EmitLabel("line_prolog_end", 0);
2264 // A sequence for each text section.
2265 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2266 // Isolate current sections line info.
2267 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2269 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2271 // Dwarf assumes we start with first line of first source file.
2272 unsigned Source = 1;
2275 // Construct rows of the address, source, line, column matrix.
2276 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2277 const SourceLineInfo &LineInfo = LineInfos[i];
2278 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2279 if (!LabelID) continue;
2281 unsigned SourceID = LineInfo.getSourceID();
2282 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2283 unsigned DirectoryID = SourceFile.getDirectoryID();
2284 Asm->EOL(Directories[DirectoryID]
2285 + SourceFile.getName()
2287 + utostr_32(LineInfo.getLine()));
2289 // Define the line address.
2290 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2291 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2292 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2293 EmitReference("label", LabelID); Asm->EOL("Location label");
2295 // If change of source, then switch to the new source.
2296 if (Source != LineInfo.getSourceID()) {
2297 Source = LineInfo.getSourceID();
2298 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2299 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2302 // If change of line.
2303 if (Line != LineInfo.getLine()) {
2304 // Determine offset.
2305 int Offset = LineInfo.getLine() - Line;
2306 int Delta = Offset - MinLineDelta;
2309 Line = LineInfo.getLine();
2311 // If delta is small enough and in range...
2312 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2313 // ... then use fast opcode.
2314 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2316 // ... otherwise use long hand.
2317 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2318 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2319 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2322 // Copy the previous row (different address or source)
2323 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2327 // Define last address of section.
2328 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2329 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2330 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2331 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2333 // Mark end of matrix.
2334 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2335 Asm->EmitULEB128Bytes(1); Asm->EOL();
2336 Asm->EmitInt8(1); Asm->EOL();
2339 EmitLabel("line_end", 0);
2344 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2346 void EmitCommonDebugFrame() {
2347 if (!TAI->doesDwarfRequireFrameSection())
2351 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2352 TargetFrameInfo::StackGrowsUp ?
2353 TD->getPointerSize() : -TD->getPointerSize();
2355 // Start the dwarf frame section.
2356 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2358 EmitLabel("debug_frame_common", 0);
2359 EmitDifference("debug_frame_common_end", 0,
2360 "debug_frame_common_begin", 0, true);
2361 Asm->EOL("Length of Common Information Entry");
2363 EmitLabel("debug_frame_common_begin", 0);
2364 Asm->EmitInt32((int)DW_CIE_ID);
2365 Asm->EOL("CIE Identifier Tag");
2366 Asm->EmitInt8(DW_CIE_VERSION);
2367 Asm->EOL("CIE Version");
2368 Asm->EmitString("");
2369 Asm->EOL("CIE Augmentation");
2370 Asm->EmitULEB128Bytes(1);
2371 Asm->EOL("CIE Code Alignment Factor");
2372 Asm->EmitSLEB128Bytes(stackGrowth);
2373 Asm->EOL("CIE Data Alignment Factor");
2374 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2375 Asm->EOL("CIE RA Column");
2377 std::vector<MachineMove> Moves;
2378 RI->getInitialFrameState(Moves);
2380 EmitFrameMoves(NULL, 0, Moves, false);
2382 Asm->EmitAlignment(2);
2383 EmitLabel("debug_frame_common_end", 0);
2388 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2390 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2391 if (!TAI->doesDwarfRequireFrameSection())
2394 // Start the dwarf frame section.
2395 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2397 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2398 "debug_frame_begin", DebugFrameInfo.Number, true);
2399 Asm->EOL("Length of Frame Information Entry");
2401 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2403 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2405 Asm->EOL("FDE CIE offset");
2407 EmitReference("func_begin", DebugFrameInfo.Number);
2408 Asm->EOL("FDE initial location");
2409 EmitDifference("func_end", DebugFrameInfo.Number,
2410 "func_begin", DebugFrameInfo.Number);
2411 Asm->EOL("FDE address range");
2413 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2415 Asm->EmitAlignment(2);
2416 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2421 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2423 void EmitDebugPubNames() {
2424 // Start the dwarf pubnames section.
2425 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2427 CompileUnit *Unit = GetBaseCompileUnit();
2429 EmitDifference("pubnames_end", Unit->getID(),
2430 "pubnames_begin", Unit->getID(), true);
2431 Asm->EOL("Length of Public Names Info");
2433 EmitLabel("pubnames_begin", Unit->getID());
2435 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2437 EmitSectionOffset("info_begin", "section_info",
2438 Unit->getID(), 0, true, false);
2439 Asm->EOL("Offset of Compilation Unit Info");
2441 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2442 Asm->EOL("Compilation Unit Length");
2444 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2446 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2449 const std::string &Name = GI->first;
2450 DIE * Entity = GI->second;
2452 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2453 Asm->EmitString(Name); Asm->EOL("External Name");
2456 Asm->EmitInt32(0); Asm->EOL("End Mark");
2457 EmitLabel("pubnames_end", Unit->getID());
2462 /// EmitDebugStr - Emit visible names into a debug str section.
2464 void EmitDebugStr() {
2465 // Check to see if it is worth the effort.
2466 if (!StringPool.empty()) {
2467 // Start the dwarf str section.
2468 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2470 // For each of strings in the string pool.
2471 for (unsigned StringID = 1, N = StringPool.size();
2472 StringID <= N; ++StringID) {
2473 // Emit a label for reference from debug information entries.
2474 EmitLabel("string", StringID);
2475 // Emit the string itself.
2476 const std::string &String = StringPool[StringID];
2477 Asm->EmitString(String); Asm->EOL();
2484 /// EmitDebugLoc - Emit visible names into a debug loc section.
2486 void EmitDebugLoc() {
2487 // Start the dwarf loc section.
2488 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2493 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2495 void EmitDebugARanges() {
2496 // Start the dwarf aranges section.
2497 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2501 CompileUnit *Unit = GetBaseCompileUnit();
2503 // Don't include size of length
2504 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2506 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2508 EmitReference("info_begin", Unit->getID());
2509 Asm->EOL("Offset of Compilation Unit Info");
2511 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2513 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2515 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2516 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2519 EmitReference("text_begin", 0); Asm->EOL("Address");
2520 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2522 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2523 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2529 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2531 void EmitDebugRanges() {
2532 // Start the dwarf ranges section.
2533 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2538 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2540 void EmitDebugMacInfo() {
2541 // Start the dwarf macinfo section.
2542 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2547 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2549 void ConstructCompileUnitDIEs() {
2550 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2552 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2553 unsigned ID = MMI->RecordSource(CUW[i]);
2554 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2555 CompileUnits.push_back(Unit);
2559 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2560 /// global variables.
2561 void ConstructGlobalDIEs() {
2562 std::vector<GlobalVariableDesc *> GlobalVariables =
2563 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2565 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2566 GlobalVariableDesc *GVD = GlobalVariables[i];
2567 NewGlobalVariable(GVD);
2571 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2573 void ConstructSubprogramDIEs() {
2574 std::vector<SubprogramDesc *> Subprograms =
2575 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2577 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2578 SubprogramDesc *SPD = Subprograms[i];
2584 //===--------------------------------------------------------------------===//
2585 // Main entry points.
2587 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2588 : Dwarf(OS, A, T, "dbg")
2590 , AbbreviationsSet(InitAbbreviationsSetSize)
2592 , ValuesSet(InitValuesSetSize)
2597 , SectionSourceLines()
2602 virtual ~DwarfDebug() {
2603 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2604 delete CompileUnits[i];
2605 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2609 /// SetModuleInfo - Set machine module information when it's known that pass
2610 /// manager has created it. Set by the target AsmPrinter.
2611 void SetModuleInfo(MachineModuleInfo *mmi) {
2612 // Make sure initial declarations are made.
2613 if (!MMI && mmi->hasDebugInfo()) {
2617 // Create all the compile unit DIEs.
2618 ConstructCompileUnitDIEs();
2620 // Create DIEs for each of the externally visible global variables.
2621 ConstructGlobalDIEs();
2623 // Create DIEs for each of the externally visible subprograms.
2624 ConstructSubprogramDIEs();
2626 // Prime section data.
2627 SectionMap.insert(TAI->getTextSection());
2629 // Print out .file directives to specify files for .loc directives. These
2630 // are printed out early so that they precede any .loc directives.
2631 if (TAI->hasDotLocAndDotFile()) {
2632 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2633 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2634 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2635 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2636 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2637 assert(AppendOk && "Could not append filename to directory!");
2638 Asm->EmitFile(i, FullPath.toString());
2643 // Emit initial sections
2648 /// BeginModule - Emit all Dwarf sections that should come prior to the
2650 void BeginModule(Module *M) {
2653 if (!ShouldEmitDwarf()) return;
2656 /// EndModule - Emit all Dwarf sections that should come after the content.
2659 if (!ShouldEmitDwarf()) return;
2661 // Standard sections final addresses.
2662 Asm->SwitchToTextSection(TAI->getTextSection());
2663 EmitLabel("text_end", 0);
2664 Asm->SwitchToDataSection(TAI->getDataSection());
2665 EmitLabel("data_end", 0);
2667 // End text sections.
2668 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2669 Asm->SwitchToTextSection(SectionMap[i].c_str());
2670 EmitLabel("section_end", i);
2673 // Emit common frame information.
2674 EmitCommonDebugFrame();
2676 // Emit function debug frame information
2677 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2678 E = DebugFrames.end(); I != E; ++I)
2679 EmitFunctionDebugFrame(*I);
2681 // Compute DIE offsets and sizes.
2684 // Emit all the DIEs into a debug info section
2687 // Corresponding abbreviations into a abbrev section.
2688 EmitAbbreviations();
2690 // Emit source line correspondence into a debug line section.
2693 // Emit info into a debug pubnames section.
2694 EmitDebugPubNames();
2696 // Emit info into a debug str section.
2699 // Emit info into a debug loc section.
2702 // Emit info into a debug aranges section.
2705 // Emit info into a debug ranges section.
2708 // Emit info into a debug macinfo section.
2712 /// BeginFunction - Gather pre-function debug information. Assumes being
2713 /// emitted immediately after the function entry point.
2714 void BeginFunction(MachineFunction *MF) {
2717 if (!ShouldEmitDwarf()) return;
2719 // Begin accumulating function debug information.
2720 MMI->BeginFunction(MF);
2722 // Assumes in correct section after the entry point.
2723 EmitLabel("func_begin", ++SubprogramCount);
2725 // Emit label for the implicitly defined dbg.stoppoint at the start of
2727 const SourceLineInfo &LineInfo = MMI->getSourceLines()[0];
2728 Asm->printLabel(LineInfo.getLabelID());
2731 /// EndFunction - Gather and emit post-function debug information.
2733 void EndFunction() {
2734 if (!ShouldEmitDwarf()) return;
2736 // Define end label for subprogram.
2737 EmitLabel("func_end", SubprogramCount);
2739 // Get function line info.
2740 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2742 if (!LineInfos.empty()) {
2743 // Get section line info.
2744 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2745 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2746 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2747 // Append the function info to section info.
2748 SectionLineInfos.insert(SectionLineInfos.end(),
2749 LineInfos.begin(), LineInfos.end());
2752 // Construct scopes for subprogram.
2753 ConstructRootScope(MMI->getRootScope());
2755 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2756 MMI->getFrameMoves()));
2760 //===----------------------------------------------------------------------===//
2761 /// DwarfException - Emits Dwarf exception handling directives.
2763 class DwarfException : public Dwarf {
2766 struct FunctionEHFrameInfo {
2769 unsigned PersonalityIndex;
2771 bool hasLandingPads;
2772 std::vector<MachineMove> Moves;
2773 const Function * function;
2775 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2777 const std::vector<MachineMove> &M,
2779 FnName(FN), Number(Num), PersonalityIndex(P),
2780 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2783 std::vector<FunctionEHFrameInfo> EHFrames;
2785 /// shouldEmit - Flag to indicate if debug information should be emitted.
2789 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2791 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2792 // Size and sign of stack growth.
2794 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2795 TargetFrameInfo::StackGrowsUp ?
2796 TD->getPointerSize() : -TD->getPointerSize();
2798 // Begin eh frame section.
2799 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2800 O << "EH_frame" << Index << ":\n";
2801 EmitLabel("section_eh_frame", Index);
2803 // Define base labels.
2804 EmitLabel("eh_frame_common", Index);
2806 // Define the eh frame length.
2807 EmitDifference("eh_frame_common_end", Index,
2808 "eh_frame_common_begin", Index, true);
2809 Asm->EOL("Length of Common Information Entry");
2812 EmitLabel("eh_frame_common_begin", Index);
2813 Asm->EmitInt32((int)0);
2814 Asm->EOL("CIE Identifier Tag");
2815 Asm->EmitInt8(DW_CIE_VERSION);
2816 Asm->EOL("CIE Version");
2818 // The personality presence indicates that language specific information
2819 // will show up in the eh frame.
2820 Asm->EmitString(Personality ? "zPLR" : "zR");
2821 Asm->EOL("CIE Augmentation");
2823 // Round out reader.
2824 Asm->EmitULEB128Bytes(1);
2825 Asm->EOL("CIE Code Alignment Factor");
2826 Asm->EmitSLEB128Bytes(stackGrowth);
2827 Asm->EOL("CIE Data Alignment Factor");
2828 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2829 Asm->EOL("CIE RA Column");
2831 // If there is a personality, we need to indicate the functions location.
2833 Asm->EmitULEB128Bytes(7);
2834 Asm->EOL("Augmentation Size");
2836 if (TAI->getNeedsIndirectEncoding())
2837 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2839 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2841 Asm->EOL("Personality (pcrel sdata4 indirect)");
2843 PrintRelDirective(TAI->getShortenEHDataOn64Bit());
2844 O << TAI->getPersonalityPrefix();
2845 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2846 O << TAI->getPersonalitySuffix();
2847 if (!TAI->getShortenEHDataOn64Bit()) {
2848 O << "-" << TAI->getPCSymbol();
2850 Asm->EOL("Personality");
2852 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2853 Asm->EOL("LSDA Encoding (pcrel)");
2854 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2855 Asm->EOL("FDE Encoding (pcrel)");
2857 Asm->EmitULEB128Bytes(1);
2858 Asm->EOL("Augmentation Size");
2859 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2860 Asm->EOL("FDE Encoding (pcrel)");
2863 // Indicate locations of general callee saved registers in frame.
2864 std::vector<MachineMove> Moves;
2865 RI->getInitialFrameState(Moves);
2866 EmitFrameMoves(NULL, 0, Moves, true);
2868 Asm->EmitAlignment(2);
2869 EmitLabel("eh_frame_common_end", Index);
2874 /// EmitEHFrame - Emit function exception frame information.
2876 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2877 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
2879 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2881 // Externally visible entry into the functions eh frame info.
2882 // If the corresponding function is static, this should not be
2883 // externally visible.
2884 if (linkage != Function::InternalLinkage) {
2885 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
2886 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
2889 // If corresponding function is weak definition, this should be too.
2890 if ((linkage == Function::WeakLinkage ||
2891 linkage == Function::LinkOnceLinkage) &&
2892 TAI->getWeakDefDirective())
2893 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
2895 // If there are no calls then you can't unwind. This may mean we can
2896 // omit the EH Frame, but some environments do not handle weak absolute
2898 if (!EHFrameInfo.hasCalls &&
2899 ((linkage != Function::WeakLinkage &&
2900 linkage != Function::LinkOnceLinkage) ||
2901 !TAI->getWeakDefDirective() ||
2902 TAI->getSupportsWeakOmittedEHFrame()))
2904 O << EHFrameInfo.FnName << " = 0\n";
2905 // This name has no connection to the function, so it might get
2906 // dead-stripped when the function is not, erroneously. Prohibit
2907 // dead-stripping unconditionally.
2908 if (const char *UsedDirective = TAI->getUsedDirective())
2909 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2911 O << EHFrameInfo.FnName << ":\n";
2914 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2915 "eh_frame_begin", EHFrameInfo.Number, true);
2916 Asm->EOL("Length of Frame Information Entry");
2918 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2920 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2921 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2923 Asm->EOL("FDE CIE offset");
2925 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2926 Asm->EOL("FDE initial location");
2927 EmitDifference("eh_func_end", EHFrameInfo.Number,
2928 "eh_func_begin", EHFrameInfo.Number);
2929 Asm->EOL("FDE address range");
2931 // If there is a personality and landing pads then point to the language
2932 // specific data area in the exception table.
2933 if (EHFrameInfo.PersonalityIndex) {
2934 Asm->EmitULEB128Bytes(TAI->getShortenEHDataOn64Bit() ? 8 : 4);
2935 Asm->EOL("Augmentation size");
2937 if (EHFrameInfo.hasLandingPads) {
2938 EmitReference("exception", EHFrameInfo.Number, true);
2939 } else if (TD->getPointerSize() == 8) {
2940 Asm->EmitInt64((int)0);
2942 Asm->EmitInt32((int)0);
2944 Asm->EOL("Language Specific Data Area");
2946 Asm->EmitULEB128Bytes(0);
2947 Asm->EOL("Augmentation size");
2950 // Indicate locations of function specific callee saved registers in
2952 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
2954 Asm->EmitAlignment(2);
2955 EmitLabel("eh_frame_end", EHFrameInfo.Number);
2957 // If the function is marked used, this table should be also. We cannot
2958 // make the mark unconditional in this case, since retaining the table
2959 // also retains the function in this case, and there is code around
2960 // that depends on unused functions (calling undefined externals) being
2961 // dead-stripped to link correctly. Yes, there really is.
2962 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
2963 if (const char *UsedDirective = TAI->getUsedDirective())
2964 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2968 /// EmitExceptionTable - Emit landing pads and actions.
2970 /// The general organization of the table is complex, but the basic concepts
2971 /// are easy. First there is a header which describes the location and
2972 /// organization of the three components that follow.
2973 /// 1. The landing pad site information describes the range of code covered
2974 /// by the try. In our case it's an accumulation of the ranges covered
2975 /// by the invokes in the try. There is also a reference to the landing
2976 /// pad that handles the exception once processed. Finally an index into
2977 /// the actions table.
2978 /// 2. The action table, in our case, is composed of pairs of type ids
2979 /// and next action offset. Starting with the action index from the
2980 /// landing pad site, each type Id is checked for a match to the current
2981 /// exception. If it matches then the exception and type id are passed
2982 /// on to the landing pad. Otherwise the next action is looked up. This
2983 /// chain is terminated with a next action of zero. If no type id is
2984 /// found the the frame is unwound and handling continues.
2985 /// 3. Type id table contains references to all the C++ typeinfo for all
2986 /// catches in the function. This tables is reversed indexed base 1.
2988 /// SharedTypeIds - How many leading type ids two landing pads have in common.
2989 static unsigned SharedTypeIds(const LandingPadInfo *L,
2990 const LandingPadInfo *R) {
2991 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2992 unsigned LSize = LIds.size(), RSize = RIds.size();
2993 unsigned MinSize = LSize < RSize ? LSize : RSize;
2996 for (; Count != MinSize; ++Count)
2997 if (LIds[Count] != RIds[Count])
3003 /// PadLT - Order landing pads lexicographically by type id.
3004 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3005 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3006 unsigned LSize = LIds.size(), RSize = RIds.size();
3007 unsigned MinSize = LSize < RSize ? LSize : RSize;
3009 for (unsigned i = 0; i != MinSize; ++i)
3010 if (LIds[i] != RIds[i])
3011 return LIds[i] < RIds[i];
3013 return LSize < RSize;
3017 static inline unsigned getEmptyKey() { return -1U; }
3018 static inline unsigned getTombstoneKey() { return -2U; }
3019 static unsigned getHashValue(const unsigned &Key) { return Key; }
3020 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3021 static bool isPod() { return true; }
3024 /// ActionEntry - Structure describing an entry in the actions table.
3025 struct ActionEntry {
3026 int ValueForTypeID; // The value to write - may not be equal to the type id.
3028 struct ActionEntry *Previous;
3031 /// PadRange - Structure holding a try-range and the associated landing pad.
3033 // The index of the landing pad.
3035 // The index of the begin and end labels in the landing pad's label lists.
3036 unsigned RangeIndex;
3039 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3041 /// CallSiteEntry - Structure describing an entry in the call-site table.
3042 struct CallSiteEntry {
3043 // The 'try-range' is BeginLabel .. EndLabel.
3044 unsigned BeginLabel; // zero indicates the start of the function.
3045 unsigned EndLabel; // zero indicates the end of the function.
3046 // The landing pad starts at PadLabel.
3047 unsigned PadLabel; // zero indicates that there is no landing pad.
3051 void EmitExceptionTable() {
3052 // Map all labels and get rid of any dead landing pads.
3053 MMI->TidyLandingPads();
3055 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3056 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3057 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3058 if (PadInfos.empty()) return;
3060 // Sort the landing pads in order of their type ids. This is used to fold
3061 // duplicate actions.
3062 SmallVector<const LandingPadInfo *, 64> LandingPads;
3063 LandingPads.reserve(PadInfos.size());
3064 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3065 LandingPads.push_back(&PadInfos[i]);
3066 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3068 // Negative type ids index into FilterIds, positive type ids index into
3069 // TypeInfos. The value written for a positive type id is just the type
3070 // id itself. For a negative type id, however, the value written is the
3071 // (negative) byte offset of the corresponding FilterIds entry. The byte
3072 // offset is usually equal to the type id, because the FilterIds entries
3073 // are written using a variable width encoding which outputs one byte per
3074 // entry as long as the value written is not too large, but can differ.
3075 // This kind of complication does not occur for positive type ids because
3076 // type infos are output using a fixed width encoding.
3077 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3078 SmallVector<int, 16> FilterOffsets;
3079 FilterOffsets.reserve(FilterIds.size());
3081 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3082 E = FilterIds.end(); I != E; ++I) {
3083 FilterOffsets.push_back(Offset);
3084 Offset -= Asm->SizeULEB128(*I);
3087 // Compute the actions table and gather the first action index for each
3088 // landing pad site.
3089 SmallVector<ActionEntry, 32> Actions;
3090 SmallVector<unsigned, 64> FirstActions;
3091 FirstActions.reserve(LandingPads.size());
3093 int FirstAction = 0;
3094 unsigned SizeActions = 0;
3095 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3096 const LandingPadInfo *LP = LandingPads[i];
3097 const std::vector<int> &TypeIds = LP->TypeIds;
3098 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3099 unsigned SizeSiteActions = 0;
3101 if (NumShared < TypeIds.size()) {
3102 unsigned SizeAction = 0;
3103 ActionEntry *PrevAction = 0;
3106 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3107 assert(Actions.size());
3108 PrevAction = &Actions.back();
3109 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3110 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3111 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3112 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3113 SizeAction += -PrevAction->NextAction;
3114 PrevAction = PrevAction->Previous;
3118 // Compute the actions.
3119 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3120 int TypeID = TypeIds[I];
3121 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3122 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3123 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3125 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3126 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3127 SizeSiteActions += SizeAction;
3129 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3130 Actions.push_back(Action);
3132 PrevAction = &Actions.back();
3135 // Record the first action of the landing pad site.
3136 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3137 } // else identical - re-use previous FirstAction
3139 FirstActions.push_back(FirstAction);
3141 // Compute this sites contribution to size.
3142 SizeActions += SizeSiteActions;
3145 // Compute the call-site table. The entry for an invoke has a try-range
3146 // containing the call, a non-zero landing pad and an appropriate action.
3147 // The entry for an ordinary call has a try-range containing the call and
3148 // zero for the landing pad and the action. Calls marked 'nounwind' have
3149 // no entry and must not be contained in the try-range of any entry - they
3150 // form gaps in the table. Entries must be ordered by try-range address.
3151 SmallVector<CallSiteEntry, 64> CallSites;
3153 RangeMapType PadMap;
3154 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3155 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3156 // try-ranges for them need be deduced.
3157 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3158 const LandingPadInfo *LandingPad = LandingPads[i];
3159 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3160 unsigned BeginLabel = LandingPad->BeginLabels[j];
3161 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3162 PadRange P = { i, j };
3163 PadMap[BeginLabel] = P;
3167 // The end label of the previous invoke or nounwind try-range.
3168 unsigned LastLabel = 0;
3170 // Whether there is a potentially throwing instruction (currently this means
3171 // an ordinary call) between the end of the previous try-range and now.
3172 bool SawPotentiallyThrowing = false;
3174 // Whether the last callsite entry was for an invoke.
3175 bool PreviousIsInvoke = false;
3177 // Visit all instructions in order of address.
3178 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3180 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3182 if (MI->getOpcode() != TargetInstrInfo::LABEL) {
3183 SawPotentiallyThrowing |= MI->getDesc().isCall();
3187 unsigned BeginLabel = MI->getOperand(0).getImm();
3188 assert(BeginLabel && "Invalid label!");
3190 // End of the previous try-range?
3191 if (BeginLabel == LastLabel)
3192 SawPotentiallyThrowing = false;
3194 // Beginning of a new try-range?
3195 RangeMapType::iterator L = PadMap.find(BeginLabel);
3196 if (L == PadMap.end())
3197 // Nope, it was just some random label.
3200 PadRange P = L->second;
3201 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3203 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3204 "Inconsistent landing pad map!");
3206 // If some instruction between the previous try-range and this one may
3207 // throw, create a call-site entry with no landing pad for the region
3208 // between the try-ranges.
3209 if (SawPotentiallyThrowing) {
3210 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3211 CallSites.push_back(Site);
3212 PreviousIsInvoke = false;
3215 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3216 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3218 if (LandingPad->LandingPadLabel) {
3219 // This try-range is for an invoke.
3220 CallSiteEntry Site = {BeginLabel, LastLabel,
3221 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3223 // Try to merge with the previous call-site.
3224 if (PreviousIsInvoke) {
3225 CallSiteEntry &Prev = CallSites[CallSites.size()-1];
3226 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3227 // Extend the range of the previous entry.
3228 Prev.EndLabel = Site.EndLabel;
3233 // Otherwise, create a new call-site.
3234 CallSites.push_back(Site);
3235 PreviousIsInvoke = true;
3238 PreviousIsInvoke = false;
3242 // If some instruction between the previous try-range and the end of the
3243 // function may throw, create a call-site entry with no landing pad for the
3244 // region following the try-range.
3245 if (SawPotentiallyThrowing) {
3246 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3247 CallSites.push_back(Site);
3251 unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
3252 sizeof(int32_t) + // Site length.
3253 sizeof(int32_t)); // Landing pad.
3254 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3255 SizeSites += Asm->SizeULEB128(CallSites[i].Action);
3257 unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
3259 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3260 Asm->SizeULEB128(SizeSites) + // Call-site table length
3261 SizeSites + SizeActions + SizeTypes;
3263 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3264 sizeof(int8_t) + // TType format
3265 Asm->SizeULEB128(TypeOffset) + // TType base offset
3268 unsigned SizeAlign = (4 - TotalSize) & 3;
3270 // Begin the exception table.
3271 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3272 O << "GCC_except_table" << SubprogramCount << ":\n";
3273 Asm->EmitAlignment(2);
3274 for (unsigned i = 0; i != SizeAlign; ++i) {
3276 Asm->EOL("Padding");
3278 EmitLabel("exception", SubprogramCount);
3281 Asm->EmitInt8(DW_EH_PE_omit);
3282 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3283 Asm->EmitInt8(DW_EH_PE_absptr);
3284 Asm->EOL("TType format (DW_EH_PE_absptr)");
3285 Asm->EmitULEB128Bytes(TypeOffset);
3286 Asm->EOL("TType base offset");
3287 Asm->EmitInt8(DW_EH_PE_udata4);
3288 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3289 Asm->EmitULEB128Bytes(SizeSites);
3290 Asm->EOL("Call-site table length");
3292 // Emit the landing pad site information.
3293 for (unsigned i = 0; i < CallSites.size(); ++i) {
3294 CallSiteEntry &S = CallSites[i];
3295 const char *BeginTag;
3296 unsigned BeginNumber;
3298 if (!S.BeginLabel) {
3299 BeginTag = "eh_func_begin";
3300 BeginNumber = SubprogramCount;
3303 BeginNumber = S.BeginLabel;
3306 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3307 TAI->getShortenEHDataOn64Bit(), true);
3308 Asm->EOL("Region start");
3311 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3312 TAI->getShortenEHDataOn64Bit());
3314 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber,
3315 TAI->getShortenEHDataOn64Bit());
3317 Asm->EOL("Region length");
3320 if (TD->getPointerSize() == sizeof(int32_t) || TAI->getShortenEHDataOn64Bit())
3325 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3326 TAI->getShortenEHDataOn64Bit(), true);
3328 Asm->EOL("Landing pad");
3330 Asm->EmitULEB128Bytes(S.Action);
3334 // Emit the actions.
3335 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3336 ActionEntry &Action = Actions[I];
3338 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3339 Asm->EOL("TypeInfo index");
3340 Asm->EmitSLEB128Bytes(Action.NextAction);
3341 Asm->EOL("Next action");
3344 // Emit the type ids.
3345 for (unsigned M = TypeInfos.size(); M; --M) {
3346 GlobalVariable *GV = TypeInfos[M - 1];
3348 PrintRelDirective();
3351 O << Asm->getGlobalLinkName(GV);
3355 Asm->EOL("TypeInfo");
3358 // Emit the filter typeids.
3359 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3360 unsigned TypeID = FilterIds[j];
3361 Asm->EmitULEB128Bytes(TypeID);
3362 Asm->EOL("Filter TypeInfo index");
3365 Asm->EmitAlignment(2);
3369 //===--------------------------------------------------------------------===//
3370 // Main entry points.
3372 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3373 : Dwarf(OS, A, T, "eh")
3377 virtual ~DwarfException() {}
3379 /// SetModuleInfo - Set machine module information when it's known that pass
3380 /// manager has created it. Set by the target AsmPrinter.
3381 void SetModuleInfo(MachineModuleInfo *mmi) {
3385 /// BeginModule - Emit all exception information that should come prior to the
3387 void BeginModule(Module *M) {
3391 /// EndModule - Emit all exception information that should come after the
3394 if (!shouldEmit) return;
3396 const std::vector<Function *> Personalities = MMI->getPersonalities();
3397 for (unsigned i =0; i < Personalities.size(); ++i)
3398 EmitCommonEHFrame(Personalities[i], i);
3400 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3401 E = EHFrames.end(); I != E; ++I)
3405 /// BeginFunction - Gather pre-function exception information. Assumes being
3406 /// emitted immediately after the function entry point.
3407 void BeginFunction(MachineFunction *MF) {
3411 ExceptionHandling &&
3412 TAI->doesSupportExceptionHandling()) {
3414 // Assumes in correct section after the entry point.
3415 EmitLabel("eh_func_begin", ++SubprogramCount);
3419 /// EndFunction - Gather and emit post-function exception information.
3421 void EndFunction() {
3422 if (!shouldEmit) return;
3424 EmitLabel("eh_func_end", SubprogramCount);
3425 EmitExceptionTable();
3427 // Save EH frame information
3429 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3431 MMI->getPersonalityIndex(),
3432 MF->getFrameInfo()->hasCalls(),
3433 !MMI->getLandingPads().empty(),
3434 MMI->getFrameMoves(),
3435 MF->getFunction()));
3439 } // End of namespace llvm
3441 //===----------------------------------------------------------------------===//
3443 /// Emit - Print the abbreviation using the specified Dwarf writer.
3445 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3446 // Emit its Dwarf tag type.
3447 DD.getAsm()->EmitULEB128Bytes(Tag);
3448 DD.getAsm()->EOL(TagString(Tag));
3450 // Emit whether it has children DIEs.
3451 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3452 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3454 // For each attribute description.
3455 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3456 const DIEAbbrevData &AttrData = Data[i];
3458 // Emit attribute type.
3459 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3460 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3463 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3464 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3467 // Mark end of abbreviation.
3468 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3469 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3473 void DIEAbbrev::print(std::ostream &O) {
3474 O << "Abbreviation @"
3475 << std::hex << (intptr_t)this << std::dec
3479 << ChildrenString(ChildrenFlag)
3482 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3484 << AttributeString(Data[i].getAttribute())
3486 << FormEncodingString(Data[i].getForm())
3490 void DIEAbbrev::dump() { print(cerr); }
3493 //===----------------------------------------------------------------------===//
3496 void DIEValue::dump() {
3501 //===----------------------------------------------------------------------===//
3503 /// EmitValue - Emit integer of appropriate size.
3505 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3507 case DW_FORM_flag: // Fall thru
3508 case DW_FORM_ref1: // Fall thru
3509 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3510 case DW_FORM_ref2: // Fall thru
3511 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3512 case DW_FORM_ref4: // Fall thru
3513 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3514 case DW_FORM_ref8: // Fall thru
3515 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3516 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3517 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3518 default: assert(0 && "DIE Value form not supported yet"); break;
3522 /// SizeOf - Determine size of integer value in bytes.
3524 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3526 case DW_FORM_flag: // Fall thru
3527 case DW_FORM_ref1: // Fall thru
3528 case DW_FORM_data1: return sizeof(int8_t);
3529 case DW_FORM_ref2: // Fall thru
3530 case DW_FORM_data2: return sizeof(int16_t);
3531 case DW_FORM_ref4: // Fall thru
3532 case DW_FORM_data4: return sizeof(int32_t);
3533 case DW_FORM_ref8: // Fall thru
3534 case DW_FORM_data8: return sizeof(int64_t);
3535 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3536 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3537 default: assert(0 && "DIE Value form not supported yet"); break;
3542 //===----------------------------------------------------------------------===//
3544 /// EmitValue - Emit string value.
3546 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3547 DD.getAsm()->EmitString(String);
3550 //===----------------------------------------------------------------------===//
3552 /// EmitValue - Emit label value.
3554 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3555 bool IsSmall = Form == DW_FORM_data4;
3556 DD.EmitReference(Label, false, IsSmall);
3559 /// SizeOf - Determine size of label value in bytes.
3561 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3562 if (Form == DW_FORM_data4) return 4;
3563 return DD.getTargetData()->getPointerSize();
3566 //===----------------------------------------------------------------------===//
3568 /// EmitValue - Emit label value.
3570 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3571 bool IsSmall = Form == DW_FORM_data4;
3572 DD.EmitReference(Label, false, IsSmall);
3575 /// SizeOf - Determine size of label value in bytes.
3577 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3578 if (Form == DW_FORM_data4) return 4;
3579 return DD.getTargetData()->getPointerSize();
3582 //===----------------------------------------------------------------------===//
3584 /// EmitValue - Emit delta value.
3586 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3587 bool IsSmall = Form == DW_FORM_data4;
3588 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3591 /// SizeOf - Determine size of delta value in bytes.
3593 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3594 if (Form == DW_FORM_data4) return 4;
3595 return DD.getTargetData()->getPointerSize();
3598 //===----------------------------------------------------------------------===//
3600 /// EmitValue - Emit debug information entry offset.
3602 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3603 DD.getAsm()->EmitInt32(Entry->getOffset());
3606 //===----------------------------------------------------------------------===//
3608 /// ComputeSize - calculate the size of the block.
3610 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3612 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3614 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3615 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3621 /// EmitValue - Emit block data.
3623 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3625 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3626 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3627 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3628 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3629 default: assert(0 && "Improper form for block"); break;
3632 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3634 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3636 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3640 /// SizeOf - Determine size of block data in bytes.
3642 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3644 case DW_FORM_block1: return Size + sizeof(int8_t);
3645 case DW_FORM_block2: return Size + sizeof(int16_t);
3646 case DW_FORM_block4: return Size + sizeof(int32_t);
3647 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3648 default: assert(0 && "Improper form for block"); break;
3653 //===----------------------------------------------------------------------===//
3654 /// DIE Implementation
3657 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3661 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3663 void DIE::AddSiblingOffset() {
3664 DIEInteger *DI = new DIEInteger(0);
3665 Values.insert(Values.begin(), DI);
3666 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3669 /// Profile - Used to gather unique data for the value folding set.
3671 void DIE::Profile(FoldingSetNodeID &ID) {
3674 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3675 ID.AddPointer(Children[i]);
3677 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3678 ID.AddPointer(Values[j]);
3682 void DIE::print(std::ostream &O, unsigned IncIndent) {
3683 static unsigned IndentCount = 0;
3684 IndentCount += IncIndent;
3685 const std::string Indent(IndentCount, ' ');
3686 bool isBlock = Abbrev.getTag() == 0;
3691 << "0x" << std::hex << (intptr_t)this << std::dec
3692 << ", Offset: " << Offset
3693 << ", Size: " << Size
3697 << TagString(Abbrev.getTag())
3699 << ChildrenString(Abbrev.getChildrenFlag());
3701 O << "Size: " << Size;
3705 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3708 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3711 O << AttributeString(Data[i].getAttribute());
3713 O << "Blk[" << i << "]";
3716 << FormEncodingString(Data[i].getForm())
3718 Values[i]->print(O);
3723 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3724 Children[j]->print(O, 4);
3727 if (!isBlock) O << "\n";
3728 IndentCount -= IncIndent;
3736 //===----------------------------------------------------------------------===//
3737 /// DwarfWriter Implementation
3740 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3741 const TargetAsmInfo *T) {
3742 DE = new DwarfException(OS, A, T);
3743 DD = new DwarfDebug(OS, A, T);
3746 DwarfWriter::~DwarfWriter() {
3751 /// SetModuleInfo - Set machine module info when it's known that pass manager
3752 /// has created it. Set by the target AsmPrinter.
3753 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3754 DD->SetModuleInfo(MMI);
3755 DE->SetModuleInfo(MMI);
3758 /// BeginModule - Emit all Dwarf sections that should come prior to the
3760 void DwarfWriter::BeginModule(Module *M) {
3765 /// EndModule - Emit all Dwarf sections that should come after the content.
3767 void DwarfWriter::EndModule() {
3772 /// BeginFunction - Gather pre-function debug information. Assumes being
3773 /// emitted immediately after the function entry point.
3774 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3775 DE->BeginFunction(MF);
3776 DD->BeginFunction(MF);
3779 /// EndFunction - Gather and emit post-function debug information.
3781 void DwarfWriter::EndFunction() {
3785 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3786 // Clear function debug information.