1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/System/Path.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm::dwarf;
46 //===----------------------------------------------------------------------===//
48 /// Configuration values for initial hash set sizes (log2).
50 static const unsigned InitDiesSetSize = 9; // 512
51 static const unsigned InitAbbreviationsSetSize = 9; // 512
52 static const unsigned InitValuesSetSize = 9; // 512
54 //===----------------------------------------------------------------------===//
55 /// Forward declarations.
60 //===----------------------------------------------------------------------===//
61 /// DWLabel - Labels are used to track locations in the assembler file.
62 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
63 /// where the tag is a category of label (Ex. location) and number is a value
64 /// unique in that category.
67 /// Tag - Label category tag. Should always be a staticly declared C string.
71 /// Number - Value to make label unique.
75 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
77 void Profile(FoldingSetNodeID &ID) const {
78 ID.AddString(std::string(Tag));
79 ID.AddInteger(Number);
83 void print(std::ostream *O) const {
86 void print(std::ostream &O) const {
88 if (Number) O << Number;
93 //===----------------------------------------------------------------------===//
94 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
95 /// Dwarf abbreviation.
98 /// Attribute - Dwarf attribute code.
102 /// Form - Dwarf form code.
107 DIEAbbrevData(unsigned A, unsigned F)
113 unsigned getAttribute() const { return Attribute; }
114 unsigned getForm() const { return Form; }
116 /// Profile - Used to gather unique data for the abbreviation folding set.
118 void Profile(FoldingSetNodeID &ID)const {
119 ID.AddInteger(Attribute);
124 //===----------------------------------------------------------------------===//
125 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
126 /// information object.
127 class DIEAbbrev : public FoldingSetNode {
129 /// Tag - Dwarf tag code.
133 /// Unique number for node.
137 /// ChildrenFlag - Dwarf children flag.
139 unsigned ChildrenFlag;
141 /// Data - Raw data bytes for abbreviation.
143 std::vector<DIEAbbrevData> Data;
147 DIEAbbrev(unsigned T, unsigned C)
155 unsigned getTag() const { return Tag; }
156 unsigned getNumber() const { return Number; }
157 unsigned getChildrenFlag() const { return ChildrenFlag; }
158 const std::vector<DIEAbbrevData> &getData() const { return Data; }
159 void setTag(unsigned T) { Tag = T; }
160 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
161 void setNumber(unsigned N) { Number = N; }
163 /// AddAttribute - Adds another set of attribute information to the
165 void AddAttribute(unsigned Attribute, unsigned Form) {
166 Data.push_back(DIEAbbrevData(Attribute, Form));
169 /// AddFirstAttribute - Adds a set of attribute information to the front
170 /// of the abbreviation.
171 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
172 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
175 /// Profile - Used to gather unique data for the abbreviation folding set.
177 void Profile(FoldingSetNodeID &ID) {
179 ID.AddInteger(ChildrenFlag);
181 // For each attribute description.
182 for (unsigned i = 0, N = Data.size(); i < N; ++i)
186 /// Emit - Print the abbreviation using the specified Dwarf writer.
188 void Emit(const DwarfDebug &DD) const;
191 void print(std::ostream *O) {
194 void print(std::ostream &O);
199 //===----------------------------------------------------------------------===//
200 /// DIE - A structured debug information entry. Has an abbreviation which
201 /// describes it's organization.
202 class DIE : public FoldingSetNode {
204 /// Abbrev - Buffer for constructing abbreviation.
208 /// Offset - Offset in debug info section.
212 /// Size - Size of instance + children.
218 std::vector<DIE *> Children;
220 /// Attributes values.
222 std::vector<DIEValue *> Values;
225 explicit DIE(unsigned Tag)
226 : Abbrev(Tag, DW_CHILDREN_no)
235 DIEAbbrev &getAbbrev() { return Abbrev; }
236 unsigned getAbbrevNumber() const {
237 return Abbrev.getNumber();
239 unsigned getTag() const { return Abbrev.getTag(); }
240 unsigned getOffset() const { return Offset; }
241 unsigned getSize() const { return Size; }
242 const std::vector<DIE *> &getChildren() const { return Children; }
243 std::vector<DIEValue *> &getValues() { return Values; }
244 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
245 void setOffset(unsigned O) { Offset = O; }
246 void setSize(unsigned S) { Size = S; }
248 /// AddValue - Add a value and attributes to a DIE.
250 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
251 Abbrev.AddAttribute(Attribute, Form);
252 Values.push_back(Value);
255 /// SiblingOffset - Return the offset of the debug information entry's
257 unsigned SiblingOffset() const { return Offset + Size; }
259 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
261 void AddSiblingOffset();
263 /// AddChild - Add a child to the DIE.
265 void AddChild(DIE *Child) {
266 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
267 Children.push_back(Child);
270 /// Detach - Detaches objects connected to it after copying.
276 /// Profile - Used to gather unique data for the value folding set.
278 void Profile(FoldingSetNodeID &ID) ;
281 void print(std::ostream *O, unsigned IncIndent = 0) {
282 if (O) print(*O, IncIndent);
284 void print(std::ostream &O, unsigned IncIndent = 0);
289 //===----------------------------------------------------------------------===//
290 /// DIEValue - A debug information entry value.
292 class DIEValue : public FoldingSetNode {
304 /// Type - Type of data stored in the value.
308 explicit DIEValue(unsigned T)
311 virtual ~DIEValue() {}
314 unsigned getType() const { return Type; }
316 // Implement isa/cast/dyncast.
317 static bool classof(const DIEValue *) { return true; }
319 /// EmitValue - Emit value via the Dwarf writer.
321 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
323 /// SizeOf - Return the size of a value in bytes.
325 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
327 /// Profile - Used to gather unique data for the value folding set.
329 virtual void Profile(FoldingSetNodeID &ID) = 0;
332 void print(std::ostream *O) {
335 virtual void print(std::ostream &O) = 0;
340 //===----------------------------------------------------------------------===//
341 /// DWInteger - An integer value DIE.
343 class DIEInteger : public DIEValue {
348 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
350 // Implement isa/cast/dyncast.
351 static bool classof(const DIEInteger *) { return true; }
352 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
354 /// BestForm - Choose the best form for integer.
356 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
358 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
359 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
360 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
362 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
363 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
364 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
366 return DW_FORM_data8;
369 /// EmitValue - Emit integer of appropriate size.
371 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
373 /// SizeOf - Determine size of integer value in bytes.
375 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
377 /// Profile - Used to gather unique data for the value folding set.
379 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
380 ID.AddInteger(isInteger);
381 ID.AddInteger(Integer);
383 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
386 virtual void print(std::ostream &O) {
387 O << "Int: " << (int64_t)Integer
388 << " 0x" << std::hex << Integer << std::dec;
393 //===----------------------------------------------------------------------===//
394 /// DIEString - A string value DIE.
396 class DIEString : public DIEValue {
398 const std::string String;
400 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
402 // Implement isa/cast/dyncast.
403 static bool classof(const DIEString *) { return true; }
404 static bool classof(const DIEValue *S) { return S->Type == isString; }
406 /// EmitValue - Emit string value.
408 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
410 /// SizeOf - Determine size of string value in bytes.
412 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
413 return String.size() + sizeof(char); // sizeof('\0');
416 /// Profile - Used to gather unique data for the value folding set.
418 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
419 ID.AddInteger(isString);
420 ID.AddString(String);
422 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
425 virtual void print(std::ostream &O) {
426 O << "Str: \"" << String << "\"";
431 //===----------------------------------------------------------------------===//
432 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
434 class DIEDwarfLabel : public DIEValue {
439 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
441 // Implement isa/cast/dyncast.
442 static bool classof(const DIEDwarfLabel *) { return true; }
443 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
445 /// EmitValue - Emit label value.
447 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
449 /// SizeOf - Determine size of label value in bytes.
451 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
453 /// Profile - Used to gather unique data for the value folding set.
455 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
456 ID.AddInteger(isLabel);
459 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
462 virtual void print(std::ostream &O) {
470 //===----------------------------------------------------------------------===//
471 /// DIEObjectLabel - A label to an object in code or data.
473 class DIEObjectLabel : public DIEValue {
475 const std::string Label;
477 explicit DIEObjectLabel(const std::string &L)
478 : DIEValue(isAsIsLabel), Label(L) {}
480 // Implement isa/cast/dyncast.
481 static bool classof(const DIEObjectLabel *) { return true; }
482 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
484 /// EmitValue - Emit label value.
486 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
488 /// SizeOf - Determine size of label value in bytes.
490 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
492 /// Profile - Used to gather unique data for the value folding set.
494 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
495 ID.AddInteger(isAsIsLabel);
498 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
501 virtual void print(std::ostream &O) {
502 O << "Obj: " << Label;
507 //===----------------------------------------------------------------------===//
508 /// DIEDelta - A simple label difference DIE.
510 class DIEDelta : public DIEValue {
512 const DWLabel LabelHi;
513 const DWLabel LabelLo;
515 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
516 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
518 // Implement isa/cast/dyncast.
519 static bool classof(const DIEDelta *) { return true; }
520 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
522 /// EmitValue - Emit delta value.
524 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
526 /// SizeOf - Determine size of delta value in bytes.
528 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
530 /// Profile - Used to gather unique data for the value folding set.
532 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
533 const DWLabel &LabelLo) {
534 ID.AddInteger(isDelta);
538 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
541 virtual void print(std::ostream &O) {
550 //===----------------------------------------------------------------------===//
551 /// DIEntry - A pointer to another debug information entry. An instance of this
552 /// class can also be used as a proxy for a debug information entry not yet
553 /// defined (ie. types.)
554 class DIEntry : public DIEValue {
558 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
560 // Implement isa/cast/dyncast.
561 static bool classof(const DIEntry *) { return true; }
562 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
564 /// EmitValue - Emit debug information entry offset.
566 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
568 /// SizeOf - Determine size of debug information entry in bytes.
570 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
571 return sizeof(int32_t);
574 /// Profile - Used to gather unique data for the value folding set.
576 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
577 ID.AddInteger(isEntry);
578 ID.AddPointer(Entry);
580 virtual void Profile(FoldingSetNodeID &ID) {
581 ID.AddInteger(isEntry);
584 ID.AddPointer(Entry);
591 virtual void print(std::ostream &O) {
592 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
597 //===----------------------------------------------------------------------===//
598 /// DIEBlock - A block of values. Primarily used for location expressions.
600 class DIEBlock : public DIEValue, public DIE {
602 unsigned Size; // Size in bytes excluding size header.
612 // Implement isa/cast/dyncast.
613 static bool classof(const DIEBlock *) { return true; }
614 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
616 /// ComputeSize - calculate the size of the block.
618 unsigned ComputeSize(DwarfDebug &DD);
620 /// BestForm - Choose the best form for data.
622 unsigned BestForm() const {
623 if ((unsigned char)Size == Size) return DW_FORM_block1;
624 if ((unsigned short)Size == Size) return DW_FORM_block2;
625 if ((unsigned int)Size == Size) return DW_FORM_block4;
626 return DW_FORM_block;
629 /// EmitValue - Emit block data.
631 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
633 /// SizeOf - Determine size of block data in bytes.
635 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
638 /// Profile - Used to gather unique data for the value folding set.
640 virtual void Profile(FoldingSetNodeID &ID) {
641 ID.AddInteger(isBlock);
646 virtual void print(std::ostream &O) {
653 //===----------------------------------------------------------------------===//
654 /// CompileUnit - This dwarf writer support class manages information associate
655 /// with a source file.
658 /// Desc - Compile unit debug descriptor.
660 CompileUnitDesc *Desc;
662 /// ID - File identifier for source.
666 /// Die - Compile unit debug information entry.
670 /// DescToDieMap - Tracks the mapping of unit level debug informaton
671 /// descriptors to debug information entries.
672 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
674 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
675 /// descriptors to debug information entries using a DIEntry proxy.
676 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
678 /// Globals - A map of globally visible named entities for this unit.
680 std::map<std::string, DIE *> Globals;
682 /// DiesSet - Used to uniquely define dies within the compile unit.
684 FoldingSet<DIE> DiesSet;
686 /// Dies - List of all dies in the compile unit.
688 std::vector<DIE *> Dies;
691 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
698 , DiesSet(InitDiesSetSize)
705 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
710 CompileUnitDesc *getDesc() const { return Desc; }
711 unsigned getID() const { return ID; }
712 DIE* getDie() const { return Die; }
713 std::map<std::string, DIE *> &getGlobals() { return Globals; }
715 /// hasContent - Return true if this compile unit has something to write out.
717 bool hasContent() const {
718 return !Die->getChildren().empty();
721 /// AddGlobal - Add a new global entity to the compile unit.
723 void AddGlobal(const std::string &Name, DIE *Die) {
727 /// getDieMapSlotFor - Returns the debug information entry map slot for the
728 /// specified debug descriptor.
729 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
730 return DescToDieMap[DID];
733 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
734 /// specified debug descriptor.
735 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
736 return DescToDIEntryMap[DID];
739 /// AddDie - Adds or interns the DIE to the compile unit.
741 DIE *AddDie(DIE &Buffer) {
745 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
748 Die = new DIE(Buffer);
749 DiesSet.InsertNode(Die, Where);
750 this->Die->AddChild(Die);
758 //===----------------------------------------------------------------------===//
759 /// Dwarf - Emits general Dwarf directives.
765 //===--------------------------------------------------------------------===//
766 // Core attributes used by the Dwarf writer.
770 /// O - Stream to .s file.
774 /// Asm - Target of Dwarf emission.
778 /// TAI - Target Asm Printer.
779 const TargetAsmInfo *TAI;
781 /// TD - Target data.
782 const TargetData *TD;
784 /// RI - Register Information.
785 const TargetRegisterInfo *RI;
787 /// M - Current module.
791 /// MF - Current machine function.
795 /// MMI - Collected machine module information.
797 MachineModuleInfo *MMI;
799 /// SubprogramCount - The running count of functions being compiled.
801 unsigned SubprogramCount;
803 /// Flavor - A unique string indicating what dwarf producer this is, used to
805 const char * const Flavor;
808 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
813 , TD(Asm->TM.getTargetData())
814 , RI(Asm->TM.getRegisterInfo())
826 //===--------------------------------------------------------------------===//
829 AsmPrinter *getAsm() const { return Asm; }
830 MachineModuleInfo *getMMI() const { return MMI; }
831 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
832 const TargetData *getTargetData() const { return TD; }
834 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
836 if (isInSection && TAI->getDwarfSectionOffsetDirective())
837 O << TAI->getDwarfSectionOffsetDirective();
838 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
839 O << TAI->getData32bitsDirective();
841 O << TAI->getData64bitsDirective();
844 /// PrintLabelName - Print label name in form used by Dwarf writer.
846 void PrintLabelName(DWLabel Label) const {
847 PrintLabelName(Label.Tag, Label.Number);
849 void PrintLabelName(const char *Tag, unsigned Number) const {
850 O << TAI->getPrivateGlobalPrefix() << Tag;
851 if (Number) O << Number;
854 void PrintLabelName(const char *Tag, unsigned Number,
855 const char *Suffix) const {
856 O << TAI->getPrivateGlobalPrefix() << Tag;
857 if (Number) O << Number;
861 /// EmitLabel - Emit location label for internal use by Dwarf.
863 void EmitLabel(DWLabel Label) const {
864 EmitLabel(Label.Tag, Label.Number);
866 void EmitLabel(const char *Tag, unsigned Number) const {
867 PrintLabelName(Tag, Number);
871 /// EmitReference - Emit a reference to a label.
873 void EmitReference(DWLabel Label, bool IsPCRelative = false,
874 bool Force32Bit = false) const {
875 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
877 void EmitReference(const char *Tag, unsigned Number,
878 bool IsPCRelative = false, bool Force32Bit = false) const {
879 PrintRelDirective(Force32Bit);
880 PrintLabelName(Tag, Number);
882 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
884 void EmitReference(const std::string &Name, bool IsPCRelative = false,
885 bool Force32Bit = false) const {
886 PrintRelDirective(Force32Bit);
890 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
893 /// EmitDifference - Emit the difference between two labels. Some
894 /// assemblers do not behave with absolute expressions with data directives,
895 /// so there is an option (needsSet) to use an intermediary set expression.
896 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
897 bool IsSmall = false) {
898 EmitDifference(LabelHi.Tag, LabelHi.Number,
899 LabelLo.Tag, LabelLo.Number,
902 void EmitDifference(const char *TagHi, unsigned NumberHi,
903 const char *TagLo, unsigned NumberLo,
904 bool IsSmall = false) {
905 if (TAI->needsSet()) {
907 PrintLabelName("set", SetCounter, Flavor);
909 PrintLabelName(TagHi, NumberHi);
911 PrintLabelName(TagLo, NumberLo);
914 PrintRelDirective(IsSmall);
915 PrintLabelName("set", SetCounter, Flavor);
918 PrintRelDirective(IsSmall);
920 PrintLabelName(TagHi, NumberHi);
922 PrintLabelName(TagLo, NumberLo);
926 void EmitSectionOffset(const char* Label, const char* Section,
927 unsigned LabelNumber, unsigned SectionNumber,
928 bool IsSmall = false, bool isEH = false,
929 bool useSet = true) {
930 bool printAbsolute = false;
932 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
934 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
936 if (TAI->needsSet() && useSet) {
938 PrintLabelName("set", SetCounter, Flavor);
940 PrintLabelName(Label, LabelNumber);
942 if (!printAbsolute) {
944 PrintLabelName(Section, SectionNumber);
948 PrintRelDirective(IsSmall);
950 PrintLabelName("set", SetCounter, Flavor);
953 PrintRelDirective(IsSmall, true);
955 PrintLabelName(Label, LabelNumber);
957 if (!printAbsolute) {
959 PrintLabelName(Section, SectionNumber);
964 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
966 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
967 const std::vector<MachineMove> &Moves, bool isEH) {
969 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
970 TargetFrameInfo::StackGrowsUp ?
971 TD->getPointerSize() : -TD->getPointerSize();
972 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
974 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
975 const MachineMove &Move = Moves[i];
976 unsigned LabelID = Move.getLabelID();
979 LabelID = MMI->MappedLabel(LabelID);
981 // Throw out move if the label is invalid.
982 if (!LabelID) continue;
985 const MachineLocation &Dst = Move.getDestination();
986 const MachineLocation &Src = Move.getSource();
988 // Advance row if new location.
989 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
990 Asm->EmitInt8(DW_CFA_advance_loc4);
991 Asm->EOL("DW_CFA_advance_loc4");
992 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
995 BaseLabelID = LabelID;
1000 // If advancing cfa.
1001 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1002 if (!Src.isRegister()) {
1003 if (Src.getRegister() == MachineLocation::VirtualFP) {
1004 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1005 Asm->EOL("DW_CFA_def_cfa_offset");
1007 Asm->EmitInt8(DW_CFA_def_cfa);
1008 Asm->EOL("DW_CFA_def_cfa");
1009 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister(), isEH));
1010 Asm->EOL("Register");
1013 int Offset = -Src.getOffset();
1015 Asm->EmitULEB128Bytes(Offset);
1018 assert(0 && "Machine move no supported yet.");
1020 } else if (Src.isRegister() &&
1021 Src.getRegister() == MachineLocation::VirtualFP) {
1022 if (Dst.isRegister()) {
1023 Asm->EmitInt8(DW_CFA_def_cfa_register);
1024 Asm->EOL("DW_CFA_def_cfa_register");
1025 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister(), isEH));
1026 Asm->EOL("Register");
1028 assert(0 && "Machine move no supported yet.");
1031 unsigned Reg = RI->getDwarfRegNum(Src.getRegister(), isEH);
1032 int Offset = Dst.getOffset() / stackGrowth;
1035 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1036 Asm->EOL("DW_CFA_offset_extended_sf");
1037 Asm->EmitULEB128Bytes(Reg);
1039 Asm->EmitSLEB128Bytes(Offset);
1041 } else if (Reg < 64) {
1042 Asm->EmitInt8(DW_CFA_offset + Reg);
1043 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1044 Asm->EmitULEB128Bytes(Offset);
1047 Asm->EmitInt8(DW_CFA_offset_extended);
1048 Asm->EOL("DW_CFA_offset_extended");
1049 Asm->EmitULEB128Bytes(Reg);
1051 Asm->EmitULEB128Bytes(Offset);
1060 //===----------------------------------------------------------------------===//
1061 /// DwarfDebug - Emits Dwarf debug directives.
1063 class DwarfDebug : public Dwarf {
1066 //===--------------------------------------------------------------------===//
1067 // Attributes used to construct specific Dwarf sections.
1070 /// CompileUnits - All the compile units involved in this build. The index
1071 /// of each entry in this vector corresponds to the sources in MMI.
1072 std::vector<CompileUnit *> CompileUnits;
1074 /// AbbreviationsSet - Used to uniquely define abbreviations.
1076 FoldingSet<DIEAbbrev> AbbreviationsSet;
1078 /// Abbreviations - A list of all the unique abbreviations in use.
1080 std::vector<DIEAbbrev *> Abbreviations;
1082 /// ValuesSet - Used to uniquely define values.
1084 FoldingSet<DIEValue> ValuesSet;
1086 /// Values - A list of all the unique values in use.
1088 std::vector<DIEValue *> Values;
1090 /// StringPool - A UniqueVector of strings used by indirect references.
1092 UniqueVector<std::string> StringPool;
1094 /// UnitMap - Map debug information descriptor to compile unit.
1096 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1098 /// SectionMap - Provides a unique id per text section.
1100 UniqueVector<std::string> SectionMap;
1102 /// SectionSourceLines - Tracks line numbers per text section.
1104 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1106 /// didInitial - Flag to indicate if initial emission has been done.
1110 /// shouldEmit - Flag to indicate if debug information should be emitted.
1114 struct FunctionDebugFrameInfo {
1116 std::vector<MachineMove> Moves;
1118 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1119 Number(Num), Moves(M) { }
1122 std::vector<FunctionDebugFrameInfo> DebugFrames;
1126 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1128 bool ShouldEmitDwarf() const { return shouldEmit; }
1130 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1132 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1133 // Profile the node so that we can make it unique.
1134 FoldingSetNodeID ID;
1137 // Check the set for priors.
1138 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1140 // If it's newly added.
1141 if (InSet == &Abbrev) {
1142 // Add to abbreviation list.
1143 Abbreviations.push_back(&Abbrev);
1144 // Assign the vector position + 1 as its number.
1145 Abbrev.setNumber(Abbreviations.size());
1147 // Assign existing abbreviation number.
1148 Abbrev.setNumber(InSet->getNumber());
1152 /// NewString - Add a string to the constant pool and returns a label.
1154 DWLabel NewString(const std::string &String) {
1155 unsigned StringID = StringPool.insert(String);
1156 return DWLabel("string", StringID);
1159 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1161 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1165 FoldingSetNodeID ID;
1166 DIEntry::Profile(ID, Entry);
1168 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1170 if (Value) return Value;
1172 Value = new DIEntry(Entry);
1173 ValuesSet.InsertNode(Value, Where);
1175 Value = new DIEntry(Entry);
1178 Values.push_back(Value);
1182 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1184 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1185 Value->Entry = Entry;
1186 // Add to values set if not already there. If it is, we merely have a
1187 // duplicate in the values list (no harm.)
1188 ValuesSet.GetOrInsertNode(Value);
1191 /// AddUInt - Add an unsigned integer attribute data and value.
1193 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1194 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1196 FoldingSetNodeID ID;
1197 DIEInteger::Profile(ID, Integer);
1199 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1201 Value = new DIEInteger(Integer);
1202 ValuesSet.InsertNode(Value, Where);
1203 Values.push_back(Value);
1206 Die->AddValue(Attribute, Form, Value);
1209 /// AddSInt - Add an signed integer attribute data and value.
1211 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1212 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1214 FoldingSetNodeID ID;
1215 DIEInteger::Profile(ID, (uint64_t)Integer);
1217 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1219 Value = new DIEInteger(Integer);
1220 ValuesSet.InsertNode(Value, Where);
1221 Values.push_back(Value);
1224 Die->AddValue(Attribute, Form, Value);
1227 /// AddString - Add a std::string attribute data and value.
1229 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1230 const std::string &String) {
1231 FoldingSetNodeID ID;
1232 DIEString::Profile(ID, String);
1234 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1236 Value = new DIEString(String);
1237 ValuesSet.InsertNode(Value, Where);
1238 Values.push_back(Value);
1241 Die->AddValue(Attribute, Form, Value);
1244 /// AddLabel - Add a Dwarf label attribute data and value.
1246 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1247 const DWLabel &Label) {
1248 FoldingSetNodeID ID;
1249 DIEDwarfLabel::Profile(ID, Label);
1251 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1253 Value = new DIEDwarfLabel(Label);
1254 ValuesSet.InsertNode(Value, Where);
1255 Values.push_back(Value);
1258 Die->AddValue(Attribute, Form, Value);
1261 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1263 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1264 const std::string &Label) {
1265 FoldingSetNodeID ID;
1266 DIEObjectLabel::Profile(ID, Label);
1268 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1270 Value = new DIEObjectLabel(Label);
1271 ValuesSet.InsertNode(Value, Where);
1272 Values.push_back(Value);
1275 Die->AddValue(Attribute, Form, Value);
1278 /// AddDelta - Add a label delta attribute data and value.
1280 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1281 const DWLabel &Hi, const DWLabel &Lo) {
1282 FoldingSetNodeID ID;
1283 DIEDelta::Profile(ID, Hi, Lo);
1285 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1287 Value = new DIEDelta(Hi, Lo);
1288 ValuesSet.InsertNode(Value, Where);
1289 Values.push_back(Value);
1292 Die->AddValue(Attribute, Form, Value);
1295 /// AddDIEntry - Add a DIE attribute data and value.
1297 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1298 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1301 /// AddBlock - Add block data.
1303 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1304 Block->ComputeSize(*this);
1305 FoldingSetNodeID ID;
1308 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1311 ValuesSet.InsertNode(Value, Where);
1312 Values.push_back(Value);
1314 // Already exists, reuse the previous one.
1316 Block = cast<DIEBlock>(Value);
1319 Die->AddValue(Attribute, Block->BestForm(), Value);
1324 /// AddSourceLine - Add location information to specified debug information
1326 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1328 CompileUnit *FileUnit = FindCompileUnit(File);
1329 unsigned FileID = FileUnit->getID();
1330 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1331 AddUInt(Die, DW_AT_decl_line, 0, Line);
1335 /// AddAddress - Add an address attribute to a die based on the location
1337 void AddAddress(DIE *Die, unsigned Attribute,
1338 const MachineLocation &Location) {
1339 unsigned Reg = RI->getDwarfRegNum(Location.getRegister(), false);
1340 DIEBlock *Block = new DIEBlock();
1342 if (Location.isRegister()) {
1344 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1346 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1347 AddUInt(Block, 0, DW_FORM_udata, Reg);
1351 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1353 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1354 AddUInt(Block, 0, DW_FORM_udata, Reg);
1356 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1359 AddBlock(Die, Attribute, 0, Block);
1362 /// AddBasicType - Add a new basic type attribute to the specified entity.
1364 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1365 const std::string &Name,
1366 unsigned Encoding, unsigned Size) {
1367 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1368 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1371 /// ConstructBasicType - Construct a new basic type.
1373 DIE *ConstructBasicType(CompileUnit *Unit,
1374 const std::string &Name,
1375 unsigned Encoding, unsigned Size) {
1376 DIE Buffer(DW_TAG_base_type);
1377 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1378 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1379 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1380 return Unit->AddDie(Buffer);
1383 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1385 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1386 DIE *Die = ConstructPointerType(Unit, Name);
1387 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1390 /// ConstructPointerType - Construct a new pointer type.
1392 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1393 DIE Buffer(DW_TAG_pointer_type);
1394 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1395 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1396 return Unit->AddDie(Buffer);
1399 /// AddType - Add a new type attribute to the specified entity.
1401 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1403 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1405 // Check for pre-existence.
1406 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1408 // If it exists then use the existing value.
1410 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1414 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1415 // FIXME - Not sure why programs and variables are coming through here.
1416 // Short cut for handling subprogram types (not really a TyDesc.)
1417 AddPointerType(Entity, Unit, SubprogramTy->getName());
1418 } else if (GlobalVariableDesc *GlobalTy =
1419 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1420 // FIXME - Not sure why programs and variables are coming through here.
1421 // Short cut for handling global variable types (not really a TyDesc.)
1422 AddPointerType(Entity, Unit, GlobalTy->getName());
1425 Slot = NewDIEntry();
1428 DIE Buffer(DW_TAG_base_type);
1429 ConstructType(Buffer, TyDesc, Unit);
1431 // Add debug information entry to entity and unit.
1432 DIE *Die = Unit->AddDie(Buffer);
1433 SetDIEntry(Slot, Die);
1434 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1439 /// ConstructType - Adds all the required attributes to the type.
1441 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1442 // Get core information.
1443 const std::string &Name = TyDesc->getName();
1444 uint64_t Size = TyDesc->getSize() >> 3;
1446 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1447 // Fundamental types like int, float, bool
1448 Buffer.setTag(DW_TAG_base_type);
1449 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1450 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1452 unsigned Tag = DerivedTy->getTag();
1453 // FIXME - Workaround for templates.
1454 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1455 // Pointers, typedefs et al.
1457 // Map to main type, void will not have a type.
1458 if (TypeDesc *FromTy = DerivedTy->getFromType())
1459 AddType(&Buffer, FromTy, Unit);
1460 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1462 unsigned Tag = CompTy->getTag();
1464 // Set tag accordingly.
1465 if (Tag == DW_TAG_vector_type)
1466 Buffer.setTag(DW_TAG_array_type);
1470 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1473 case DW_TAG_vector_type:
1474 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1476 case DW_TAG_array_type: {
1477 // Add element type.
1478 if (TypeDesc *FromTy = CompTy->getFromType())
1479 AddType(&Buffer, FromTy, Unit);
1481 // Don't emit size attribute.
1484 // Construct an anonymous type for index type.
1485 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1488 // Add subranges to array type.
1489 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1490 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1491 int64_t Lo = SRD->getLo();
1492 int64_t Hi = SRD->getHi();
1493 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1495 // If a range is available.
1497 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1498 // Only add low if non-zero.
1499 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1500 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1503 Buffer.AddChild(Subrange);
1507 case DW_TAG_structure_type:
1508 case DW_TAG_union_type: {
1509 // Add elements to structure type.
1510 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1511 DebugInfoDesc *Element = Elements[i];
1513 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1514 // Add field or base class.
1516 unsigned Tag = MemberDesc->getTag();
1518 // Extract the basic information.
1519 const std::string &Name = MemberDesc->getName();
1520 uint64_t Size = MemberDesc->getSize();
1521 uint64_t Align = MemberDesc->getAlign();
1522 uint64_t Offset = MemberDesc->getOffset();
1524 // Construct member debug information entry.
1525 DIE *Member = new DIE(Tag);
1527 // Add name if not "".
1529 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1530 // Add location if available.
1531 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1533 // Most of the time the field info is the same as the members.
1534 uint64_t FieldSize = Size;
1535 uint64_t FieldAlign = Align;
1536 uint64_t FieldOffset = Offset;
1538 // Set the member type.
1539 TypeDesc *FromTy = MemberDesc->getFromType();
1540 AddType(Member, FromTy, Unit);
1542 // Walk up typedefs until a real size is found.
1544 if (FromTy->getTag() != DW_TAG_typedef) {
1545 FieldSize = FromTy->getSize();
1546 FieldAlign = FromTy->getSize();
1550 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1553 // Unless we have a bit field.
1554 if (Tag == DW_TAG_member && FieldSize != Size) {
1555 // Construct the alignment mask.
1556 uint64_t AlignMask = ~(FieldAlign - 1);
1557 // Determine the high bit + 1 of the declared size.
1558 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1559 // Work backwards to determine the base offset of the field.
1560 FieldOffset = HiMark - FieldSize;
1561 // Now normalize offset to the field.
1562 Offset -= FieldOffset;
1564 // Maybe we need to work from the other end.
1565 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1567 // Add size and offset.
1568 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1569 AddUInt(Member, DW_AT_bit_size, 0, Size);
1570 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1573 // Add computation for offset.
1574 DIEBlock *Block = new DIEBlock();
1575 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1576 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1577 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1579 // Add accessibility (public default unless is base class.
1580 if (MemberDesc->isProtected()) {
1581 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1582 } else if (MemberDesc->isPrivate()) {
1583 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1584 } else if (Tag == DW_TAG_inheritance) {
1585 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1588 Buffer.AddChild(Member);
1589 } else if (GlobalVariableDesc *StaticDesc =
1590 dyn_cast<GlobalVariableDesc>(Element)) {
1591 // Add static member.
1593 // Construct member debug information entry.
1594 DIE *Static = new DIE(DW_TAG_variable);
1596 // Add name and mangled name.
1597 const std::string &Name = StaticDesc->getName();
1598 const std::string &LinkageName = StaticDesc->getLinkageName();
1599 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1600 if (!LinkageName.empty()) {
1601 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1606 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1609 if (TypeDesc *StaticTy = StaticDesc->getType())
1610 AddType(Static, StaticTy, Unit);
1613 if (!StaticDesc->isStatic())
1614 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1615 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1617 Buffer.AddChild(Static);
1618 } else if (SubprogramDesc *MethodDesc =
1619 dyn_cast<SubprogramDesc>(Element)) {
1620 // Add member function.
1622 // Construct member debug information entry.
1623 DIE *Method = new DIE(DW_TAG_subprogram);
1625 // Add name and mangled name.
1626 const std::string &Name = MethodDesc->getName();
1627 const std::string &LinkageName = MethodDesc->getLinkageName();
1629 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1630 bool IsCTor = TyDesc->getName() == Name;
1632 if (!LinkageName.empty()) {
1633 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1638 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1641 if (CompositeTypeDesc *MethodTy =
1642 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1643 // Get argument information.
1644 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1649 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1653 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1654 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1655 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1656 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1657 Method->AddChild(Arg);
1662 if (!MethodDesc->isStatic())
1663 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1664 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1666 Buffer.AddChild(Method);
1671 case DW_TAG_enumeration_type: {
1672 // Add enumerators to enumeration type.
1673 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1674 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1675 const std::string &Name = ED->getName();
1676 int64_t Value = ED->getValue();
1677 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1678 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1679 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1680 Buffer.AddChild(Enumerator);
1685 case DW_TAG_subroutine_type: {
1686 // Add prototype flag.
1687 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1689 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1692 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1693 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1694 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1695 Buffer.AddChild(Arg);
1704 // Add size if non-zero (derived types don't have a size.)
1705 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1706 // Add name if not anonymous or intermediate type.
1707 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1708 // Add source line info if available.
1709 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1712 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1714 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1715 // Construct debug information entry.
1716 DIE *Die = new DIE(DW_TAG_compile_unit);
1717 if (TAI->isAbsoluteDebugSectionOffsets())
1718 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1720 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1721 DWLabel("section_line", 0));
1722 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1723 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1724 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1725 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1727 // Construct compile unit.
1728 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1730 // Add Unit to compile unit map.
1731 DescToUnitMap[UnitDesc] = Unit;
1736 /// GetBaseCompileUnit - Get the main compile unit.
1738 CompileUnit *GetBaseCompileUnit() const {
1739 CompileUnit *Unit = CompileUnits[0];
1740 assert(Unit && "Missing compile unit.");
1744 /// FindCompileUnit - Get the compile unit for the given descriptor.
1746 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1747 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1748 assert(Unit && "Missing compile unit.");
1752 /// NewGlobalVariable - Add a new global variable DIE.
1754 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1755 // Get the compile unit context.
1756 CompileUnitDesc *UnitDesc =
1757 static_cast<CompileUnitDesc *>(GVD->getContext());
1758 CompileUnit *Unit = GetBaseCompileUnit();
1760 // Check for pre-existence.
1761 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1762 if (Slot) return Slot;
1764 // Get the global variable itself.
1765 GlobalVariable *GV = GVD->getGlobalVariable();
1767 const std::string &Name = GVD->getName();
1768 const std::string &FullName = GVD->getFullName();
1769 const std::string &LinkageName = GVD->getLinkageName();
1770 // Create the global's variable DIE.
1771 DIE *VariableDie = new DIE(DW_TAG_variable);
1772 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1773 if (!LinkageName.empty()) {
1774 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1777 AddType(VariableDie, GVD->getType(), Unit);
1778 if (!GVD->isStatic())
1779 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1781 // Add source line info if available.
1782 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1785 DIEBlock *Block = new DIEBlock();
1786 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1787 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1788 AddBlock(VariableDie, DW_AT_location, 0, Block);
1793 // Add to context owner.
1794 Unit->getDie()->AddChild(VariableDie);
1796 // Expose as global.
1797 // FIXME - need to check external flag.
1798 Unit->AddGlobal(FullName, VariableDie);
1803 /// NewSubprogram - Add a new subprogram DIE.
1805 DIE *NewSubprogram(SubprogramDesc *SPD) {
1806 // Get the compile unit context.
1807 CompileUnitDesc *UnitDesc =
1808 static_cast<CompileUnitDesc *>(SPD->getContext());
1809 CompileUnit *Unit = GetBaseCompileUnit();
1811 // Check for pre-existence.
1812 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1813 if (Slot) return Slot;
1815 // Gather the details (simplify add attribute code.)
1816 const std::string &Name = SPD->getName();
1817 const std::string &FullName = SPD->getFullName();
1818 const std::string &LinkageName = SPD->getLinkageName();
1820 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1821 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1822 if (!LinkageName.empty()) {
1823 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1826 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1827 if (!SPD->isStatic())
1828 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1829 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1831 // Add source line info if available.
1832 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1835 Slot = SubprogramDie;
1837 // Add to context owner.
1838 Unit->getDie()->AddChild(SubprogramDie);
1840 // Expose as global.
1841 Unit->AddGlobal(FullName, SubprogramDie);
1843 return SubprogramDie;
1846 /// NewScopeVariable - Create a new scope variable.
1848 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1849 // Get the descriptor.
1850 VariableDesc *VD = DV->getDesc();
1852 // Translate tag to proper Dwarf tag. The result variable is dropped for
1855 switch (VD->getTag()) {
1856 case DW_TAG_return_variable: return NULL;
1857 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1858 case DW_TAG_auto_variable: // fall thru
1859 default: Tag = DW_TAG_variable; break;
1862 // Define variable debug information entry.
1863 DIE *VariableDie = new DIE(Tag);
1864 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1866 // Add source line info if available.
1867 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1869 // Add variable type.
1870 AddType(VariableDie, VD->getType(), Unit);
1872 // Add variable address.
1873 MachineLocation Location;
1874 Location.set(RI->getFrameRegister(*MF),
1875 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1876 AddAddress(VariableDie, DW_AT_location, Location);
1881 /// ConstructScope - Construct the components of a scope.
1883 void ConstructScope(DebugScope *ParentScope,
1884 unsigned ParentStartID, unsigned ParentEndID,
1885 DIE *ParentDie, CompileUnit *Unit) {
1886 // Add variables to scope.
1887 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1888 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1889 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1890 if (VariableDie) ParentDie->AddChild(VariableDie);
1893 // Add nested scopes.
1894 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1895 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1896 // Define the Scope debug information entry.
1897 DebugScope *Scope = Scopes[j];
1898 // FIXME - Ignore inlined functions for the time being.
1899 if (!Scope->getParent()) continue;
1901 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1902 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1904 // Ignore empty scopes.
1905 if (StartID == EndID && StartID != 0) continue;
1906 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1908 if (StartID == ParentStartID && EndID == ParentEndID) {
1909 // Just add stuff to the parent scope.
1910 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1912 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1914 // Add the scope bounds.
1916 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1917 DWLabel("label", StartID));
1919 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1920 DWLabel("func_begin", SubprogramCount));
1923 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1924 DWLabel("label", EndID));
1926 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1927 DWLabel("func_end", SubprogramCount));
1930 // Add the scope contents.
1931 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1932 ParentDie->AddChild(ScopeDie);
1937 /// ConstructRootScope - Construct the scope for the subprogram.
1939 void ConstructRootScope(DebugScope *RootScope) {
1940 // Exit if there is no root scope.
1941 if (!RootScope) return;
1943 // Get the subprogram debug information entry.
1944 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1946 // Get the compile unit context.
1947 CompileUnit *Unit = GetBaseCompileUnit();
1949 // Get the subprogram die.
1950 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1951 assert(SPDie && "Missing subprogram descriptor");
1953 // Add the function bounds.
1954 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1955 DWLabel("func_begin", SubprogramCount));
1956 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1957 DWLabel("func_end", SubprogramCount));
1958 MachineLocation Location(RI->getFrameRegister(*MF));
1959 AddAddress(SPDie, DW_AT_frame_base, Location);
1961 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1964 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1965 /// tools to recognize the object file contains Dwarf information.
1966 void EmitInitial() {
1967 // Check to see if we already emitted intial headers.
1968 if (didInitial) return;
1971 // Dwarf sections base addresses.
1972 if (TAI->doesDwarfRequireFrameSection()) {
1973 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1974 EmitLabel("section_debug_frame", 0);
1976 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1977 EmitLabel("section_info", 0);
1978 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1979 EmitLabel("section_abbrev", 0);
1980 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1981 EmitLabel("section_aranges", 0);
1982 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1983 EmitLabel("section_macinfo", 0);
1984 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1985 EmitLabel("section_line", 0);
1986 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1987 EmitLabel("section_loc", 0);
1988 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1989 EmitLabel("section_pubnames", 0);
1990 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1991 EmitLabel("section_str", 0);
1992 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1993 EmitLabel("section_ranges", 0);
1995 Asm->SwitchToTextSection(TAI->getTextSection());
1996 EmitLabel("text_begin", 0);
1997 Asm->SwitchToDataSection(TAI->getDataSection());
1998 EmitLabel("data_begin", 0);
2001 /// EmitDIE - Recusively Emits a debug information entry.
2003 void EmitDIE(DIE *Die) {
2004 // Get the abbreviation for this DIE.
2005 unsigned AbbrevNumber = Die->getAbbrevNumber();
2006 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2010 // Emit the code (index) for the abbreviation.
2011 Asm->EmitULEB128Bytes(AbbrevNumber);
2012 Asm->EOL(std::string("Abbrev [" +
2013 utostr(AbbrevNumber) +
2014 "] 0x" + utohexstr(Die->getOffset()) +
2015 ":0x" + utohexstr(Die->getSize()) + " " +
2016 TagString(Abbrev->getTag())));
2018 std::vector<DIEValue *> &Values = Die->getValues();
2019 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2021 // Emit the DIE attribute values.
2022 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2023 unsigned Attr = AbbrevData[i].getAttribute();
2024 unsigned Form = AbbrevData[i].getForm();
2025 assert(Form && "Too many attributes for DIE (check abbreviation)");
2028 case DW_AT_sibling: {
2029 Asm->EmitInt32(Die->SiblingOffset());
2033 // Emit an attribute using the defined form.
2034 Values[i]->EmitValue(*this, Form);
2039 Asm->EOL(AttributeString(Attr));
2042 // Emit the DIE children if any.
2043 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2044 const std::vector<DIE *> &Children = Die->getChildren();
2046 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2047 EmitDIE(Children[j]);
2050 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2054 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2056 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2057 // Get the children.
2058 const std::vector<DIE *> &Children = Die->getChildren();
2060 // If not last sibling and has children then add sibling offset attribute.
2061 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2063 // Record the abbreviation.
2064 AssignAbbrevNumber(Die->getAbbrev());
2066 // Get the abbreviation for this DIE.
2067 unsigned AbbrevNumber = Die->getAbbrevNumber();
2068 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2071 Die->setOffset(Offset);
2073 // Start the size with the size of abbreviation code.
2074 Offset += Asm->SizeULEB128(AbbrevNumber);
2076 const std::vector<DIEValue *> &Values = Die->getValues();
2077 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2079 // Size the DIE attribute values.
2080 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2081 // Size attribute value.
2082 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2085 // Size the DIE children if any.
2086 if (!Children.empty()) {
2087 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2088 "Children flag not set");
2090 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2091 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2094 // End of children marker.
2095 Offset += sizeof(int8_t);
2098 Die->setSize(Offset - Die->getOffset());
2102 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2104 void SizeAndOffsets() {
2105 // Process base compile unit.
2106 CompileUnit *Unit = GetBaseCompileUnit();
2107 // Compute size of compile unit header
2108 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2109 sizeof(int16_t) + // DWARF version number
2110 sizeof(int32_t) + // Offset Into Abbrev. Section
2111 sizeof(int8_t); // Pointer Size (in bytes)
2112 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2115 /// EmitDebugInfo - Emit the debug info section.
2117 void EmitDebugInfo() {
2118 // Start debug info section.
2119 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2121 CompileUnit *Unit = GetBaseCompileUnit();
2122 DIE *Die = Unit->getDie();
2123 // Emit the compile units header.
2124 EmitLabel("info_begin", Unit->getID());
2125 // Emit size of content not including length itself
2126 unsigned ContentSize = Die->getSize() +
2127 sizeof(int16_t) + // DWARF version number
2128 sizeof(int32_t) + // Offset Into Abbrev. Section
2129 sizeof(int8_t) + // Pointer Size (in bytes)
2130 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2132 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2133 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2134 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2135 Asm->EOL("Offset Into Abbrev. Section");
2136 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2139 // FIXME - extra padding for gdb bug.
2140 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2141 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2142 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2143 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2144 EmitLabel("info_end", Unit->getID());
2149 /// EmitAbbreviations - Emit the abbreviation section.
2151 void EmitAbbreviations() const {
2152 // Check to see if it is worth the effort.
2153 if (!Abbreviations.empty()) {
2154 // Start the debug abbrev section.
2155 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2157 EmitLabel("abbrev_begin", 0);
2159 // For each abbrevation.
2160 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2161 // Get abbreviation data
2162 const DIEAbbrev *Abbrev = Abbreviations[i];
2164 // Emit the abbrevations code (base 1 index.)
2165 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2166 Asm->EOL("Abbreviation Code");
2168 // Emit the abbreviations data.
2169 Abbrev->Emit(*this);
2174 // Mark end of abbreviations.
2175 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2177 EmitLabel("abbrev_end", 0);
2183 /// EmitDebugLines - Emit source line information.
2185 void EmitDebugLines() {
2186 // If there are no lines to emit (such as when we're using .loc directives
2187 // to emit .debug_line information) don't emit a .debug_line header.
2188 if (SectionSourceLines.empty())
2191 // Minimum line delta, thus ranging from -10..(255-10).
2192 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2193 // Maximum line delta, thus ranging from -10..(255-10).
2194 const int MaxLineDelta = 255 + MinLineDelta;
2196 // Start the dwarf line section.
2197 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2199 // Construct the section header.
2201 EmitDifference("line_end", 0, "line_begin", 0, true);
2202 Asm->EOL("Length of Source Line Info");
2203 EmitLabel("line_begin", 0);
2205 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2207 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2208 Asm->EOL("Prolog Length");
2209 EmitLabel("line_prolog_begin", 0);
2211 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2213 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2215 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2217 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2219 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2221 // Line number standard opcode encodings argument count
2222 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2223 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2224 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2225 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2226 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2227 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2228 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2229 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2230 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2232 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2233 const UniqueVector<SourceFileInfo>
2234 &SourceFiles = MMI->getSourceFiles();
2236 // Emit directories.
2237 for (unsigned DirectoryID = 1, NDID = Directories.size();
2238 DirectoryID <= NDID; ++DirectoryID) {
2239 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2241 Asm->EmitInt8(0); Asm->EOL("End of directories");
2244 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2245 SourceID <= NSID; ++SourceID) {
2246 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2247 Asm->EmitString(SourceFile.getName());
2249 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2250 Asm->EOL("Directory #");
2251 Asm->EmitULEB128Bytes(0);
2252 Asm->EOL("Mod date");
2253 Asm->EmitULEB128Bytes(0);
2254 Asm->EOL("File size");
2256 Asm->EmitInt8(0); Asm->EOL("End of files");
2258 EmitLabel("line_prolog_end", 0);
2260 // A sequence for each text section.
2261 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2262 // Isolate current sections line info.
2263 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2265 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2267 // Dwarf assumes we start with first line of first source file.
2268 unsigned Source = 1;
2271 // Construct rows of the address, source, line, column matrix.
2272 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2273 const SourceLineInfo &LineInfo = LineInfos[i];
2274 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2275 if (!LabelID) continue;
2277 unsigned SourceID = LineInfo.getSourceID();
2278 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2279 unsigned DirectoryID = SourceFile.getDirectoryID();
2280 Asm->EOL(Directories[DirectoryID]
2281 + SourceFile.getName()
2283 + utostr_32(LineInfo.getLine()));
2285 // Define the line address.
2286 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2287 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2288 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2289 EmitReference("label", LabelID); Asm->EOL("Location label");
2291 // If change of source, then switch to the new source.
2292 if (Source != LineInfo.getSourceID()) {
2293 Source = LineInfo.getSourceID();
2294 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2295 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2298 // If change of line.
2299 if (Line != LineInfo.getLine()) {
2300 // Determine offset.
2301 int Offset = LineInfo.getLine() - Line;
2302 int Delta = Offset - MinLineDelta;
2305 Line = LineInfo.getLine();
2307 // If delta is small enough and in range...
2308 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2309 // ... then use fast opcode.
2310 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2312 // ... otherwise use long hand.
2313 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2314 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2315 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2318 // Copy the previous row (different address or source)
2319 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2323 // Define last address of section.
2324 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2325 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2326 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2327 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2329 // Mark end of matrix.
2330 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2331 Asm->EmitULEB128Bytes(1); Asm->EOL();
2332 Asm->EmitInt8(1); Asm->EOL();
2335 EmitLabel("line_end", 0);
2340 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2342 void EmitCommonDebugFrame() {
2343 if (!TAI->doesDwarfRequireFrameSection())
2347 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2348 TargetFrameInfo::StackGrowsUp ?
2349 TD->getPointerSize() : -TD->getPointerSize();
2351 // Start the dwarf frame section.
2352 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2354 EmitLabel("debug_frame_common", 0);
2355 EmitDifference("debug_frame_common_end", 0,
2356 "debug_frame_common_begin", 0, true);
2357 Asm->EOL("Length of Common Information Entry");
2359 EmitLabel("debug_frame_common_begin", 0);
2360 Asm->EmitInt32((int)DW_CIE_ID);
2361 Asm->EOL("CIE Identifier Tag");
2362 Asm->EmitInt8(DW_CIE_VERSION);
2363 Asm->EOL("CIE Version");
2364 Asm->EmitString("");
2365 Asm->EOL("CIE Augmentation");
2366 Asm->EmitULEB128Bytes(1);
2367 Asm->EOL("CIE Code Alignment Factor");
2368 Asm->EmitSLEB128Bytes(stackGrowth);
2369 Asm->EOL("CIE Data Alignment Factor");
2370 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2371 Asm->EOL("CIE RA Column");
2373 std::vector<MachineMove> Moves;
2374 RI->getInitialFrameState(Moves);
2376 EmitFrameMoves(NULL, 0, Moves, false);
2378 Asm->EmitAlignment(2, 0, 0, false);
2379 EmitLabel("debug_frame_common_end", 0);
2384 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2386 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2387 if (!TAI->doesDwarfRequireFrameSection())
2390 // Start the dwarf frame section.
2391 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2393 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2394 "debug_frame_begin", DebugFrameInfo.Number, true);
2395 Asm->EOL("Length of Frame Information Entry");
2397 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2399 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2401 Asm->EOL("FDE CIE offset");
2403 EmitReference("func_begin", DebugFrameInfo.Number);
2404 Asm->EOL("FDE initial location");
2405 EmitDifference("func_end", DebugFrameInfo.Number,
2406 "func_begin", DebugFrameInfo.Number);
2407 Asm->EOL("FDE address range");
2409 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2411 Asm->EmitAlignment(2, 0, 0, false);
2412 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2417 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2419 void EmitDebugPubNames() {
2420 // Start the dwarf pubnames section.
2421 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2423 CompileUnit *Unit = GetBaseCompileUnit();
2425 EmitDifference("pubnames_end", Unit->getID(),
2426 "pubnames_begin", Unit->getID(), true);
2427 Asm->EOL("Length of Public Names Info");
2429 EmitLabel("pubnames_begin", Unit->getID());
2431 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2433 EmitSectionOffset("info_begin", "section_info",
2434 Unit->getID(), 0, true, false);
2435 Asm->EOL("Offset of Compilation Unit Info");
2437 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2438 Asm->EOL("Compilation Unit Length");
2440 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2442 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2445 const std::string &Name = GI->first;
2446 DIE * Entity = GI->second;
2448 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2449 Asm->EmitString(Name); Asm->EOL("External Name");
2452 Asm->EmitInt32(0); Asm->EOL("End Mark");
2453 EmitLabel("pubnames_end", Unit->getID());
2458 /// EmitDebugStr - Emit visible names into a debug str section.
2460 void EmitDebugStr() {
2461 // Check to see if it is worth the effort.
2462 if (!StringPool.empty()) {
2463 // Start the dwarf str section.
2464 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2466 // For each of strings in the string pool.
2467 for (unsigned StringID = 1, N = StringPool.size();
2468 StringID <= N; ++StringID) {
2469 // Emit a label for reference from debug information entries.
2470 EmitLabel("string", StringID);
2471 // Emit the string itself.
2472 const std::string &String = StringPool[StringID];
2473 Asm->EmitString(String); Asm->EOL();
2480 /// EmitDebugLoc - Emit visible names into a debug loc section.
2482 void EmitDebugLoc() {
2483 // Start the dwarf loc section.
2484 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2489 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2491 void EmitDebugARanges() {
2492 // Start the dwarf aranges section.
2493 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2497 CompileUnit *Unit = GetBaseCompileUnit();
2499 // Don't include size of length
2500 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2502 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2504 EmitReference("info_begin", Unit->getID());
2505 Asm->EOL("Offset of Compilation Unit Info");
2507 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2509 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2511 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2512 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2515 EmitReference("text_begin", 0); Asm->EOL("Address");
2516 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2518 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2519 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2525 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2527 void EmitDebugRanges() {
2528 // Start the dwarf ranges section.
2529 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2534 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2536 void EmitDebugMacInfo() {
2537 // Start the dwarf macinfo section.
2538 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2543 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2545 void ConstructCompileUnitDIEs() {
2546 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2548 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2549 unsigned ID = MMI->RecordSource(CUW[i]);
2550 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2551 CompileUnits.push_back(Unit);
2555 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2556 /// global variables.
2557 void ConstructGlobalDIEs() {
2558 std::vector<GlobalVariableDesc *> GlobalVariables =
2559 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2561 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2562 GlobalVariableDesc *GVD = GlobalVariables[i];
2563 NewGlobalVariable(GVD);
2567 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2569 void ConstructSubprogramDIEs() {
2570 std::vector<SubprogramDesc *> Subprograms =
2571 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2573 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2574 SubprogramDesc *SPD = Subprograms[i];
2580 //===--------------------------------------------------------------------===//
2581 // Main entry points.
2583 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2584 : Dwarf(OS, A, T, "dbg")
2586 , AbbreviationsSet(InitAbbreviationsSetSize)
2588 , ValuesSet(InitValuesSetSize)
2593 , SectionSourceLines()
2598 virtual ~DwarfDebug() {
2599 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2600 delete CompileUnits[i];
2601 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2605 /// SetModuleInfo - Set machine module information when it's known that pass
2606 /// manager has created it. Set by the target AsmPrinter.
2607 void SetModuleInfo(MachineModuleInfo *mmi) {
2608 // Make sure initial declarations are made.
2609 if (!MMI && mmi->hasDebugInfo()) {
2613 // Create all the compile unit DIEs.
2614 ConstructCompileUnitDIEs();
2616 // Create DIEs for each of the externally visible global variables.
2617 ConstructGlobalDIEs();
2619 // Create DIEs for each of the externally visible subprograms.
2620 ConstructSubprogramDIEs();
2622 // Prime section data.
2623 SectionMap.insert(TAI->getTextSection());
2625 // Print out .file directives to specify files for .loc directives. These
2626 // are printed out early so that they precede any .loc directives.
2627 if (TAI->hasDotLocAndDotFile()) {
2628 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2629 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2630 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2631 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2632 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2633 assert(AppendOk && "Could not append filename to directory!");
2634 Asm->EmitFile(i, FullPath.toString());
2639 // Emit initial sections
2644 /// BeginModule - Emit all Dwarf sections that should come prior to the
2646 void BeginModule(Module *M) {
2649 if (!ShouldEmitDwarf()) return;
2652 /// EndModule - Emit all Dwarf sections that should come after the content.
2655 if (!ShouldEmitDwarf()) return;
2657 // Standard sections final addresses.
2658 Asm->SwitchToTextSection(TAI->getTextSection());
2659 EmitLabel("text_end", 0);
2660 Asm->SwitchToDataSection(TAI->getDataSection());
2661 EmitLabel("data_end", 0);
2663 // End text sections.
2664 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2665 Asm->SwitchToTextSection(SectionMap[i].c_str());
2666 EmitLabel("section_end", i);
2669 // Emit common frame information.
2670 EmitCommonDebugFrame();
2672 // Emit function debug frame information
2673 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2674 E = DebugFrames.end(); I != E; ++I)
2675 EmitFunctionDebugFrame(*I);
2677 // Compute DIE offsets and sizes.
2680 // Emit all the DIEs into a debug info section
2683 // Corresponding abbreviations into a abbrev section.
2684 EmitAbbreviations();
2686 // Emit source line correspondence into a debug line section.
2689 // Emit info into a debug pubnames section.
2690 EmitDebugPubNames();
2692 // Emit info into a debug str section.
2695 // Emit info into a debug loc section.
2698 // Emit info into a debug aranges section.
2701 // Emit info into a debug ranges section.
2704 // Emit info into a debug macinfo section.
2708 /// BeginFunction - Gather pre-function debug information. Assumes being
2709 /// emitted immediately after the function entry point.
2710 void BeginFunction(MachineFunction *MF) {
2713 if (!ShouldEmitDwarf()) return;
2715 // Begin accumulating function debug information.
2716 MMI->BeginFunction(MF);
2718 // Assumes in correct section after the entry point.
2719 EmitLabel("func_begin", ++SubprogramCount);
2721 // Emit label for the implicitly defined dbg.stoppoint at the start of
2723 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2724 if (!LineInfos.empty()) {
2725 const SourceLineInfo &LineInfo = LineInfos[0];
2726 Asm->printLabel(LineInfo.getLabelID());
2730 /// EndFunction - Gather and emit post-function debug information.
2732 void EndFunction() {
2733 if (!ShouldEmitDwarf()) return;
2735 // Define end label for subprogram.
2736 EmitLabel("func_end", SubprogramCount);
2738 // Get function line info.
2739 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2741 if (!LineInfos.empty()) {
2742 // Get section line info.
2743 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2744 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2745 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2746 // Append the function info to section info.
2747 SectionLineInfos.insert(SectionLineInfos.end(),
2748 LineInfos.begin(), LineInfos.end());
2751 // Construct scopes for subprogram.
2752 ConstructRootScope(MMI->getRootScope());
2754 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2755 MMI->getFrameMoves()));
2759 //===----------------------------------------------------------------------===//
2760 /// DwarfException - Emits Dwarf exception handling directives.
2762 class DwarfException : public Dwarf {
2765 struct FunctionEHFrameInfo {
2768 unsigned PersonalityIndex;
2770 bool hasLandingPads;
2771 std::vector<MachineMove> Moves;
2772 const Function * function;
2774 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2776 const std::vector<MachineMove> &M,
2778 FnName(FN), Number(Num), PersonalityIndex(P),
2779 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2782 std::vector<FunctionEHFrameInfo> EHFrames;
2784 /// shouldEmitTable - Per-function flag to indicate if EH tables should
2786 bool shouldEmitTable;
2788 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
2789 /// should be emitted.
2790 bool shouldEmitMoves;
2792 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
2793 /// should be emitted.
2794 bool shouldEmitTableModule;
2796 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
2797 /// should be emitted.
2798 bool shouldEmitMovesModule;
2800 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2802 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2803 // Size and sign of stack growth.
2805 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2806 TargetFrameInfo::StackGrowsUp ?
2807 TD->getPointerSize() : -TD->getPointerSize();
2809 // Begin eh frame section.
2810 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2811 O << "EH_frame" << Index << ":\n";
2812 EmitLabel("section_eh_frame", Index);
2814 // Define base labels.
2815 EmitLabel("eh_frame_common", Index);
2817 // Define the eh frame length.
2818 EmitDifference("eh_frame_common_end", Index,
2819 "eh_frame_common_begin", Index, true);
2820 Asm->EOL("Length of Common Information Entry");
2823 EmitLabel("eh_frame_common_begin", Index);
2824 Asm->EmitInt32((int)0);
2825 Asm->EOL("CIE Identifier Tag");
2826 Asm->EmitInt8(DW_CIE_VERSION);
2827 Asm->EOL("CIE Version");
2829 // The personality presence indicates that language specific information
2830 // will show up in the eh frame.
2831 Asm->EmitString(Personality ? "zPLR" : "zR");
2832 Asm->EOL("CIE Augmentation");
2834 // Round out reader.
2835 Asm->EmitULEB128Bytes(1);
2836 Asm->EOL("CIE Code Alignment Factor");
2837 Asm->EmitSLEB128Bytes(stackGrowth);
2838 Asm->EOL("CIE Data Alignment Factor");
2839 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2840 Asm->EOL("CIE RA Column");
2842 // If there is a personality, we need to indicate the functions location.
2844 Asm->EmitULEB128Bytes(7);
2845 Asm->EOL("Augmentation Size");
2847 if (TAI->getNeedsIndirectEncoding())
2848 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2850 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2852 Asm->EOL("Personality (pcrel sdata4 indirect)");
2854 PrintRelDirective(TAI->getShortenEHDataOn64Bit());
2855 O << TAI->getPersonalityPrefix();
2856 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2857 O << TAI->getPersonalitySuffix();
2858 if (!TAI->getShortenEHDataOn64Bit()) {
2859 O << "-" << TAI->getPCSymbol();
2861 Asm->EOL("Personality");
2863 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2864 Asm->EOL("LSDA Encoding (pcrel)");
2865 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2866 Asm->EOL("FDE Encoding (pcrel)");
2868 Asm->EmitULEB128Bytes(1);
2869 Asm->EOL("Augmentation Size");
2870 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2871 Asm->EOL("FDE Encoding (pcrel)");
2874 // Indicate locations of general callee saved registers in frame.
2875 std::vector<MachineMove> Moves;
2876 RI->getInitialFrameState(Moves);
2877 EmitFrameMoves(NULL, 0, Moves, true);
2879 // On Darwin the linker honors the alignment of eh_frame, which means it
2880 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
2881 // you get holes which confuse readers of eh_frame.
2882 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
2884 EmitLabel("eh_frame_common_end", Index);
2889 /// EmitEHFrame - Emit function exception frame information.
2891 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2892 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
2894 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2896 // Externally visible entry into the functions eh frame info.
2897 // If the corresponding function is static, this should not be
2898 // externally visible.
2899 if (linkage != Function::InternalLinkage) {
2900 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
2901 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
2904 // If corresponding function is weak definition, this should be too.
2905 if ((linkage == Function::WeakLinkage ||
2906 linkage == Function::LinkOnceLinkage) &&
2907 TAI->getWeakDefDirective())
2908 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
2910 // If there are no calls then you can't unwind. This may mean we can
2911 // omit the EH Frame, but some environments do not handle weak absolute
2913 // If UnwindTablesMandatory is set we cannot do this optimization; the
2914 // unwind info is to be available for non-EH uses.
2915 if (!EHFrameInfo.hasCalls &&
2916 !UnwindTablesMandatory &&
2917 ((linkage != Function::WeakLinkage &&
2918 linkage != Function::LinkOnceLinkage) ||
2919 !TAI->getWeakDefDirective() ||
2920 TAI->getSupportsWeakOmittedEHFrame()))
2922 O << EHFrameInfo.FnName << " = 0\n";
2923 // This name has no connection to the function, so it might get
2924 // dead-stripped when the function is not, erroneously. Prohibit
2925 // dead-stripping unconditionally.
2926 if (const char *UsedDirective = TAI->getUsedDirective())
2927 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2929 O << EHFrameInfo.FnName << ":\n";
2932 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2933 "eh_frame_begin", EHFrameInfo.Number, true);
2934 Asm->EOL("Length of Frame Information Entry");
2936 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2938 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2939 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2941 Asm->EOL("FDE CIE offset");
2943 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2944 Asm->EOL("FDE initial location");
2945 EmitDifference("eh_func_end", EHFrameInfo.Number,
2946 "eh_func_begin", EHFrameInfo.Number);
2947 Asm->EOL("FDE address range");
2949 // If there is a personality and landing pads then point to the language
2950 // specific data area in the exception table.
2951 if (EHFrameInfo.PersonalityIndex) {
2952 Asm->EmitULEB128Bytes(TAI->getShortenEHDataOn64Bit() ? 8 : 4);
2953 Asm->EOL("Augmentation size");
2955 if (EHFrameInfo.hasLandingPads) {
2956 EmitReference("exception", EHFrameInfo.Number, true);
2957 } else if (TD->getPointerSize() == 8) {
2958 Asm->EmitInt64((int)0);
2960 Asm->EmitInt32((int)0);
2962 Asm->EOL("Language Specific Data Area");
2964 Asm->EmitULEB128Bytes(0);
2965 Asm->EOL("Augmentation size");
2968 // Indicate locations of function specific callee saved registers in
2970 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
2972 // On Darwin the linker honors the alignment of eh_frame, which means it
2973 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
2974 // you get holes which confuse readers of eh_frame.
2975 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
2977 EmitLabel("eh_frame_end", EHFrameInfo.Number);
2979 // If the function is marked used, this table should be also. We cannot
2980 // make the mark unconditional in this case, since retaining the table
2981 // also retains the function in this case, and there is code around
2982 // that depends on unused functions (calling undefined externals) being
2983 // dead-stripped to link correctly. Yes, there really is.
2984 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
2985 if (const char *UsedDirective = TAI->getUsedDirective())
2986 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2990 /// EmitExceptionTable - Emit landing pads and actions.
2992 /// The general organization of the table is complex, but the basic concepts
2993 /// are easy. First there is a header which describes the location and
2994 /// organization of the three components that follow.
2995 /// 1. The landing pad site information describes the range of code covered
2996 /// by the try. In our case it's an accumulation of the ranges covered
2997 /// by the invokes in the try. There is also a reference to the landing
2998 /// pad that handles the exception once processed. Finally an index into
2999 /// the actions table.
3000 /// 2. The action table, in our case, is composed of pairs of type ids
3001 /// and next action offset. Starting with the action index from the
3002 /// landing pad site, each type Id is checked for a match to the current
3003 /// exception. If it matches then the exception and type id are passed
3004 /// on to the landing pad. Otherwise the next action is looked up. This
3005 /// chain is terminated with a next action of zero. If no type id is
3006 /// found the the frame is unwound and handling continues.
3007 /// 3. Type id table contains references to all the C++ typeinfo for all
3008 /// catches in the function. This tables is reversed indexed base 1.
3010 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3011 static unsigned SharedTypeIds(const LandingPadInfo *L,
3012 const LandingPadInfo *R) {
3013 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3014 unsigned LSize = LIds.size(), RSize = RIds.size();
3015 unsigned MinSize = LSize < RSize ? LSize : RSize;
3018 for (; Count != MinSize; ++Count)
3019 if (LIds[Count] != RIds[Count])
3025 /// PadLT - Order landing pads lexicographically by type id.
3026 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3027 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3028 unsigned LSize = LIds.size(), RSize = RIds.size();
3029 unsigned MinSize = LSize < RSize ? LSize : RSize;
3031 for (unsigned i = 0; i != MinSize; ++i)
3032 if (LIds[i] != RIds[i])
3033 return LIds[i] < RIds[i];
3035 return LSize < RSize;
3039 static inline unsigned getEmptyKey() { return -1U; }
3040 static inline unsigned getTombstoneKey() { return -2U; }
3041 static unsigned getHashValue(const unsigned &Key) { return Key; }
3042 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3043 static bool isPod() { return true; }
3046 /// ActionEntry - Structure describing an entry in the actions table.
3047 struct ActionEntry {
3048 int ValueForTypeID; // The value to write - may not be equal to the type id.
3050 struct ActionEntry *Previous;
3053 /// PadRange - Structure holding a try-range and the associated landing pad.
3055 // The index of the landing pad.
3057 // The index of the begin and end labels in the landing pad's label lists.
3058 unsigned RangeIndex;
3061 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3063 /// CallSiteEntry - Structure describing an entry in the call-site table.
3064 struct CallSiteEntry {
3065 // The 'try-range' is BeginLabel .. EndLabel.
3066 unsigned BeginLabel; // zero indicates the start of the function.
3067 unsigned EndLabel; // zero indicates the end of the function.
3068 // The landing pad starts at PadLabel.
3069 unsigned PadLabel; // zero indicates that there is no landing pad.
3073 void EmitExceptionTable() {
3074 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3075 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3076 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3077 if (PadInfos.empty()) return;
3079 // Sort the landing pads in order of their type ids. This is used to fold
3080 // duplicate actions.
3081 SmallVector<const LandingPadInfo *, 64> LandingPads;
3082 LandingPads.reserve(PadInfos.size());
3083 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3084 LandingPads.push_back(&PadInfos[i]);
3085 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3087 // Negative type ids index into FilterIds, positive type ids index into
3088 // TypeInfos. The value written for a positive type id is just the type
3089 // id itself. For a negative type id, however, the value written is the
3090 // (negative) byte offset of the corresponding FilterIds entry. The byte
3091 // offset is usually equal to the type id, because the FilterIds entries
3092 // are written using a variable width encoding which outputs one byte per
3093 // entry as long as the value written is not too large, but can differ.
3094 // This kind of complication does not occur for positive type ids because
3095 // type infos are output using a fixed width encoding.
3096 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3097 SmallVector<int, 16> FilterOffsets;
3098 FilterOffsets.reserve(FilterIds.size());
3100 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3101 E = FilterIds.end(); I != E; ++I) {
3102 FilterOffsets.push_back(Offset);
3103 Offset -= Asm->SizeULEB128(*I);
3106 // Compute the actions table and gather the first action index for each
3107 // landing pad site.
3108 SmallVector<ActionEntry, 32> Actions;
3109 SmallVector<unsigned, 64> FirstActions;
3110 FirstActions.reserve(LandingPads.size());
3112 int FirstAction = 0;
3113 unsigned SizeActions = 0;
3114 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3115 const LandingPadInfo *LP = LandingPads[i];
3116 const std::vector<int> &TypeIds = LP->TypeIds;
3117 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3118 unsigned SizeSiteActions = 0;
3120 if (NumShared < TypeIds.size()) {
3121 unsigned SizeAction = 0;
3122 ActionEntry *PrevAction = 0;
3125 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3126 assert(Actions.size());
3127 PrevAction = &Actions.back();
3128 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3129 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3130 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3131 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3132 SizeAction += -PrevAction->NextAction;
3133 PrevAction = PrevAction->Previous;
3137 // Compute the actions.
3138 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3139 int TypeID = TypeIds[I];
3140 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3141 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3142 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3144 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3145 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3146 SizeSiteActions += SizeAction;
3148 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3149 Actions.push_back(Action);
3151 PrevAction = &Actions.back();
3154 // Record the first action of the landing pad site.
3155 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3156 } // else identical - re-use previous FirstAction
3158 FirstActions.push_back(FirstAction);
3160 // Compute this sites contribution to size.
3161 SizeActions += SizeSiteActions;
3164 // Compute the call-site table. The entry for an invoke has a try-range
3165 // containing the call, a non-zero landing pad and an appropriate action.
3166 // The entry for an ordinary call has a try-range containing the call and
3167 // zero for the landing pad and the action. Calls marked 'nounwind' have
3168 // no entry and must not be contained in the try-range of any entry - they
3169 // form gaps in the table. Entries must be ordered by try-range address.
3170 SmallVector<CallSiteEntry, 64> CallSites;
3172 RangeMapType PadMap;
3173 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3174 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3175 // try-ranges for them need be deduced.
3176 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3177 const LandingPadInfo *LandingPad = LandingPads[i];
3178 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3179 unsigned BeginLabel = LandingPad->BeginLabels[j];
3180 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3181 PadRange P = { i, j };
3182 PadMap[BeginLabel] = P;
3186 // The end label of the previous invoke or nounwind try-range.
3187 unsigned LastLabel = 0;
3189 // Whether there is a potentially throwing instruction (currently this means
3190 // an ordinary call) between the end of the previous try-range and now.
3191 bool SawPotentiallyThrowing = false;
3193 // Whether the last callsite entry was for an invoke.
3194 bool PreviousIsInvoke = false;
3196 // Visit all instructions in order of address.
3197 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3199 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3201 if (MI->getOpcode() != TargetInstrInfo::LABEL) {
3202 SawPotentiallyThrowing |= MI->getDesc().isCall();
3206 unsigned BeginLabel = MI->getOperand(0).getImm();
3207 assert(BeginLabel && "Invalid label!");
3209 // End of the previous try-range?
3210 if (BeginLabel == LastLabel)
3211 SawPotentiallyThrowing = false;
3213 // Beginning of a new try-range?
3214 RangeMapType::iterator L = PadMap.find(BeginLabel);
3215 if (L == PadMap.end())
3216 // Nope, it was just some random label.
3219 PadRange P = L->second;
3220 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3222 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3223 "Inconsistent landing pad map!");
3225 // If some instruction between the previous try-range and this one may
3226 // throw, create a call-site entry with no landing pad for the region
3227 // between the try-ranges.
3228 if (SawPotentiallyThrowing) {
3229 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3230 CallSites.push_back(Site);
3231 PreviousIsInvoke = false;
3234 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3235 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3237 if (LandingPad->LandingPadLabel) {
3238 // This try-range is for an invoke.
3239 CallSiteEntry Site = {BeginLabel, LastLabel,
3240 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3242 // Try to merge with the previous call-site.
3243 if (PreviousIsInvoke) {
3244 CallSiteEntry &Prev = CallSites[CallSites.size()-1];
3245 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3246 // Extend the range of the previous entry.
3247 Prev.EndLabel = Site.EndLabel;
3252 // Otherwise, create a new call-site.
3253 CallSites.push_back(Site);
3254 PreviousIsInvoke = true;
3257 PreviousIsInvoke = false;
3261 // If some instruction between the previous try-range and the end of the
3262 // function may throw, create a call-site entry with no landing pad for the
3263 // region following the try-range.
3264 if (SawPotentiallyThrowing) {
3265 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3266 CallSites.push_back(Site);
3270 unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
3271 sizeof(int32_t) + // Site length.
3272 sizeof(int32_t)); // Landing pad.
3273 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3274 SizeSites += Asm->SizeULEB128(CallSites[i].Action);
3276 unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
3278 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3279 Asm->SizeULEB128(SizeSites) + // Call-site table length
3280 SizeSites + SizeActions + SizeTypes;
3282 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3283 sizeof(int8_t) + // TType format
3284 Asm->SizeULEB128(TypeOffset) + // TType base offset
3287 unsigned SizeAlign = (4 - TotalSize) & 3;
3289 // Begin the exception table.
3290 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3291 O << "GCC_except_table" << SubprogramCount << ":\n";
3292 Asm->EmitAlignment(2, 0, 0, false);
3293 for (unsigned i = 0; i != SizeAlign; ++i) {
3295 Asm->EOL("Padding");
3297 EmitLabel("exception", SubprogramCount);
3300 Asm->EmitInt8(DW_EH_PE_omit);
3301 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3302 Asm->EmitInt8(DW_EH_PE_absptr);
3303 Asm->EOL("TType format (DW_EH_PE_absptr)");
3304 Asm->EmitULEB128Bytes(TypeOffset);
3305 Asm->EOL("TType base offset");
3306 Asm->EmitInt8(DW_EH_PE_udata4);
3307 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3308 Asm->EmitULEB128Bytes(SizeSites);
3309 Asm->EOL("Call-site table length");
3311 // Emit the landing pad site information.
3312 for (unsigned i = 0; i < CallSites.size(); ++i) {
3313 CallSiteEntry &S = CallSites[i];
3314 const char *BeginTag;
3315 unsigned BeginNumber;
3317 if (!S.BeginLabel) {
3318 BeginTag = "eh_func_begin";
3319 BeginNumber = SubprogramCount;
3322 BeginNumber = S.BeginLabel;
3325 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3326 TAI->getShortenEHDataOn64Bit(), true);
3327 Asm->EOL("Region start");
3330 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3331 TAI->getShortenEHDataOn64Bit());
3333 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber,
3334 TAI->getShortenEHDataOn64Bit());
3336 Asm->EOL("Region length");
3339 if (TD->getPointerSize() == sizeof(int32_t) || TAI->getShortenEHDataOn64Bit())
3344 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3345 TAI->getShortenEHDataOn64Bit(), true);
3347 Asm->EOL("Landing pad");
3349 Asm->EmitULEB128Bytes(S.Action);
3353 // Emit the actions.
3354 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3355 ActionEntry &Action = Actions[I];
3357 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3358 Asm->EOL("TypeInfo index");
3359 Asm->EmitSLEB128Bytes(Action.NextAction);
3360 Asm->EOL("Next action");
3363 // Emit the type ids.
3364 for (unsigned M = TypeInfos.size(); M; --M) {
3365 GlobalVariable *GV = TypeInfos[M - 1];
3367 PrintRelDirective();
3370 O << Asm->getGlobalLinkName(GV);
3374 Asm->EOL("TypeInfo");
3377 // Emit the filter typeids.
3378 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3379 unsigned TypeID = FilterIds[j];
3380 Asm->EmitULEB128Bytes(TypeID);
3381 Asm->EOL("Filter TypeInfo index");
3384 Asm->EmitAlignment(2, 0, 0, false);
3388 //===--------------------------------------------------------------------===//
3389 // Main entry points.
3391 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3392 : Dwarf(OS, A, T, "eh")
3393 , shouldEmitTable(false)
3394 , shouldEmitMoves(false)
3395 , shouldEmitTableModule(false)
3396 , shouldEmitMovesModule(false)
3399 virtual ~DwarfException() {}
3401 /// SetModuleInfo - Set machine module information when it's known that pass
3402 /// manager has created it. Set by the target AsmPrinter.
3403 void SetModuleInfo(MachineModuleInfo *mmi) {
3407 /// BeginModule - Emit all exception information that should come prior to the
3409 void BeginModule(Module *M) {
3413 /// EndModule - Emit all exception information that should come after the
3416 if (shouldEmitMovesModule || shouldEmitTableModule) {
3417 const std::vector<Function *> Personalities = MMI->getPersonalities();
3418 for (unsigned i =0; i < Personalities.size(); ++i)
3419 EmitCommonEHFrame(Personalities[i], i);
3421 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3422 E = EHFrames.end(); I != E; ++I)
3427 /// BeginFunction - Gather pre-function exception information. Assumes being
3428 /// emitted immediately after the function entry point.
3429 void BeginFunction(MachineFunction *MF) {
3431 shouldEmitTable = shouldEmitMoves = false;
3432 if (MMI && TAI->doesSupportExceptionHandling()) {
3434 // Map all labels and get rid of any dead landing pads.
3435 MMI->TidyLandingPads();
3436 // If any landing pads survive, we need an EH table.
3437 if (MMI->getLandingPads().size())
3438 shouldEmitTable = true;
3440 // See if we need frame move info.
3441 if (MMI->hasDebugInfo() ||
3442 !MF->getFunction()->doesNotThrow() ||
3443 UnwindTablesMandatory)
3444 shouldEmitMoves = true;
3446 if (shouldEmitMoves || shouldEmitTable)
3447 // Assumes in correct section after the entry point.
3448 EmitLabel("eh_func_begin", ++SubprogramCount);
3450 shouldEmitTableModule |= shouldEmitTable;
3451 shouldEmitMovesModule |= shouldEmitMoves;
3454 /// EndFunction - Gather and emit post-function exception information.
3456 void EndFunction() {
3457 if (shouldEmitMoves || shouldEmitTable) {
3458 EmitLabel("eh_func_end", SubprogramCount);
3459 EmitExceptionTable();
3461 // Save EH frame information
3463 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3465 MMI->getPersonalityIndex(),
3466 MF->getFrameInfo()->hasCalls(),
3467 !MMI->getLandingPads().empty(),
3468 MMI->getFrameMoves(),
3469 MF->getFunction()));
3474 } // End of namespace llvm
3476 //===----------------------------------------------------------------------===//
3478 /// Emit - Print the abbreviation using the specified Dwarf writer.
3480 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3481 // Emit its Dwarf tag type.
3482 DD.getAsm()->EmitULEB128Bytes(Tag);
3483 DD.getAsm()->EOL(TagString(Tag));
3485 // Emit whether it has children DIEs.
3486 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3487 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3489 // For each attribute description.
3490 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3491 const DIEAbbrevData &AttrData = Data[i];
3493 // Emit attribute type.
3494 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3495 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3498 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3499 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3502 // Mark end of abbreviation.
3503 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3504 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3508 void DIEAbbrev::print(std::ostream &O) {
3509 O << "Abbreviation @"
3510 << std::hex << (intptr_t)this << std::dec
3514 << ChildrenString(ChildrenFlag)
3517 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3519 << AttributeString(Data[i].getAttribute())
3521 << FormEncodingString(Data[i].getForm())
3525 void DIEAbbrev::dump() { print(cerr); }
3528 //===----------------------------------------------------------------------===//
3531 void DIEValue::dump() {
3536 //===----------------------------------------------------------------------===//
3538 /// EmitValue - Emit integer of appropriate size.
3540 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3542 case DW_FORM_flag: // Fall thru
3543 case DW_FORM_ref1: // Fall thru
3544 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3545 case DW_FORM_ref2: // Fall thru
3546 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3547 case DW_FORM_ref4: // Fall thru
3548 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3549 case DW_FORM_ref8: // Fall thru
3550 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3551 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3552 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3553 default: assert(0 && "DIE Value form not supported yet"); break;
3557 /// SizeOf - Determine size of integer value in bytes.
3559 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3561 case DW_FORM_flag: // Fall thru
3562 case DW_FORM_ref1: // Fall thru
3563 case DW_FORM_data1: return sizeof(int8_t);
3564 case DW_FORM_ref2: // Fall thru
3565 case DW_FORM_data2: return sizeof(int16_t);
3566 case DW_FORM_ref4: // Fall thru
3567 case DW_FORM_data4: return sizeof(int32_t);
3568 case DW_FORM_ref8: // Fall thru
3569 case DW_FORM_data8: return sizeof(int64_t);
3570 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3571 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3572 default: assert(0 && "DIE Value form not supported yet"); break;
3577 //===----------------------------------------------------------------------===//
3579 /// EmitValue - Emit string value.
3581 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3582 DD.getAsm()->EmitString(String);
3585 //===----------------------------------------------------------------------===//
3587 /// EmitValue - Emit label value.
3589 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3590 bool IsSmall = Form == DW_FORM_data4;
3591 DD.EmitReference(Label, false, IsSmall);
3594 /// SizeOf - Determine size of label value in bytes.
3596 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3597 if (Form == DW_FORM_data4) return 4;
3598 return DD.getTargetData()->getPointerSize();
3601 //===----------------------------------------------------------------------===//
3603 /// EmitValue - Emit label value.
3605 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3606 bool IsSmall = Form == DW_FORM_data4;
3607 DD.EmitReference(Label, false, IsSmall);
3610 /// SizeOf - Determine size of label value in bytes.
3612 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3613 if (Form == DW_FORM_data4) return 4;
3614 return DD.getTargetData()->getPointerSize();
3617 //===----------------------------------------------------------------------===//
3619 /// EmitValue - Emit delta value.
3621 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3622 bool IsSmall = Form == DW_FORM_data4;
3623 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3626 /// SizeOf - Determine size of delta value in bytes.
3628 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3629 if (Form == DW_FORM_data4) return 4;
3630 return DD.getTargetData()->getPointerSize();
3633 //===----------------------------------------------------------------------===//
3635 /// EmitValue - Emit debug information entry offset.
3637 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3638 DD.getAsm()->EmitInt32(Entry->getOffset());
3641 //===----------------------------------------------------------------------===//
3643 /// ComputeSize - calculate the size of the block.
3645 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3647 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3649 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3650 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3656 /// EmitValue - Emit block data.
3658 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3660 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3661 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3662 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3663 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3664 default: assert(0 && "Improper form for block"); break;
3667 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3669 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3671 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3675 /// SizeOf - Determine size of block data in bytes.
3677 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3679 case DW_FORM_block1: return Size + sizeof(int8_t);
3680 case DW_FORM_block2: return Size + sizeof(int16_t);
3681 case DW_FORM_block4: return Size + sizeof(int32_t);
3682 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3683 default: assert(0 && "Improper form for block"); break;
3688 //===----------------------------------------------------------------------===//
3689 /// DIE Implementation
3692 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3696 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3698 void DIE::AddSiblingOffset() {
3699 DIEInteger *DI = new DIEInteger(0);
3700 Values.insert(Values.begin(), DI);
3701 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3704 /// Profile - Used to gather unique data for the value folding set.
3706 void DIE::Profile(FoldingSetNodeID &ID) {
3709 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3710 ID.AddPointer(Children[i]);
3712 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3713 ID.AddPointer(Values[j]);
3717 void DIE::print(std::ostream &O, unsigned IncIndent) {
3718 static unsigned IndentCount = 0;
3719 IndentCount += IncIndent;
3720 const std::string Indent(IndentCount, ' ');
3721 bool isBlock = Abbrev.getTag() == 0;
3726 << "0x" << std::hex << (intptr_t)this << std::dec
3727 << ", Offset: " << Offset
3728 << ", Size: " << Size
3732 << TagString(Abbrev.getTag())
3734 << ChildrenString(Abbrev.getChildrenFlag());
3736 O << "Size: " << Size;
3740 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3743 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3746 O << AttributeString(Data[i].getAttribute());
3748 O << "Blk[" << i << "]";
3751 << FormEncodingString(Data[i].getForm())
3753 Values[i]->print(O);
3758 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3759 Children[j]->print(O, 4);
3762 if (!isBlock) O << "\n";
3763 IndentCount -= IncIndent;
3771 //===----------------------------------------------------------------------===//
3772 /// DwarfWriter Implementation
3775 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3776 const TargetAsmInfo *T) {
3777 DE = new DwarfException(OS, A, T);
3778 DD = new DwarfDebug(OS, A, T);
3781 DwarfWriter::~DwarfWriter() {
3786 /// SetModuleInfo - Set machine module info when it's known that pass manager
3787 /// has created it. Set by the target AsmPrinter.
3788 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3789 DD->SetModuleInfo(MMI);
3790 DE->SetModuleInfo(MMI);
3793 /// BeginModule - Emit all Dwarf sections that should come prior to the
3795 void DwarfWriter::BeginModule(Module *M) {
3800 /// EndModule - Emit all Dwarf sections that should come after the content.
3802 void DwarfWriter::EndModule() {
3807 /// BeginFunction - Gather pre-function debug information. Assumes being
3808 /// emitted immediately after the function entry point.
3809 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3810 DE->BeginFunction(MF);
3811 DD->BeginFunction(MF);
3814 /// EndFunction - Gather and emit post-function debug information.
3816 void DwarfWriter::EndFunction() {
3820 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3821 // Clear function debug information.