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/MachineDebugInfoDesc.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/System/Path.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetFrameInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
43 using namespace llvm::dwarf;
47 //===----------------------------------------------------------------------===//
49 /// Configuration values for initial hash set sizes (log2).
51 static const unsigned InitDiesSetSize = 9; // 512
52 static const unsigned InitAbbreviationsSetSize = 9; // 512
53 static const unsigned InitValuesSetSize = 9; // 512
55 //===----------------------------------------------------------------------===//
56 /// Forward declarations.
61 //===----------------------------------------------------------------------===//
62 /// DWLabel - Labels are used to track locations in the assembler file.
63 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
64 /// where the tag is a category of label (Ex. location) and number is a value
65 /// unique in that category.
68 /// Tag - Label category tag. Should always be a staticly declared C string.
72 /// Number - Value to make label unique.
76 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
78 void Profile(FoldingSetNodeID &ID) const {
79 ID.AddString(std::string(Tag));
80 ID.AddInteger(Number);
84 void print(std::ostream *O) const {
87 void print(std::ostream &O) const {
89 if (Number) O << Number;
94 //===----------------------------------------------------------------------===//
95 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
96 /// Dwarf abbreviation.
99 /// Attribute - Dwarf attribute code.
103 /// Form - Dwarf form code.
108 DIEAbbrevData(unsigned A, unsigned F)
114 unsigned getAttribute() const { return Attribute; }
115 unsigned getForm() const { return Form; }
117 /// Profile - Used to gather unique data for the abbreviation folding set.
119 void Profile(FoldingSetNodeID &ID)const {
120 ID.AddInteger(Attribute);
125 //===----------------------------------------------------------------------===//
126 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
127 /// information object.
128 class DIEAbbrev : public FoldingSetNode {
130 /// Tag - Dwarf tag code.
134 /// Unique number for node.
138 /// ChildrenFlag - Dwarf children flag.
140 unsigned ChildrenFlag;
142 /// Data - Raw data bytes for abbreviation.
144 SmallVector<DIEAbbrevData, 8> Data;
148 DIEAbbrev(unsigned T, unsigned C)
156 unsigned getTag() const { return Tag; }
157 unsigned getNumber() const { return Number; }
158 unsigned getChildrenFlag() const { return ChildrenFlag; }
159 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
160 void setTag(unsigned T) { Tag = T; }
161 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
162 void setNumber(unsigned N) { Number = N; }
164 /// AddAttribute - Adds another set of attribute information to the
166 void AddAttribute(unsigned Attribute, unsigned Form) {
167 Data.push_back(DIEAbbrevData(Attribute, Form));
170 /// AddFirstAttribute - Adds a set of attribute information to the front
171 /// of the abbreviation.
172 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
173 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
176 /// Profile - Used to gather unique data for the abbreviation folding set.
178 void Profile(FoldingSetNodeID &ID) {
180 ID.AddInteger(ChildrenFlag);
182 // For each attribute description.
183 for (unsigned i = 0, N = Data.size(); i < N; ++i)
187 /// Emit - Print the abbreviation using the specified Dwarf writer.
189 void Emit(const DwarfDebug &DD) const;
192 void print(std::ostream *O) {
195 void print(std::ostream &O);
200 //===----------------------------------------------------------------------===//
201 /// DIE - A structured debug information entry. Has an abbreviation which
202 /// describes it's organization.
203 class DIE : public FoldingSetNode {
205 /// Abbrev - Buffer for constructing abbreviation.
209 /// Offset - Offset in debug info section.
213 /// Size - Size of instance + children.
219 std::vector<DIE *> Children;
221 /// Attributes values.
223 SmallVector<DIEValue*, 32> Values;
226 explicit DIE(unsigned Tag)
227 : Abbrev(Tag, DW_CHILDREN_no)
236 DIEAbbrev &getAbbrev() { return Abbrev; }
237 unsigned getAbbrevNumber() const {
238 return Abbrev.getNumber();
240 unsigned getTag() const { return Abbrev.getTag(); }
241 unsigned getOffset() const { return Offset; }
242 unsigned getSize() const { return Size; }
243 const std::vector<DIE *> &getChildren() const { return Children; }
244 SmallVector<DIEValue*, 32> &getValues() { return Values; }
245 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
246 void setOffset(unsigned O) { Offset = O; }
247 void setSize(unsigned S) { Size = S; }
249 /// AddValue - Add a value and attributes to a DIE.
251 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
252 Abbrev.AddAttribute(Attribute, Form);
253 Values.push_back(Value);
256 /// SiblingOffset - Return the offset of the debug information entry's
258 unsigned SiblingOffset() const { return Offset + Size; }
260 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
262 void AddSiblingOffset();
264 /// AddChild - Add a child to the DIE.
266 void AddChild(DIE *Child) {
267 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
268 Children.push_back(Child);
271 /// Detach - Detaches objects connected to it after copying.
277 /// Profile - Used to gather unique data for the value folding set.
279 void Profile(FoldingSetNodeID &ID) ;
282 void print(std::ostream *O, unsigned IncIndent = 0) {
283 if (O) print(*O, IncIndent);
285 void print(std::ostream &O, unsigned IncIndent = 0);
290 //===----------------------------------------------------------------------===//
291 /// DIEValue - A debug information entry value.
293 class DIEValue : public FoldingSetNode {
306 /// Type - Type of data stored in the value.
310 explicit DIEValue(unsigned T)
313 virtual ~DIEValue() {}
316 unsigned getType() const { return Type; }
318 // Implement isa/cast/dyncast.
319 static bool classof(const DIEValue *) { return true; }
321 /// EmitValue - Emit value via the Dwarf writer.
323 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
325 /// SizeOf - Return the size of a value in bytes.
327 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
329 /// Profile - Used to gather unique data for the value folding set.
331 virtual void Profile(FoldingSetNodeID &ID) = 0;
334 void print(std::ostream *O) {
337 virtual void print(std::ostream &O) = 0;
342 //===----------------------------------------------------------------------===//
343 /// DWInteger - An integer value DIE.
345 class DIEInteger : public DIEValue {
350 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
352 // Implement isa/cast/dyncast.
353 static bool classof(const DIEInteger *) { return true; }
354 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
356 /// BestForm - Choose the best form for integer.
358 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
360 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
361 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
362 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
364 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
365 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
366 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
368 return DW_FORM_data8;
371 /// EmitValue - Emit integer of appropriate size.
373 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
375 /// SizeOf - Determine size of integer value in bytes.
377 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
379 /// Profile - Used to gather unique data for the value folding set.
381 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
382 ID.AddInteger(isInteger);
383 ID.AddInteger(Integer);
385 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
388 virtual void print(std::ostream &O) {
389 O << "Int: " << (int64_t)Integer
390 << " 0x" << std::hex << Integer << std::dec;
395 //===----------------------------------------------------------------------===//
396 /// DIEString - A string value DIE.
398 class DIEString : public DIEValue {
400 const std::string String;
402 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
404 // Implement isa/cast/dyncast.
405 static bool classof(const DIEString *) { return true; }
406 static bool classof(const DIEValue *S) { return S->Type == isString; }
408 /// EmitValue - Emit string value.
410 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
412 /// SizeOf - Determine size of string value in bytes.
414 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
415 return String.size() + sizeof(char); // sizeof('\0');
418 /// Profile - Used to gather unique data for the value folding set.
420 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
421 ID.AddInteger(isString);
422 ID.AddString(String);
424 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
427 virtual void print(std::ostream &O) {
428 O << "Str: \"" << String << "\"";
433 //===----------------------------------------------------------------------===//
434 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
436 class DIEDwarfLabel : public DIEValue {
441 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
443 // Implement isa/cast/dyncast.
444 static bool classof(const DIEDwarfLabel *) { return true; }
445 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
447 /// EmitValue - Emit label value.
449 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
451 /// SizeOf - Determine size of label value in bytes.
453 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
455 /// Profile - Used to gather unique data for the value folding set.
457 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
458 ID.AddInteger(isLabel);
461 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
464 virtual void print(std::ostream &O) {
472 //===----------------------------------------------------------------------===//
473 /// DIEObjectLabel - A label to an object in code or data.
475 class DIEObjectLabel : public DIEValue {
477 const std::string Label;
479 explicit DIEObjectLabel(const std::string &L)
480 : DIEValue(isAsIsLabel), Label(L) {}
482 // Implement isa/cast/dyncast.
483 static bool classof(const DIEObjectLabel *) { return true; }
484 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
486 /// EmitValue - Emit label value.
488 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
490 /// SizeOf - Determine size of label value in bytes.
492 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
494 /// Profile - Used to gather unique data for the value folding set.
496 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
497 ID.AddInteger(isAsIsLabel);
500 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
503 virtual void print(std::ostream &O) {
504 O << "Obj: " << Label;
509 //===----------------------------------------------------------------------===//
510 /// DIESectionOffset - A section offset DIE.
512 class DIESectionOffset : public DIEValue {
515 const DWLabel Section;
519 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
520 bool isEH = false, bool useSet = true)
521 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
522 IsEH(isEH), UseSet(useSet) {}
524 // Implement isa/cast/dyncast.
525 static bool classof(const DIESectionOffset *) { return true; }
526 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
528 /// EmitValue - Emit section offset.
530 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
532 /// SizeOf - Determine size of section offset value in bytes.
534 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
536 /// Profile - Used to gather unique data for the value folding set.
538 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
539 const DWLabel &Section) {
540 ID.AddInteger(isSectionOffset);
543 // IsEH and UseSet are specific to the Label/Section that we will emit
544 // the offset for; so Label/Section are enough for uniqueness.
546 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
549 virtual void print(std::ostream &O) {
554 O << "-" << IsEH << "-" << UseSet;
559 //===----------------------------------------------------------------------===//
560 /// DIEDelta - A simple label difference DIE.
562 class DIEDelta : public DIEValue {
564 const DWLabel LabelHi;
565 const DWLabel LabelLo;
567 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
568 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
570 // Implement isa/cast/dyncast.
571 static bool classof(const DIEDelta *) { return true; }
572 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
574 /// EmitValue - Emit delta value.
576 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
578 /// SizeOf - Determine size of delta value in bytes.
580 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
582 /// Profile - Used to gather unique data for the value folding set.
584 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
585 const DWLabel &LabelLo) {
586 ID.AddInteger(isDelta);
590 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
593 virtual void print(std::ostream &O) {
602 //===----------------------------------------------------------------------===//
603 /// DIEntry - A pointer to another debug information entry. An instance of this
604 /// class can also be used as a proxy for a debug information entry not yet
605 /// defined (ie. types.)
606 class DIEntry : public DIEValue {
610 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
612 // Implement isa/cast/dyncast.
613 static bool classof(const DIEntry *) { return true; }
614 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
616 /// EmitValue - Emit debug information entry offset.
618 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
620 /// SizeOf - Determine size of debug information entry in bytes.
622 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
623 return sizeof(int32_t);
626 /// Profile - Used to gather unique data for the value folding set.
628 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
629 ID.AddInteger(isEntry);
630 ID.AddPointer(Entry);
632 virtual void Profile(FoldingSetNodeID &ID) {
633 ID.AddInteger(isEntry);
636 ID.AddPointer(Entry);
643 virtual void print(std::ostream &O) {
644 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
649 //===----------------------------------------------------------------------===//
650 /// DIEBlock - A block of values. Primarily used for location expressions.
652 class DIEBlock : public DIEValue, public DIE {
654 unsigned Size; // Size in bytes excluding size header.
664 // Implement isa/cast/dyncast.
665 static bool classof(const DIEBlock *) { return true; }
666 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
668 /// ComputeSize - calculate the size of the block.
670 unsigned ComputeSize(DwarfDebug &DD);
672 /// BestForm - Choose the best form for data.
674 unsigned BestForm() const {
675 if ((unsigned char)Size == Size) return DW_FORM_block1;
676 if ((unsigned short)Size == Size) return DW_FORM_block2;
677 if ((unsigned int)Size == Size) return DW_FORM_block4;
678 return DW_FORM_block;
681 /// EmitValue - Emit block data.
683 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
685 /// SizeOf - Determine size of block data in bytes.
687 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
690 /// Profile - Used to gather unique data for the value folding set.
692 virtual void Profile(FoldingSetNodeID &ID) {
693 ID.AddInteger(isBlock);
698 virtual void print(std::ostream &O) {
705 //===----------------------------------------------------------------------===//
706 /// CompileUnit - This dwarf writer support class manages information associate
707 /// with a source file.
710 /// Desc - Compile unit debug descriptor.
712 CompileUnitDesc *Desc;
714 /// ID - File identifier for source.
718 /// Die - Compile unit debug information entry.
722 /// DescToDieMap - Tracks the mapping of unit level debug informaton
723 /// descriptors to debug information entries.
724 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
726 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
727 /// descriptors to debug information entries using a DIEntry proxy.
728 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
730 /// Globals - A map of globally visible named entities for this unit.
732 std::map<std::string, DIE *> Globals;
734 /// DiesSet - Used to uniquely define dies within the compile unit.
736 FoldingSet<DIE> DiesSet;
738 /// Dies - List of all dies in the compile unit.
740 std::vector<DIE *> Dies;
743 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
750 , DiesSet(InitDiesSetSize)
757 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
762 CompileUnitDesc *getDesc() const { return Desc; }
763 unsigned getID() const { return ID; }
764 DIE* getDie() const { return Die; }
765 std::map<std::string, DIE *> &getGlobals() { return Globals; }
767 /// hasContent - Return true if this compile unit has something to write out.
769 bool hasContent() const {
770 return !Die->getChildren().empty();
773 /// AddGlobal - Add a new global entity to the compile unit.
775 void AddGlobal(const std::string &Name, DIE *Die) {
779 /// getDieMapSlotFor - Returns the debug information entry map slot for the
780 /// specified debug descriptor.
781 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
782 return DescToDieMap[DID];
785 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
786 /// specified debug descriptor.
787 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
788 return DescToDIEntryMap[DID];
791 /// AddDie - Adds or interns the DIE to the compile unit.
793 DIE *AddDie(DIE &Buffer) {
797 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
800 Die = new DIE(Buffer);
801 DiesSet.InsertNode(Die, Where);
802 this->Die->AddChild(Die);
810 //===----------------------------------------------------------------------===//
811 /// Dwarf - Emits general Dwarf directives.
817 //===--------------------------------------------------------------------===//
818 // Core attributes used by the Dwarf writer.
822 /// O - Stream to .s file.
826 /// Asm - Target of Dwarf emission.
830 /// TAI - Target Asm Printer.
831 const TargetAsmInfo *TAI;
833 /// TD - Target data.
834 const TargetData *TD;
836 /// RI - Register Information.
837 const TargetRegisterInfo *RI;
839 /// M - Current module.
843 /// MF - Current machine function.
847 /// MMI - Collected machine module information.
849 MachineModuleInfo *MMI;
851 /// SubprogramCount - The running count of functions being compiled.
853 unsigned SubprogramCount;
855 /// Flavor - A unique string indicating what dwarf producer this is, used to
857 const char * const Flavor;
860 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
865 , TD(Asm->TM.getTargetData())
866 , RI(Asm->TM.getRegisterInfo())
878 //===--------------------------------------------------------------------===//
881 AsmPrinter *getAsm() const { return Asm; }
882 MachineModuleInfo *getMMI() const { return MMI; }
883 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
884 const TargetData *getTargetData() const { return TD; }
886 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
888 if (isInSection && TAI->getDwarfSectionOffsetDirective())
889 O << TAI->getDwarfSectionOffsetDirective();
890 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
891 O << TAI->getData32bitsDirective();
893 O << TAI->getData64bitsDirective();
896 /// PrintLabelName - Print label name in form used by Dwarf writer.
898 void PrintLabelName(DWLabel Label) const {
899 PrintLabelName(Label.Tag, Label.Number);
901 void PrintLabelName(const char *Tag, unsigned Number) const {
902 O << TAI->getPrivateGlobalPrefix() << Tag;
903 if (Number) O << Number;
906 void PrintLabelName(const char *Tag, unsigned Number,
907 const char *Suffix) const {
908 O << TAI->getPrivateGlobalPrefix() << Tag;
909 if (Number) O << Number;
913 /// EmitLabel - Emit location label for internal use by Dwarf.
915 void EmitLabel(DWLabel Label) const {
916 EmitLabel(Label.Tag, Label.Number);
918 void EmitLabel(const char *Tag, unsigned Number) const {
919 PrintLabelName(Tag, Number);
923 /// EmitReference - Emit a reference to a label.
925 void EmitReference(DWLabel Label, bool IsPCRelative = false,
926 bool Force32Bit = false) const {
927 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
929 void EmitReference(const char *Tag, unsigned Number,
930 bool IsPCRelative = false, bool Force32Bit = false) const {
931 PrintRelDirective(Force32Bit);
932 PrintLabelName(Tag, Number);
934 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
936 void EmitReference(const std::string &Name, bool IsPCRelative = false,
937 bool Force32Bit = false) const {
938 PrintRelDirective(Force32Bit);
942 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
945 /// EmitDifference - Emit the difference between two labels. Some
946 /// assemblers do not behave with absolute expressions with data directives,
947 /// so there is an option (needsSet) to use an intermediary set expression.
948 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
949 bool IsSmall = false) {
950 EmitDifference(LabelHi.Tag, LabelHi.Number,
951 LabelLo.Tag, LabelLo.Number,
954 void EmitDifference(const char *TagHi, unsigned NumberHi,
955 const char *TagLo, unsigned NumberLo,
956 bool IsSmall = false) {
957 if (TAI->needsSet()) {
959 PrintLabelName("set", SetCounter, Flavor);
961 PrintLabelName(TagHi, NumberHi);
963 PrintLabelName(TagLo, NumberLo);
966 PrintRelDirective(IsSmall);
967 PrintLabelName("set", SetCounter, Flavor);
970 PrintRelDirective(IsSmall);
972 PrintLabelName(TagHi, NumberHi);
974 PrintLabelName(TagLo, NumberLo);
978 void EmitSectionOffset(const char* Label, const char* Section,
979 unsigned LabelNumber, unsigned SectionNumber,
980 bool IsSmall = false, bool isEH = false,
981 bool useSet = true) {
982 bool printAbsolute = false;
984 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
986 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
988 if (TAI->needsSet() && useSet) {
990 PrintLabelName("set", SetCounter, Flavor);
992 PrintLabelName(Label, LabelNumber);
994 if (!printAbsolute) {
996 PrintLabelName(Section, SectionNumber);
1000 PrintRelDirective(IsSmall);
1002 PrintLabelName("set", SetCounter, Flavor);
1005 PrintRelDirective(IsSmall, true);
1007 PrintLabelName(Label, LabelNumber);
1009 if (!printAbsolute) {
1011 PrintLabelName(Section, SectionNumber);
1016 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1018 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1019 const std::vector<MachineMove> &Moves, bool isEH) {
1021 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1022 TargetFrameInfo::StackGrowsUp ?
1023 TD->getPointerSize() : -TD->getPointerSize();
1024 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1026 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1027 const MachineMove &Move = Moves[i];
1028 unsigned LabelID = Move.getLabelID();
1031 LabelID = MMI->MappedLabel(LabelID);
1033 // Throw out move if the label is invalid.
1034 if (!LabelID) continue;
1037 const MachineLocation &Dst = Move.getDestination();
1038 const MachineLocation &Src = Move.getSource();
1040 // Advance row if new location.
1041 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1042 Asm->EmitInt8(DW_CFA_advance_loc4);
1043 Asm->EOL("DW_CFA_advance_loc4");
1044 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1047 BaseLabelID = LabelID;
1048 BaseLabel = "label";
1052 // If advancing cfa.
1053 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1054 if (!Src.isRegister()) {
1055 if (Src.getRegister() == MachineLocation::VirtualFP) {
1056 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1057 Asm->EOL("DW_CFA_def_cfa_offset");
1059 Asm->EmitInt8(DW_CFA_def_cfa);
1060 Asm->EOL("DW_CFA_def_cfa");
1061 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister(), isEH));
1062 Asm->EOL("Register");
1065 int Offset = -Src.getOffset();
1067 Asm->EmitULEB128Bytes(Offset);
1070 assert(0 && "Machine move no supported yet.");
1072 } else if (Src.isRegister() &&
1073 Src.getRegister() == MachineLocation::VirtualFP) {
1074 if (Dst.isRegister()) {
1075 Asm->EmitInt8(DW_CFA_def_cfa_register);
1076 Asm->EOL("DW_CFA_def_cfa_register");
1077 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister(), isEH));
1078 Asm->EOL("Register");
1080 assert(0 && "Machine move no supported yet.");
1083 unsigned Reg = RI->getDwarfRegNum(Src.getRegister(), isEH);
1084 int Offset = Dst.getOffset() / stackGrowth;
1087 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1088 Asm->EOL("DW_CFA_offset_extended_sf");
1089 Asm->EmitULEB128Bytes(Reg);
1091 Asm->EmitSLEB128Bytes(Offset);
1093 } else if (Reg < 64) {
1094 Asm->EmitInt8(DW_CFA_offset + Reg);
1095 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1096 Asm->EmitULEB128Bytes(Offset);
1099 Asm->EmitInt8(DW_CFA_offset_extended);
1100 Asm->EOL("DW_CFA_offset_extended");
1101 Asm->EmitULEB128Bytes(Reg);
1103 Asm->EmitULEB128Bytes(Offset);
1112 //===----------------------------------------------------------------------===//
1113 /// DwarfDebug - Emits Dwarf debug directives.
1115 class DwarfDebug : public Dwarf {
1118 //===--------------------------------------------------------------------===//
1119 // Attributes used to construct specific Dwarf sections.
1122 /// CompileUnits - All the compile units involved in this build. The index
1123 /// of each entry in this vector corresponds to the sources in MMI.
1124 std::vector<CompileUnit *> CompileUnits;
1126 /// AbbreviationsSet - Used to uniquely define abbreviations.
1128 FoldingSet<DIEAbbrev> AbbreviationsSet;
1130 /// Abbreviations - A list of all the unique abbreviations in use.
1132 std::vector<DIEAbbrev *> Abbreviations;
1134 /// ValuesSet - Used to uniquely define values.
1136 FoldingSet<DIEValue> ValuesSet;
1138 /// Values - A list of all the unique values in use.
1140 std::vector<DIEValue *> Values;
1142 /// StringPool - A UniqueVector of strings used by indirect references.
1144 UniqueVector<std::string> StringPool;
1146 /// UnitMap - Map debug information descriptor to compile unit.
1148 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1150 /// SectionMap - Provides a unique id per text section.
1152 UniqueVector<std::string> SectionMap;
1154 /// SectionSourceLines - Tracks line numbers per text section.
1156 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1158 /// didInitial - Flag to indicate if initial emission has been done.
1162 /// shouldEmit - Flag to indicate if debug information should be emitted.
1166 struct FunctionDebugFrameInfo {
1168 std::vector<MachineMove> Moves;
1170 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1171 Number(Num), Moves(M) { }
1174 std::vector<FunctionDebugFrameInfo> DebugFrames;
1178 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1180 bool ShouldEmitDwarf() const { return shouldEmit; }
1182 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1184 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1185 // Profile the node so that we can make it unique.
1186 FoldingSetNodeID ID;
1189 // Check the set for priors.
1190 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1192 // If it's newly added.
1193 if (InSet == &Abbrev) {
1194 // Add to abbreviation list.
1195 Abbreviations.push_back(&Abbrev);
1196 // Assign the vector position + 1 as its number.
1197 Abbrev.setNumber(Abbreviations.size());
1199 // Assign existing abbreviation number.
1200 Abbrev.setNumber(InSet->getNumber());
1204 /// NewString - Add a string to the constant pool and returns a label.
1206 DWLabel NewString(const std::string &String) {
1207 unsigned StringID = StringPool.insert(String);
1208 return DWLabel("string", StringID);
1211 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1213 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1217 FoldingSetNodeID ID;
1218 DIEntry::Profile(ID, Entry);
1220 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1222 if (Value) return Value;
1224 Value = new DIEntry(Entry);
1225 ValuesSet.InsertNode(Value, Where);
1227 Value = new DIEntry(Entry);
1230 Values.push_back(Value);
1234 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1236 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1237 Value->Entry = Entry;
1238 // Add to values set if not already there. If it is, we merely have a
1239 // duplicate in the values list (no harm.)
1240 ValuesSet.GetOrInsertNode(Value);
1243 /// AddUInt - Add an unsigned integer attribute data and value.
1245 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1246 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1248 FoldingSetNodeID ID;
1249 DIEInteger::Profile(ID, Integer);
1251 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1253 Value = new DIEInteger(Integer);
1254 ValuesSet.InsertNode(Value, Where);
1255 Values.push_back(Value);
1258 Die->AddValue(Attribute, Form, Value);
1261 /// AddSInt - Add an signed integer attribute data and value.
1263 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1264 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1266 FoldingSetNodeID ID;
1267 DIEInteger::Profile(ID, (uint64_t)Integer);
1269 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1271 Value = new DIEInteger(Integer);
1272 ValuesSet.InsertNode(Value, Where);
1273 Values.push_back(Value);
1276 Die->AddValue(Attribute, Form, Value);
1279 /// AddString - Add a std::string attribute data and value.
1281 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1282 const std::string &String) {
1283 FoldingSetNodeID ID;
1284 DIEString::Profile(ID, String);
1286 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1288 Value = new DIEString(String);
1289 ValuesSet.InsertNode(Value, Where);
1290 Values.push_back(Value);
1293 Die->AddValue(Attribute, Form, Value);
1296 /// AddLabel - Add a Dwarf label attribute data and value.
1298 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1299 const DWLabel &Label) {
1300 FoldingSetNodeID ID;
1301 DIEDwarfLabel::Profile(ID, Label);
1303 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1305 Value = new DIEDwarfLabel(Label);
1306 ValuesSet.InsertNode(Value, Where);
1307 Values.push_back(Value);
1310 Die->AddValue(Attribute, Form, Value);
1313 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1315 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1316 const std::string &Label) {
1317 FoldingSetNodeID ID;
1318 DIEObjectLabel::Profile(ID, Label);
1320 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1322 Value = new DIEObjectLabel(Label);
1323 ValuesSet.InsertNode(Value, Where);
1324 Values.push_back(Value);
1327 Die->AddValue(Attribute, Form, Value);
1330 /// AddSectionOffset - Add a section offset label attribute data and value.
1332 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1333 const DWLabel &Label, const DWLabel &Section,
1334 bool isEH = false, bool useSet = true) {
1335 FoldingSetNodeID ID;
1336 DIESectionOffset::Profile(ID, Label, Section);
1338 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1340 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1341 ValuesSet.InsertNode(Value, Where);
1342 Values.push_back(Value);
1345 Die->AddValue(Attribute, Form, Value);
1348 /// AddDelta - Add a label delta attribute data and value.
1350 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1351 const DWLabel &Hi, const DWLabel &Lo) {
1352 FoldingSetNodeID ID;
1353 DIEDelta::Profile(ID, Hi, Lo);
1355 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1357 Value = new DIEDelta(Hi, Lo);
1358 ValuesSet.InsertNode(Value, Where);
1359 Values.push_back(Value);
1362 Die->AddValue(Attribute, Form, Value);
1365 /// AddDIEntry - Add a DIE attribute data and value.
1367 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1368 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1371 /// AddBlock - Add block data.
1373 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1374 Block->ComputeSize(*this);
1375 FoldingSetNodeID ID;
1378 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1381 ValuesSet.InsertNode(Value, Where);
1382 Values.push_back(Value);
1384 // Already exists, reuse the previous one.
1386 Block = cast<DIEBlock>(Value);
1389 Die->AddValue(Attribute, Block->BestForm(), Value);
1394 /// AddSourceLine - Add location information to specified debug information
1396 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1398 CompileUnit *FileUnit = FindCompileUnit(File);
1399 unsigned FileID = FileUnit->getID();
1400 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1401 AddUInt(Die, DW_AT_decl_line, 0, Line);
1405 /// AddAddress - Add an address attribute to a die based on the location
1407 void AddAddress(DIE *Die, unsigned Attribute,
1408 const MachineLocation &Location) {
1409 unsigned Reg = RI->getDwarfRegNum(Location.getRegister(), false);
1410 DIEBlock *Block = new DIEBlock();
1412 if (Location.isRegister()) {
1414 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1416 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1417 AddUInt(Block, 0, DW_FORM_udata, Reg);
1421 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1423 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1424 AddUInt(Block, 0, DW_FORM_udata, Reg);
1426 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1429 AddBlock(Die, Attribute, 0, Block);
1432 /// AddBasicType - Add a new basic type attribute to the specified entity.
1434 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1435 const std::string &Name,
1436 unsigned Encoding, unsigned Size) {
1437 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1438 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1441 /// ConstructBasicType - Construct a new basic type.
1443 DIE *ConstructBasicType(CompileUnit *Unit,
1444 const std::string &Name,
1445 unsigned Encoding, unsigned Size) {
1446 DIE Buffer(DW_TAG_base_type);
1447 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1448 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1449 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1450 return Unit->AddDie(Buffer);
1453 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1455 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1456 DIE *Die = ConstructPointerType(Unit, Name);
1457 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1460 /// ConstructPointerType - Construct a new pointer type.
1462 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1463 DIE Buffer(DW_TAG_pointer_type);
1464 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1465 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1466 return Unit->AddDie(Buffer);
1469 /// AddType - Add a new type attribute to the specified entity.
1471 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1473 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1475 // Check for pre-existence.
1476 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1478 // If it exists then use the existing value.
1480 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1484 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1485 // FIXME - Not sure why programs and variables are coming through here.
1486 // Short cut for handling subprogram types (not really a TyDesc.)
1487 AddPointerType(Entity, Unit, SubprogramTy->getName());
1488 } else if (GlobalVariableDesc *GlobalTy =
1489 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1490 // FIXME - Not sure why programs and variables are coming through here.
1491 // Short cut for handling global variable types (not really a TyDesc.)
1492 AddPointerType(Entity, Unit, GlobalTy->getName());
1495 Slot = NewDIEntry();
1498 DIE Buffer(DW_TAG_base_type);
1499 ConstructType(Buffer, TyDesc, Unit);
1501 // Add debug information entry to entity and unit.
1502 DIE *Die = Unit->AddDie(Buffer);
1503 SetDIEntry(Slot, Die);
1504 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1509 /// ConstructType - Adds all the required attributes to the type.
1511 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1512 // Get core information.
1513 const std::string &Name = TyDesc->getName();
1514 uint64_t Size = TyDesc->getSize() >> 3;
1516 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1517 // Fundamental types like int, float, bool
1518 Buffer.setTag(DW_TAG_base_type);
1519 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1520 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1522 unsigned Tag = DerivedTy->getTag();
1523 // FIXME - Workaround for templates.
1524 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1525 // Pointers, typedefs et al.
1527 // Map to main type, void will not have a type.
1528 if (TypeDesc *FromTy = DerivedTy->getFromType())
1529 AddType(&Buffer, FromTy, Unit);
1530 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1532 unsigned Tag = CompTy->getTag();
1534 // Set tag accordingly.
1535 if (Tag == DW_TAG_vector_type)
1536 Buffer.setTag(DW_TAG_array_type);
1540 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1543 case DW_TAG_vector_type:
1544 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1546 case DW_TAG_array_type: {
1547 // Add element type.
1548 if (TypeDesc *FromTy = CompTy->getFromType())
1549 AddType(&Buffer, FromTy, Unit);
1551 // Don't emit size attribute.
1554 // Construct an anonymous type for index type.
1555 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1558 // Add subranges to array type.
1559 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1560 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1561 int64_t Lo = SRD->getLo();
1562 int64_t Hi = SRD->getHi();
1563 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1565 // If a range is available.
1567 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1568 // Only add low if non-zero.
1569 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1570 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1573 Buffer.AddChild(Subrange);
1577 case DW_TAG_structure_type:
1578 case DW_TAG_union_type: {
1579 // Add elements to structure type.
1580 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1581 DebugInfoDesc *Element = Elements[i];
1583 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1584 // Add field or base class.
1586 unsigned Tag = MemberDesc->getTag();
1588 // Extract the basic information.
1589 const std::string &Name = MemberDesc->getName();
1590 uint64_t Size = MemberDesc->getSize();
1591 uint64_t Align = MemberDesc->getAlign();
1592 uint64_t Offset = MemberDesc->getOffset();
1594 // Construct member debug information entry.
1595 DIE *Member = new DIE(Tag);
1597 // Add name if not "".
1599 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1600 // Add location if available.
1601 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1603 // Most of the time the field info is the same as the members.
1604 uint64_t FieldSize = Size;
1605 uint64_t FieldAlign = Align;
1606 uint64_t FieldOffset = Offset;
1608 // Set the member type.
1609 TypeDesc *FromTy = MemberDesc->getFromType();
1610 AddType(Member, FromTy, Unit);
1612 // Walk up typedefs until a real size is found.
1614 if (FromTy->getTag() != DW_TAG_typedef) {
1615 FieldSize = FromTy->getSize();
1616 FieldAlign = FromTy->getSize();
1620 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1623 // Unless we have a bit field.
1624 if (Tag == DW_TAG_member && FieldSize != Size) {
1625 // Construct the alignment mask.
1626 uint64_t AlignMask = ~(FieldAlign - 1);
1627 // Determine the high bit + 1 of the declared size.
1628 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1629 // Work backwards to determine the base offset of the field.
1630 FieldOffset = HiMark - FieldSize;
1631 // Now normalize offset to the field.
1632 Offset -= FieldOffset;
1634 // Maybe we need to work from the other end.
1635 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1637 // Add size and offset.
1638 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1639 AddUInt(Member, DW_AT_bit_size, 0, Size);
1640 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1643 // Add computation for offset.
1644 DIEBlock *Block = new DIEBlock();
1645 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1646 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1647 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1649 // Add accessibility (public default unless is base class.
1650 if (MemberDesc->isProtected()) {
1651 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1652 } else if (MemberDesc->isPrivate()) {
1653 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1654 } else if (Tag == DW_TAG_inheritance) {
1655 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1658 Buffer.AddChild(Member);
1659 } else if (GlobalVariableDesc *StaticDesc =
1660 dyn_cast<GlobalVariableDesc>(Element)) {
1661 // Add static member.
1663 // Construct member debug information entry.
1664 DIE *Static = new DIE(DW_TAG_variable);
1666 // Add name and mangled name.
1667 const std::string &Name = StaticDesc->getName();
1668 const std::string &LinkageName = StaticDesc->getLinkageName();
1669 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1670 if (!LinkageName.empty()) {
1671 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1676 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1679 if (TypeDesc *StaticTy = StaticDesc->getType())
1680 AddType(Static, StaticTy, Unit);
1683 if (!StaticDesc->isStatic())
1684 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1685 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1687 Buffer.AddChild(Static);
1688 } else if (SubprogramDesc *MethodDesc =
1689 dyn_cast<SubprogramDesc>(Element)) {
1690 // Add member function.
1692 // Construct member debug information entry.
1693 DIE *Method = new DIE(DW_TAG_subprogram);
1695 // Add name and mangled name.
1696 const std::string &Name = MethodDesc->getName();
1697 const std::string &LinkageName = MethodDesc->getLinkageName();
1699 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1700 bool IsCTor = TyDesc->getName() == Name;
1702 if (!LinkageName.empty()) {
1703 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1708 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1711 if (CompositeTypeDesc *MethodTy =
1712 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1713 // Get argument information.
1714 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1719 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1723 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1724 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1725 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1726 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1727 Method->AddChild(Arg);
1732 if (!MethodDesc->isStatic())
1733 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1734 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1736 Buffer.AddChild(Method);
1741 case DW_TAG_enumeration_type: {
1742 // Add enumerators to enumeration type.
1743 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1744 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1745 const std::string &Name = ED->getName();
1746 int64_t Value = ED->getValue();
1747 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1748 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1749 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1750 Buffer.AddChild(Enumerator);
1755 case DW_TAG_subroutine_type: {
1756 // Add prototype flag.
1757 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1759 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1762 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1763 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1764 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1765 Buffer.AddChild(Arg);
1774 // Add size if non-zero (derived types don't have a size.)
1775 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1776 // Add name if not anonymous or intermediate type.
1777 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1778 // Add source line info if available.
1779 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1782 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1784 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1785 // Construct debug information entry.
1786 DIE *Die = new DIE(DW_TAG_compile_unit);
1787 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
1788 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
1789 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1790 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1791 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1792 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1794 // Construct compile unit.
1795 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1797 // Add Unit to compile unit map.
1798 DescToUnitMap[UnitDesc] = Unit;
1803 /// GetBaseCompileUnit - Get the main compile unit.
1805 CompileUnit *GetBaseCompileUnit() const {
1806 CompileUnit *Unit = CompileUnits[0];
1807 assert(Unit && "Missing compile unit.");
1811 /// FindCompileUnit - Get the compile unit for the given descriptor.
1813 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1814 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1815 assert(Unit && "Missing compile unit.");
1819 /// NewGlobalVariable - Add a new global variable DIE.
1821 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1822 // Get the compile unit context.
1823 CompileUnitDesc *UnitDesc =
1824 static_cast<CompileUnitDesc *>(GVD->getContext());
1825 CompileUnit *Unit = GetBaseCompileUnit();
1827 // Check for pre-existence.
1828 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1829 if (Slot) return Slot;
1831 // Get the global variable itself.
1832 GlobalVariable *GV = GVD->getGlobalVariable();
1834 const std::string &Name = GVD->getName();
1835 const std::string &FullName = GVD->getFullName();
1836 const std::string &LinkageName = GVD->getLinkageName();
1837 // Create the global's variable DIE.
1838 DIE *VariableDie = new DIE(DW_TAG_variable);
1839 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1840 if (!LinkageName.empty()) {
1841 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1844 AddType(VariableDie, GVD->getType(), Unit);
1845 if (!GVD->isStatic())
1846 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1848 // Add source line info if available.
1849 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1852 DIEBlock *Block = new DIEBlock();
1853 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1854 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1855 AddBlock(VariableDie, DW_AT_location, 0, Block);
1860 // Add to context owner.
1861 Unit->getDie()->AddChild(VariableDie);
1863 // Expose as global.
1864 // FIXME - need to check external flag.
1865 Unit->AddGlobal(FullName, VariableDie);
1870 /// NewSubprogram - Add a new subprogram DIE.
1872 DIE *NewSubprogram(SubprogramDesc *SPD) {
1873 // Get the compile unit context.
1874 CompileUnitDesc *UnitDesc =
1875 static_cast<CompileUnitDesc *>(SPD->getContext());
1876 CompileUnit *Unit = GetBaseCompileUnit();
1878 // Check for pre-existence.
1879 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1880 if (Slot) return Slot;
1882 // Gather the details (simplify add attribute code.)
1883 const std::string &Name = SPD->getName();
1884 const std::string &FullName = SPD->getFullName();
1885 const std::string &LinkageName = SPD->getLinkageName();
1887 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1888 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1889 if (!LinkageName.empty()) {
1890 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1893 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1894 if (!SPD->isStatic())
1895 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1896 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1898 // Add source line info if available.
1899 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1902 Slot = SubprogramDie;
1904 // Add to context owner.
1905 Unit->getDie()->AddChild(SubprogramDie);
1907 // Expose as global.
1908 Unit->AddGlobal(FullName, SubprogramDie);
1910 return SubprogramDie;
1913 /// NewScopeVariable - Create a new scope variable.
1915 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1916 // Get the descriptor.
1917 VariableDesc *VD = DV->getDesc();
1919 // Translate tag to proper Dwarf tag. The result variable is dropped for
1922 switch (VD->getTag()) {
1923 case DW_TAG_return_variable: return NULL;
1924 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1925 case DW_TAG_auto_variable: // fall thru
1926 default: Tag = DW_TAG_variable; break;
1929 // Define variable debug information entry.
1930 DIE *VariableDie = new DIE(Tag);
1931 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1933 // Add source line info if available.
1934 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1936 // Add variable type.
1937 AddType(VariableDie, VD->getType(), Unit);
1939 // Add variable address.
1940 MachineLocation Location;
1941 Location.set(RI->getFrameRegister(*MF),
1942 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1943 AddAddress(VariableDie, DW_AT_location, Location);
1948 /// ConstructScope - Construct the components of a scope.
1950 void ConstructScope(DebugScope *ParentScope,
1951 unsigned ParentStartID, unsigned ParentEndID,
1952 DIE *ParentDie, CompileUnit *Unit) {
1953 // Add variables to scope.
1954 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1955 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1956 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1957 if (VariableDie) ParentDie->AddChild(VariableDie);
1960 // Add nested scopes.
1961 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1962 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1963 // Define the Scope debug information entry.
1964 DebugScope *Scope = Scopes[j];
1965 // FIXME - Ignore inlined functions for the time being.
1966 if (!Scope->getParent()) continue;
1968 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1969 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1971 // Ignore empty scopes.
1972 if (StartID == EndID && StartID != 0) continue;
1973 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1975 if (StartID == ParentStartID && EndID == ParentEndID) {
1976 // Just add stuff to the parent scope.
1977 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1979 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1981 // Add the scope bounds.
1983 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1984 DWLabel("label", StartID));
1986 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1987 DWLabel("func_begin", SubprogramCount));
1990 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1991 DWLabel("label", EndID));
1993 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1994 DWLabel("func_end", SubprogramCount));
1997 // Add the scope contents.
1998 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1999 ParentDie->AddChild(ScopeDie);
2004 /// ConstructRootScope - Construct the scope for the subprogram.
2006 void ConstructRootScope(DebugScope *RootScope) {
2007 // Exit if there is no root scope.
2008 if (!RootScope) return;
2010 // Get the subprogram debug information entry.
2011 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2013 // Get the compile unit context.
2014 CompileUnit *Unit = GetBaseCompileUnit();
2016 // Get the subprogram die.
2017 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2018 assert(SPDie && "Missing subprogram descriptor");
2020 // Add the function bounds.
2021 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2022 DWLabel("func_begin", SubprogramCount));
2023 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2024 DWLabel("func_end", SubprogramCount));
2025 MachineLocation Location(RI->getFrameRegister(*MF));
2026 AddAddress(SPDie, DW_AT_frame_base, Location);
2028 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2031 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2032 /// tools to recognize the object file contains Dwarf information.
2033 void EmitInitial() {
2034 // Check to see if we already emitted intial headers.
2035 if (didInitial) return;
2038 // Dwarf sections base addresses.
2039 if (TAI->doesDwarfRequireFrameSection()) {
2040 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2041 EmitLabel("section_debug_frame", 0);
2043 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2044 EmitLabel("section_info", 0);
2045 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2046 EmitLabel("section_abbrev", 0);
2047 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2048 EmitLabel("section_aranges", 0);
2049 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2050 EmitLabel("section_macinfo", 0);
2051 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2052 EmitLabel("section_line", 0);
2053 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2054 EmitLabel("section_loc", 0);
2055 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2056 EmitLabel("section_pubnames", 0);
2057 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2058 EmitLabel("section_str", 0);
2059 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2060 EmitLabel("section_ranges", 0);
2062 Asm->SwitchToTextSection(TAI->getTextSection());
2063 EmitLabel("text_begin", 0);
2064 Asm->SwitchToDataSection(TAI->getDataSection());
2065 EmitLabel("data_begin", 0);
2068 /// EmitDIE - Recusively Emits a debug information entry.
2070 void EmitDIE(DIE *Die) {
2071 // Get the abbreviation for this DIE.
2072 unsigned AbbrevNumber = Die->getAbbrevNumber();
2073 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2077 // Emit the code (index) for the abbreviation.
2078 Asm->EmitULEB128Bytes(AbbrevNumber);
2079 Asm->EOL(std::string("Abbrev [" +
2080 utostr(AbbrevNumber) +
2081 "] 0x" + utohexstr(Die->getOffset()) +
2082 ":0x" + utohexstr(Die->getSize()) + " " +
2083 TagString(Abbrev->getTag())));
2085 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2086 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2088 // Emit the DIE attribute values.
2089 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2090 unsigned Attr = AbbrevData[i].getAttribute();
2091 unsigned Form = AbbrevData[i].getForm();
2092 assert(Form && "Too many attributes for DIE (check abbreviation)");
2095 case DW_AT_sibling: {
2096 Asm->EmitInt32(Die->SiblingOffset());
2100 // Emit an attribute using the defined form.
2101 Values[i]->EmitValue(*this, Form);
2106 Asm->EOL(AttributeString(Attr));
2109 // Emit the DIE children if any.
2110 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2111 const std::vector<DIE *> &Children = Die->getChildren();
2113 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2114 EmitDIE(Children[j]);
2117 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2121 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2123 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2124 // Get the children.
2125 const std::vector<DIE *> &Children = Die->getChildren();
2127 // If not last sibling and has children then add sibling offset attribute.
2128 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2130 // Record the abbreviation.
2131 AssignAbbrevNumber(Die->getAbbrev());
2133 // Get the abbreviation for this DIE.
2134 unsigned AbbrevNumber = Die->getAbbrevNumber();
2135 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2138 Die->setOffset(Offset);
2140 // Start the size with the size of abbreviation code.
2141 Offset += Asm->SizeULEB128(AbbrevNumber);
2143 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2144 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2146 // Size the DIE attribute values.
2147 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2148 // Size attribute value.
2149 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2152 // Size the DIE children if any.
2153 if (!Children.empty()) {
2154 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2155 "Children flag not set");
2157 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2158 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2161 // End of children marker.
2162 Offset += sizeof(int8_t);
2165 Die->setSize(Offset - Die->getOffset());
2169 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2171 void SizeAndOffsets() {
2172 // Process base compile unit.
2173 CompileUnit *Unit = GetBaseCompileUnit();
2174 // Compute size of compile unit header
2175 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2176 sizeof(int16_t) + // DWARF version number
2177 sizeof(int32_t) + // Offset Into Abbrev. Section
2178 sizeof(int8_t); // Pointer Size (in bytes)
2179 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2182 /// EmitDebugInfo - Emit the debug info section.
2184 void EmitDebugInfo() {
2185 // Start debug info section.
2186 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2188 CompileUnit *Unit = GetBaseCompileUnit();
2189 DIE *Die = Unit->getDie();
2190 // Emit the compile units header.
2191 EmitLabel("info_begin", Unit->getID());
2192 // Emit size of content not including length itself
2193 unsigned ContentSize = Die->getSize() +
2194 sizeof(int16_t) + // DWARF version number
2195 sizeof(int32_t) + // Offset Into Abbrev. Section
2196 sizeof(int8_t) + // Pointer Size (in bytes)
2197 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2199 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2200 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2201 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2202 Asm->EOL("Offset Into Abbrev. Section");
2203 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2206 // FIXME - extra padding for gdb bug.
2207 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2208 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2209 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2210 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2211 EmitLabel("info_end", Unit->getID());
2216 /// EmitAbbreviations - Emit the abbreviation section.
2218 void EmitAbbreviations() const {
2219 // Check to see if it is worth the effort.
2220 if (!Abbreviations.empty()) {
2221 // Start the debug abbrev section.
2222 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2224 EmitLabel("abbrev_begin", 0);
2226 // For each abbrevation.
2227 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2228 // Get abbreviation data
2229 const DIEAbbrev *Abbrev = Abbreviations[i];
2231 // Emit the abbrevations code (base 1 index.)
2232 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2233 Asm->EOL("Abbreviation Code");
2235 // Emit the abbreviations data.
2236 Abbrev->Emit(*this);
2241 // Mark end of abbreviations.
2242 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2244 EmitLabel("abbrev_end", 0);
2250 /// EmitDebugLines - Emit source line information.
2252 void EmitDebugLines() {
2253 // If there are no lines to emit (such as when we're using .loc directives
2254 // to emit .debug_line information) don't emit a .debug_line header.
2255 if (SectionSourceLines.empty())
2258 // Minimum line delta, thus ranging from -10..(255-10).
2259 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2260 // Maximum line delta, thus ranging from -10..(255-10).
2261 const int MaxLineDelta = 255 + MinLineDelta;
2263 // Start the dwarf line section.
2264 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2266 // Construct the section header.
2268 EmitDifference("line_end", 0, "line_begin", 0, true);
2269 Asm->EOL("Length of Source Line Info");
2270 EmitLabel("line_begin", 0);
2272 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2274 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2275 Asm->EOL("Prolog Length");
2276 EmitLabel("line_prolog_begin", 0);
2278 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2280 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2282 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2284 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2286 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2288 // Line number standard opcode encodings argument count
2289 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2290 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2291 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2292 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2293 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2294 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2295 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2296 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2297 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2299 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2300 const UniqueVector<SourceFileInfo>
2301 &SourceFiles = MMI->getSourceFiles();
2303 // Emit directories.
2304 for (unsigned DirectoryID = 1, NDID = Directories.size();
2305 DirectoryID <= NDID; ++DirectoryID) {
2306 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2308 Asm->EmitInt8(0); Asm->EOL("End of directories");
2311 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2312 SourceID <= NSID; ++SourceID) {
2313 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2314 Asm->EmitString(SourceFile.getName());
2316 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2317 Asm->EOL("Directory #");
2318 Asm->EmitULEB128Bytes(0);
2319 Asm->EOL("Mod date");
2320 Asm->EmitULEB128Bytes(0);
2321 Asm->EOL("File size");
2323 Asm->EmitInt8(0); Asm->EOL("End of files");
2325 EmitLabel("line_prolog_end", 0);
2327 // A sequence for each text section.
2328 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2329 // Isolate current sections line info.
2330 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2332 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2334 // Dwarf assumes we start with first line of first source file.
2335 unsigned Source = 1;
2338 // Construct rows of the address, source, line, column matrix.
2339 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2340 const SourceLineInfo &LineInfo = LineInfos[i];
2341 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2342 if (!LabelID) continue;
2344 unsigned SourceID = LineInfo.getSourceID();
2345 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2346 unsigned DirectoryID = SourceFile.getDirectoryID();
2347 Asm->EOL(Directories[DirectoryID]
2348 + SourceFile.getName()
2350 + utostr_32(LineInfo.getLine()));
2352 // Define the line address.
2353 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2354 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2355 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2356 EmitReference("label", LabelID); Asm->EOL("Location label");
2358 // If change of source, then switch to the new source.
2359 if (Source != LineInfo.getSourceID()) {
2360 Source = LineInfo.getSourceID();
2361 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2362 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2365 // If change of line.
2366 if (Line != LineInfo.getLine()) {
2367 // Determine offset.
2368 int Offset = LineInfo.getLine() - Line;
2369 int Delta = Offset - MinLineDelta;
2372 Line = LineInfo.getLine();
2374 // If delta is small enough and in range...
2375 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2376 // ... then use fast opcode.
2377 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2379 // ... otherwise use long hand.
2380 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2381 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2382 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2385 // Copy the previous row (different address or source)
2386 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2390 // Define last address of section.
2391 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2392 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2393 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2394 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2396 // Mark end of matrix.
2397 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2398 Asm->EmitULEB128Bytes(1); Asm->EOL();
2399 Asm->EmitInt8(1); Asm->EOL();
2402 EmitLabel("line_end", 0);
2407 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2409 void EmitCommonDebugFrame() {
2410 if (!TAI->doesDwarfRequireFrameSection())
2414 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2415 TargetFrameInfo::StackGrowsUp ?
2416 TD->getPointerSize() : -TD->getPointerSize();
2418 // Start the dwarf frame section.
2419 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2421 EmitLabel("debug_frame_common", 0);
2422 EmitDifference("debug_frame_common_end", 0,
2423 "debug_frame_common_begin", 0, true);
2424 Asm->EOL("Length of Common Information Entry");
2426 EmitLabel("debug_frame_common_begin", 0);
2427 Asm->EmitInt32((int)DW_CIE_ID);
2428 Asm->EOL("CIE Identifier Tag");
2429 Asm->EmitInt8(DW_CIE_VERSION);
2430 Asm->EOL("CIE Version");
2431 Asm->EmitString("");
2432 Asm->EOL("CIE Augmentation");
2433 Asm->EmitULEB128Bytes(1);
2434 Asm->EOL("CIE Code Alignment Factor");
2435 Asm->EmitSLEB128Bytes(stackGrowth);
2436 Asm->EOL("CIE Data Alignment Factor");
2437 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2438 Asm->EOL("CIE RA Column");
2440 std::vector<MachineMove> Moves;
2441 RI->getInitialFrameState(Moves);
2443 EmitFrameMoves(NULL, 0, Moves, false);
2445 Asm->EmitAlignment(2, 0, 0, false);
2446 EmitLabel("debug_frame_common_end", 0);
2451 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2453 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2454 if (!TAI->doesDwarfRequireFrameSection())
2457 // Start the dwarf frame section.
2458 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2460 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2461 "debug_frame_begin", DebugFrameInfo.Number, true);
2462 Asm->EOL("Length of Frame Information Entry");
2464 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2466 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2468 Asm->EOL("FDE CIE offset");
2470 EmitReference("func_begin", DebugFrameInfo.Number);
2471 Asm->EOL("FDE initial location");
2472 EmitDifference("func_end", DebugFrameInfo.Number,
2473 "func_begin", DebugFrameInfo.Number);
2474 Asm->EOL("FDE address range");
2476 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2478 Asm->EmitAlignment(2, 0, 0, false);
2479 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2484 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2486 void EmitDebugPubNames() {
2487 // Start the dwarf pubnames section.
2488 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2490 CompileUnit *Unit = GetBaseCompileUnit();
2492 EmitDifference("pubnames_end", Unit->getID(),
2493 "pubnames_begin", Unit->getID(), true);
2494 Asm->EOL("Length of Public Names Info");
2496 EmitLabel("pubnames_begin", Unit->getID());
2498 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2500 EmitSectionOffset("info_begin", "section_info",
2501 Unit->getID(), 0, true, false);
2502 Asm->EOL("Offset of Compilation Unit Info");
2504 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2505 Asm->EOL("Compilation Unit Length");
2507 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2509 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2512 const std::string &Name = GI->first;
2513 DIE * Entity = GI->second;
2515 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2516 Asm->EmitString(Name); Asm->EOL("External Name");
2519 Asm->EmitInt32(0); Asm->EOL("End Mark");
2520 EmitLabel("pubnames_end", Unit->getID());
2525 /// EmitDebugStr - Emit visible names into a debug str section.
2527 void EmitDebugStr() {
2528 // Check to see if it is worth the effort.
2529 if (!StringPool.empty()) {
2530 // Start the dwarf str section.
2531 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2533 // For each of strings in the string pool.
2534 for (unsigned StringID = 1, N = StringPool.size();
2535 StringID <= N; ++StringID) {
2536 // Emit a label for reference from debug information entries.
2537 EmitLabel("string", StringID);
2538 // Emit the string itself.
2539 const std::string &String = StringPool[StringID];
2540 Asm->EmitString(String); Asm->EOL();
2547 /// EmitDebugLoc - Emit visible names into a debug loc section.
2549 void EmitDebugLoc() {
2550 // Start the dwarf loc section.
2551 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2556 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2558 void EmitDebugARanges() {
2559 // Start the dwarf aranges section.
2560 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2564 CompileUnit *Unit = GetBaseCompileUnit();
2566 // Don't include size of length
2567 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2569 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2571 EmitReference("info_begin", Unit->getID());
2572 Asm->EOL("Offset of Compilation Unit Info");
2574 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2576 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2578 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2579 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2582 EmitReference("text_begin", 0); Asm->EOL("Address");
2583 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2585 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2586 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2592 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2594 void EmitDebugRanges() {
2595 // Start the dwarf ranges section.
2596 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2601 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2603 void EmitDebugMacInfo() {
2604 // Start the dwarf macinfo section.
2605 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2610 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2612 void ConstructCompileUnitDIEs() {
2613 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2615 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2616 unsigned ID = MMI->RecordSource(CUW[i]);
2617 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2618 CompileUnits.push_back(Unit);
2622 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2623 /// global variables.
2624 void ConstructGlobalDIEs() {
2625 std::vector<void*> GlobalVariables;
2626 GlobalVariableDesc GVD;
2627 MMI->getAnchoredDescriptors(*M, &GVD, GlobalVariables);
2629 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i)
2630 NewGlobalVariable((GlobalVariableDesc *)GlobalVariables[i]);
2633 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2635 void ConstructSubprogramDIEs() {
2636 std::vector<void*> Subprograms;
2638 MMI->getAnchoredDescriptors(*M, &SPD, Subprograms);
2640 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i)
2641 NewSubprogram((SubprogramDesc*)Subprograms[i]);
2645 //===--------------------------------------------------------------------===//
2646 // Main entry points.
2648 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2649 : Dwarf(OS, A, T, "dbg")
2651 , AbbreviationsSet(InitAbbreviationsSetSize)
2653 , ValuesSet(InitValuesSetSize)
2658 , SectionSourceLines()
2663 virtual ~DwarfDebug() {
2664 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2665 delete CompileUnits[i];
2666 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2670 /// SetModuleInfo - Set machine module information when it's known that pass
2671 /// manager has created it. Set by the target AsmPrinter.
2672 void SetModuleInfo(MachineModuleInfo *mmi) {
2673 // Make sure initial declarations are made.
2674 if (!MMI && mmi->hasDebugInfo()) {
2678 // Create all the compile unit DIEs.
2679 ConstructCompileUnitDIEs();
2681 // Create DIEs for each of the externally visible global variables.
2682 ConstructGlobalDIEs();
2684 // Create DIEs for each of the externally visible subprograms.
2685 ConstructSubprogramDIEs();
2687 // Prime section data.
2688 SectionMap.insert(TAI->getTextSection());
2690 // Print out .file directives to specify files for .loc directives. These
2691 // are printed out early so that they precede any .loc directives.
2692 if (TAI->hasDotLocAndDotFile()) {
2693 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2694 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2695 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2696 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2697 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2698 assert(AppendOk && "Could not append filename to directory!");
2699 Asm->EmitFile(i, FullPath.toString());
2704 // Emit initial sections
2709 /// BeginModule - Emit all Dwarf sections that should come prior to the
2711 void BeginModule(Module *M) {
2714 if (!ShouldEmitDwarf()) return;
2717 /// EndModule - Emit all Dwarf sections that should come after the content.
2720 if (!ShouldEmitDwarf()) return;
2722 // Standard sections final addresses.
2723 Asm->SwitchToTextSection(TAI->getTextSection());
2724 EmitLabel("text_end", 0);
2725 Asm->SwitchToDataSection(TAI->getDataSection());
2726 EmitLabel("data_end", 0);
2728 // End text sections.
2729 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2730 Asm->SwitchToTextSection(SectionMap[i].c_str());
2731 EmitLabel("section_end", i);
2734 // Emit common frame information.
2735 EmitCommonDebugFrame();
2737 // Emit function debug frame information
2738 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2739 E = DebugFrames.end(); I != E; ++I)
2740 EmitFunctionDebugFrame(*I);
2742 // Compute DIE offsets and sizes.
2745 // Emit all the DIEs into a debug info section
2748 // Corresponding abbreviations into a abbrev section.
2749 EmitAbbreviations();
2751 // Emit source line correspondence into a debug line section.
2754 // Emit info into a debug pubnames section.
2755 EmitDebugPubNames();
2757 // Emit info into a debug str section.
2760 // Emit info into a debug loc section.
2763 // Emit info into a debug aranges section.
2766 // Emit info into a debug ranges section.
2769 // Emit info into a debug macinfo section.
2773 /// BeginFunction - Gather pre-function debug information. Assumes being
2774 /// emitted immediately after the function entry point.
2775 void BeginFunction(MachineFunction *MF) {
2778 if (!ShouldEmitDwarf()) return;
2780 // Begin accumulating function debug information.
2781 MMI->BeginFunction(MF);
2783 // Assumes in correct section after the entry point.
2784 EmitLabel("func_begin", ++SubprogramCount);
2786 // Emit label for the implicitly defined dbg.stoppoint at the start of
2788 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2789 if (!LineInfos.empty()) {
2790 const SourceLineInfo &LineInfo = LineInfos[0];
2791 Asm->printLabel(LineInfo.getLabelID());
2795 /// EndFunction - Gather and emit post-function debug information.
2797 void EndFunction() {
2798 if (!ShouldEmitDwarf()) return;
2800 // Define end label for subprogram.
2801 EmitLabel("func_end", SubprogramCount);
2803 // Get function line info.
2804 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2806 if (!LineInfos.empty()) {
2807 // Get section line info.
2808 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2809 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2810 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2811 // Append the function info to section info.
2812 SectionLineInfos.insert(SectionLineInfos.end(),
2813 LineInfos.begin(), LineInfos.end());
2816 // Construct scopes for subprogram.
2817 ConstructRootScope(MMI->getRootScope());
2819 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2820 MMI->getFrameMoves()));
2824 //===----------------------------------------------------------------------===//
2825 /// DwarfException - Emits Dwarf exception handling directives.
2827 class DwarfException : public Dwarf {
2830 struct FunctionEHFrameInfo {
2833 unsigned PersonalityIndex;
2835 bool hasLandingPads;
2836 std::vector<MachineMove> Moves;
2837 const Function * function;
2839 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2841 const std::vector<MachineMove> &M,
2843 FnName(FN), Number(Num), PersonalityIndex(P),
2844 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2847 std::vector<FunctionEHFrameInfo> EHFrames;
2849 /// shouldEmitTable - Per-function flag to indicate if EH tables should
2851 bool shouldEmitTable;
2853 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
2854 /// should be emitted.
2855 bool shouldEmitMoves;
2857 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
2858 /// should be emitted.
2859 bool shouldEmitTableModule;
2861 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
2862 /// should be emitted.
2863 bool shouldEmitMovesModule;
2865 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2867 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2868 // Size and sign of stack growth.
2870 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2871 TargetFrameInfo::StackGrowsUp ?
2872 TD->getPointerSize() : -TD->getPointerSize();
2874 // Begin eh frame section.
2875 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2876 O << "EH_frame" << Index << ":\n";
2877 EmitLabel("section_eh_frame", Index);
2879 // Define base labels.
2880 EmitLabel("eh_frame_common", Index);
2882 // Define the eh frame length.
2883 EmitDifference("eh_frame_common_end", Index,
2884 "eh_frame_common_begin", Index, true);
2885 Asm->EOL("Length of Common Information Entry");
2888 EmitLabel("eh_frame_common_begin", Index);
2889 Asm->EmitInt32((int)0);
2890 Asm->EOL("CIE Identifier Tag");
2891 Asm->EmitInt8(DW_CIE_VERSION);
2892 Asm->EOL("CIE Version");
2894 // The personality presence indicates that language specific information
2895 // will show up in the eh frame.
2896 Asm->EmitString(Personality ? "zPLR" : "zR");
2897 Asm->EOL("CIE Augmentation");
2899 // Round out reader.
2900 Asm->EmitULEB128Bytes(1);
2901 Asm->EOL("CIE Code Alignment Factor");
2902 Asm->EmitSLEB128Bytes(stackGrowth);
2903 Asm->EOL("CIE Data Alignment Factor");
2904 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2905 Asm->EOL("CIE Return Address Column");
2907 // If there is a personality, we need to indicate the functions location.
2909 Asm->EmitULEB128Bytes(7);
2910 Asm->EOL("Augmentation Size");
2912 if (TAI->getNeedsIndirectEncoding()) {
2913 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2914 Asm->EOL("Personality (pcrel sdata4 indirect)");
2916 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2917 Asm->EOL("Personality (pcrel sdata4)");
2920 PrintRelDirective(true);
2921 O << TAI->getPersonalityPrefix();
2922 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2923 O << TAI->getPersonalitySuffix();
2924 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
2925 O << "-" << TAI->getPCSymbol();
2926 Asm->EOL("Personality");
2928 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2929 Asm->EOL("LSDA Encoding (pcrel sdata4)");
2930 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2931 Asm->EOL("FDE Encoding (pcrel sdata4)");
2933 Asm->EmitULEB128Bytes(1);
2934 Asm->EOL("Augmentation Size");
2935 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2936 Asm->EOL("FDE Encoding (pcrel sdata4)");
2939 // Indicate locations of general callee saved registers in frame.
2940 std::vector<MachineMove> Moves;
2941 RI->getInitialFrameState(Moves);
2942 EmitFrameMoves(NULL, 0, Moves, true);
2944 // On Darwin the linker honors the alignment of eh_frame, which means it
2945 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
2946 // you get holes which confuse readers of eh_frame.
2947 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
2949 EmitLabel("eh_frame_common_end", Index);
2954 /// EmitEHFrame - Emit function exception frame information.
2956 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2957 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
2959 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2961 // Externally visible entry into the functions eh frame info.
2962 // If the corresponding function is static, this should not be
2963 // externally visible.
2964 if (linkage != Function::InternalLinkage) {
2965 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
2966 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
2969 // If corresponding function is weak definition, this should be too.
2970 if ((linkage == Function::WeakLinkage ||
2971 linkage == Function::LinkOnceLinkage) &&
2972 TAI->getWeakDefDirective())
2973 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
2975 // If there are no calls then you can't unwind. This may mean we can
2976 // omit the EH Frame, but some environments do not handle weak absolute
2978 // If UnwindTablesMandatory is set we cannot do this optimization; the
2979 // unwind info is to be available for non-EH uses.
2980 if (!EHFrameInfo.hasCalls &&
2981 !UnwindTablesMandatory &&
2982 ((linkage != Function::WeakLinkage &&
2983 linkage != Function::LinkOnceLinkage) ||
2984 !TAI->getWeakDefDirective() ||
2985 TAI->getSupportsWeakOmittedEHFrame()))
2987 O << EHFrameInfo.FnName << " = 0\n";
2988 // This name has no connection to the function, so it might get
2989 // dead-stripped when the function is not, erroneously. Prohibit
2990 // dead-stripping unconditionally.
2991 if (const char *UsedDirective = TAI->getUsedDirective())
2992 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2994 O << EHFrameInfo.FnName << ":\n";
2997 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2998 "eh_frame_begin", EHFrameInfo.Number, true);
2999 Asm->EOL("Length of Frame Information Entry");
3001 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3003 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3004 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3006 Asm->EOL("FDE CIE offset");
3008 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3009 Asm->EOL("FDE initial location");
3010 EmitDifference("eh_func_end", EHFrameInfo.Number,
3011 "eh_func_begin", EHFrameInfo.Number, true);
3012 Asm->EOL("FDE address range");
3014 // If there is a personality and landing pads then point to the language
3015 // specific data area in the exception table.
3016 if (EHFrameInfo.PersonalityIndex) {
3017 Asm->EmitULEB128Bytes(4);
3018 Asm->EOL("Augmentation size");
3020 if (EHFrameInfo.hasLandingPads)
3021 EmitReference("exception", EHFrameInfo.Number, true, true);
3023 Asm->EmitInt32((int)0);
3024 Asm->EOL("Language Specific Data Area");
3026 Asm->EmitULEB128Bytes(0);
3027 Asm->EOL("Augmentation size");
3030 // Indicate locations of function specific callee saved registers in
3032 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3034 // On Darwin the linker honors the alignment of eh_frame, which means it
3035 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3036 // you get holes which confuse readers of eh_frame.
3037 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3039 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3041 // If the function is marked used, this table should be also. We cannot
3042 // make the mark unconditional in this case, since retaining the table
3043 // also retains the function in this case, and there is code around
3044 // that depends on unused functions (calling undefined externals) being
3045 // dead-stripped to link correctly. Yes, there really is.
3046 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3047 if (const char *UsedDirective = TAI->getUsedDirective())
3048 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3052 /// EmitExceptionTable - Emit landing pads and actions.
3054 /// The general organization of the table is complex, but the basic concepts
3055 /// are easy. First there is a header which describes the location and
3056 /// organization of the three components that follow.
3057 /// 1. The landing pad site information describes the range of code covered
3058 /// by the try. In our case it's an accumulation of the ranges covered
3059 /// by the invokes in the try. There is also a reference to the landing
3060 /// pad that handles the exception once processed. Finally an index into
3061 /// the actions table.
3062 /// 2. The action table, in our case, is composed of pairs of type ids
3063 /// and next action offset. Starting with the action index from the
3064 /// landing pad site, each type Id is checked for a match to the current
3065 /// exception. If it matches then the exception and type id are passed
3066 /// on to the landing pad. Otherwise the next action is looked up. This
3067 /// chain is terminated with a next action of zero. If no type id is
3068 /// found the the frame is unwound and handling continues.
3069 /// 3. Type id table contains references to all the C++ typeinfo for all
3070 /// catches in the function. This tables is reversed indexed base 1.
3072 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3073 static unsigned SharedTypeIds(const LandingPadInfo *L,
3074 const LandingPadInfo *R) {
3075 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3076 unsigned LSize = LIds.size(), RSize = RIds.size();
3077 unsigned MinSize = LSize < RSize ? LSize : RSize;
3080 for (; Count != MinSize; ++Count)
3081 if (LIds[Count] != RIds[Count])
3087 /// PadLT - Order landing pads lexicographically by type id.
3088 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3089 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3090 unsigned LSize = LIds.size(), RSize = RIds.size();
3091 unsigned MinSize = LSize < RSize ? LSize : RSize;
3093 for (unsigned i = 0; i != MinSize; ++i)
3094 if (LIds[i] != RIds[i])
3095 return LIds[i] < RIds[i];
3097 return LSize < RSize;
3101 static inline unsigned getEmptyKey() { return -1U; }
3102 static inline unsigned getTombstoneKey() { return -2U; }
3103 static unsigned getHashValue(const unsigned &Key) { return Key; }
3104 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3105 static bool isPod() { return true; }
3108 /// ActionEntry - Structure describing an entry in the actions table.
3109 struct ActionEntry {
3110 int ValueForTypeID; // The value to write - may not be equal to the type id.
3112 struct ActionEntry *Previous;
3115 /// PadRange - Structure holding a try-range and the associated landing pad.
3117 // The index of the landing pad.
3119 // The index of the begin and end labels in the landing pad's label lists.
3120 unsigned RangeIndex;
3123 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3125 /// CallSiteEntry - Structure describing an entry in the call-site table.
3126 struct CallSiteEntry {
3127 // The 'try-range' is BeginLabel .. EndLabel.
3128 unsigned BeginLabel; // zero indicates the start of the function.
3129 unsigned EndLabel; // zero indicates the end of the function.
3130 // The landing pad starts at PadLabel.
3131 unsigned PadLabel; // zero indicates that there is no landing pad.
3135 void EmitExceptionTable() {
3136 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3137 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3138 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3139 if (PadInfos.empty()) return;
3141 // Sort the landing pads in order of their type ids. This is used to fold
3142 // duplicate actions.
3143 SmallVector<const LandingPadInfo *, 64> LandingPads;
3144 LandingPads.reserve(PadInfos.size());
3145 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3146 LandingPads.push_back(&PadInfos[i]);
3147 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3149 // Negative type ids index into FilterIds, positive type ids index into
3150 // TypeInfos. The value written for a positive type id is just the type
3151 // id itself. For a negative type id, however, the value written is the
3152 // (negative) byte offset of the corresponding FilterIds entry. The byte
3153 // offset is usually equal to the type id, because the FilterIds entries
3154 // are written using a variable width encoding which outputs one byte per
3155 // entry as long as the value written is not too large, but can differ.
3156 // This kind of complication does not occur for positive type ids because
3157 // type infos are output using a fixed width encoding.
3158 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3159 SmallVector<int, 16> FilterOffsets;
3160 FilterOffsets.reserve(FilterIds.size());
3162 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3163 E = FilterIds.end(); I != E; ++I) {
3164 FilterOffsets.push_back(Offset);
3165 Offset -= Asm->SizeULEB128(*I);
3168 // Compute the actions table and gather the first action index for each
3169 // landing pad site.
3170 SmallVector<ActionEntry, 32> Actions;
3171 SmallVector<unsigned, 64> FirstActions;
3172 FirstActions.reserve(LandingPads.size());
3174 int FirstAction = 0;
3175 unsigned SizeActions = 0;
3176 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3177 const LandingPadInfo *LP = LandingPads[i];
3178 const std::vector<int> &TypeIds = LP->TypeIds;
3179 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3180 unsigned SizeSiteActions = 0;
3182 if (NumShared < TypeIds.size()) {
3183 unsigned SizeAction = 0;
3184 ActionEntry *PrevAction = 0;
3187 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3188 assert(Actions.size());
3189 PrevAction = &Actions.back();
3190 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3191 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3192 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3193 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3194 SizeAction += -PrevAction->NextAction;
3195 PrevAction = PrevAction->Previous;
3199 // Compute the actions.
3200 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3201 int TypeID = TypeIds[I];
3202 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3203 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3204 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3206 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3207 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3208 SizeSiteActions += SizeAction;
3210 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3211 Actions.push_back(Action);
3213 PrevAction = &Actions.back();
3216 // Record the first action of the landing pad site.
3217 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3218 } // else identical - re-use previous FirstAction
3220 FirstActions.push_back(FirstAction);
3222 // Compute this sites contribution to size.
3223 SizeActions += SizeSiteActions;
3226 // Compute the call-site table. The entry for an invoke has a try-range
3227 // containing the call, a non-zero landing pad and an appropriate action.
3228 // The entry for an ordinary call has a try-range containing the call and
3229 // zero for the landing pad and the action. Calls marked 'nounwind' have
3230 // no entry and must not be contained in the try-range of any entry - they
3231 // form gaps in the table. Entries must be ordered by try-range address.
3232 SmallVector<CallSiteEntry, 64> CallSites;
3234 RangeMapType PadMap;
3235 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3236 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3237 // try-ranges for them need be deduced.
3238 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3239 const LandingPadInfo *LandingPad = LandingPads[i];
3240 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3241 unsigned BeginLabel = LandingPad->BeginLabels[j];
3242 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3243 PadRange P = { i, j };
3244 PadMap[BeginLabel] = P;
3248 // The end label of the previous invoke or nounwind try-range.
3249 unsigned LastLabel = 0;
3251 // Whether there is a potentially throwing instruction (currently this means
3252 // an ordinary call) between the end of the previous try-range and now.
3253 bool SawPotentiallyThrowing = false;
3255 // Whether the last callsite entry was for an invoke.
3256 bool PreviousIsInvoke = false;
3258 // Visit all instructions in order of address.
3259 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3261 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3263 if (MI->getOpcode() != TargetInstrInfo::LABEL) {
3264 SawPotentiallyThrowing |= MI->getDesc().isCall();
3268 unsigned BeginLabel = MI->getOperand(0).getImm();
3269 assert(BeginLabel && "Invalid label!");
3271 // End of the previous try-range?
3272 if (BeginLabel == LastLabel)
3273 SawPotentiallyThrowing = false;
3275 // Beginning of a new try-range?
3276 RangeMapType::iterator L = PadMap.find(BeginLabel);
3277 if (L == PadMap.end())
3278 // Nope, it was just some random label.
3281 PadRange P = L->second;
3282 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3284 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3285 "Inconsistent landing pad map!");
3287 // If some instruction between the previous try-range and this one may
3288 // throw, create a call-site entry with no landing pad for the region
3289 // between the try-ranges.
3290 if (SawPotentiallyThrowing) {
3291 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3292 CallSites.push_back(Site);
3293 PreviousIsInvoke = false;
3296 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3297 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3299 if (LandingPad->LandingPadLabel) {
3300 // This try-range is for an invoke.
3301 CallSiteEntry Site = {BeginLabel, LastLabel,
3302 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3304 // Try to merge with the previous call-site.
3305 if (PreviousIsInvoke) {
3306 CallSiteEntry &Prev = CallSites.back();
3307 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3308 // Extend the range of the previous entry.
3309 Prev.EndLabel = Site.EndLabel;
3314 // Otherwise, create a new call-site.
3315 CallSites.push_back(Site);
3316 PreviousIsInvoke = true;
3319 PreviousIsInvoke = false;
3323 // If some instruction between the previous try-range and the end of the
3324 // function may throw, create a call-site entry with no landing pad for the
3325 // region following the try-range.
3326 if (SawPotentiallyThrowing) {
3327 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3328 CallSites.push_back(Site);
3334 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3335 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3336 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3337 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3340 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3341 SizeSites += Asm->SizeULEB128(CallSites[i].Action);
3344 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3345 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3347 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3348 Asm->SizeULEB128(SizeSites) + // Call-site table length
3349 SizeSites + SizeActions + SizeTypes;
3351 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3352 sizeof(int8_t) + // TType format
3353 Asm->SizeULEB128(TypeOffset) + // TType base offset
3356 unsigned SizeAlign = (4 - TotalSize) & 3;
3358 // Begin the exception table.
3359 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3360 O << "GCC_except_table" << SubprogramCount << ":\n";
3361 Asm->EmitAlignment(2, 0, 0, false);
3362 for (unsigned i = 0; i != SizeAlign; ++i) {
3364 Asm->EOL("Padding");
3366 EmitLabel("exception", SubprogramCount);
3369 Asm->EmitInt8(DW_EH_PE_omit);
3370 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3371 Asm->EmitInt8(DW_EH_PE_absptr);
3372 Asm->EOL("TType format (DW_EH_PE_absptr)");
3373 Asm->EmitULEB128Bytes(TypeOffset);
3374 Asm->EOL("TType base offset");
3375 Asm->EmitInt8(DW_EH_PE_udata4);
3376 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3377 Asm->EmitULEB128Bytes(SizeSites);
3378 Asm->EOL("Call-site table length");
3380 // Emit the landing pad site information.
3381 for (unsigned i = 0; i < CallSites.size(); ++i) {
3382 CallSiteEntry &S = CallSites[i];
3383 const char *BeginTag;
3384 unsigned BeginNumber;
3386 if (!S.BeginLabel) {
3387 BeginTag = "eh_func_begin";
3388 BeginNumber = SubprogramCount;
3391 BeginNumber = S.BeginLabel;
3394 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3396 Asm->EOL("Region start");
3399 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3402 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3404 Asm->EOL("Region length");
3409 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3411 Asm->EOL("Landing pad");
3413 Asm->EmitULEB128Bytes(S.Action);
3417 // Emit the actions.
3418 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3419 ActionEntry &Action = Actions[I];
3421 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3422 Asm->EOL("TypeInfo index");
3423 Asm->EmitSLEB128Bytes(Action.NextAction);
3424 Asm->EOL("Next action");
3427 // Emit the type ids.
3428 for (unsigned M = TypeInfos.size(); M; --M) {
3429 GlobalVariable *GV = TypeInfos[M - 1];
3431 PrintRelDirective();
3434 O << Asm->getGlobalLinkName(GV);
3438 Asm->EOL("TypeInfo");
3441 // Emit the filter typeids.
3442 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3443 unsigned TypeID = FilterIds[j];
3444 Asm->EmitULEB128Bytes(TypeID);
3445 Asm->EOL("Filter TypeInfo index");
3448 Asm->EmitAlignment(2, 0, 0, false);
3452 //===--------------------------------------------------------------------===//
3453 // Main entry points.
3455 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3456 : Dwarf(OS, A, T, "eh")
3457 , shouldEmitTable(false)
3458 , shouldEmitMoves(false)
3459 , shouldEmitTableModule(false)
3460 , shouldEmitMovesModule(false)
3463 virtual ~DwarfException() {}
3465 /// SetModuleInfo - Set machine module information when it's known that pass
3466 /// manager has created it. Set by the target AsmPrinter.
3467 void SetModuleInfo(MachineModuleInfo *mmi) {
3471 /// BeginModule - Emit all exception information that should come prior to the
3473 void BeginModule(Module *M) {
3477 /// EndModule - Emit all exception information that should come after the
3480 if (shouldEmitMovesModule || shouldEmitTableModule) {
3481 const std::vector<Function *> Personalities = MMI->getPersonalities();
3482 for (unsigned i =0; i < Personalities.size(); ++i)
3483 EmitCommonEHFrame(Personalities[i], i);
3485 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3486 E = EHFrames.end(); I != E; ++I)
3491 /// BeginFunction - Gather pre-function exception information. Assumes being
3492 /// emitted immediately after the function entry point.
3493 void BeginFunction(MachineFunction *MF) {
3495 shouldEmitTable = shouldEmitMoves = false;
3496 if (MMI && TAI->doesSupportExceptionHandling()) {
3498 // Map all labels and get rid of any dead landing pads.
3499 MMI->TidyLandingPads();
3500 // If any landing pads survive, we need an EH table.
3501 if (MMI->getLandingPads().size())
3502 shouldEmitTable = true;
3504 // See if we need frame move info.
3505 if (MMI->hasDebugInfo() ||
3506 !MF->getFunction()->doesNotThrow() ||
3507 UnwindTablesMandatory)
3508 shouldEmitMoves = true;
3510 if (shouldEmitMoves || shouldEmitTable)
3511 // Assumes in correct section after the entry point.
3512 EmitLabel("eh_func_begin", ++SubprogramCount);
3514 shouldEmitTableModule |= shouldEmitTable;
3515 shouldEmitMovesModule |= shouldEmitMoves;
3518 /// EndFunction - Gather and emit post-function exception information.
3520 void EndFunction() {
3521 if (shouldEmitMoves || shouldEmitTable) {
3522 EmitLabel("eh_func_end", SubprogramCount);
3523 EmitExceptionTable();
3525 // Save EH frame information
3527 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3529 MMI->getPersonalityIndex(),
3530 MF->getFrameInfo()->hasCalls(),
3531 !MMI->getLandingPads().empty(),
3532 MMI->getFrameMoves(),
3533 MF->getFunction()));
3538 } // End of namespace llvm
3540 //===----------------------------------------------------------------------===//
3542 /// Emit - Print the abbreviation using the specified Dwarf writer.
3544 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3545 // Emit its Dwarf tag type.
3546 DD.getAsm()->EmitULEB128Bytes(Tag);
3547 DD.getAsm()->EOL(TagString(Tag));
3549 // Emit whether it has children DIEs.
3550 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3551 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3553 // For each attribute description.
3554 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3555 const DIEAbbrevData &AttrData = Data[i];
3557 // Emit attribute type.
3558 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3559 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3562 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3563 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3566 // Mark end of abbreviation.
3567 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3568 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3572 void DIEAbbrev::print(std::ostream &O) {
3573 O << "Abbreviation @"
3574 << std::hex << (intptr_t)this << std::dec
3578 << ChildrenString(ChildrenFlag)
3581 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3583 << AttributeString(Data[i].getAttribute())
3585 << FormEncodingString(Data[i].getForm())
3589 void DIEAbbrev::dump() { print(cerr); }
3592 //===----------------------------------------------------------------------===//
3595 void DIEValue::dump() {
3600 //===----------------------------------------------------------------------===//
3602 /// EmitValue - Emit integer of appropriate size.
3604 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3606 case DW_FORM_flag: // Fall thru
3607 case DW_FORM_ref1: // Fall thru
3608 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3609 case DW_FORM_ref2: // Fall thru
3610 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3611 case DW_FORM_ref4: // Fall thru
3612 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3613 case DW_FORM_ref8: // Fall thru
3614 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3615 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3616 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3617 default: assert(0 && "DIE Value form not supported yet"); break;
3621 /// SizeOf - Determine size of integer value in bytes.
3623 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3625 case DW_FORM_flag: // Fall thru
3626 case DW_FORM_ref1: // Fall thru
3627 case DW_FORM_data1: return sizeof(int8_t);
3628 case DW_FORM_ref2: // Fall thru
3629 case DW_FORM_data2: return sizeof(int16_t);
3630 case DW_FORM_ref4: // Fall thru
3631 case DW_FORM_data4: return sizeof(int32_t);
3632 case DW_FORM_ref8: // Fall thru
3633 case DW_FORM_data8: return sizeof(int64_t);
3634 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3635 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3636 default: assert(0 && "DIE Value form not supported yet"); break;
3641 //===----------------------------------------------------------------------===//
3643 /// EmitValue - Emit string value.
3645 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3646 DD.getAsm()->EmitString(String);
3649 //===----------------------------------------------------------------------===//
3651 /// EmitValue - Emit label value.
3653 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3654 bool IsSmall = Form == DW_FORM_data4;
3655 DD.EmitReference(Label, false, IsSmall);
3658 /// SizeOf - Determine size of label value in bytes.
3660 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3661 if (Form == DW_FORM_data4) return 4;
3662 return DD.getTargetData()->getPointerSize();
3665 //===----------------------------------------------------------------------===//
3667 /// EmitValue - Emit label value.
3669 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3670 bool IsSmall = Form == DW_FORM_data4;
3671 DD.EmitReference(Label, false, IsSmall);
3674 /// SizeOf - Determine size of label value in bytes.
3676 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3677 if (Form == DW_FORM_data4) return 4;
3678 return DD.getTargetData()->getPointerSize();
3681 //===----------------------------------------------------------------------===//
3683 /// EmitValue - Emit delta value.
3685 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
3686 bool IsSmall = Form == DW_FORM_data4;
3687 DD.EmitSectionOffset(Label.Tag, Section.Tag,
3688 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
3691 /// SizeOf - Determine size of delta value in bytes.
3693 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3694 if (Form == DW_FORM_data4) return 4;
3695 return DD.getTargetData()->getPointerSize();
3698 //===----------------------------------------------------------------------===//
3700 /// EmitValue - Emit delta value.
3702 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3703 bool IsSmall = Form == DW_FORM_data4;
3704 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3707 /// SizeOf - Determine size of delta value in bytes.
3709 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3710 if (Form == DW_FORM_data4) return 4;
3711 return DD.getTargetData()->getPointerSize();
3714 //===----------------------------------------------------------------------===//
3716 /// EmitValue - Emit debug information entry offset.
3718 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3719 DD.getAsm()->EmitInt32(Entry->getOffset());
3722 //===----------------------------------------------------------------------===//
3724 /// ComputeSize - calculate the size of the block.
3726 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3728 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3730 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3731 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3737 /// EmitValue - Emit block data.
3739 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3741 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3742 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3743 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3744 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3745 default: assert(0 && "Improper form for block"); break;
3748 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3750 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3752 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3756 /// SizeOf - Determine size of block data in bytes.
3758 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3760 case DW_FORM_block1: return Size + sizeof(int8_t);
3761 case DW_FORM_block2: return Size + sizeof(int16_t);
3762 case DW_FORM_block4: return Size + sizeof(int32_t);
3763 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3764 default: assert(0 && "Improper form for block"); break;
3769 //===----------------------------------------------------------------------===//
3770 /// DIE Implementation
3773 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3777 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3779 void DIE::AddSiblingOffset() {
3780 DIEInteger *DI = new DIEInteger(0);
3781 Values.insert(Values.begin(), DI);
3782 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3785 /// Profile - Used to gather unique data for the value folding set.
3787 void DIE::Profile(FoldingSetNodeID &ID) {
3790 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3791 ID.AddPointer(Children[i]);
3793 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3794 ID.AddPointer(Values[j]);
3798 void DIE::print(std::ostream &O, unsigned IncIndent) {
3799 static unsigned IndentCount = 0;
3800 IndentCount += IncIndent;
3801 const std::string Indent(IndentCount, ' ');
3802 bool isBlock = Abbrev.getTag() == 0;
3807 << "0x" << std::hex << (intptr_t)this << std::dec
3808 << ", Offset: " << Offset
3809 << ", Size: " << Size
3813 << TagString(Abbrev.getTag())
3815 << ChildrenString(Abbrev.getChildrenFlag());
3817 O << "Size: " << Size;
3821 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
3824 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3827 O << AttributeString(Data[i].getAttribute());
3829 O << "Blk[" << i << "]";
3832 << FormEncodingString(Data[i].getForm())
3834 Values[i]->print(O);
3839 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3840 Children[j]->print(O, 4);
3843 if (!isBlock) O << "\n";
3844 IndentCount -= IncIndent;
3852 //===----------------------------------------------------------------------===//
3853 /// DwarfWriter Implementation
3856 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3857 const TargetAsmInfo *T) {
3858 DE = new DwarfException(OS, A, T);
3859 DD = new DwarfDebug(OS, A, T);
3862 DwarfWriter::~DwarfWriter() {
3867 /// SetModuleInfo - Set machine module info when it's known that pass manager
3868 /// has created it. Set by the target AsmPrinter.
3869 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3870 DD->SetModuleInfo(MMI);
3871 DE->SetModuleInfo(MMI);
3874 /// BeginModule - Emit all Dwarf sections that should come prior to the
3876 void DwarfWriter::BeginModule(Module *M) {
3881 /// EndModule - Emit all Dwarf sections that should come after the content.
3883 void DwarfWriter::EndModule() {
3888 /// BeginFunction - Gather pre-function debug information. Assumes being
3889 /// emitted immediately after the function entry point.
3890 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3891 DE->BeginFunction(MF);
3892 DD->BeginFunction(MF);
3895 /// EndFunction - Gather and emit post-function debug information.
3897 void DwarfWriter::EndFunction() {
3901 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3902 // Clear function debug information.