1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source 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/FoldingSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/UniqueVector.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineLocation.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/DataTypes.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm::dwarf;
43 //===----------------------------------------------------------------------===//
45 /// Configuration values for initial hash set sizes (log2).
47 static const unsigned InitDiesSetSize = 9; // 512
48 static const unsigned InitAbbreviationsSetSize = 9; // 512
49 static const unsigned InitValuesSetSize = 9; // 512
51 //===----------------------------------------------------------------------===//
52 /// Forward declarations.
57 //===----------------------------------------------------------------------===//
58 /// DWLabel - Labels are used to track locations in the assembler file.
59 /// Labels appear in the form <prefix><Tag><Number>, where the tag is a
60 /// category of label (Ex. location) and number is a value unique in that
64 /// Tag - Label category tag. Should always be a staticly declared C string.
68 /// Number - Value to make label unique.
72 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
74 void Profile(FoldingSetNodeID &ID) const {
75 ID.AddString(std::string(Tag));
76 ID.AddInteger(Number);
80 void print(std::ostream *O) const {
83 void print(std::ostream &O) const {
85 if (Number) O << Number;
90 //===----------------------------------------------------------------------===//
91 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
92 /// Dwarf abbreviation.
95 /// Attribute - Dwarf attribute code.
99 /// Form - Dwarf form code.
104 DIEAbbrevData(unsigned A, unsigned F)
110 unsigned getAttribute() const { return Attribute; }
111 unsigned getForm() const { return Form; }
113 /// Profile - Used to gather unique data for the abbreviation folding set.
115 void Profile(FoldingSetNodeID &ID)const {
116 ID.AddInteger(Attribute);
121 //===----------------------------------------------------------------------===//
122 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
123 /// information object.
124 class DIEAbbrev : public FoldingSetNode {
126 /// Tag - Dwarf tag code.
130 /// Unique number for node.
134 /// ChildrenFlag - Dwarf children flag.
136 unsigned ChildrenFlag;
138 /// Data - Raw data bytes for abbreviation.
140 std::vector<DIEAbbrevData> Data;
144 DIEAbbrev(unsigned T, unsigned C)
152 unsigned getTag() const { return Tag; }
153 unsigned getNumber() const { return Number; }
154 unsigned getChildrenFlag() const { return ChildrenFlag; }
155 const std::vector<DIEAbbrevData> &getData() const { return Data; }
156 void setTag(unsigned T) { Tag = T; }
157 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
158 void setNumber(unsigned N) { Number = N; }
160 /// AddAttribute - Adds another set of attribute information to the
162 void AddAttribute(unsigned Attribute, unsigned Form) {
163 Data.push_back(DIEAbbrevData(Attribute, Form));
166 /// AddFirstAttribute - Adds a set of attribute information to the front
167 /// of the abbreviation.
168 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
169 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
172 /// Profile - Used to gather unique data for the abbreviation folding set.
174 void Profile(FoldingSetNodeID &ID) {
176 ID.AddInteger(ChildrenFlag);
178 // For each attribute description.
179 for (unsigned i = 0, N = Data.size(); i < N; ++i)
183 /// Emit - Print the abbreviation using the specified Dwarf writer.
185 void Emit(const DwarfDebug &DD) const;
188 void print(std::ostream *O) {
191 void print(std::ostream &O);
196 //===----------------------------------------------------------------------===//
197 /// DIE - A structured debug information entry. Has an abbreviation which
198 /// describes it's organization.
199 class DIE : public FoldingSetNode {
201 /// Abbrev - Buffer for constructing abbreviation.
205 /// Offset - Offset in debug info section.
209 /// Size - Size of instance + children.
215 std::vector<DIE *> Children;
217 /// Attributes values.
219 std::vector<DIEValue *> Values;
223 : Abbrev(Tag, DW_CHILDREN_no)
232 DIEAbbrev &getAbbrev() { return Abbrev; }
233 unsigned getAbbrevNumber() const {
234 return Abbrev.getNumber();
236 unsigned getTag() const { return Abbrev.getTag(); }
237 unsigned getOffset() const { return Offset; }
238 unsigned getSize() const { return Size; }
239 const std::vector<DIE *> &getChildren() const { return Children; }
240 std::vector<DIEValue *> &getValues() { return Values; }
241 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
242 void setOffset(unsigned O) { Offset = O; }
243 void setSize(unsigned S) { Size = S; }
245 /// AddValue - Add a value and attributes to a DIE.
247 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
248 Abbrev.AddAttribute(Attribute, Form);
249 Values.push_back(Value);
252 /// SiblingOffset - Return the offset of the debug information entry's
254 unsigned SiblingOffset() const { return Offset + Size; }
256 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
258 void AddSiblingOffset();
260 /// AddChild - Add a child to the DIE.
262 void AddChild(DIE *Child) {
263 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
264 Children.push_back(Child);
267 /// Detach - Detaches objects connected to it after copying.
273 /// Profile - Used to gather unique data for the value folding set.
275 void Profile(FoldingSetNodeID &ID) ;
278 void print(std::ostream *O, unsigned IncIndent = 0) {
279 if (O) print(*O, IncIndent);
281 void print(std::ostream &O, unsigned IncIndent = 0);
286 //===----------------------------------------------------------------------===//
287 /// DIEValue - A debug information entry value.
289 class DIEValue : public FoldingSetNode {
301 /// Type - Type of data stored in the value.
308 virtual ~DIEValue() {}
311 unsigned getType() const { return Type; }
313 // Implement isa/cast/dyncast.
314 static bool classof(const DIEValue *) { return true; }
316 /// EmitValue - Emit value via the Dwarf writer.
318 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
320 /// SizeOf - Return the size of a value in bytes.
322 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
324 /// Profile - Used to gather unique data for the value folding set.
326 virtual void Profile(FoldingSetNodeID &ID) = 0;
329 void print(std::ostream *O) {
332 virtual void print(std::ostream &O) = 0;
337 //===----------------------------------------------------------------------===//
338 /// DWInteger - An integer value DIE.
340 class DIEInteger : public DIEValue {
345 DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
347 // Implement isa/cast/dyncast.
348 static bool classof(const DIEInteger *) { return true; }
349 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
351 /// BestForm - Choose the best form for integer.
353 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
355 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
356 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
357 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
359 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
360 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
361 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
363 return DW_FORM_data8;
366 /// EmitValue - Emit integer of appropriate size.
368 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
370 /// SizeOf - Determine size of integer value in bytes.
372 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
374 /// Profile - Used to gather unique data for the value folding set.
376 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
377 ID.AddInteger(isInteger);
378 ID.AddInteger(Integer);
380 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
383 virtual void print(std::ostream &O) {
384 O << "Int: " << (int64_t)Integer
385 << " 0x" << std::hex << Integer << std::dec;
390 //===----------------------------------------------------------------------===//
391 /// DIEString - A string value DIE.
393 class DIEString : public DIEValue {
395 const std::string String;
397 DIEString(const std::string &S) : DIEValue(isString), String(S) {}
399 // Implement isa/cast/dyncast.
400 static bool classof(const DIEString *) { return true; }
401 static bool classof(const DIEValue *S) { return S->Type == isString; }
403 /// EmitValue - Emit string value.
405 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
407 /// SizeOf - Determine size of string value in bytes.
409 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
410 return String.size() + sizeof(char); // sizeof('\0');
413 /// Profile - Used to gather unique data for the value folding set.
415 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
416 ID.AddInteger(isString);
417 ID.AddString(String);
419 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
422 virtual void print(std::ostream &O) {
423 O << "Str: \"" << String << "\"";
428 //===----------------------------------------------------------------------===//
429 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
431 class DIEDwarfLabel : public DIEValue {
436 DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
438 // Implement isa/cast/dyncast.
439 static bool classof(const DIEDwarfLabel *) { return true; }
440 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
442 /// EmitValue - Emit label value.
444 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
446 /// SizeOf - Determine size of label value in bytes.
448 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
450 /// Profile - Used to gather unique data for the value folding set.
452 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
453 ID.AddInteger(isLabel);
456 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
459 virtual void print(std::ostream &O) {
467 //===----------------------------------------------------------------------===//
468 /// DIEObjectLabel - A label to an object in code or data.
470 class DIEObjectLabel : public DIEValue {
472 const std::string Label;
474 DIEObjectLabel(const std::string &L) : DIEValue(isAsIsLabel), Label(L) {}
476 // Implement isa/cast/dyncast.
477 static bool classof(const DIEObjectLabel *) { return true; }
478 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
480 /// EmitValue - Emit label value.
482 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
484 /// SizeOf - Determine size of label value in bytes.
486 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
488 /// Profile - Used to gather unique data for the value folding set.
490 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
491 ID.AddInteger(isAsIsLabel);
494 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
497 virtual void print(std::ostream &O) {
498 O << "Obj: " << Label;
503 //===----------------------------------------------------------------------===//
504 /// DIEDelta - A simple label difference DIE.
506 class DIEDelta : public DIEValue {
508 const DWLabel LabelHi;
509 const DWLabel LabelLo;
511 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
512 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
514 // Implement isa/cast/dyncast.
515 static bool classof(const DIEDelta *) { return true; }
516 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
518 /// EmitValue - Emit delta value.
520 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
522 /// SizeOf - Determine size of delta value in bytes.
524 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
526 /// Profile - Used to gather unique data for the value folding set.
528 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
529 const DWLabel &LabelLo) {
530 ID.AddInteger(isDelta);
534 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
537 virtual void print(std::ostream &O) {
546 //===----------------------------------------------------------------------===//
547 /// DIEntry - A pointer to another debug information entry. An instance of this
548 /// class can also be used as a proxy for a debug information entry not yet
549 /// defined (ie. types.)
550 class DIEntry : public DIEValue {
554 DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
556 // Implement isa/cast/dyncast.
557 static bool classof(const DIEntry *) { return true; }
558 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
560 /// EmitValue - Emit debug information entry offset.
562 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
564 /// SizeOf - Determine size of debug information entry in bytes.
566 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
567 return sizeof(int32_t);
570 /// Profile - Used to gather unique data for the value folding set.
572 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
573 ID.AddInteger(isEntry);
574 ID.AddPointer(Entry);
576 virtual void Profile(FoldingSetNodeID &ID) {
577 ID.AddInteger(isEntry);
580 ID.AddPointer(Entry);
587 virtual void print(std::ostream &O) {
588 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
593 //===----------------------------------------------------------------------===//
594 /// DIEBlock - A block of values. Primarily used for location expressions.
596 class DIEBlock : public DIEValue, public DIE {
598 unsigned Size; // Size in bytes excluding size header.
608 // Implement isa/cast/dyncast.
609 static bool classof(const DIEBlock *) { return true; }
610 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
612 /// ComputeSize - calculate the size of the block.
614 unsigned ComputeSize(DwarfDebug &DD);
616 /// BestForm - Choose the best form for data.
618 unsigned BestForm() const {
619 if ((unsigned char)Size == Size) return DW_FORM_block1;
620 if ((unsigned short)Size == Size) return DW_FORM_block2;
621 if ((unsigned int)Size == Size) return DW_FORM_block4;
622 return DW_FORM_block;
625 /// EmitValue - Emit block data.
627 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
629 /// SizeOf - Determine size of block data in bytes.
631 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
634 /// Profile - Used to gather unique data for the value folding set.
636 virtual void Profile(FoldingSetNodeID &ID) {
637 ID.AddInteger(isBlock);
642 virtual void print(std::ostream &O) {
649 //===----------------------------------------------------------------------===//
650 /// CompileUnit - This dwarf writer support class manages information associate
651 /// with a source file.
654 /// Desc - Compile unit debug descriptor.
656 CompileUnitDesc *Desc;
658 /// ID - File identifier for source.
662 /// Die - Compile unit debug information entry.
666 /// DescToDieMap - Tracks the mapping of unit level debug informaton
667 /// descriptors to debug information entries.
668 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
670 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
671 /// descriptors to debug information entries using a DIEntry proxy.
672 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
674 /// Globals - A map of globally visible named entities for this unit.
676 std::map<std::string, DIE *> Globals;
678 /// DiesSet - Used to uniquely define dies within the compile unit.
680 FoldingSet<DIE> DiesSet;
682 /// Dies - List of all dies in the compile unit.
684 std::vector<DIE *> Dies;
687 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
694 , DiesSet(InitDiesSetSize)
701 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
706 CompileUnitDesc *getDesc() const { return Desc; }
707 unsigned getID() const { return ID; }
708 DIE* getDie() const { return Die; }
709 std::map<std::string, DIE *> &getGlobals() { return Globals; }
711 /// hasContent - Return true if this compile unit has something to write out.
713 bool hasContent() const {
714 return !Die->getChildren().empty();
717 /// AddGlobal - Add a new global entity to the compile unit.
719 void AddGlobal(const std::string &Name, DIE *Die) {
723 /// getDieMapSlotFor - Returns the debug information entry map slot for the
724 /// specified debug descriptor.
725 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
726 return DescToDieMap[DID];
729 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
730 /// specified debug descriptor.
731 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
732 return DescToDIEntryMap[DID];
735 /// AddDie - Adds or interns the DIE to the compile unit.
737 DIE *AddDie(DIE &Buffer) {
741 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
744 Die = new DIE(Buffer);
745 DiesSet.InsertNode(Die, Where);
746 this->Die->AddChild(Die);
754 //===----------------------------------------------------------------------===//
755 /// Dwarf - Emits general Dwarf directives.
761 //===--------------------------------------------------------------------===//
762 // Core attributes used by the Dwarf writer.
766 /// O - Stream to .s file.
770 /// Asm - Target of Dwarf emission.
774 /// TAI - Target Asm Printer.
775 const TargetAsmInfo *TAI;
777 /// TD - Target data.
778 const TargetData *TD;
780 /// RI - Register Information.
781 const MRegisterInfo *RI;
783 /// M - Current module.
787 /// MF - Current machine function.
791 /// MMI - Collected machine module information.
793 MachineModuleInfo *MMI;
795 /// SubprogramCount - The running count of functions being compiled.
797 unsigned SubprogramCount;
800 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
804 , TD(Asm->TM.getTargetData())
805 , RI(Asm->TM.getRegisterInfo())
816 //===--------------------------------------------------------------------===//
819 AsmPrinter *getAsm() const { return Asm; }
820 MachineModuleInfo *getMMI() const { return MMI; }
821 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
823 /// PrintLabelName - Print label name in form used by Dwarf writer.
825 void PrintLabelName(DWLabel Label) const {
826 PrintLabelName(Label.Tag, Label.Number);
828 void PrintLabelName(const char *Tag, unsigned Number,
829 bool isInSection = false) const {
830 if (isInSection && TAI->getDwarfSectionOffsetDirective())
831 O << TAI->getDwarfSectionOffsetDirective() << Tag;
833 O << TAI->getPrivateGlobalPrefix() << Tag;
834 if (Number) O << Number;
837 /// EmitLabel - Emit location label for internal use by Dwarf.
839 void EmitLabel(DWLabel Label) const {
840 EmitLabel(Label.Tag, Label.Number);
842 void EmitLabel(const char *Tag, unsigned Number) const {
843 PrintLabelName(Tag, Number);
847 /// EmitReference - Emit a reference to a label.
849 void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
850 EmitReference(Label.Tag, Label.Number, IsPCRelative);
852 void EmitReference(const char *Tag, unsigned Number,
853 bool IsPCRelative = false) const {
854 if (TAI->getAddressSize() == sizeof(int32_t))
855 O << TAI->getData32bitsDirective();
857 O << TAI->getData64bitsDirective();
859 PrintLabelName(Tag, Number);
861 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
863 void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
864 if (TAI->getAddressSize() == sizeof(int32_t))
865 O << TAI->getData32bitsDirective();
867 O << TAI->getData64bitsDirective();
871 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
874 /// EmitDifference - Emit the difference between two labels. Some
875 /// assemblers do not behave with absolute expressions with data directives,
876 /// so there is an option (needsSet) to use an intermediary set expression.
877 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
878 bool IsSmall = false) {
879 EmitDifference(LabelHi.Tag, LabelHi.Number,
880 LabelLo.Tag, LabelLo.Number,
883 void EmitDifference(const char *TagHi, unsigned NumberHi,
884 const char *TagLo, unsigned NumberLo,
885 bool IsSmall = false) {
886 if (TAI->needsSet()) {
888 PrintLabelName("set", SetCounter);
890 PrintLabelName(TagHi, NumberHi);
892 PrintLabelName(TagLo, NumberLo);
895 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
896 O << TAI->getData32bitsDirective();
898 O << TAI->getData64bitsDirective();
900 PrintLabelName("set", SetCounter);
904 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
905 O << TAI->getData32bitsDirective();
907 O << TAI->getData64bitsDirective();
909 PrintLabelName(TagHi, NumberHi);
911 PrintLabelName(TagLo, NumberLo);
915 void EmitSectionOffset(const char* Label, const char* Section,
916 unsigned LabelNumber, unsigned SectionNumber,
917 bool IsSmall = false) {
918 if (TAI->needsSet()) {
920 PrintLabelName("set", SetCounter);
922 PrintLabelName(Label, LabelNumber, true);
923 if (!TAI->isAbsoluteSectionOffsets()) {
925 PrintLabelName(Section, SectionNumber);
929 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
930 O << TAI->getData32bitsDirective();
932 O << TAI->getData64bitsDirective();
934 PrintLabelName("set", SetCounter);
937 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
938 O << TAI->getData32bitsDirective();
940 O << TAI->getData64bitsDirective();
942 PrintLabelName(Label, LabelNumber, true);
943 if (!TAI->isAbsoluteSectionOffsets()) {
945 PrintLabelName(Section, SectionNumber);
950 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
952 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
953 std::vector<MachineMove> &Moves) {
955 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
956 TargetFrameInfo::StackGrowsUp ?
957 TAI->getAddressSize() : -TAI->getAddressSize();
958 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
960 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
961 MachineMove &Move = Moves[i];
962 unsigned LabelID = Move.getLabelID();
965 LabelID = MMI->MappedLabel(LabelID);
967 // Throw out move if the label is invalid.
968 if (!LabelID) continue;
971 const MachineLocation &Dst = Move.getDestination();
972 const MachineLocation &Src = Move.getSource();
974 // Advance row if new location.
975 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
976 Asm->EmitInt8(DW_CFA_advance_loc4);
977 Asm->EOL("DW_CFA_advance_loc4");
978 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
981 BaseLabelID = LabelID;
987 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
988 if (!Src.isRegister()) {
989 if (Src.getRegister() == MachineLocation::VirtualFP) {
990 Asm->EmitInt8(DW_CFA_def_cfa_offset);
991 Asm->EOL("DW_CFA_def_cfa_offset");
993 Asm->EmitInt8(DW_CFA_def_cfa);
994 Asm->EOL("DW_CFA_def_cfa");
995 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
996 Asm->EOL("Register");
999 int Offset = -Src.getOffset();
1001 Asm->EmitULEB128Bytes(Offset);
1004 assert(0 && "Machine move no supported yet.");
1006 } else if (Src.isRegister() &&
1007 Src.getRegister() == MachineLocation::VirtualFP) {
1008 if (Dst.isRegister()) {
1009 Asm->EmitInt8(DW_CFA_def_cfa_register);
1010 Asm->EOL("DW_CFA_def_cfa_register");
1011 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1012 Asm->EOL("Register");
1014 assert(0 && "Machine move no supported yet.");
1017 unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1018 int Offset = Dst.getOffset() / stackGrowth;
1021 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1022 Asm->EOL("DW_CFA_offset_extended_sf");
1023 Asm->EmitULEB128Bytes(Reg);
1025 Asm->EmitSLEB128Bytes(Offset);
1027 } else if (Reg < 64) {
1028 Asm->EmitInt8(DW_CFA_offset + Reg);
1029 Asm->EOL("DW_CFA_offset + Reg");
1030 Asm->EmitULEB128Bytes(Offset);
1033 Asm->EmitInt8(DW_CFA_offset_extended);
1034 Asm->EOL("DW_CFA_offset_extended");
1035 Asm->EmitULEB128Bytes(Reg);
1037 Asm->EmitULEB128Bytes(Offset);
1046 //===----------------------------------------------------------------------===//
1047 /// DwarfDebug - Emits Dwarf debug directives.
1049 class DwarfDebug : public Dwarf {
1052 //===--------------------------------------------------------------------===//
1053 // Attributes used to construct specific Dwarf sections.
1056 /// CompileUnits - All the compile units involved in this build. The index
1057 /// of each entry in this vector corresponds to the sources in MMI.
1058 std::vector<CompileUnit *> CompileUnits;
1060 /// AbbreviationsSet - Used to uniquely define abbreviations.
1062 FoldingSet<DIEAbbrev> AbbreviationsSet;
1064 /// Abbreviations - A list of all the unique abbreviations in use.
1066 std::vector<DIEAbbrev *> Abbreviations;
1068 /// ValuesSet - Used to uniquely define values.
1070 FoldingSet<DIEValue> ValuesSet;
1072 /// Values - A list of all the unique values in use.
1074 std::vector<DIEValue *> Values;
1076 /// StringPool - A UniqueVector of strings used by indirect references.
1078 UniqueVector<std::string> StringPool;
1080 /// UnitMap - Map debug information descriptor to compile unit.
1082 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1084 /// SectionMap - Provides a unique id per text section.
1086 UniqueVector<std::string> SectionMap;
1088 /// SectionSourceLines - Tracks line numbers per text section.
1090 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1092 /// didInitial - Flag to indicate if initial emission has been done.
1096 /// shouldEmit - Flag to indicate if debug information should be emitted.
1102 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1104 bool ShouldEmitDwarf() const { return shouldEmit; }
1106 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1108 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1109 // Profile the node so that we can make it unique.
1110 FoldingSetNodeID ID;
1113 // Check the set for priors.
1114 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1116 // If it's newly added.
1117 if (InSet == &Abbrev) {
1118 // Add to abbreviation list.
1119 Abbreviations.push_back(&Abbrev);
1120 // Assign the vector position + 1 as its number.
1121 Abbrev.setNumber(Abbreviations.size());
1123 // Assign existing abbreviation number.
1124 Abbrev.setNumber(InSet->getNumber());
1128 /// NewString - Add a string to the constant pool and returns a label.
1130 DWLabel NewString(const std::string &String) {
1131 unsigned StringID = StringPool.insert(String);
1132 return DWLabel("string", StringID);
1135 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1137 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1141 FoldingSetNodeID ID;
1142 DIEntry::Profile(ID, Entry);
1144 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1146 if (Value) return Value;
1148 Value = new DIEntry(Entry);
1149 ValuesSet.InsertNode(Value, Where);
1151 Value = new DIEntry(Entry);
1154 Values.push_back(Value);
1158 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1160 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1161 Value->Entry = Entry;
1162 // Add to values set if not already there. If it is, we merely have a
1163 // duplicate in the values list (no harm.)
1164 ValuesSet.GetOrInsertNode(Value);
1167 /// AddUInt - Add an unsigned integer attribute data and value.
1169 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1170 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1172 FoldingSetNodeID ID;
1173 DIEInteger::Profile(ID, Integer);
1175 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1177 Value = new DIEInteger(Integer);
1178 ValuesSet.InsertNode(Value, Where);
1179 Values.push_back(Value);
1182 Die->AddValue(Attribute, Form, Value);
1185 /// AddSInt - Add an signed integer attribute data and value.
1187 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1188 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1190 FoldingSetNodeID ID;
1191 DIEInteger::Profile(ID, (uint64_t)Integer);
1193 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1195 Value = new DIEInteger(Integer);
1196 ValuesSet.InsertNode(Value, Where);
1197 Values.push_back(Value);
1200 Die->AddValue(Attribute, Form, Value);
1203 /// AddString - Add a std::string attribute data and value.
1205 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1206 const std::string &String) {
1207 FoldingSetNodeID ID;
1208 DIEString::Profile(ID, String);
1210 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1212 Value = new DIEString(String);
1213 ValuesSet.InsertNode(Value, Where);
1214 Values.push_back(Value);
1217 Die->AddValue(Attribute, Form, Value);
1220 /// AddLabel - Add a Dwarf label attribute data and value.
1222 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1223 const DWLabel &Label) {
1224 FoldingSetNodeID ID;
1225 DIEDwarfLabel::Profile(ID, Label);
1227 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1229 Value = new DIEDwarfLabel(Label);
1230 ValuesSet.InsertNode(Value, Where);
1231 Values.push_back(Value);
1234 Die->AddValue(Attribute, Form, Value);
1237 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1239 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1240 const std::string &Label) {
1241 FoldingSetNodeID ID;
1242 DIEObjectLabel::Profile(ID, Label);
1244 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1246 Value = new DIEObjectLabel(Label);
1247 ValuesSet.InsertNode(Value, Where);
1248 Values.push_back(Value);
1251 Die->AddValue(Attribute, Form, Value);
1254 /// AddDelta - Add a label delta attribute data and value.
1256 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1257 const DWLabel &Hi, const DWLabel &Lo) {
1258 FoldingSetNodeID ID;
1259 DIEDelta::Profile(ID, Hi, Lo);
1261 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1263 Value = new DIEDelta(Hi, Lo);
1264 ValuesSet.InsertNode(Value, Where);
1265 Values.push_back(Value);
1268 Die->AddValue(Attribute, Form, Value);
1271 /// AddDIEntry - Add a DIE attribute data and value.
1273 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1274 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1277 /// AddBlock - Add block data.
1279 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1280 Block->ComputeSize(*this);
1281 FoldingSetNodeID ID;
1284 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1287 ValuesSet.InsertNode(Value, Where);
1288 Values.push_back(Value);
1293 Die->AddValue(Attribute, Block->BestForm(), Value);
1298 /// AddSourceLine - Add location information to specified debug information
1300 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1302 CompileUnit *FileUnit = FindCompileUnit(File);
1303 unsigned FileID = FileUnit->getID();
1304 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1305 AddUInt(Die, DW_AT_decl_line, 0, Line);
1309 /// AddAddress - Add an address attribute to a die based on the location
1311 void AddAddress(DIE *Die, unsigned Attribute,
1312 const MachineLocation &Location) {
1313 unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1314 DIEBlock *Block = new DIEBlock();
1316 if (Location.isRegister()) {
1318 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1320 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1321 AddUInt(Block, 0, DW_FORM_udata, Reg);
1325 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1327 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1328 AddUInt(Block, 0, DW_FORM_udata, Reg);
1330 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1333 AddBlock(Die, Attribute, 0, Block);
1336 /// AddBasicType - Add a new basic type attribute to the specified entity.
1338 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1339 const std::string &Name,
1340 unsigned Encoding, unsigned Size) {
1341 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1342 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1345 /// ConstructBasicType - Construct a new basic type.
1347 DIE *ConstructBasicType(CompileUnit *Unit,
1348 const std::string &Name,
1349 unsigned Encoding, unsigned Size) {
1350 DIE Buffer(DW_TAG_base_type);
1351 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1352 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1353 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1354 return Unit->AddDie(Buffer);
1357 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1359 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1360 DIE *Die = ConstructPointerType(Unit, Name);
1361 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1364 /// ConstructPointerType - Construct a new pointer type.
1366 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1367 DIE Buffer(DW_TAG_pointer_type);
1368 AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1369 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1370 return Unit->AddDie(Buffer);
1373 /// AddType - Add a new type attribute to the specified entity.
1375 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1377 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1379 // Check for pre-existence.
1380 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1382 // If it exists then use the existing value.
1384 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1388 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1389 // FIXME - Not sure why programs and variables are coming through here.
1390 // Short cut for handling subprogram types (not really a TyDesc.)
1391 AddPointerType(Entity, Unit, SubprogramTy->getName());
1392 } else if (GlobalVariableDesc *GlobalTy =
1393 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1394 // FIXME - Not sure why programs and variables are coming through here.
1395 // Short cut for handling global variable types (not really a TyDesc.)
1396 AddPointerType(Entity, Unit, GlobalTy->getName());
1399 Slot = NewDIEntry();
1402 DIE Buffer(DW_TAG_base_type);
1403 ConstructType(Buffer, TyDesc, Unit);
1405 // Add debug information entry to entity and unit.
1406 DIE *Die = Unit->AddDie(Buffer);
1407 SetDIEntry(Slot, Die);
1408 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1413 /// ConstructType - Adds all the required attributes to the type.
1415 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1416 // Get core information.
1417 const std::string &Name = TyDesc->getName();
1418 uint64_t Size = TyDesc->getSize() >> 3;
1420 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1421 // Fundamental types like int, float, bool
1422 Buffer.setTag(DW_TAG_base_type);
1423 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1424 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1426 unsigned Tag = DerivedTy->getTag();
1427 // FIXME - Workaround for templates.
1428 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1429 // Pointers, typedefs et al.
1431 // Map to main type, void will not have a type.
1432 if (TypeDesc *FromTy = DerivedTy->getFromType())
1433 AddType(&Buffer, FromTy, Unit);
1434 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1436 unsigned Tag = CompTy->getTag();
1438 // Set tag accordingly.
1439 if (Tag == DW_TAG_vector_type)
1440 Buffer.setTag(DW_TAG_array_type);
1444 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1447 case DW_TAG_vector_type:
1448 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1450 case DW_TAG_array_type: {
1451 // Add element type.
1452 if (TypeDesc *FromTy = CompTy->getFromType())
1453 AddType(&Buffer, FromTy, Unit);
1455 // Don't emit size attribute.
1458 // Construct an anonymous type for index type.
1459 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1462 // Add subranges to array type.
1463 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1464 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1465 int64_t Lo = SRD->getLo();
1466 int64_t Hi = SRD->getHi();
1467 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1469 // If a range is available.
1471 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1472 // Only add low if non-zero.
1473 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1474 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1477 Buffer.AddChild(Subrange);
1481 case DW_TAG_structure_type:
1482 case DW_TAG_union_type: {
1483 // Add elements to structure type.
1484 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1485 DebugInfoDesc *Element = Elements[i];
1487 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1488 // Add field or base class.
1490 unsigned Tag = MemberDesc->getTag();
1492 // Extract the basic information.
1493 const std::string &Name = MemberDesc->getName();
1494 uint64_t Size = MemberDesc->getSize();
1495 uint64_t Align = MemberDesc->getAlign();
1496 uint64_t Offset = MemberDesc->getOffset();
1498 // Construct member debug information entry.
1499 DIE *Member = new DIE(Tag);
1501 // Add name if not "".
1503 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1504 // Add location if available.
1505 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1507 // Most of the time the field info is the same as the members.
1508 uint64_t FieldSize = Size;
1509 uint64_t FieldAlign = Align;
1510 uint64_t FieldOffset = Offset;
1512 // Set the member type.
1513 TypeDesc *FromTy = MemberDesc->getFromType();
1514 AddType(Member, FromTy, Unit);
1516 // Walk up typedefs until a real size is found.
1518 if (FromTy->getTag() != DW_TAG_typedef) {
1519 FieldSize = FromTy->getSize();
1520 FieldAlign = FromTy->getSize();
1524 FromTy = dyn_cast<DerivedTypeDesc>(FromTy)->getFromType();
1527 // Unless we have a bit field.
1528 if (Tag == DW_TAG_member && FieldSize != Size) {
1529 // Construct the alignment mask.
1530 uint64_t AlignMask = ~(FieldAlign - 1);
1531 // Determine the high bit + 1 of the declared size.
1532 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1533 // Work backwards to determine the base offset of the field.
1534 FieldOffset = HiMark - FieldSize;
1535 // Now normalize offset to the field.
1536 Offset -= FieldOffset;
1538 // Maybe we need to work from the other end.
1539 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1541 // Add size and offset.
1542 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1543 AddUInt(Member, DW_AT_bit_size, 0, Size);
1544 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1547 // Add computation for offset.
1548 DIEBlock *Block = new DIEBlock();
1549 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1550 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1551 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1553 // Add accessibility (public default unless is base class.
1554 if (MemberDesc->isProtected()) {
1555 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1556 } else if (MemberDesc->isPrivate()) {
1557 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1558 } else if (Tag == DW_TAG_inheritance) {
1559 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1562 Buffer.AddChild(Member);
1563 } else if (GlobalVariableDesc *StaticDesc =
1564 dyn_cast<GlobalVariableDesc>(Element)) {
1565 // Add static member.
1567 // Construct member debug information entry.
1568 DIE *Static = new DIE(DW_TAG_variable);
1570 // Add name and mangled name.
1571 const std::string &Name = StaticDesc->getName();
1572 const std::string &LinkageName = StaticDesc->getLinkageName();
1573 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1574 if (!LinkageName.empty()) {
1575 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1580 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1583 if (TypeDesc *StaticTy = StaticDesc->getType())
1584 AddType(Static, StaticTy, Unit);
1587 if (!StaticDesc->isStatic())
1588 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1589 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1591 Buffer.AddChild(Static);
1592 } else if (SubprogramDesc *MethodDesc =
1593 dyn_cast<SubprogramDesc>(Element)) {
1594 // Add member function.
1596 // Construct member debug information entry.
1597 DIE *Method = new DIE(DW_TAG_subprogram);
1599 // Add name and mangled name.
1600 const std::string &Name = MethodDesc->getName();
1601 const std::string &LinkageName = MethodDesc->getLinkageName();
1603 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1604 bool IsCTor = TyDesc->getName() == Name;
1606 if (!LinkageName.empty()) {
1607 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1612 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1615 if (CompositeTypeDesc *MethodTy =
1616 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1617 // Get argument information.
1618 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1623 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1627 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1628 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1629 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1630 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1631 Method->AddChild(Arg);
1636 if (!MethodDesc->isStatic())
1637 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1638 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1640 Buffer.AddChild(Method);
1645 case DW_TAG_enumeration_type: {
1646 // Add enumerators to enumeration type.
1647 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1648 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1649 const std::string &Name = ED->getName();
1650 int64_t Value = ED->getValue();
1651 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1652 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1653 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1654 Buffer.AddChild(Enumerator);
1659 case DW_TAG_subroutine_type: {
1660 // Add prototype flag.
1661 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1663 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1666 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1667 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1668 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1669 Buffer.AddChild(Arg);
1678 // Add size if non-zero (derived types don't have a size.)
1679 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1680 // Add name if not anonymous or intermediate type.
1681 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1682 // Add source line info if available.
1683 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1686 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1688 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1689 // Construct debug information entry.
1690 DIE *Die = new DIE(DW_TAG_compile_unit);
1691 if (TAI->isAbsoluteSectionOffsets())
1692 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1694 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1695 DWLabel("section_line", 0));
1696 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1697 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1698 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1699 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1701 // Construct compile unit.
1702 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1704 // Add Unit to compile unit map.
1705 DescToUnitMap[UnitDesc] = Unit;
1710 /// GetBaseCompileUnit - Get the main compile unit.
1712 CompileUnit *GetBaseCompileUnit() const {
1713 CompileUnit *Unit = CompileUnits[0];
1714 assert(Unit && "Missing compile unit.");
1718 /// FindCompileUnit - Get the compile unit for the given descriptor.
1720 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1721 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1722 assert(Unit && "Missing compile unit.");
1726 /// NewGlobalVariable - Add a new global variable DIE.
1728 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1729 // Get the compile unit context.
1730 CompileUnitDesc *UnitDesc =
1731 static_cast<CompileUnitDesc *>(GVD->getContext());
1732 CompileUnit *Unit = GetBaseCompileUnit();
1734 // Check for pre-existence.
1735 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1736 if (Slot) return Slot;
1738 // Get the global variable itself.
1739 GlobalVariable *GV = GVD->getGlobalVariable();
1741 const std::string &Name = GVD->getName();
1742 const std::string &FullName = GVD->getFullName();
1743 const std::string &LinkageName = GVD->getLinkageName();
1744 // Create the global's variable DIE.
1745 DIE *VariableDie = new DIE(DW_TAG_variable);
1746 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1747 if (!LinkageName.empty()) {
1748 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1751 AddType(VariableDie, GVD->getType(), Unit);
1752 if (!GVD->isStatic())
1753 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1755 // Add source line info if available.
1756 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1759 DIEBlock *Block = new DIEBlock();
1760 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1761 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1762 AddBlock(VariableDie, DW_AT_location, 0, Block);
1767 // Add to context owner.
1768 Unit->getDie()->AddChild(VariableDie);
1770 // Expose as global.
1771 // FIXME - need to check external flag.
1772 Unit->AddGlobal(FullName, VariableDie);
1777 /// NewSubprogram - Add a new subprogram DIE.
1779 DIE *NewSubprogram(SubprogramDesc *SPD) {
1780 // Get the compile unit context.
1781 CompileUnitDesc *UnitDesc =
1782 static_cast<CompileUnitDesc *>(SPD->getContext());
1783 CompileUnit *Unit = GetBaseCompileUnit();
1785 // Check for pre-existence.
1786 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1787 if (Slot) return Slot;
1789 // Gather the details (simplify add attribute code.)
1790 const std::string &Name = SPD->getName();
1791 const std::string &FullName = SPD->getFullName();
1792 const std::string &LinkageName = SPD->getLinkageName();
1794 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1795 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1796 if (!LinkageName.empty()) {
1797 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1800 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1801 if (!SPD->isStatic())
1802 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1803 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1805 // Add source line info if available.
1806 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1809 Slot = SubprogramDie;
1811 // Add to context owner.
1812 Unit->getDie()->AddChild(SubprogramDie);
1814 // Expose as global.
1815 Unit->AddGlobal(FullName, SubprogramDie);
1817 return SubprogramDie;
1820 /// NewScopeVariable - Create a new scope variable.
1822 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1823 // Get the descriptor.
1824 VariableDesc *VD = DV->getDesc();
1826 // Translate tag to proper Dwarf tag. The result variable is dropped for
1829 switch (VD->getTag()) {
1830 case DW_TAG_return_variable: return NULL;
1831 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1832 case DW_TAG_auto_variable: // fall thru
1833 default: Tag = DW_TAG_variable; break;
1836 // Define variable debug information entry.
1837 DIE *VariableDie = new DIE(Tag);
1838 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1840 // Add source line info if available.
1841 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1843 // Add variable type.
1844 AddType(VariableDie, VD->getType(), Unit);
1846 // Add variable address.
1847 MachineLocation Location;
1848 RI->getLocation(*MF, DV->getFrameIndex(), Location);
1849 AddAddress(VariableDie, DW_AT_location, Location);
1854 /// ConstructScope - Construct the components of a scope.
1856 void ConstructScope(DebugScope *ParentScope,
1857 unsigned ParentStartID, unsigned ParentEndID,
1858 DIE *ParentDie, CompileUnit *Unit) {
1859 // Add variables to scope.
1860 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1861 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1862 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1863 if (VariableDie) ParentDie->AddChild(VariableDie);
1866 // Add nested scopes.
1867 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1868 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1869 // Define the Scope debug information entry.
1870 DebugScope *Scope = Scopes[j];
1871 // FIXME - Ignore inlined functions for the time being.
1872 if (!Scope->getParent()) continue;
1874 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1875 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1877 // Ignore empty scopes.
1878 if (StartID == EndID && StartID != 0) continue;
1879 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1881 if (StartID == ParentStartID && EndID == ParentEndID) {
1882 // Just add stuff to the parent scope.
1883 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1885 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1887 // Add the scope bounds.
1889 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1890 DWLabel("label", StartID));
1892 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1893 DWLabel("func_begin", SubprogramCount));
1896 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1897 DWLabel("label", EndID));
1899 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1900 DWLabel("func_end", SubprogramCount));
1903 // Add the scope contents.
1904 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1905 ParentDie->AddChild(ScopeDie);
1910 /// ConstructRootScope - Construct the scope for the subprogram.
1912 void ConstructRootScope(DebugScope *RootScope) {
1913 // Exit if there is no root scope.
1914 if (!RootScope) return;
1916 // Get the subprogram debug information entry.
1917 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1919 // Get the compile unit context.
1920 CompileUnit *Unit = GetBaseCompileUnit();
1922 // Get the subprogram die.
1923 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1924 assert(SPDie && "Missing subprogram descriptor");
1926 // Add the function bounds.
1927 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1928 DWLabel("func_begin", SubprogramCount));
1929 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1930 DWLabel("func_end", SubprogramCount));
1931 MachineLocation Location(RI->getFrameRegister(*MF));
1932 AddAddress(SPDie, DW_AT_frame_base, Location);
1934 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1937 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1938 /// tools to recognize the object file contains Dwarf information.
1939 void EmitInitial() {
1940 // Check to see if we already emitted intial headers.
1941 if (didInitial) return;
1944 // Dwarf sections base addresses.
1945 if (TAI->getDwarfRequiresFrameSection()) {
1946 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1947 EmitLabel("section_frame", 0);
1949 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1950 EmitLabel("section_info", 0);
1951 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1952 EmitLabel("section_abbrev", 0);
1953 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1954 EmitLabel("section_aranges", 0);
1955 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1956 EmitLabel("section_macinfo", 0);
1957 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1958 EmitLabel("section_line", 0);
1959 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1960 EmitLabel("section_loc", 0);
1961 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1962 EmitLabel("section_pubnames", 0);
1963 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1964 EmitLabel("section_str", 0);
1965 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1966 EmitLabel("section_ranges", 0);
1968 Asm->SwitchToTextSection(TAI->getTextSection());
1969 EmitLabel("text_begin", 0);
1970 Asm->SwitchToDataSection(TAI->getDataSection());
1971 EmitLabel("data_begin", 0);
1973 // Emit common frame information.
1974 EmitInitialDebugFrame();
1977 /// EmitDIE - Recusively Emits a debug information entry.
1979 void EmitDIE(DIE *Die) {
1980 // Get the abbreviation for this DIE.
1981 unsigned AbbrevNumber = Die->getAbbrevNumber();
1982 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1986 // Emit the code (index) for the abbreviation.
1987 Asm->EmitULEB128Bytes(AbbrevNumber);
1988 Asm->EOL(std::string("Abbrev [" +
1989 utostr(AbbrevNumber) +
1990 "] 0x" + utohexstr(Die->getOffset()) +
1991 ":0x" + utohexstr(Die->getSize()) + " " +
1992 TagString(Abbrev->getTag())));
1994 std::vector<DIEValue *> &Values = Die->getValues();
1995 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1997 // Emit the DIE attribute values.
1998 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1999 unsigned Attr = AbbrevData[i].getAttribute();
2000 unsigned Form = AbbrevData[i].getForm();
2001 assert(Form && "Too many attributes for DIE (check abbreviation)");
2004 case DW_AT_sibling: {
2005 Asm->EmitInt32(Die->SiblingOffset());
2009 // Emit an attribute using the defined form.
2010 Values[i]->EmitValue(*this, Form);
2015 Asm->EOL(AttributeString(Attr));
2018 // Emit the DIE children if any.
2019 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2020 const std::vector<DIE *> &Children = Die->getChildren();
2022 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2023 EmitDIE(Children[j]);
2026 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2030 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2032 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2033 // Get the children.
2034 const std::vector<DIE *> &Children = Die->getChildren();
2036 // If not last sibling and has children then add sibling offset attribute.
2037 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2039 // Record the abbreviation.
2040 AssignAbbrevNumber(Die->getAbbrev());
2042 // Get the abbreviation for this DIE.
2043 unsigned AbbrevNumber = Die->getAbbrevNumber();
2044 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2047 Die->setOffset(Offset);
2049 // Start the size with the size of abbreviation code.
2050 Offset += Asm->SizeULEB128(AbbrevNumber);
2052 const std::vector<DIEValue *> &Values = Die->getValues();
2053 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2055 // Size the DIE attribute values.
2056 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2057 // Size attribute value.
2058 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2061 // Size the DIE children if any.
2062 if (!Children.empty()) {
2063 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2064 "Children flag not set");
2066 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2067 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2070 // End of children marker.
2071 Offset += sizeof(int8_t);
2074 Die->setSize(Offset - Die->getOffset());
2078 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2080 void SizeAndOffsets() {
2081 // Process base compile unit.
2082 CompileUnit *Unit = GetBaseCompileUnit();
2083 // Compute size of compile unit header
2084 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2085 sizeof(int16_t) + // DWARF version number
2086 sizeof(int32_t) + // Offset Into Abbrev. Section
2087 sizeof(int8_t); // Pointer Size (in bytes)
2088 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2091 /// EmitDebugInfo - Emit the debug info section.
2093 void EmitDebugInfo() {
2094 // Start debug info section.
2095 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2097 CompileUnit *Unit = GetBaseCompileUnit();
2098 DIE *Die = Unit->getDie();
2099 // Emit the compile units header.
2100 EmitLabel("info_begin", Unit->getID());
2101 // Emit size of content not including length itself
2102 unsigned ContentSize = Die->getSize() +
2103 sizeof(int16_t) + // DWARF version number
2104 sizeof(int32_t) + // Offset Into Abbrev. Section
2105 sizeof(int8_t) + // Pointer Size (in bytes)
2106 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2108 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2109 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2110 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true);
2111 Asm->EOL("Offset Into Abbrev. Section");
2112 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2115 // FIXME - extra padding for gdb bug.
2116 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2117 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2118 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2119 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2120 EmitLabel("info_end", Unit->getID());
2125 /// EmitAbbreviations - Emit the abbreviation section.
2127 void EmitAbbreviations() const {
2128 // Check to see if it is worth the effort.
2129 if (!Abbreviations.empty()) {
2130 // Start the debug abbrev section.
2131 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2133 EmitLabel("abbrev_begin", 0);
2135 // For each abbrevation.
2136 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2137 // Get abbreviation data
2138 const DIEAbbrev *Abbrev = Abbreviations[i];
2140 // Emit the abbrevations code (base 1 index.)
2141 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2142 Asm->EOL("Abbreviation Code");
2144 // Emit the abbreviations data.
2145 Abbrev->Emit(*this);
2150 // Mark end of abbreviations.
2151 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2153 EmitLabel("abbrev_end", 0);
2159 /// EmitDebugLines - Emit source line information.
2161 void EmitDebugLines() {
2162 // Minimum line delta, thus ranging from -10..(255-10).
2163 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2164 // Maximum line delta, thus ranging from -10..(255-10).
2165 const int MaxLineDelta = 255 + MinLineDelta;
2167 // Start the dwarf line section.
2168 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2170 // Construct the section header.
2172 EmitDifference("line_end", 0, "line_begin", 0, true);
2173 Asm->EOL("Length of Source Line Info");
2174 EmitLabel("line_begin", 0);
2176 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2178 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2179 Asm->EOL("Prolog Length");
2180 EmitLabel("line_prolog_begin", 0);
2182 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2184 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2186 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2188 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2190 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2192 // Line number standard opcode encodings argument count
2193 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2194 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2195 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2196 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2197 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2198 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2199 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2200 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2201 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2203 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2204 const UniqueVector<SourceFileInfo>
2205 &SourceFiles = MMI->getSourceFiles();
2207 // Emit directories.
2208 for (unsigned DirectoryID = 1, NDID = Directories.size();
2209 DirectoryID <= NDID; ++DirectoryID) {
2210 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2212 Asm->EmitInt8(0); Asm->EOL("End of directories");
2215 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2216 SourceID <= NSID; ++SourceID) {
2217 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2218 Asm->EmitString(SourceFile.getName());
2220 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2221 Asm->EOL("Directory #");
2222 Asm->EmitULEB128Bytes(0);
2223 Asm->EOL("Mod date");
2224 Asm->EmitULEB128Bytes(0);
2225 Asm->EOL("File size");
2227 Asm->EmitInt8(0); Asm->EOL("End of files");
2229 EmitLabel("line_prolog_end", 0);
2231 // A sequence for each text section.
2232 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2233 // Isolate current sections line info.
2234 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2236 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2238 // Dwarf assumes we start with first line of first source file.
2239 unsigned Source = 1;
2242 // Construct rows of the address, source, line, column matrix.
2243 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2244 const SourceLineInfo &LineInfo = LineInfos[i];
2245 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2246 if (!LabelID) continue;
2248 unsigned SourceID = LineInfo.getSourceID();
2249 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2250 unsigned DirectoryID = SourceFile.getDirectoryID();
2251 Asm->EOL(Directories[DirectoryID]
2252 + SourceFile.getName()
2254 + utostr_32(LineInfo.getLine()));
2256 // Define the line address.
2257 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2258 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2259 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2260 EmitReference("label", LabelID); Asm->EOL("Location label");
2262 // If change of source, then switch to the new source.
2263 if (Source != LineInfo.getSourceID()) {
2264 Source = LineInfo.getSourceID();
2265 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2266 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2269 // If change of line.
2270 if (Line != LineInfo.getLine()) {
2271 // Determine offset.
2272 int Offset = LineInfo.getLine() - Line;
2273 int Delta = Offset - MinLineDelta;
2276 Line = LineInfo.getLine();
2278 // If delta is small enough and in range...
2279 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2280 // ... then use fast opcode.
2281 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2283 // ... otherwise use long hand.
2284 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2285 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2286 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2289 // Copy the previous row (different address or source)
2290 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2294 // Define last address of section.
2295 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2296 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2297 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2298 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2300 // Mark end of matrix.
2301 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2302 Asm->EmitULEB128Bytes(1); Asm->EOL();
2303 Asm->EmitInt8(1); Asm->EOL();
2306 EmitLabel("line_end", 0);
2311 /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2313 void EmitInitialDebugFrame() {
2314 if (!TAI->getDwarfRequiresFrameSection())
2318 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2319 TargetFrameInfo::StackGrowsUp ?
2320 TAI->getAddressSize() : -TAI->getAddressSize();
2322 // Start the dwarf frame section.
2323 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2325 EmitLabel("frame_common", 0);
2326 EmitDifference("frame_common_end", 0,
2327 "frame_common_begin", 0, true);
2328 Asm->EOL("Length of Common Information Entry");
2330 EmitLabel("frame_common_begin", 0);
2331 Asm->EmitInt32((int)DW_CIE_ID);
2332 Asm->EOL("CIE Identifier Tag");
2333 Asm->EmitInt8(DW_CIE_VERSION);
2334 Asm->EOL("CIE Version");
2335 Asm->EmitString("");
2336 Asm->EOL("CIE Augmentation");
2337 Asm->EmitULEB128Bytes(1);
2338 Asm->EOL("CIE Code Alignment Factor");
2339 Asm->EmitSLEB128Bytes(stackGrowth);
2340 Asm->EOL("CIE Data Alignment Factor");
2341 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2342 Asm->EOL("CIE RA Column");
2344 std::vector<MachineMove> Moves;
2345 RI->getInitialFrameState(Moves);
2346 EmitFrameMoves(NULL, 0, Moves);
2348 Asm->EmitAlignment(2);
2349 EmitLabel("frame_common_end", 0);
2354 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2356 void EmitFunctionDebugFrame() {
2357 if (!TAI->getDwarfRequiresFrameSection())
2360 // Start the dwarf frame section.
2361 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2363 EmitDifference("frame_end", SubprogramCount,
2364 "frame_begin", SubprogramCount, true);
2365 Asm->EOL("Length of Frame Information Entry");
2367 EmitLabel("frame_begin", SubprogramCount);
2369 EmitSectionOffset("frame_common_begin", "section_frame", 0, 0, true);
2370 Asm->EOL("FDE CIE offset");
2372 EmitReference("func_begin", SubprogramCount);
2373 Asm->EOL("FDE initial location");
2374 EmitDifference("func_end", SubprogramCount,
2375 "func_begin", SubprogramCount);
2376 Asm->EOL("FDE address range");
2378 std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2380 EmitFrameMoves("func_begin", SubprogramCount, Moves);
2382 Asm->EmitAlignment(2);
2383 EmitLabel("frame_end", SubprogramCount);
2388 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2390 void EmitDebugPubNames() {
2391 // Start the dwarf pubnames section.
2392 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2394 CompileUnit *Unit = GetBaseCompileUnit();
2396 EmitDifference("pubnames_end", Unit->getID(),
2397 "pubnames_begin", Unit->getID(), true);
2398 Asm->EOL("Length of Public Names Info");
2400 EmitLabel("pubnames_begin", Unit->getID());
2402 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2404 EmitSectionOffset("info_begin", "section_info", Unit->getID(), 0, true);
2405 Asm->EOL("Offset of Compilation Unit Info");
2407 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2408 Asm->EOL("Compilation Unit Length");
2410 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2412 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2415 const std::string &Name = GI->first;
2416 DIE * Entity = GI->second;
2418 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2419 Asm->EmitString(Name); Asm->EOL("External Name");
2422 Asm->EmitInt32(0); Asm->EOL("End Mark");
2423 EmitLabel("pubnames_end", Unit->getID());
2428 /// EmitDebugStr - Emit visible names into a debug str section.
2430 void EmitDebugStr() {
2431 // Check to see if it is worth the effort.
2432 if (!StringPool.empty()) {
2433 // Start the dwarf str section.
2434 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2436 // For each of strings in the string pool.
2437 for (unsigned StringID = 1, N = StringPool.size();
2438 StringID <= N; ++StringID) {
2439 // Emit a label for reference from debug information entries.
2440 EmitLabel("string", StringID);
2441 // Emit the string itself.
2442 const std::string &String = StringPool[StringID];
2443 Asm->EmitString(String); Asm->EOL();
2450 /// EmitDebugLoc - Emit visible names into a debug loc section.
2452 void EmitDebugLoc() {
2453 // Start the dwarf loc section.
2454 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2459 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2461 void EmitDebugARanges() {
2462 // Start the dwarf aranges section.
2463 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2467 CompileUnit *Unit = GetBaseCompileUnit();
2469 // Don't include size of length
2470 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2472 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2474 EmitReference("info_begin", Unit->getID());
2475 Asm->EOL("Offset of Compilation Unit Info");
2477 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2479 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2481 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2482 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2485 EmitReference("text_begin", 0); Asm->EOL("Address");
2486 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2488 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2489 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2495 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2497 void EmitDebugRanges() {
2498 // Start the dwarf ranges section.
2499 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2504 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2506 void EmitDebugMacInfo() {
2507 // Start the dwarf macinfo section.
2508 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2513 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2515 void ConstructCompileUnitDIEs() {
2516 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2518 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2519 unsigned ID = MMI->RecordSource(CUW[i]);
2520 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2521 CompileUnits.push_back(Unit);
2525 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2526 /// global variables.
2527 void ConstructGlobalDIEs() {
2528 std::vector<GlobalVariableDesc *> GlobalVariables =
2529 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2531 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2532 GlobalVariableDesc *GVD = GlobalVariables[i];
2533 NewGlobalVariable(GVD);
2537 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2539 void ConstructSubprogramDIEs() {
2540 std::vector<SubprogramDesc *> Subprograms =
2541 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2543 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2544 SubprogramDesc *SPD = Subprograms[i];
2550 //===--------------------------------------------------------------------===//
2551 // Main entry points.
2553 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2556 , AbbreviationsSet(InitAbbreviationsSetSize)
2558 , ValuesSet(InitValuesSetSize)
2563 , SectionSourceLines()
2568 virtual ~DwarfDebug() {
2569 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2570 delete CompileUnits[i];
2571 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2575 /// SetModuleInfo - Set machine module information when it's known that pass
2576 /// manager has created it. Set by the target AsmPrinter.
2577 void SetModuleInfo(MachineModuleInfo *mmi) {
2578 // Make sure initial declarations are made.
2579 if (!MMI && mmi->hasDebugInfo()) {
2583 // Emit initial sections
2586 // Create all the compile unit DIEs.
2587 ConstructCompileUnitDIEs();
2589 // Create DIEs for each of the externally visible global variables.
2590 ConstructGlobalDIEs();
2592 // Create DIEs for each of the externally visible subprograms.
2593 ConstructSubprogramDIEs();
2595 // Prime section data.
2596 SectionMap.insert(TAI->getTextSection());
2600 /// BeginModule - Emit all Dwarf sections that should come prior to the
2602 void BeginModule(Module *M) {
2605 if (!ShouldEmitDwarf()) return;
2608 /// EndModule - Emit all Dwarf sections that should come after the content.
2611 if (!ShouldEmitDwarf()) return;
2613 // Standard sections final addresses.
2614 Asm->SwitchToTextSection(TAI->getTextSection());
2615 EmitLabel("text_end", 0);
2616 Asm->SwitchToDataSection(TAI->getDataSection());
2617 EmitLabel("data_end", 0);
2619 // End text sections.
2620 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2621 Asm->SwitchToTextSection(SectionMap[i].c_str());
2622 EmitLabel("section_end", i);
2625 // Compute DIE offsets and sizes.
2628 // Emit all the DIEs into a debug info section
2631 // Corresponding abbreviations into a abbrev section.
2632 EmitAbbreviations();
2634 // Emit source line correspondence into a debug line section.
2637 // Emit info into a debug pubnames section.
2638 EmitDebugPubNames();
2640 // Emit info into a debug str section.
2643 // Emit info into a debug loc section.
2646 // Emit info into a debug aranges section.
2649 // Emit info into a debug ranges section.
2652 // Emit info into a debug macinfo section.
2656 /// BeginFunction - Gather pre-function debug information. Assumes being
2657 /// emitted immediately after the function entry point.
2658 void BeginFunction(MachineFunction *MF) {
2661 if (!ShouldEmitDwarf()) return;
2663 // Begin accumulating function debug information.
2664 MMI->BeginFunction(MF);
2666 // Assumes in correct section after the entry point.
2667 EmitLabel("func_begin", ++SubprogramCount);
2670 /// EndFunction - Gather and emit post-function debug information.
2672 void EndFunction() {
2673 if (!ShouldEmitDwarf()) return;
2675 // Define end label for subprogram.
2676 EmitLabel("func_end", SubprogramCount);
2678 // Get function line info.
2679 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2681 if (!LineInfos.empty()) {
2682 // Get section line info.
2683 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2684 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2685 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2686 // Append the function info to section info.
2687 SectionLineInfos.insert(SectionLineInfos.end(),
2688 LineInfos.begin(), LineInfos.end());
2691 // Construct scopes for subprogram.
2692 ConstructRootScope(MMI->getRootScope());
2694 // Emit function frame information.
2695 EmitFunctionDebugFrame();
2699 //===----------------------------------------------------------------------===//
2700 /// DwarfException - Emits Dwarf exception handling directives.
2702 class DwarfException : public Dwarf {
2706 /// didInitial - Flag to indicate if initial emission has been done.
2710 /// shouldEmit - Flag to indicate if debug information should be emitted.
2714 /// FuncCPPPersonality - C++ persoanlity function.
2716 Function *FuncCPPPersonality;
2718 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2720 void EmitCommonEHFrame() {
2722 if (didInitial) return;
2725 // If there is a personality present then we need to indicate that
2726 // in the common eh frame.
2727 Function *Personality = FuncCPPPersonality;
2729 // Size and sign of stack growth.
2731 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2732 TargetFrameInfo::StackGrowsUp ?
2733 TAI->getAddressSize() : -TAI->getAddressSize();
2735 // Begin eh frame section.
2736 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2738 EmitLabel("section_eh_frame", 0);
2740 // Define base labels.
2741 EmitLabel("eh_frame_common", 0);
2743 // Define the eh frame length.
2744 EmitDifference("eh_frame_common_end", 0,
2745 "eh_frame_common_begin", 0, true);
2746 Asm->EOL("Length of Common Information Entry");
2749 EmitLabel("eh_frame_common_begin", 0);
2750 Asm->EmitInt32((int)0);
2751 Asm->EOL("CIE Identifier Tag");
2752 Asm->EmitInt8(DW_CIE_VERSION);
2753 Asm->EOL("CIE Version");
2755 // The personality presence indicates that language specific information
2756 // will show up in the eh frame.
2757 Asm->EmitString(Personality ? "zPLR" : "zR");
2758 Asm->EOL("CIE Augmentation");
2760 // Round out reader.
2761 Asm->EmitULEB128Bytes(1);
2762 Asm->EOL("CIE Code Alignment Factor");
2763 Asm->EmitSLEB128Bytes(stackGrowth);
2764 Asm->EOL("CIE Data Alignment Factor");
2765 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2766 Asm->EOL("CIE RA Column");
2768 // If there is a personality, we need to indicate the functions location.
2770 Asm->EmitULEB128Bytes(7);
2771 Asm->EOL("Augmentation Size");
2772 Asm->EmitInt8(DW_EH_PE_indirect |
2775 Asm->EOL("Personality (indirect pcrel sdata4)");
2777 O << TAI->getData32bitsDirective();
2778 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2779 O << "-" << TAI->getPCSymbol();
2780 Asm->EOL("Personality");
2782 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2783 Asm->EOL("LSDA Encoding (pcrel)");
2784 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2785 Asm->EOL("FDE Encoding (pcrel)");
2787 Asm->EmitULEB128Bytes(1);
2788 Asm->EOL("Augmentation Size");
2789 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2790 Asm->EOL("FDE Encoding (pcrel)");
2793 // Indicate locations of general callee saved registers in frame.
2794 std::vector<MachineMove> Moves;
2795 RI->getInitialFrameState(Moves);
2796 EmitFrameMoves(NULL, 0, Moves);
2798 Asm->EmitAlignment(2);
2799 EmitLabel("eh_frame_common_end", 0);
2804 /// EmitEHFrame - Emit initial exception information.
2806 void EmitEHFrame() {
2807 // If there is a personality present then we need to indicate that
2808 // in the common eh frame.
2809 Function *Personality = FuncCPPPersonality;
2810 // Function *Personality = MMI->getPersonality();
2811 MachineFrameInfo *MFI = MF->getFrameInfo();
2813 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2815 // Externally visible entry into the functions eh frame info.
2816 if (const char *GlobalDirective = TAI->getGlobalDirective())
2817 O << GlobalDirective << getAsm()->CurrentFnName << ".eh\n";
2819 // If there are no calls then you can't unwind.
2820 if (!MFI->hasCalls()) {
2821 O << getAsm()->CurrentFnName << ".eh = 0\n";
2823 O << getAsm()->CurrentFnName << ".eh:\n";
2826 EmitDifference("eh_frame_end", SubprogramCount,
2827 "eh_frame_begin", SubprogramCount, true);
2828 Asm->EOL("Length of Frame Information Entry");
2830 EmitLabel("eh_frame_begin", SubprogramCount);
2832 EmitSectionOffset("eh_frame_begin", "section_eh_frame",
2833 SubprogramCount, 0, true);
2834 Asm->EOL("FDE CIE offset");
2836 EmitReference("eh_func_begin", SubprogramCount, true);
2837 Asm->EOL("FDE initial location");
2838 EmitDifference("eh_func_end", SubprogramCount,
2839 "eh_func_begin", SubprogramCount);
2840 Asm->EOL("FDE address range");
2842 // If there is a personality and landing pads then point to the language
2843 // specific data area in the exception table.
2845 Asm->EmitULEB128Bytes(4);
2846 Asm->EOL("Augmentation size");
2848 if (!MMI->getLandingPads().empty()) {
2849 EmitReference("exception", SubprogramCount, true);
2850 } else if(TAI->getAddressSize() == 8) {
2851 Asm->EmitInt64((int)0);
2853 Asm->EmitInt32((int)0);
2855 Asm->EOL("Language Specific Data Area");
2857 Asm->EmitULEB128Bytes(0);
2858 Asm->EOL("Augmentation size");
2861 // Indicate locations of function specific callee saved registers in
2863 std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2864 EmitFrameMoves("eh_func_begin", SubprogramCount, Moves);
2866 Asm->EmitAlignment(2);
2867 EmitLabel("eh_frame_end", SubprogramCount);
2870 if (const char *UsedDirective = TAI->getUsedDirective())
2871 O << UsedDirective << getAsm()->CurrentFnName << ".eh\n\n";
2874 /// EmitExceptionTable - Emit landpads and actions.
2876 /// The general organization of the table is complex, but the basic concepts
2877 /// are easy. First there is a header which describes the location and
2878 /// organization of the three components that follow.
2879 /// 1. The landing pad site information describes the range of code covered
2880 /// by the try. In our case it's an accumulation of the ranges covered
2881 /// by the invokes in the try. There is also a reference to the landing
2882 /// pad that handles the exception once processed. Finally an index into
2883 /// the actions table.
2884 /// 2. The action table, in our case, is composed of pairs of type ids
2885 /// and next action offset. Starting with the action index from the
2886 /// landing pad site, each type Id is checked for a match to the current
2887 /// exception. If it matches then the exception and type id are passed
2888 /// on to the landing pad. Otherwise the next action is looked up. This
2889 /// chain is terminated with a next action of zero. If no type id is
2890 /// found the the frame is unwound and handling continues.
2891 /// 3. Type id table contains references to all the C++ typeinfo for all
2892 /// catches in the function. This tables is reversed indexed base 1.
2893 void EmitExceptionTable() {
2894 // Map all labels and get rid of any dead landing pads.
2895 MMI->TidyLandingPads();
2897 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
2898 const std::vector<LandingPadInfo> &LandingPads = MMI->getLandingPads();
2899 if (LandingPads.empty()) return;
2901 // FIXME - Should fold actions for multiple landing pads.
2903 // Gather first action index for each landing pad site.
2904 SmallVector<unsigned, 8> Actions;
2906 // FIXME - Assume there is only one filter typeinfo list per function
2907 // time being. I.E., Each call to eh_filter will have the same list.
2908 // This can change if a function is inlined.
2909 const LandingPadInfo *Filter = 0;
2911 // Compute sizes for exception table.
2912 unsigned SizeHeader = sizeof(int8_t) + // LPStart format
2913 sizeof(int8_t) + // TType format
2914 sizeof(int8_t) + // TType base offset (NEED ULEB128)
2915 sizeof(int8_t) + // Call site format
2916 sizeof(int8_t); // Call-site table length
2917 unsigned SizeSites = 0;
2918 unsigned SizeActions = 0;
2920 // Look at each landing pad site to compute size. We need the size of each
2921 // landing pad site info and the size of the landing pad's actions.
2922 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2923 const LandingPadInfo &LandingPad = LandingPads[i];
2924 bool IsFilter = LandingPad.IsFilter;
2925 unsigned SizeSiteActions = 0;
2926 const std::vector<unsigned> &TypeIds = LandingPad.TypeIds;
2927 unsigned SizeAction = 0;
2931 // FIXME - Assume there is only one filter typeinfo list per function
2932 // time being. I.E., Each call to eh_filter will have the same list.
2933 // This can change if a function is inlined.
2934 Filter = &LandingPad;
2935 SizeAction = Asm->SizeSLEB128(-1) + Asm->SizeSLEB128(0);
2936 SizeSiteActions += SizeAction;
2937 // Record the first action of the landing pad site.
2938 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
2939 } else if (TypeIds.empty()) {
2942 // Gather the action sizes
2943 for (unsigned j = 0, M = TypeIds.size(); j != M; ++j) {
2944 unsigned TypeID = TypeIds[i];
2945 unsigned SizeTypeID = Asm->SizeSLEB128(TypeID);
2946 signed Action = j ? -(SizeAction + SizeTypeID) : 0;
2947 SizeAction = SizeTypeID + Asm->SizeSLEB128(Action);
2948 SizeSiteActions += SizeAction;
2951 // Record the first action of the landing pad site.
2952 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
2955 Actions.push_back(FirstAction);
2957 // Compute this sites contribution to size.
2958 SizeActions += SizeSiteActions;
2959 SizeSites += sizeof(int32_t) + // Site start.
2960 sizeof(int32_t) + // Site length.
2961 sizeof(int32_t) + // Landing pad.
2962 Asm->SizeSLEB128(FirstAction); // Action.
2966 unsigned SizeTypes = TypeInfos.size() * TAI->getAddressSize();
2967 unsigned SizePreType = SizeHeader + SizeSites + SizeActions;
2968 unsigned SizeAlign = (4 - SizePreType) & 3;
2969 unsigned TypeOffset = SizePreType +
2972 sizeof(int8_t) - // LPStart format
2973 sizeof(int8_t) - // TType format
2974 sizeof(int8_t); // TType base offset (NEED ULEB128)
2976 // Begin the exception table.
2977 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
2978 O << "GCC_except_table" << SubprogramCount << ":\n";
2979 EmitLabel("exception", SubprogramCount);
2982 Asm->EmitInt8(DW_EH_PE_omit);
2983 Asm->EOL("LPStart format (DW_EH_PE_omit)");
2984 Asm->EmitInt8(DW_EH_PE_absptr);
2985 Asm->EOL("TType format (DW_EH_PE_absptr)");
2986 Asm->EmitULEB128Bytes(TypeOffset);
2987 Asm->EOL("TType base offset");
2988 Asm->EmitInt8(DW_EH_PE_udata4);
2989 Asm->EOL("Call site format (DW_EH_PE_udata4)");
2990 Asm->EmitULEB128Bytes(SizeSites);
2991 Asm->EOL("Call-site table length");
2993 // Emit the landng pad site information.
2994 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2995 const LandingPadInfo &LandingPad = LandingPads[i];
2996 EmitSectionOffset("label", "eh_func_begin",
2997 LandingPad.BeginLabel, SubprogramCount);
2998 Asm->EOL("Region start");
3000 EmitDifference("label", LandingPad.EndLabel,
3001 "label", LandingPad.BeginLabel);
3002 Asm->EOL("Region length");
3004 if (LandingPad.TypeIds.empty()) {
3005 if (TAI->getAddressSize() == sizeof(int32_t))
3010 EmitSectionOffset("label", "eh_func_begin",
3011 LandingPad.LandingPadLabel, SubprogramCount);
3013 Asm->EOL("Landing pad");
3015 Asm->EmitULEB128Bytes(Actions[i]);
3019 // Emit the actions.
3020 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3021 const LandingPadInfo &LandingPad = LandingPads[i];
3022 const std::vector<unsigned> &TypeIds = LandingPad.TypeIds;
3023 unsigned SizeAction = 0;
3025 if (LandingPad.IsFilter) {
3026 Asm->EmitSLEB128Bytes(-1);
3027 Asm->EOL("TypeInfo index");
3028 Asm->EmitSLEB128Bytes(0);
3029 Asm->EOL("Next action");
3031 for (unsigned j = 0, M = TypeIds.size(); j < M; ++j) {
3032 unsigned TypeID = TypeIds[j];
3033 unsigned SizeTypeID = Asm->SizeSLEB128(TypeID);
3034 Asm->EmitSLEB128Bytes(TypeID);
3035 Asm->EOL("TypeInfo index");
3036 signed Action = j ? -(SizeAction + SizeTypeID) : 0;
3037 SizeAction = SizeTypeID + Asm->SizeSLEB128(Action);
3038 Asm->EmitSLEB128Bytes(Action);
3039 Asm->EOL("Next action");
3044 // Emit the type ids.
3045 Asm->EmitAlignment(2);
3046 for (unsigned M = TypeInfos.size(); M; --M) {
3047 GlobalVariable *GV = TypeInfos[M - 1];
3049 if (TAI->getAddressSize() == sizeof(int32_t))
3050 O << TAI->getData32bitsDirective();
3052 O << TAI->getData64bitsDirective();
3055 O << Asm->getGlobalLinkName(GV);
3059 Asm->EOL("TypeInfo");
3062 // Emit the filter typeinfo.
3064 const std::vector<unsigned> &TypeIds = Filter->TypeIds;
3065 for (unsigned j = 0, M = TypeIds.size(); j < M; ++j) {
3066 unsigned TypeID = TypeIds[j];
3067 Asm->EmitSLEB128Bytes(TypeID);
3068 Asm->EOL("TypeInfo index");
3070 Asm->EmitSLEB128Bytes(0);
3071 Asm->EOL("End of filter typeinfo");
3074 Asm->EmitAlignment(2);
3078 //===--------------------------------------------------------------------===//
3079 // Main entry points.
3081 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3085 , FuncCPPPersonality(NULL)
3088 virtual ~DwarfException() {}
3090 /// SetModuleInfo - Set machine module information when it's known that pass
3091 /// manager has created it. Set by the target AsmPrinter.
3092 void SetModuleInfo(MachineModuleInfo *mmi) {
3096 /// BeginModule - Emit all exception information that should come prior to the
3098 void BeginModule(Module *M) {
3100 FuncCPPPersonality = M->getFunction("__gxx_personality_v0");
3103 /// EndModule - Emit all exception information that should come after the
3108 /// BeginFunction - Gather pre-function exception information. Assumes being
3109 /// emitted immediately after the function entry point.
3110 void BeginFunction(MachineFunction *MF) {
3114 ExceptionHandling &&
3115 TAI->getSupportsExceptionHandling()) {
3117 // Assumes in correct section after the entry point.
3118 EmitLabel("eh_func_begin", ++SubprogramCount);
3122 /// EndFunction - Gather and emit post-function exception information.
3124 void EndFunction() {
3125 if (!shouldEmit) return;
3127 EmitLabel("eh_func_end", SubprogramCount);
3128 EmitExceptionTable();
3129 EmitCommonEHFrame();
3134 } // End of namespace llvm
3136 //===----------------------------------------------------------------------===//
3138 /// Emit - Print the abbreviation using the specified Dwarf writer.
3140 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3141 // Emit its Dwarf tag type.
3142 DD.getAsm()->EmitULEB128Bytes(Tag);
3143 DD.getAsm()->EOL(TagString(Tag));
3145 // Emit whether it has children DIEs.
3146 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3147 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3149 // For each attribute description.
3150 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3151 const DIEAbbrevData &AttrData = Data[i];
3153 // Emit attribute type.
3154 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3155 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3158 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3159 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3162 // Mark end of abbreviation.
3163 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3164 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3168 void DIEAbbrev::print(std::ostream &O) {
3169 O << "Abbreviation @"
3170 << std::hex << (intptr_t)this << std::dec
3174 << ChildrenString(ChildrenFlag)
3177 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3179 << AttributeString(Data[i].getAttribute())
3181 << FormEncodingString(Data[i].getForm())
3185 void DIEAbbrev::dump() { print(cerr); }
3188 //===----------------------------------------------------------------------===//
3191 void DIEValue::dump() {
3196 //===----------------------------------------------------------------------===//
3198 /// EmitValue - Emit integer of appropriate size.
3200 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3202 case DW_FORM_flag: // Fall thru
3203 case DW_FORM_ref1: // Fall thru
3204 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3205 case DW_FORM_ref2: // Fall thru
3206 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3207 case DW_FORM_ref4: // Fall thru
3208 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3209 case DW_FORM_ref8: // Fall thru
3210 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3211 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3212 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3213 default: assert(0 && "DIE Value form not supported yet"); break;
3217 /// SizeOf - Determine size of integer value in bytes.
3219 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3221 case DW_FORM_flag: // Fall thru
3222 case DW_FORM_ref1: // Fall thru
3223 case DW_FORM_data1: return sizeof(int8_t);
3224 case DW_FORM_ref2: // Fall thru
3225 case DW_FORM_data2: return sizeof(int16_t);
3226 case DW_FORM_ref4: // Fall thru
3227 case DW_FORM_data4: return sizeof(int32_t);
3228 case DW_FORM_ref8: // Fall thru
3229 case DW_FORM_data8: return sizeof(int64_t);
3230 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3231 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3232 default: assert(0 && "DIE Value form not supported yet"); break;
3237 //===----------------------------------------------------------------------===//
3239 /// EmitValue - Emit string value.
3241 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3242 DD.getAsm()->EmitString(String);
3245 //===----------------------------------------------------------------------===//
3247 /// EmitValue - Emit label value.
3249 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3250 DD.EmitReference(Label);
3253 /// SizeOf - Determine size of label value in bytes.
3255 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3256 return DD.getTargetAsmInfo()->getAddressSize();
3259 //===----------------------------------------------------------------------===//
3261 /// EmitValue - Emit label value.
3263 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3264 DD.EmitReference(Label);
3267 /// SizeOf - Determine size of label value in bytes.
3269 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3270 return DD.getTargetAsmInfo()->getAddressSize();
3273 //===----------------------------------------------------------------------===//
3275 /// EmitValue - Emit delta value.
3277 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3278 bool IsSmall = Form == DW_FORM_data4;
3279 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3282 /// SizeOf - Determine size of delta value in bytes.
3284 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3285 if (Form == DW_FORM_data4) return 4;
3286 return DD.getTargetAsmInfo()->getAddressSize();
3289 //===----------------------------------------------------------------------===//
3291 /// EmitValue - Emit debug information entry offset.
3293 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3294 DD.getAsm()->EmitInt32(Entry->getOffset());
3297 //===----------------------------------------------------------------------===//
3299 /// ComputeSize - calculate the size of the block.
3301 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3303 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3305 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3306 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3312 /// EmitValue - Emit block data.
3314 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3316 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3317 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3318 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3319 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3320 default: assert(0 && "Improper form for block"); break;
3323 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3325 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3327 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3331 /// SizeOf - Determine size of block data in bytes.
3333 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3335 case DW_FORM_block1: return Size + sizeof(int8_t);
3336 case DW_FORM_block2: return Size + sizeof(int16_t);
3337 case DW_FORM_block4: return Size + sizeof(int32_t);
3338 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3339 default: assert(0 && "Improper form for block"); break;
3344 //===----------------------------------------------------------------------===//
3345 /// DIE Implementation
3348 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3352 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3354 void DIE::AddSiblingOffset() {
3355 DIEInteger *DI = new DIEInteger(0);
3356 Values.insert(Values.begin(), DI);
3357 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3360 /// Profile - Used to gather unique data for the value folding set.
3362 void DIE::Profile(FoldingSetNodeID &ID) {
3365 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3366 ID.AddPointer(Children[i]);
3368 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3369 ID.AddPointer(Values[j]);
3373 void DIE::print(std::ostream &O, unsigned IncIndent) {
3374 static unsigned IndentCount = 0;
3375 IndentCount += IncIndent;
3376 const std::string Indent(IndentCount, ' ');
3377 bool isBlock = Abbrev.getTag() == 0;
3382 << "0x" << std::hex << (intptr_t)this << std::dec
3383 << ", Offset: " << Offset
3384 << ", Size: " << Size
3388 << TagString(Abbrev.getTag())
3390 << ChildrenString(Abbrev.getChildrenFlag());
3392 O << "Size: " << Size;
3396 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3399 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3402 O << AttributeString(Data[i].getAttribute());
3404 O << "Blk[" << i << "]";
3407 << FormEncodingString(Data[i].getForm())
3409 Values[i]->print(O);
3414 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3415 Children[j]->print(O, 4);
3418 if (!isBlock) O << "\n";
3419 IndentCount -= IncIndent;
3427 //===----------------------------------------------------------------------===//
3428 /// DwarfWriter Implementation
3431 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3432 const TargetAsmInfo *T) {
3433 DE = new DwarfException(OS, A, T);
3434 DD = new DwarfDebug(OS, A, T);
3437 DwarfWriter::~DwarfWriter() {
3442 /// SetModuleInfo - Set machine module info when it's known that pass manager
3443 /// has created it. Set by the target AsmPrinter.
3444 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3445 DD->SetModuleInfo(MMI);
3446 DE->SetModuleInfo(MMI);
3449 /// BeginModule - Emit all Dwarf sections that should come prior to the
3451 void DwarfWriter::BeginModule(Module *M) {
3456 /// EndModule - Emit all Dwarf sections that should come after the content.
3458 void DwarfWriter::EndModule() {
3463 /// BeginFunction - Gather pre-function debug information. Assumes being
3464 /// emitted immediately after the function entry point.
3465 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3466 DE->BeginFunction(MF);
3467 DD->BeginFunction(MF);
3470 /// EndFunction - Gather and emit post-function debug information.
3472 void DwarfWriter::EndFunction() {
3476 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3477 // Clear function debug information.