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 const std::vector<DIEValue *> &getValues() const { 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(const DwarfDebug &DD, unsigned Form) const = 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(const DwarfDebug &DD, unsigned Form) const;
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(const DwarfDebug &DD, unsigned Form) const;
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(const DwarfDebug &DD, unsigned Form) const;
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(const DwarfDebug &DD, unsigned Form) const;
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(const DwarfDebug &DD, unsigned Form) const;
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(const DwarfDebug &DD, unsigned Form) const;
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(const DwarfDebug &DD, unsigned Form) const;
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;
799 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
803 , TD(Asm->TM.getTargetData())
804 , RI(Asm->TM.getRegisterInfo())
814 //===--------------------------------------------------------------------===//
817 AsmPrinter *getAsm() const { return Asm; }
818 MachineModuleInfo *getMMI() const { return MMI; }
819 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
821 /// PrintLabelName - Print label name in form used by Dwarf writer.
823 void PrintLabelName(DWLabel Label) const {
824 PrintLabelName(Label.Tag, Label.Number);
826 void PrintLabelName(const char *Tag, unsigned Number,
827 bool isInSection = false) const {
828 if (isInSection && TAI->getDwarfSectionOffsetDirective())
829 O << TAI->getDwarfSectionOffsetDirective() << Tag;
831 O << TAI->getPrivateGlobalPrefix() << Tag;
832 if (Number) O << Number;
835 /// EmitLabel - Emit location label for internal use by Dwarf.
837 void EmitLabel(DWLabel Label) const {
838 EmitLabel(Label.Tag, Label.Number);
840 void EmitLabel(const char *Tag, unsigned Number) const {
841 PrintLabelName(Tag, Number);
845 /// EmitReference - Emit a reference to a label.
847 void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
848 EmitReference(Label.Tag, Label.Number, IsPCRelative);
850 void EmitReference(const char *Tag, unsigned Number,
851 bool IsPCRelative = false) const {
852 if (TAI->getAddressSize() == sizeof(int32_t))
853 O << TAI->getData32bitsDirective();
855 O << TAI->getData64bitsDirective();
857 PrintLabelName(Tag, Number);
859 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
861 void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
862 if (TAI->getAddressSize() == sizeof(int32_t))
863 O << TAI->getData32bitsDirective();
865 O << TAI->getData64bitsDirective();
869 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
872 /// EmitDifference - Emit the difference between two labels. Some
873 /// assemblers do not behave with absolute expressions with data directives,
874 /// so there is an option (needsSet) to use an intermediary set expression.
875 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
876 bool IsSmall = false) const {
877 EmitDifference(LabelHi.Tag, LabelHi.Number,
878 LabelLo.Tag, LabelLo.Number,
881 void EmitDifference(const char *TagHi, unsigned NumberHi,
882 const char *TagLo, unsigned NumberLo,
883 bool IsSmall = false) const {
884 if (TAI->needsSet()) {
885 static unsigned SetCounter = 1;
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) const {
918 if (TAI->needsSet()) {
919 static unsigned SetCounter = 1;
922 PrintLabelName("set", SetCounter);
924 PrintLabelName(Label, LabelNumber, true);
925 if (!TAI->isAbsoluteSectionOffsets()) {
927 PrintLabelName(Section, SectionNumber);
931 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
932 O << TAI->getData32bitsDirective();
934 O << TAI->getData64bitsDirective();
936 PrintLabelName("set", SetCounter);
939 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
940 O << TAI->getData32bitsDirective();
942 O << TAI->getData64bitsDirective();
944 PrintLabelName(Label, LabelNumber, true);
945 if (!TAI->isAbsoluteSectionOffsets()) {
947 PrintLabelName(Section, SectionNumber);
952 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
954 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
955 std::vector<MachineMove> &Moves) {
957 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
958 TargetFrameInfo::StackGrowsUp ?
959 TAI->getAddressSize() : -TAI->getAddressSize();
960 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
962 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
963 MachineMove &Move = Moves[i];
964 unsigned LabelID = Move.getLabelID();
967 LabelID = MMI->MappedLabel(LabelID);
969 // Throw out move if the label is invalid.
970 if (!LabelID) continue;
973 const MachineLocation &Dst = Move.getDestination();
974 const MachineLocation &Src = Move.getSource();
976 // Advance row if new location.
977 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
978 Asm->EmitInt8(DW_CFA_advance_loc4);
979 Asm->EOL("DW_CFA_advance_loc4");
980 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
983 BaseLabelID = LabelID;
989 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
990 if (!Src.isRegister()) {
991 if (Src.getRegister() == MachineLocation::VirtualFP) {
992 Asm->EmitInt8(DW_CFA_def_cfa_offset);
993 Asm->EOL("DW_CFA_def_cfa_offset");
995 Asm->EmitInt8(DW_CFA_def_cfa);
996 Asm->EOL("DW_CFA_def_cfa");
997 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
998 Asm->EOL("Register");
1001 int Offset = -Src.getOffset();
1003 Asm->EmitULEB128Bytes(Offset);
1006 assert(0 && "Machine move no supported yet.");
1008 } else if (Src.isRegister() &&
1009 Src.getRegister() == MachineLocation::VirtualFP) {
1010 if (Dst.isRegister()) {
1011 Asm->EmitInt8(DW_CFA_def_cfa_register);
1012 Asm->EOL("DW_CFA_def_cfa_register");
1013 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1014 Asm->EOL("Register");
1016 assert(0 && "Machine move no supported yet.");
1019 unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1020 int Offset = Dst.getOffset() / stackGrowth;
1023 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1024 Asm->EOL("DW_CFA_offset_extended_sf");
1025 Asm->EmitULEB128Bytes(Reg);
1027 Asm->EmitSLEB128Bytes(Offset);
1029 } else if (Reg < 64) {
1030 Asm->EmitInt8(DW_CFA_offset + Reg);
1031 Asm->EOL("DW_CFA_offset + Reg");
1032 Asm->EmitULEB128Bytes(Offset);
1035 Asm->EmitInt8(DW_CFA_offset_extended);
1036 Asm->EOL("DW_CFA_offset_extended");
1037 Asm->EmitULEB128Bytes(Reg);
1039 Asm->EmitULEB128Bytes(Offset);
1048 //===----------------------------------------------------------------------===//
1049 /// DwarfDebug - Emits Dwarf debug directives.
1051 class DwarfDebug : public Dwarf {
1054 //===--------------------------------------------------------------------===//
1055 // Attributes used to construct specific Dwarf sections.
1058 /// CompileUnits - All the compile units involved in this build. The index
1059 /// of each entry in this vector corresponds to the sources in MMI.
1060 std::vector<CompileUnit *> CompileUnits;
1062 /// AbbreviationsSet - Used to uniquely define abbreviations.
1064 FoldingSet<DIEAbbrev> AbbreviationsSet;
1066 /// Abbreviations - A list of all the unique abbreviations in use.
1068 std::vector<DIEAbbrev *> Abbreviations;
1070 /// ValuesSet - Used to uniquely define values.
1072 FoldingSet<DIEValue> ValuesSet;
1074 /// Values - A list of all the unique values in use.
1076 std::vector<DIEValue *> Values;
1078 /// StringPool - A UniqueVector of strings used by indirect references.
1080 UniqueVector<std::string> StringPool;
1082 /// UnitMap - Map debug information descriptor to compile unit.
1084 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1086 /// SectionMap - Provides a unique id per text section.
1088 UniqueVector<std::string> SectionMap;
1090 /// SectionSourceLines - Tracks line numbers per text section.
1092 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1094 /// didInitial - Flag to indicate if initial emission has been done.
1098 /// shouldEmit - Flag to indicate if debug information should be emitted.
1104 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1106 bool ShouldEmitDwarf() const { return shouldEmit; }
1108 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1110 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1111 // Profile the node so that we can make it unique.
1112 FoldingSetNodeID ID;
1115 // Check the set for priors.
1116 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1118 // If it's newly added.
1119 if (InSet == &Abbrev) {
1120 // Add to abbreviation list.
1121 Abbreviations.push_back(&Abbrev);
1122 // Assign the vector position + 1 as its number.
1123 Abbrev.setNumber(Abbreviations.size());
1125 // Assign existing abbreviation number.
1126 Abbrev.setNumber(InSet->getNumber());
1130 /// NewString - Add a string to the constant pool and returns a label.
1132 DWLabel NewString(const std::string &String) {
1133 unsigned StringID = StringPool.insert(String);
1134 return DWLabel("string", StringID);
1137 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1139 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1143 FoldingSetNodeID ID;
1144 DIEntry::Profile(ID, Entry);
1146 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1148 if (Value) return Value;
1150 Value = new DIEntry(Entry);
1151 ValuesSet.InsertNode(Value, Where);
1153 Value = new DIEntry(Entry);
1156 Values.push_back(Value);
1160 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1162 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1163 Value->Entry = Entry;
1164 // Add to values set if not already there. If it is, we merely have a
1165 // duplicate in the values list (no harm.)
1166 ValuesSet.GetOrInsertNode(Value);
1169 /// AddUInt - Add an unsigned integer attribute data and value.
1171 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1172 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1174 FoldingSetNodeID ID;
1175 DIEInteger::Profile(ID, Integer);
1177 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1179 Value = new DIEInteger(Integer);
1180 ValuesSet.InsertNode(Value, Where);
1181 Values.push_back(Value);
1184 Die->AddValue(Attribute, Form, Value);
1187 /// AddSInt - Add an signed integer attribute data and value.
1189 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1190 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1192 FoldingSetNodeID ID;
1193 DIEInteger::Profile(ID, (uint64_t)Integer);
1195 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1197 Value = new DIEInteger(Integer);
1198 ValuesSet.InsertNode(Value, Where);
1199 Values.push_back(Value);
1202 Die->AddValue(Attribute, Form, Value);
1205 /// AddString - Add a std::string attribute data and value.
1207 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1208 const std::string &String) {
1209 FoldingSetNodeID ID;
1210 DIEString::Profile(ID, String);
1212 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1214 Value = new DIEString(String);
1215 ValuesSet.InsertNode(Value, Where);
1216 Values.push_back(Value);
1219 Die->AddValue(Attribute, Form, Value);
1222 /// AddLabel - Add a Dwarf label attribute data and value.
1224 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1225 const DWLabel &Label) {
1226 FoldingSetNodeID ID;
1227 DIEDwarfLabel::Profile(ID, Label);
1229 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1231 Value = new DIEDwarfLabel(Label);
1232 ValuesSet.InsertNode(Value, Where);
1233 Values.push_back(Value);
1236 Die->AddValue(Attribute, Form, Value);
1239 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1241 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1242 const std::string &Label) {
1243 FoldingSetNodeID ID;
1244 DIEObjectLabel::Profile(ID, Label);
1246 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1248 Value = new DIEObjectLabel(Label);
1249 ValuesSet.InsertNode(Value, Where);
1250 Values.push_back(Value);
1253 Die->AddValue(Attribute, Form, Value);
1256 /// AddDelta - Add a label delta attribute data and value.
1258 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1259 const DWLabel &Hi, const DWLabel &Lo) {
1260 FoldingSetNodeID ID;
1261 DIEDelta::Profile(ID, Hi, Lo);
1263 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1265 Value = new DIEDelta(Hi, Lo);
1266 ValuesSet.InsertNode(Value, Where);
1267 Values.push_back(Value);
1270 Die->AddValue(Attribute, Form, Value);
1273 /// AddDIEntry - Add a DIE attribute data and value.
1275 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1276 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1279 /// AddBlock - Add block data.
1281 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1282 Block->ComputeSize(*this);
1283 FoldingSetNodeID ID;
1286 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1289 ValuesSet.InsertNode(Value, Where);
1290 Values.push_back(Value);
1295 Die->AddValue(Attribute, Block->BestForm(), Value);
1300 /// AddSourceLine - Add location information to specified debug information
1302 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1304 CompileUnit *FileUnit = FindCompileUnit(File);
1305 unsigned FileID = FileUnit->getID();
1306 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1307 AddUInt(Die, DW_AT_decl_line, 0, Line);
1311 /// AddAddress - Add an address attribute to a die based on the location
1313 void AddAddress(DIE *Die, unsigned Attribute,
1314 const MachineLocation &Location) {
1315 unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1316 DIEBlock *Block = new DIEBlock();
1318 if (Location.isRegister()) {
1320 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1322 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1323 AddUInt(Block, 0, DW_FORM_udata, Reg);
1327 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1329 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1330 AddUInt(Block, 0, DW_FORM_udata, Reg);
1332 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1335 AddBlock(Die, Attribute, 0, Block);
1338 /// AddBasicType - Add a new basic type attribute to the specified entity.
1340 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1341 const std::string &Name,
1342 unsigned Encoding, unsigned Size) {
1343 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1344 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1347 /// ConstructBasicType - Construct a new basic type.
1349 DIE *ConstructBasicType(CompileUnit *Unit,
1350 const std::string &Name,
1351 unsigned Encoding, unsigned Size) {
1352 DIE Buffer(DW_TAG_base_type);
1353 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1354 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1355 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1356 return Unit->AddDie(Buffer);
1359 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1361 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1362 DIE *Die = ConstructPointerType(Unit, Name);
1363 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1366 /// ConstructPointerType - Construct a new pointer type.
1368 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1369 DIE Buffer(DW_TAG_pointer_type);
1370 AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1371 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1372 return Unit->AddDie(Buffer);
1375 /// AddType - Add a new type attribute to the specified entity.
1377 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1379 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1381 // Check for pre-existence.
1382 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1384 // If it exists then use the existing value.
1386 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1390 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1391 // FIXME - Not sure why programs and variables are coming through here.
1392 // Short cut for handling subprogram types (not really a TyDesc.)
1393 AddPointerType(Entity, Unit, SubprogramTy->getName());
1394 } else if (GlobalVariableDesc *GlobalTy =
1395 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1396 // FIXME - Not sure why programs and variables are coming through here.
1397 // Short cut for handling global variable types (not really a TyDesc.)
1398 AddPointerType(Entity, Unit, GlobalTy->getName());
1401 Slot = NewDIEntry();
1404 DIE Buffer(DW_TAG_base_type);
1405 ConstructType(Buffer, TyDesc, Unit);
1407 // Add debug information entry to entity and unit.
1408 DIE *Die = Unit->AddDie(Buffer);
1409 SetDIEntry(Slot, Die);
1410 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1415 /// ConstructType - Adds all the required attributes to the type.
1417 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1418 // Get core information.
1419 const std::string &Name = TyDesc->getName();
1420 uint64_t Size = TyDesc->getSize() >> 3;
1422 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1423 // Fundamental types like int, float, bool
1424 Buffer.setTag(DW_TAG_base_type);
1425 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1426 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1428 unsigned Tag = DerivedTy->getTag();
1429 // FIXME - Workaround for templates.
1430 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1431 // Pointers, typedefs et al.
1433 // Map to main type, void will not have a type.
1434 if (TypeDesc *FromTy = DerivedTy->getFromType())
1435 AddType(&Buffer, FromTy, Unit);
1436 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1438 unsigned Tag = CompTy->getTag();
1440 // Set tag accordingly.
1441 if (Tag == DW_TAG_vector_type)
1442 Buffer.setTag(DW_TAG_array_type);
1446 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1449 case DW_TAG_vector_type:
1450 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1452 case DW_TAG_array_type: {
1453 // Add element type.
1454 if (TypeDesc *FromTy = CompTy->getFromType())
1455 AddType(&Buffer, FromTy, Unit);
1457 // Don't emit size attribute.
1460 // Construct an anonymous type for index type.
1461 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1464 // Add subranges to array type.
1465 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1466 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1467 int64_t Lo = SRD->getLo();
1468 int64_t Hi = SRD->getHi();
1469 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1471 // If a range is available.
1473 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1474 // Only add low if non-zero.
1475 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1476 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1479 Buffer.AddChild(Subrange);
1483 case DW_TAG_structure_type:
1484 case DW_TAG_union_type: {
1485 // Add elements to structure type.
1486 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1487 DebugInfoDesc *Element = Elements[i];
1489 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1490 // Add field or base class.
1492 unsigned Tag = MemberDesc->getTag();
1494 // Extract the basic information.
1495 const std::string &Name = MemberDesc->getName();
1496 uint64_t Size = MemberDesc->getSize();
1497 uint64_t Align = MemberDesc->getAlign();
1498 uint64_t Offset = MemberDesc->getOffset();
1500 // Construct member debug information entry.
1501 DIE *Member = new DIE(Tag);
1503 // Add name if not "".
1505 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1506 // Add location if available.
1507 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1509 // Most of the time the field info is the same as the members.
1510 uint64_t FieldSize = Size;
1511 uint64_t FieldAlign = Align;
1512 uint64_t FieldOffset = Offset;
1514 // Set the member type.
1515 TypeDesc *FromTy = MemberDesc->getFromType();
1516 AddType(Member, FromTy, Unit);
1518 // Walk up typedefs until a real size is found.
1520 if (FromTy->getTag() != DW_TAG_typedef) {
1521 FieldSize = FromTy->getSize();
1522 FieldAlign = FromTy->getSize();
1526 FromTy = dyn_cast<DerivedTypeDesc>(FromTy)->getFromType();
1529 // Unless we have a bit field.
1530 if (Tag == DW_TAG_member && FieldSize != Size) {
1531 // Construct the alignment mask.
1532 uint64_t AlignMask = ~(FieldAlign - 1);
1533 // Determine the high bit + 1 of the declared size.
1534 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1535 // Work backwards to determine the base offset of the field.
1536 FieldOffset = HiMark - FieldSize;
1537 // Now normalize offset to the field.
1538 Offset -= FieldOffset;
1540 // Maybe we need to work from the other end.
1541 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1543 // Add size and offset.
1544 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1545 AddUInt(Member, DW_AT_bit_size, 0, Size);
1546 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1549 // Add computation for offset.
1550 DIEBlock *Block = new DIEBlock();
1551 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1552 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1553 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1555 // Add accessibility (public default unless is base class.
1556 if (MemberDesc->isProtected()) {
1557 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1558 } else if (MemberDesc->isPrivate()) {
1559 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1560 } else if (Tag == DW_TAG_inheritance) {
1561 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1564 Buffer.AddChild(Member);
1565 } else if (GlobalVariableDesc *StaticDesc =
1566 dyn_cast<GlobalVariableDesc>(Element)) {
1567 // Add static member.
1569 // Construct member debug information entry.
1570 DIE *Static = new DIE(DW_TAG_variable);
1572 // Add name and mangled name.
1573 const std::string &Name = StaticDesc->getName();
1574 const std::string &LinkageName = StaticDesc->getLinkageName();
1575 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1576 if (!LinkageName.empty()) {
1577 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1582 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1585 if (TypeDesc *StaticTy = StaticDesc->getType())
1586 AddType(Static, StaticTy, Unit);
1589 if (!StaticDesc->isStatic())
1590 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1591 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1593 Buffer.AddChild(Static);
1594 } else if (SubprogramDesc *MethodDesc =
1595 dyn_cast<SubprogramDesc>(Element)) {
1596 // Add member function.
1598 // Construct member debug information entry.
1599 DIE *Method = new DIE(DW_TAG_subprogram);
1601 // Add name and mangled name.
1602 const std::string &Name = MethodDesc->getName();
1603 const std::string &LinkageName = MethodDesc->getLinkageName();
1605 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1606 bool IsCTor = TyDesc->getName() == Name;
1608 if (!LinkageName.empty()) {
1609 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1614 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1617 if (CompositeTypeDesc *MethodTy =
1618 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1619 // Get argument information.
1620 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1625 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1629 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1630 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1631 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1632 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1633 Method->AddChild(Arg);
1638 if (!MethodDesc->isStatic())
1639 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1640 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1642 Buffer.AddChild(Method);
1647 case DW_TAG_enumeration_type: {
1648 // Add enumerators to enumeration type.
1649 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1650 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1651 const std::string &Name = ED->getName();
1652 int64_t Value = ED->getValue();
1653 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1654 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1655 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1656 Buffer.AddChild(Enumerator);
1661 case DW_TAG_subroutine_type: {
1662 // Add prototype flag.
1663 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1665 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1668 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1669 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1670 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1671 Buffer.AddChild(Arg);
1680 // Add size if non-zero (derived types don't have a size.)
1681 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1682 // Add name if not anonymous or intermediate type.
1683 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1684 // Add source line info if available.
1685 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1688 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1690 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1691 // Construct debug information entry.
1692 DIE *Die = new DIE(DW_TAG_compile_unit);
1693 if (TAI->isAbsoluteSectionOffsets())
1694 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1696 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1697 DWLabel("section_line", 0));
1698 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1699 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1700 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1701 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1703 // Construct compile unit.
1704 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1706 // Add Unit to compile unit map.
1707 DescToUnitMap[UnitDesc] = Unit;
1712 /// GetBaseCompileUnit - Get the main compile unit.
1714 CompileUnit *GetBaseCompileUnit() const {
1715 CompileUnit *Unit = CompileUnits[0];
1716 assert(Unit && "Missing compile unit.");
1720 /// FindCompileUnit - Get the compile unit for the given descriptor.
1722 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1723 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1724 assert(Unit && "Missing compile unit.");
1728 /// NewGlobalVariable - Add a new global variable DIE.
1730 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1731 // Get the compile unit context.
1732 CompileUnitDesc *UnitDesc =
1733 static_cast<CompileUnitDesc *>(GVD->getContext());
1734 CompileUnit *Unit = GetBaseCompileUnit();
1736 // Check for pre-existence.
1737 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1738 if (Slot) return Slot;
1740 // Get the global variable itself.
1741 GlobalVariable *GV = GVD->getGlobalVariable();
1743 const std::string &Name = GVD->getName();
1744 const std::string &FullName = GVD->getFullName();
1745 const std::string &LinkageName = GVD->getLinkageName();
1746 // Create the global's variable DIE.
1747 DIE *VariableDie = new DIE(DW_TAG_variable);
1748 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1749 if (!LinkageName.empty()) {
1750 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1753 AddType(VariableDie, GVD->getType(), Unit);
1754 if (!GVD->isStatic())
1755 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1757 // Add source line info if available.
1758 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1761 DIEBlock *Block = new DIEBlock();
1762 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1763 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1764 AddBlock(VariableDie, DW_AT_location, 0, Block);
1769 // Add to context owner.
1770 Unit->getDie()->AddChild(VariableDie);
1772 // Expose as global.
1773 // FIXME - need to check external flag.
1774 Unit->AddGlobal(FullName, VariableDie);
1779 /// NewSubprogram - Add a new subprogram DIE.
1781 DIE *NewSubprogram(SubprogramDesc *SPD) {
1782 // Get the compile unit context.
1783 CompileUnitDesc *UnitDesc =
1784 static_cast<CompileUnitDesc *>(SPD->getContext());
1785 CompileUnit *Unit = GetBaseCompileUnit();
1787 // Check for pre-existence.
1788 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1789 if (Slot) return Slot;
1791 // Gather the details (simplify add attribute code.)
1792 const std::string &Name = SPD->getName();
1793 const std::string &FullName = SPD->getFullName();
1794 const std::string &LinkageName = SPD->getLinkageName();
1796 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1797 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1798 if (!LinkageName.empty()) {
1799 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1802 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1803 if (!SPD->isStatic())
1804 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1805 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1807 // Add source line info if available.
1808 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1811 Slot = SubprogramDie;
1813 // Add to context owner.
1814 Unit->getDie()->AddChild(SubprogramDie);
1816 // Expose as global.
1817 Unit->AddGlobal(FullName, SubprogramDie);
1819 return SubprogramDie;
1822 /// NewScopeVariable - Create a new scope variable.
1824 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1825 // Get the descriptor.
1826 VariableDesc *VD = DV->getDesc();
1828 // Translate tag to proper Dwarf tag. The result variable is dropped for
1831 switch (VD->getTag()) {
1832 case DW_TAG_return_variable: return NULL;
1833 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1834 case DW_TAG_auto_variable: // fall thru
1835 default: Tag = DW_TAG_variable; break;
1838 // Define variable debug information entry.
1839 DIE *VariableDie = new DIE(Tag);
1840 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1842 // Add source line info if available.
1843 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1845 // Add variable type.
1846 AddType(VariableDie, VD->getType(), Unit);
1848 // Add variable address.
1849 MachineLocation Location;
1850 RI->getLocation(*MF, DV->getFrameIndex(), Location);
1851 AddAddress(VariableDie, DW_AT_location, Location);
1856 /// ConstructScope - Construct the components of a scope.
1858 void ConstructScope(DebugScope *ParentScope,
1859 unsigned ParentStartID, unsigned ParentEndID,
1860 DIE *ParentDie, CompileUnit *Unit) {
1861 // Add variables to scope.
1862 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1863 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1864 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1865 if (VariableDie) ParentDie->AddChild(VariableDie);
1868 // Add nested scopes.
1869 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1870 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1871 // Define the Scope debug information entry.
1872 DebugScope *Scope = Scopes[j];
1873 // FIXME - Ignore inlined functions for the time being.
1874 if (!Scope->getParent()) continue;
1876 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1877 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1879 // Ignore empty scopes.
1880 if (StartID == EndID && StartID != 0) continue;
1881 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1883 if (StartID == ParentStartID && EndID == ParentEndID) {
1884 // Just add stuff to the parent scope.
1885 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1887 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1889 // Add the scope bounds.
1891 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1892 DWLabel("label", StartID));
1894 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1895 DWLabel("func_begin", SubprogramCount));
1898 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1899 DWLabel("label", EndID));
1901 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1902 DWLabel("func_end", SubprogramCount));
1905 // Add the scope contents.
1906 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1907 ParentDie->AddChild(ScopeDie);
1912 /// ConstructRootScope - Construct the scope for the subprogram.
1914 void ConstructRootScope(DebugScope *RootScope) {
1915 // Exit if there is no root scope.
1916 if (!RootScope) return;
1918 // Get the subprogram debug information entry.
1919 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1921 // Get the compile unit context.
1922 CompileUnit *Unit = GetBaseCompileUnit();
1924 // Get the subprogram die.
1925 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1926 assert(SPDie && "Missing subprogram descriptor");
1928 // Add the function bounds.
1929 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1930 DWLabel("func_begin", SubprogramCount));
1931 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1932 DWLabel("func_end", SubprogramCount));
1933 MachineLocation Location(RI->getFrameRegister(*MF));
1934 AddAddress(SPDie, DW_AT_frame_base, Location);
1936 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1939 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1940 /// tools to recognize the object file contains Dwarf information.
1941 void EmitInitial() {
1942 // Check to see if we already emitted intial headers.
1943 if (didInitial) return;
1946 // Dwarf sections base addresses.
1947 if (TAI->getDwarfRequiresFrameSection()) {
1948 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1949 EmitLabel("section_frame", 0);
1951 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1952 EmitLabel("section_info", 0);
1953 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1954 EmitLabel("section_abbrev", 0);
1955 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1956 EmitLabel("section_aranges", 0);
1957 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1958 EmitLabel("section_macinfo", 0);
1959 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1960 EmitLabel("section_line", 0);
1961 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1962 EmitLabel("section_loc", 0);
1963 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1964 EmitLabel("section_pubnames", 0);
1965 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1966 EmitLabel("section_str", 0);
1967 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1968 EmitLabel("section_ranges", 0);
1970 Asm->SwitchToTextSection(TAI->getTextSection());
1971 EmitLabel("text_begin", 0);
1972 Asm->SwitchToDataSection(TAI->getDataSection());
1973 EmitLabel("data_begin", 0);
1975 // Emit common frame information.
1976 EmitInitialDebugFrame();
1979 /// EmitDIE - Recusively Emits a debug information entry.
1981 void EmitDIE(DIE *Die) const {
1982 // Get the abbreviation for this DIE.
1983 unsigned AbbrevNumber = Die->getAbbrevNumber();
1984 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1988 // Emit the code (index) for the abbreviation.
1989 Asm->EmitULEB128Bytes(AbbrevNumber);
1990 Asm->EOL(std::string("Abbrev [" +
1991 utostr(AbbrevNumber) +
1992 "] 0x" + utohexstr(Die->getOffset()) +
1993 ":0x" + utohexstr(Die->getSize()) + " " +
1994 TagString(Abbrev->getTag())));
1996 const std::vector<DIEValue *> &Values = Die->getValues();
1997 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1999 // Emit the DIE attribute values.
2000 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2001 unsigned Attr = AbbrevData[i].getAttribute();
2002 unsigned Form = AbbrevData[i].getForm();
2003 assert(Form && "Too many attributes for DIE (check abbreviation)");
2006 case DW_AT_sibling: {
2007 Asm->EmitInt32(Die->SiblingOffset());
2011 // Emit an attribute using the defined form.
2012 Values[i]->EmitValue(*this, Form);
2017 Asm->EOL(AttributeString(Attr));
2020 // Emit the DIE children if any.
2021 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2022 const std::vector<DIE *> &Children = Die->getChildren();
2024 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2025 EmitDIE(Children[j]);
2028 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2032 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2034 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2035 // Get the children.
2036 const std::vector<DIE *> &Children = Die->getChildren();
2038 // If not last sibling and has children then add sibling offset attribute.
2039 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2041 // Record the abbreviation.
2042 AssignAbbrevNumber(Die->getAbbrev());
2044 // Get the abbreviation for this DIE.
2045 unsigned AbbrevNumber = Die->getAbbrevNumber();
2046 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2049 Die->setOffset(Offset);
2051 // Start the size with the size of abbreviation code.
2052 Offset += Asm->SizeULEB128(AbbrevNumber);
2054 const std::vector<DIEValue *> &Values = Die->getValues();
2055 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2057 // Size the DIE attribute values.
2058 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2059 // Size attribute value.
2060 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2063 // Size the DIE children if any.
2064 if (!Children.empty()) {
2065 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2066 "Children flag not set");
2068 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2069 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2072 // End of children marker.
2073 Offset += sizeof(int8_t);
2076 Die->setSize(Offset - Die->getOffset());
2080 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2082 void SizeAndOffsets() {
2083 // Process base compile unit.
2084 CompileUnit *Unit = GetBaseCompileUnit();
2085 // Compute size of compile unit header
2086 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2087 sizeof(int16_t) + // DWARF version number
2088 sizeof(int32_t) + // Offset Into Abbrev. Section
2089 sizeof(int8_t); // Pointer Size (in bytes)
2090 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2093 /// EmitDebugInfo - Emit the debug info section.
2095 void EmitDebugInfo() const {
2096 // Start debug info section.
2097 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2099 CompileUnit *Unit = GetBaseCompileUnit();
2100 DIE *Die = Unit->getDie();
2101 // Emit the compile units header.
2102 EmitLabel("info_begin", Unit->getID());
2103 // Emit size of content not including length itself
2104 unsigned ContentSize = Die->getSize() +
2105 sizeof(int16_t) + // DWARF version number
2106 sizeof(int32_t) + // Offset Into Abbrev. Section
2107 sizeof(int8_t) + // Pointer Size (in bytes)
2108 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2110 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2111 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2112 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true);
2113 Asm->EOL("Offset Into Abbrev. Section");
2114 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2117 // FIXME - extra padding for gdb bug.
2118 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2119 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2120 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2121 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2122 EmitLabel("info_end", Unit->getID());
2127 /// EmitAbbreviations - Emit the abbreviation section.
2129 void EmitAbbreviations() const {
2130 // Check to see if it is worth the effort.
2131 if (!Abbreviations.empty()) {
2132 // Start the debug abbrev section.
2133 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2135 EmitLabel("abbrev_begin", 0);
2137 // For each abbrevation.
2138 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2139 // Get abbreviation data
2140 const DIEAbbrev *Abbrev = Abbreviations[i];
2142 // Emit the abbrevations code (base 1 index.)
2143 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2144 Asm->EOL("Abbreviation Code");
2146 // Emit the abbreviations data.
2147 Abbrev->Emit(*this);
2152 // Mark end of abbreviations.
2153 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2155 EmitLabel("abbrev_end", 0);
2161 /// EmitDebugLines - Emit source line information.
2163 void EmitDebugLines() const {
2164 // Minimum line delta, thus ranging from -10..(255-10).
2165 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2166 // Maximum line delta, thus ranging from -10..(255-10).
2167 const int MaxLineDelta = 255 + MinLineDelta;
2169 // Start the dwarf line section.
2170 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2172 // Construct the section header.
2174 EmitDifference("line_end", 0, "line_begin", 0, true);
2175 Asm->EOL("Length of Source Line Info");
2176 EmitLabel("line_begin", 0);
2178 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2180 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2181 Asm->EOL("Prolog Length");
2182 EmitLabel("line_prolog_begin", 0);
2184 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2186 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2188 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2190 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2192 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2194 // Line number standard opcode encodings argument count
2195 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2196 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2197 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2198 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2199 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2200 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2201 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2202 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2203 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2205 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2206 const UniqueVector<SourceFileInfo>
2207 &SourceFiles = MMI->getSourceFiles();
2209 // Emit directories.
2210 for (unsigned DirectoryID = 1, NDID = Directories.size();
2211 DirectoryID <= NDID; ++DirectoryID) {
2212 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2214 Asm->EmitInt8(0); Asm->EOL("End of directories");
2217 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2218 SourceID <= NSID; ++SourceID) {
2219 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2220 Asm->EmitString(SourceFile.getName());
2222 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2223 Asm->EOL("Directory #");
2224 Asm->EmitULEB128Bytes(0);
2225 Asm->EOL("Mod date");
2226 Asm->EmitULEB128Bytes(0);
2227 Asm->EOL("File size");
2229 Asm->EmitInt8(0); Asm->EOL("End of files");
2231 EmitLabel("line_prolog_end", 0);
2233 // A sequence for each text section.
2234 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2235 // Isolate current sections line info.
2236 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2238 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2240 // Dwarf assumes we start with first line of first source file.
2241 unsigned Source = 1;
2244 // Construct rows of the address, source, line, column matrix.
2245 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2246 const SourceLineInfo &LineInfo = LineInfos[i];
2247 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2248 if (!LabelID) continue;
2250 unsigned SourceID = LineInfo.getSourceID();
2251 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2252 unsigned DirectoryID = SourceFile.getDirectoryID();
2253 Asm->EOL(Directories[DirectoryID]
2254 + SourceFile.getName()
2256 + utostr_32(LineInfo.getLine()));
2258 // Define the line address.
2259 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2260 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2261 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2262 EmitReference("label", LabelID); Asm->EOL("Location label");
2264 // If change of source, then switch to the new source.
2265 if (Source != LineInfo.getSourceID()) {
2266 Source = LineInfo.getSourceID();
2267 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2268 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2271 // If change of line.
2272 if (Line != LineInfo.getLine()) {
2273 // Determine offset.
2274 int Offset = LineInfo.getLine() - Line;
2275 int Delta = Offset - MinLineDelta;
2278 Line = LineInfo.getLine();
2280 // If delta is small enough and in range...
2281 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2282 // ... then use fast opcode.
2283 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2285 // ... otherwise use long hand.
2286 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2287 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2288 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2291 // Copy the previous row (different address or source)
2292 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2296 // Define last address of section.
2297 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2298 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2299 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2300 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2302 // Mark end of matrix.
2303 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2304 Asm->EmitULEB128Bytes(1); Asm->EOL();
2305 Asm->EmitInt8(1); Asm->EOL();
2308 EmitLabel("line_end", 0);
2313 /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2315 void EmitInitialDebugFrame() {
2316 if (!TAI->getDwarfRequiresFrameSection())
2320 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2321 TargetFrameInfo::StackGrowsUp ?
2322 TAI->getAddressSize() : -TAI->getAddressSize();
2324 // Start the dwarf frame section.
2325 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2327 EmitLabel("frame_common", 0);
2328 EmitDifference("frame_common_end", 0,
2329 "frame_common_begin", 0, true);
2330 Asm->EOL("Length of Common Information Entry");
2332 EmitLabel("frame_common_begin", 0);
2333 Asm->EmitInt32((int)DW_CIE_ID);
2334 Asm->EOL("CIE Identifier Tag");
2335 Asm->EmitInt8(DW_CIE_VERSION);
2336 Asm->EOL("CIE Version");
2337 Asm->EmitString("");
2338 Asm->EOL("CIE Augmentation");
2339 Asm->EmitULEB128Bytes(1);
2340 Asm->EOL("CIE Code Alignment Factor");
2341 Asm->EmitSLEB128Bytes(stackGrowth);
2342 Asm->EOL("CIE Data Alignment Factor");
2343 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2344 Asm->EOL("CIE RA Column");
2346 std::vector<MachineMove> Moves;
2347 RI->getInitialFrameState(Moves);
2348 EmitFrameMoves(NULL, 0, Moves);
2350 Asm->EmitAlignment(2);
2351 EmitLabel("frame_common_end", 0);
2356 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2358 void EmitFunctionDebugFrame() {
2359 if (!TAI->getDwarfRequiresFrameSection())
2362 // Start the dwarf frame section.
2363 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2365 EmitDifference("frame_end", SubprogramCount,
2366 "frame_begin", SubprogramCount, true);
2367 Asm->EOL("Length of Frame Information Entry");
2369 EmitLabel("frame_begin", SubprogramCount);
2371 EmitSectionOffset("frame_common_begin", "section_frame", 0, 0, true);
2372 Asm->EOL("FDE CIE offset");
2374 EmitReference("func_begin", SubprogramCount);
2375 Asm->EOL("FDE initial location");
2376 EmitDifference("func_end", SubprogramCount,
2377 "func_begin", SubprogramCount);
2378 Asm->EOL("FDE address range");
2380 std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2382 EmitFrameMoves("func_begin", SubprogramCount, Moves);
2384 Asm->EmitAlignment(2);
2385 EmitLabel("frame_end", SubprogramCount);
2390 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2392 void EmitDebugPubNames() {
2393 // Start the dwarf pubnames section.
2394 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2396 CompileUnit *Unit = GetBaseCompileUnit();
2398 EmitDifference("pubnames_end", Unit->getID(),
2399 "pubnames_begin", Unit->getID(), true);
2400 Asm->EOL("Length of Public Names Info");
2402 EmitLabel("pubnames_begin", Unit->getID());
2404 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2406 EmitSectionOffset("info_begin", "section_info", Unit->getID(), 0, true);
2407 Asm->EOL("Offset of Compilation Unit Info");
2409 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2410 Asm->EOL("Compilation Unit Length");
2412 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2414 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2417 const std::string &Name = GI->first;
2418 DIE * Entity = GI->second;
2420 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2421 Asm->EmitString(Name); Asm->EOL("External Name");
2424 Asm->EmitInt32(0); Asm->EOL("End Mark");
2425 EmitLabel("pubnames_end", Unit->getID());
2430 /// EmitDebugStr - Emit visible names into a debug str section.
2432 void EmitDebugStr() {
2433 // Check to see if it is worth the effort.
2434 if (!StringPool.empty()) {
2435 // Start the dwarf str section.
2436 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2438 // For each of strings in the string pool.
2439 for (unsigned StringID = 1, N = StringPool.size();
2440 StringID <= N; ++StringID) {
2441 // Emit a label for reference from debug information entries.
2442 EmitLabel("string", StringID);
2443 // Emit the string itself.
2444 const std::string &String = StringPool[StringID];
2445 Asm->EmitString(String); Asm->EOL();
2452 /// EmitDebugLoc - Emit visible names into a debug loc section.
2454 void EmitDebugLoc() {
2455 // Start the dwarf loc section.
2456 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2461 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2463 void EmitDebugARanges() {
2464 // Start the dwarf aranges section.
2465 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2469 CompileUnit *Unit = GetBaseCompileUnit();
2471 // Don't include size of length
2472 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2474 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2476 EmitReference("info_begin", Unit->getID());
2477 Asm->EOL("Offset of Compilation Unit Info");
2479 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2481 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2483 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2484 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2487 EmitReference("text_begin", 0); Asm->EOL("Address");
2488 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2490 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2491 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2497 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2499 void EmitDebugRanges() {
2500 // Start the dwarf ranges section.
2501 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2506 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2508 void EmitDebugMacInfo() {
2509 // Start the dwarf macinfo section.
2510 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2515 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2517 void ConstructCompileUnitDIEs() {
2518 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2520 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2521 unsigned ID = MMI->RecordSource(CUW[i]);
2522 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2523 CompileUnits.push_back(Unit);
2527 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2528 /// global variables.
2529 void ConstructGlobalDIEs() {
2530 std::vector<GlobalVariableDesc *> GlobalVariables =
2531 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2533 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2534 GlobalVariableDesc *GVD = GlobalVariables[i];
2535 NewGlobalVariable(GVD);
2539 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2541 void ConstructSubprogramDIEs() {
2542 std::vector<SubprogramDesc *> Subprograms =
2543 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2545 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2546 SubprogramDesc *SPD = Subprograms[i];
2552 //===--------------------------------------------------------------------===//
2553 // Main entry points.
2555 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2558 , AbbreviationsSet(InitAbbreviationsSetSize)
2560 , ValuesSet(InitValuesSetSize)
2565 , SectionSourceLines()
2570 virtual ~DwarfDebug() {
2571 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2572 delete CompileUnits[i];
2573 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2577 /// SetModuleInfo - Set machine module information when it's known that pass
2578 /// manager has created it. Set by the target AsmPrinter.
2579 void SetModuleInfo(MachineModuleInfo *mmi) {
2580 // Make sure initial declarations are made.
2581 if (!MMI && mmi->hasDebugInfo()) {
2585 // Emit initial sections
2588 // Create all the compile unit DIEs.
2589 ConstructCompileUnitDIEs();
2591 // Create DIEs for each of the externally visible global variables.
2592 ConstructGlobalDIEs();
2594 // Create DIEs for each of the externally visible subprograms.
2595 ConstructSubprogramDIEs();
2597 // Prime section data.
2598 SectionMap.insert(TAI->getTextSection());
2602 /// BeginModule - Emit all Dwarf sections that should come prior to the
2604 void BeginModule(Module *M) {
2607 if (!ShouldEmitDwarf()) return;
2610 /// EndModule - Emit all Dwarf sections that should come after the content.
2613 if (!ShouldEmitDwarf()) return;
2615 // Standard sections final addresses.
2616 Asm->SwitchToTextSection(TAI->getTextSection());
2617 EmitLabel("text_end", 0);
2618 Asm->SwitchToDataSection(TAI->getDataSection());
2619 EmitLabel("data_end", 0);
2621 // End text sections.
2622 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2623 Asm->SwitchToTextSection(SectionMap[i].c_str());
2624 EmitLabel("section_end", i);
2627 // Compute DIE offsets and sizes.
2630 // Emit all the DIEs into a debug info section
2633 // Corresponding abbreviations into a abbrev section.
2634 EmitAbbreviations();
2636 // Emit source line correspondence into a debug line section.
2639 // Emit info into a debug pubnames section.
2640 EmitDebugPubNames();
2642 // Emit info into a debug str section.
2645 // Emit info into a debug loc section.
2648 // Emit info into a debug aranges section.
2651 // Emit info into a debug ranges section.
2654 // Emit info into a debug macinfo section.
2658 /// BeginFunction - Gather pre-function debug information. Assumes being
2659 /// emitted immediately after the function entry point.
2660 void BeginFunction(MachineFunction *MF) {
2663 if (!ShouldEmitDwarf()) return;
2665 // Begin accumulating function debug information.
2666 MMI->BeginFunction(MF);
2668 // Assumes in correct section after the entry point.
2669 EmitLabel("func_begin", ++SubprogramCount);
2672 /// EndFunction - Gather and emit post-function debug information.
2674 void EndFunction() {
2675 if (!ShouldEmitDwarf()) return;
2677 // Define end label for subprogram.
2678 EmitLabel("func_end", SubprogramCount);
2680 // Get function line info.
2681 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2683 if (!LineInfos.empty()) {
2684 // Get section line info.
2685 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2686 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2687 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2688 // Append the function info to section info.
2689 SectionLineInfos.insert(SectionLineInfos.end(),
2690 LineInfos.begin(), LineInfos.end());
2693 // Construct scopes for subprogram.
2694 ConstructRootScope(MMI->getRootScope());
2696 // Emit function frame information.
2697 EmitFunctionDebugFrame();
2701 //===----------------------------------------------------------------------===//
2702 /// DwarfException - Emits Dwarf exception handling directives.
2704 class DwarfException : public Dwarf {
2708 /// didInitial - Flag to indicate if initial emission has been done.
2712 /// shouldEmit - Flag to indicate if debug information should be emitted.
2716 /// FuncCPPPersonality - C++ persoanlity function.
2718 Function *FuncCPPPersonality;
2720 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2722 void EmitCommonEHFrame() {
2724 if (didInitial) return;
2727 // If there is a personality present then we need to indicate that
2728 // in the common eh frame.
2729 Function *Personality = FuncCPPPersonality;
2731 // Size and sign of stack growth.
2733 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2734 TargetFrameInfo::StackGrowsUp ?
2735 TAI->getAddressSize() : -TAI->getAddressSize();
2737 // Begin eh frame section.
2738 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2740 EmitLabel("section_eh_frame", 0);
2742 // Define base labels.
2743 EmitLabel("eh_frame_common", 0);
2745 // Define the eh frame length.
2746 EmitDifference("eh_frame_common_end", 0,
2747 "eh_frame_common_begin", 0, true);
2748 Asm->EOL("Length of Common Information Entry");
2751 EmitLabel("eh_frame_common_begin", 0);
2752 Asm->EmitInt32((int)0);
2753 Asm->EOL("CIE Identifier Tag");
2754 Asm->EmitInt8(DW_CIE_VERSION);
2755 Asm->EOL("CIE Version");
2757 // The personality presence indicates that language specific information
2758 // will show up in the eh frame.
2759 Asm->EmitString(Personality ? "zPLR" : "zR");
2760 Asm->EOL("CIE Augmentation");
2762 // Round out reader.
2763 Asm->EmitULEB128Bytes(1);
2764 Asm->EOL("CIE Code Alignment Factor");
2765 Asm->EmitSLEB128Bytes(stackGrowth);
2766 Asm->EOL("CIE Data Alignment Factor");
2767 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2768 Asm->EOL("CIE RA Column");
2770 // If there is a personality, we need to indicate the functions location.
2772 Asm->EmitULEB128Bytes(7);
2773 Asm->EOL("Augmentation Size");
2774 Asm->EmitInt8(DW_EH_PE_indirect |
2777 Asm->EOL("Personality (indirect pcrel sdata4)");
2779 O << TAI->getData32bitsDirective();
2780 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2781 O << "-" << TAI->getPCSymbol();
2782 Asm->EOL("Personality");
2784 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2785 Asm->EOL("LSDA Encoding (pcrel)");
2786 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2787 Asm->EOL("FDE Encoding (pcrel)");
2789 Asm->EmitULEB128Bytes(1);
2790 Asm->EOL("Augmentation Size");
2791 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2792 Asm->EOL("FDE Encoding (pcrel)");
2795 // Indicate locations of general callee saved registers in frame.
2796 std::vector<MachineMove> Moves;
2797 RI->getInitialFrameState(Moves);
2798 EmitFrameMoves(NULL, 0, Moves);
2800 Asm->EmitAlignment(2);
2801 EmitLabel("eh_frame_common_end", 0);
2806 /// EmitEHFrame - Emit initial exception information.
2808 void EmitEHFrame() {
2809 // If there is a personality present then we need to indicate that
2810 // in the common eh frame.
2811 Function *Personality = FuncCPPPersonality;
2812 // Function *Personality = MMI->getPersonality();
2813 MachineFrameInfo *MFI = MF->getFrameInfo();
2815 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2817 // Externally visible entry into the functions eh frame info.
2818 if (const char *GlobalDirective = TAI->getGlobalDirective())
2819 O << GlobalDirective << getAsm()->CurrentFnName << ".eh\n";
2821 // If there are no calls then you can't unwind.
2822 if (!MFI->hasCalls()) {
2823 O << getAsm()->CurrentFnName << ".eh = 0\n";
2825 O << getAsm()->CurrentFnName << ".eh:\n";
2828 EmitDifference("eh_frame_end", SubprogramCount,
2829 "eh_frame_begin", SubprogramCount, true);
2830 Asm->EOL("Length of Frame Information Entry");
2832 EmitLabel("eh_frame_begin", SubprogramCount);
2834 EmitSectionOffset("eh_frame_begin", "section_eh_frame",
2835 SubprogramCount, 0, true);
2836 Asm->EOL("FDE CIE offset");
2838 EmitReference("eh_func_begin", SubprogramCount, true);
2839 Asm->EOL("FDE initial location");
2840 EmitDifference("eh_func_end", SubprogramCount,
2841 "eh_func_begin", SubprogramCount);
2842 Asm->EOL("FDE address range");
2844 // If there is a personality and landing pads then point to the language
2845 // specific data area in the exception table.
2847 Asm->EmitULEB128Bytes(4);
2848 Asm->EOL("Augmentation size");
2850 if (!MMI->getLandingPads().empty()) {
2851 EmitReference("exception", SubprogramCount, true);
2852 } else if(TAI->getAddressSize() == 8) {
2853 Asm->EmitInt64((int)0);
2855 Asm->EmitInt32((int)0);
2857 Asm->EOL("Language Specific Data Area");
2859 Asm->EmitULEB128Bytes(0);
2860 Asm->EOL("Augmentation size");
2863 // Indicate locations of function specific callee saved registers in
2865 std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2866 EmitFrameMoves("eh_func_begin", SubprogramCount, Moves);
2868 Asm->EmitAlignment(2);
2869 EmitLabel("eh_frame_end", SubprogramCount);
2872 if (const char *UsedDirective = TAI->getUsedDirective())
2873 O << UsedDirective << getAsm()->CurrentFnName << ".eh\n\n";
2876 /// EmitExceptionTable - Emit landpads and actions.
2878 /// The general organization of the table is complex, but the basic concepts
2879 /// are easy. First there is a header which describes the location and
2880 /// organization of the three components that follow.
2881 /// 1. The landing pad site information describes the range of code covered
2882 /// by the try. In our case it's an accumulation of the ranges covered
2883 /// by the invokes in the try. There is also a reference to the landing
2884 /// pad that handles the exception once processed. Finally an index into
2885 /// the actions table.
2886 /// 2. The action table, in our case, is composed of pairs of type ids
2887 /// and next action offset. Starting with the action index from the
2888 /// landing pad site, each type Id is checked for a match to the current
2889 /// exception. If it matches then the exception and type id are passed
2890 /// on to the landing pad. Otherwise the next action is looked up. This
2891 /// chain is terminated with a next action of zero. If no type id is
2892 /// found the the frame is unwound and handling continues.
2893 /// 3. Type id table contains references to all the C++ typeinfo for all
2894 /// catches in the function. This tables is reversed indexed base 1.
2895 void EmitExceptionTable() {
2896 // Map all labels and get rid of any dead landing pads.
2897 MMI->TidyLandingPads();
2899 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
2900 const std::vector<LandingPadInfo> &LandingPads = MMI->getLandingPads();
2901 if (LandingPads.empty()) return;
2903 // FIXME - Should fold actions for multiple landing pads.
2905 // Gather first action index for each landing pad site.
2906 SmallVector<unsigned, 8> Actions;
2908 // FIXME - Assume there is only one filter typeinfo list per function
2909 // time being. I.E., Each call to eh_filter will have the same list.
2910 // This can change if a function is inlined.
2911 const LandingPadInfo *Filter = 0;
2913 // Compute sizes for exception table.
2914 unsigned SizeHeader = sizeof(int8_t) + // LPStart format
2915 sizeof(int8_t) + // TType format
2916 sizeof(int8_t) + // TType base offset (NEED ULEB128)
2917 sizeof(int8_t) + // Call site format
2918 sizeof(int8_t); // Call-site table length
2919 unsigned SizeSites = 0;
2920 unsigned SizeActions = 0;
2922 // Look at each landing pad site to compute size. We need the size of each
2923 // landing pad site info and the size of the landing pad's actions.
2924 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2925 const LandingPadInfo &LandingPad = LandingPads[i];
2926 bool IsFilter = LandingPad.IsFilter;
2927 unsigned SizeSiteActions = 0;
2928 const std::vector<unsigned> &TypeIds = LandingPad.TypeIds;
2929 unsigned SizeAction = 0;
2933 // FIXME - Assume there is only one filter typeinfo list per function
2934 // time being. I.E., Each call to eh_filter will have the same list.
2935 // This can change if a function is inlined.
2936 Filter = &LandingPad;
2937 SizeAction = Asm->SizeSLEB128(-1) + Asm->SizeSLEB128(0);
2938 SizeSiteActions += SizeAction;
2939 // Record the first action of the landing pad site.
2940 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
2941 } else if (TypeIds.empty()) {
2944 // Gather the action sizes
2945 for (unsigned j = 0, M = TypeIds.size(); j != M; ++j) {
2946 unsigned TypeID = TypeIds[i];
2947 unsigned SizeTypeID = Asm->SizeSLEB128(TypeID);
2948 signed Action = j ? -(SizeAction + SizeTypeID) : 0;
2949 SizeAction = SizeTypeID + Asm->SizeSLEB128(Action);
2950 SizeSiteActions += SizeAction;
2953 // Record the first action of the landing pad site.
2954 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
2957 Actions.push_back(FirstAction);
2959 // Compute this sites contribution to size.
2960 SizeActions += SizeSiteActions;
2961 SizeSites += sizeof(int32_t) + // Site start.
2962 sizeof(int32_t) + // Site length.
2963 sizeof(int32_t) + // Landing pad.
2964 Asm->SizeSLEB128(FirstAction); // Action.
2968 unsigned SizeTypes = TypeInfos.size() * TAI->getAddressSize();
2969 unsigned SizePreType = SizeHeader + SizeSites + SizeActions;
2970 unsigned SizeAlign = (4 - SizePreType) & 3;
2971 unsigned TypeOffset = SizePreType +
2974 sizeof(int8_t) - // LPStart format
2975 sizeof(int8_t) - // TType format
2976 sizeof(int8_t); // TType base offset (NEED ULEB128)
2978 // Begin the exception table.
2979 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
2980 O << "GCC_except_table" << SubprogramCount << ":\n";
2981 EmitLabel("exception", SubprogramCount);
2984 Asm->EmitInt8(DW_EH_PE_omit);
2985 Asm->EOL("LPStart format (DW_EH_PE_omit)");
2986 Asm->EmitInt8(DW_EH_PE_absptr);
2987 Asm->EOL("TType format (DW_EH_PE_absptr)");
2988 Asm->EmitULEB128Bytes(TypeOffset);
2989 Asm->EOL("TType base offset");
2990 Asm->EmitInt8(DW_EH_PE_udata4);
2991 Asm->EOL("Call site format (DW_EH_PE_udata4)");
2992 Asm->EmitULEB128Bytes(SizeSites);
2993 Asm->EOL("Call-site table length");
2995 // Emit the landng pad site information.
2996 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2997 const LandingPadInfo &LandingPad = LandingPads[i];
2998 EmitSectionOffset("label", "eh_func_begin",
2999 LandingPad.BeginLabel, SubprogramCount);
3000 Asm->EOL("Region start");
3002 EmitDifference("label", LandingPad.EndLabel,
3003 "label", LandingPad.BeginLabel);
3004 Asm->EOL("Region length");
3006 if (LandingPad.TypeIds.empty()) {
3007 if (TAI->getAddressSize() == sizeof(int32_t))
3012 EmitSectionOffset("label", "eh_func_begin",
3013 LandingPad.LandingPadLabel, SubprogramCount);
3015 Asm->EOL("Landing pad");
3017 Asm->EmitULEB128Bytes(Actions[i]);
3021 // Emit the actions.
3022 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3023 const LandingPadInfo &LandingPad = LandingPads[i];
3024 const std::vector<unsigned> &TypeIds = LandingPad.TypeIds;
3025 unsigned SizeAction = 0;
3027 if (LandingPad.IsFilter) {
3028 Asm->EmitSLEB128Bytes(-1);
3029 Asm->EOL("TypeInfo index");
3030 Asm->EmitSLEB128Bytes(0);
3031 Asm->EOL("Next action");
3033 for (unsigned j = 0, M = TypeIds.size(); j < M; ++j) {
3034 unsigned TypeID = TypeIds[j];
3035 unsigned SizeTypeID = Asm->SizeSLEB128(TypeID);
3036 Asm->EmitSLEB128Bytes(TypeID);
3037 Asm->EOL("TypeInfo index");
3038 signed Action = j ? -(SizeAction + SizeTypeID) : 0;
3039 SizeAction = SizeTypeID + Asm->SizeSLEB128(Action);
3040 Asm->EmitSLEB128Bytes(Action);
3041 Asm->EOL("Next action");
3046 // Emit the type ids.
3047 Asm->EmitAlignment(2);
3048 for (unsigned M = TypeInfos.size(); M; --M) {
3049 GlobalVariable *GV = TypeInfos[M - 1];
3051 if (TAI->getAddressSize() == sizeof(int32_t))
3052 O << TAI->getData32bitsDirective();
3054 O << TAI->getData64bitsDirective();
3057 O << Asm->getGlobalLinkName(GV);
3061 Asm->EOL("TypeInfo");
3064 // Emit the filter typeinfo.
3066 const std::vector<unsigned> &TypeIds = Filter->TypeIds;
3067 for (unsigned j = 0, M = TypeIds.size(); j < M; ++j) {
3068 unsigned TypeID = TypeIds[j];
3069 Asm->EmitSLEB128Bytes(TypeID);
3070 Asm->EOL("TypeInfo index");
3072 Asm->EmitSLEB128Bytes(0);
3073 Asm->EOL("End of filter typeinfo");
3076 Asm->EmitAlignment(2);
3080 //===--------------------------------------------------------------------===//
3081 // Main entry points.
3083 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3087 , FuncCPPPersonality(NULL)
3090 virtual ~DwarfException() {}
3092 /// SetModuleInfo - Set machine module information when it's known that pass
3093 /// manager has created it. Set by the target AsmPrinter.
3094 void SetModuleInfo(MachineModuleInfo *mmi) {
3098 /// BeginModule - Emit all exception information that should come prior to the
3100 void BeginModule(Module *M) {
3102 FuncCPPPersonality = M->getFunction("__gxx_personality_v0");
3105 /// EndModule - Emit all exception information that should come after the
3110 /// BeginFunction - Gather pre-function exception information. Assumes being
3111 /// emitted immediately after the function entry point.
3112 void BeginFunction(MachineFunction *MF) {
3116 ExceptionHandling &&
3117 TAI->getSupportsExceptionHandling()) {
3119 // Assumes in correct section after the entry point.
3120 EmitLabel("eh_func_begin", ++SubprogramCount);
3124 /// EndFunction - Gather and emit post-function exception information.
3126 void EndFunction() {
3127 if (!shouldEmit) return;
3129 EmitLabel("eh_func_end", SubprogramCount);
3130 EmitExceptionTable();
3131 EmitCommonEHFrame();
3136 } // End of namespace llvm
3138 //===----------------------------------------------------------------------===//
3140 /// Emit - Print the abbreviation using the specified Dwarf writer.
3142 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3143 // Emit its Dwarf tag type.
3144 DD.getAsm()->EmitULEB128Bytes(Tag);
3145 DD.getAsm()->EOL(TagString(Tag));
3147 // Emit whether it has children DIEs.
3148 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3149 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3151 // For each attribute description.
3152 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3153 const DIEAbbrevData &AttrData = Data[i];
3155 // Emit attribute type.
3156 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3157 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3160 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3161 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3164 // Mark end of abbreviation.
3165 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3166 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3170 void DIEAbbrev::print(std::ostream &O) {
3171 O << "Abbreviation @"
3172 << std::hex << (intptr_t)this << std::dec
3176 << ChildrenString(ChildrenFlag)
3179 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3181 << AttributeString(Data[i].getAttribute())
3183 << FormEncodingString(Data[i].getForm())
3187 void DIEAbbrev::dump() { print(cerr); }
3190 //===----------------------------------------------------------------------===//
3193 void DIEValue::dump() {
3198 //===----------------------------------------------------------------------===//
3200 /// EmitValue - Emit integer of appropriate size.
3202 void DIEInteger::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3204 case DW_FORM_flag: // Fall thru
3205 case DW_FORM_ref1: // Fall thru
3206 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3207 case DW_FORM_ref2: // Fall thru
3208 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3209 case DW_FORM_ref4: // Fall thru
3210 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3211 case DW_FORM_ref8: // Fall thru
3212 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3213 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3214 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3215 default: assert(0 && "DIE Value form not supported yet"); break;
3219 /// SizeOf - Determine size of integer value in bytes.
3221 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3223 case DW_FORM_flag: // Fall thru
3224 case DW_FORM_ref1: // Fall thru
3225 case DW_FORM_data1: return sizeof(int8_t);
3226 case DW_FORM_ref2: // Fall thru
3227 case DW_FORM_data2: return sizeof(int16_t);
3228 case DW_FORM_ref4: // Fall thru
3229 case DW_FORM_data4: return sizeof(int32_t);
3230 case DW_FORM_ref8: // Fall thru
3231 case DW_FORM_data8: return sizeof(int64_t);
3232 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3233 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3234 default: assert(0 && "DIE Value form not supported yet"); break;
3239 //===----------------------------------------------------------------------===//
3241 /// EmitValue - Emit string value.
3243 void DIEString::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3244 DD.getAsm()->EmitString(String);
3247 //===----------------------------------------------------------------------===//
3249 /// EmitValue - Emit label value.
3251 void DIEDwarfLabel::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3252 DD.EmitReference(Label);
3255 /// SizeOf - Determine size of label value in bytes.
3257 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3258 return DD.getTargetAsmInfo()->getAddressSize();
3261 //===----------------------------------------------------------------------===//
3263 /// EmitValue - Emit label value.
3265 void DIEObjectLabel::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3266 DD.EmitReference(Label);
3269 /// SizeOf - Determine size of label value in bytes.
3271 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3272 return DD.getTargetAsmInfo()->getAddressSize();
3275 //===----------------------------------------------------------------------===//
3277 /// EmitValue - Emit delta value.
3279 void DIEDelta::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3280 bool IsSmall = Form == DW_FORM_data4;
3281 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3284 /// SizeOf - Determine size of delta value in bytes.
3286 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3287 if (Form == DW_FORM_data4) return 4;
3288 return DD.getTargetAsmInfo()->getAddressSize();
3291 //===----------------------------------------------------------------------===//
3293 /// EmitValue - Emit debug information entry offset.
3295 void DIEntry::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3296 DD.getAsm()->EmitInt32(Entry->getOffset());
3299 //===----------------------------------------------------------------------===//
3301 /// ComputeSize - calculate the size of the block.
3303 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3305 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3307 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3308 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3314 /// EmitValue - Emit block data.
3316 void DIEBlock::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3318 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3319 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3320 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3321 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3322 default: assert(0 && "Improper form for block"); break;
3325 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3327 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3329 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3333 /// SizeOf - Determine size of block data in bytes.
3335 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3337 case DW_FORM_block1: return Size + sizeof(int8_t);
3338 case DW_FORM_block2: return Size + sizeof(int16_t);
3339 case DW_FORM_block4: return Size + sizeof(int32_t);
3340 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3341 default: assert(0 && "Improper form for block"); break;
3346 //===----------------------------------------------------------------------===//
3347 /// DIE Implementation
3350 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3354 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3356 void DIE::AddSiblingOffset() {
3357 DIEInteger *DI = new DIEInteger(0);
3358 Values.insert(Values.begin(), DI);
3359 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3362 /// Profile - Used to gather unique data for the value folding set.
3364 void DIE::Profile(FoldingSetNodeID &ID) {
3367 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3368 ID.AddPointer(Children[i]);
3370 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3371 ID.AddPointer(Values[j]);
3375 void DIE::print(std::ostream &O, unsigned IncIndent) {
3376 static unsigned IndentCount = 0;
3377 IndentCount += IncIndent;
3378 const std::string Indent(IndentCount, ' ');
3379 bool isBlock = Abbrev.getTag() == 0;
3384 << "0x" << std::hex << (intptr_t)this << std::dec
3385 << ", Offset: " << Offset
3386 << ", Size: " << Size
3390 << TagString(Abbrev.getTag())
3392 << ChildrenString(Abbrev.getChildrenFlag());
3394 O << "Size: " << Size;
3398 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3401 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3404 O << AttributeString(Data[i].getAttribute());
3406 O << "Blk[" << i << "]";
3409 << FormEncodingString(Data[i].getForm())
3411 Values[i]->print(O);
3416 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3417 Children[j]->print(O, 4);
3420 if (!isBlock) O << "\n";
3421 IndentCount -= IncIndent;
3429 //===----------------------------------------------------------------------===//
3430 /// DwarfWriter Implementation
3433 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3434 const TargetAsmInfo *T) {
3435 DE = new DwarfException(OS, A, T);
3436 DD = new DwarfDebug(OS, A, T);
3439 DwarfWriter::~DwarfWriter() {
3444 /// SetModuleInfo - Set machine module info when it's known that pass manager
3445 /// has created it. Set by the target AsmPrinter.
3446 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3447 DD->SetModuleInfo(MMI);
3448 DE->SetModuleInfo(MMI);
3451 /// BeginModule - Emit all Dwarf sections that should come prior to the
3453 void DwarfWriter::BeginModule(Module *M) {
3458 /// EndModule - Emit all Dwarf sections that should come after the content.
3460 void DwarfWriter::EndModule() {
3465 /// BeginFunction - Gather pre-function debug information. Assumes being
3466 /// emitted immediately after the function entry point.
3467 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3468 DE->BeginFunction(MF);
3469 DD->BeginFunction(MF);
3472 /// EndFunction - Gather and emit post-function debug information.
3474 void DwarfWriter::EndFunction() {
3478 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3479 // Clear function debug information.