1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Support/raw_ostream.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 information.
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(raw_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.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1055 if (Src.getReg() == 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.getReg(), 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.isReg() &&
1073 Src.getReg() == MachineLocation::VirtualFP) {
1075 Asm->EmitInt8(DW_CFA_def_cfa_register);
1076 Asm->EOL("DW_CFA_def_cfa_register");
1077 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1078 Asm->EOL("Register");
1080 assert(0 && "Machine move no supported yet.");
1083 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), 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);
1096 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1099 Asm->EmitULEB128Bytes(Offset);
1102 Asm->EmitInt8(DW_CFA_offset_extended);
1103 Asm->EOL("DW_CFA_offset_extended");
1104 Asm->EmitULEB128Bytes(Reg);
1106 Asm->EmitULEB128Bytes(Offset);
1115 //===----------------------------------------------------------------------===//
1116 /// DwarfDebug - Emits Dwarf debug directives.
1118 class DwarfDebug : public Dwarf {
1121 //===--------------------------------------------------------------------===//
1122 // Attributes used to construct specific Dwarf sections.
1125 /// CompileUnits - All the compile units involved in this build. The index
1126 /// of each entry in this vector corresponds to the sources in MMI.
1127 std::vector<CompileUnit *> CompileUnits;
1129 /// AbbreviationsSet - Used to uniquely define abbreviations.
1131 FoldingSet<DIEAbbrev> AbbreviationsSet;
1133 /// Abbreviations - A list of all the unique abbreviations in use.
1135 std::vector<DIEAbbrev *> Abbreviations;
1137 /// ValuesSet - Used to uniquely define values.
1139 FoldingSet<DIEValue> ValuesSet;
1141 /// Values - A list of all the unique values in use.
1143 std::vector<DIEValue *> Values;
1145 /// StringPool - A UniqueVector of strings used by indirect references.
1147 UniqueVector<std::string> StringPool;
1149 /// UnitMap - Map debug information descriptor to compile unit.
1151 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1153 /// SectionMap - Provides a unique id per text section.
1155 UniqueVector<const Section*> SectionMap;
1157 /// SectionSourceLines - Tracks line numbers per text section.
1159 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1161 /// didInitial - Flag to indicate if initial emission has been done.
1165 /// shouldEmit - Flag to indicate if debug information should be emitted.
1169 struct FunctionDebugFrameInfo {
1171 std::vector<MachineMove> Moves;
1173 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1174 Number(Num), Moves(M) { }
1177 std::vector<FunctionDebugFrameInfo> DebugFrames;
1181 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1183 bool ShouldEmitDwarf() const { return shouldEmit; }
1185 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1187 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1188 // Profile the node so that we can make it unique.
1189 FoldingSetNodeID ID;
1192 // Check the set for priors.
1193 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1195 // If it's newly added.
1196 if (InSet == &Abbrev) {
1197 // Add to abbreviation list.
1198 Abbreviations.push_back(&Abbrev);
1199 // Assign the vector position + 1 as its number.
1200 Abbrev.setNumber(Abbreviations.size());
1202 // Assign existing abbreviation number.
1203 Abbrev.setNumber(InSet->getNumber());
1207 /// NewString - Add a string to the constant pool and returns a label.
1209 DWLabel NewString(const std::string &String) {
1210 unsigned StringID = StringPool.insert(String);
1211 return DWLabel("string", StringID);
1214 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1216 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1220 FoldingSetNodeID ID;
1221 DIEntry::Profile(ID, Entry);
1223 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1225 if (Value) return Value;
1227 Value = new DIEntry(Entry);
1228 ValuesSet.InsertNode(Value, Where);
1230 Value = new DIEntry(Entry);
1233 Values.push_back(Value);
1237 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1239 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1240 Value->Entry = Entry;
1241 // Add to values set if not already there. If it is, we merely have a
1242 // duplicate in the values list (no harm.)
1243 ValuesSet.GetOrInsertNode(Value);
1246 /// AddUInt - Add an unsigned integer attribute data and value.
1248 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1249 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1251 FoldingSetNodeID ID;
1252 DIEInteger::Profile(ID, Integer);
1254 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1256 Value = new DIEInteger(Integer);
1257 ValuesSet.InsertNode(Value, Where);
1258 Values.push_back(Value);
1261 Die->AddValue(Attribute, Form, Value);
1264 /// AddSInt - Add an signed integer attribute data and value.
1266 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1267 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1269 FoldingSetNodeID ID;
1270 DIEInteger::Profile(ID, (uint64_t)Integer);
1272 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1274 Value = new DIEInteger(Integer);
1275 ValuesSet.InsertNode(Value, Where);
1276 Values.push_back(Value);
1279 Die->AddValue(Attribute, Form, Value);
1282 /// AddString - Add a std::string attribute data and value.
1284 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1285 const std::string &String) {
1286 FoldingSetNodeID ID;
1287 DIEString::Profile(ID, String);
1289 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1291 Value = new DIEString(String);
1292 ValuesSet.InsertNode(Value, Where);
1293 Values.push_back(Value);
1296 Die->AddValue(Attribute, Form, Value);
1299 /// AddLabel - Add a Dwarf label attribute data and value.
1301 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1302 const DWLabel &Label) {
1303 FoldingSetNodeID ID;
1304 DIEDwarfLabel::Profile(ID, Label);
1306 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1308 Value = new DIEDwarfLabel(Label);
1309 ValuesSet.InsertNode(Value, Where);
1310 Values.push_back(Value);
1313 Die->AddValue(Attribute, Form, Value);
1316 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1318 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1319 const std::string &Label) {
1320 FoldingSetNodeID ID;
1321 DIEObjectLabel::Profile(ID, Label);
1323 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1325 Value = new DIEObjectLabel(Label);
1326 ValuesSet.InsertNode(Value, Where);
1327 Values.push_back(Value);
1330 Die->AddValue(Attribute, Form, Value);
1333 /// AddSectionOffset - Add a section offset label attribute data and value.
1335 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1336 const DWLabel &Label, const DWLabel &Section,
1337 bool isEH = false, bool useSet = true) {
1338 FoldingSetNodeID ID;
1339 DIESectionOffset::Profile(ID, Label, Section);
1341 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1343 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1344 ValuesSet.InsertNode(Value, Where);
1345 Values.push_back(Value);
1348 Die->AddValue(Attribute, Form, Value);
1351 /// AddDelta - Add a label delta attribute data and value.
1353 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1354 const DWLabel &Hi, const DWLabel &Lo) {
1355 FoldingSetNodeID ID;
1356 DIEDelta::Profile(ID, Hi, Lo);
1358 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1360 Value = new DIEDelta(Hi, Lo);
1361 ValuesSet.InsertNode(Value, Where);
1362 Values.push_back(Value);
1365 Die->AddValue(Attribute, Form, Value);
1368 /// AddDIEntry - Add a DIE attribute data and value.
1370 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1371 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1374 /// AddBlock - Add block data.
1376 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1377 Block->ComputeSize(*this);
1378 FoldingSetNodeID ID;
1381 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1384 ValuesSet.InsertNode(Value, Where);
1385 Values.push_back(Value);
1387 // Already exists, reuse the previous one.
1389 Block = cast<DIEBlock>(Value);
1392 Die->AddValue(Attribute, Block->BestForm(), Value);
1397 /// AddSourceLine - Add location information to specified debug information
1399 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1401 CompileUnit *FileUnit = FindCompileUnit(File);
1402 unsigned FileID = FileUnit->getID();
1403 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1404 AddUInt(Die, DW_AT_decl_line, 0, Line);
1408 /// AddAddress - Add an address attribute to a die based on the location
1410 void AddAddress(DIE *Die, unsigned Attribute,
1411 const MachineLocation &Location) {
1412 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1413 DIEBlock *Block = new DIEBlock();
1415 if (Location.isReg()) {
1417 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1419 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1420 AddUInt(Block, 0, DW_FORM_udata, Reg);
1424 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1426 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1427 AddUInt(Block, 0, DW_FORM_udata, Reg);
1429 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1432 AddBlock(Die, Attribute, 0, Block);
1435 /// AddBasicType - Add a new basic type attribute to the specified entity.
1437 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1438 const std::string &Name,
1439 unsigned Encoding, unsigned Size) {
1440 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1441 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1444 /// ConstructBasicType - Construct a new basic type.
1446 DIE *ConstructBasicType(CompileUnit *Unit,
1447 const std::string &Name,
1448 unsigned Encoding, unsigned Size) {
1449 DIE Buffer(DW_TAG_base_type);
1450 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1451 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1452 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1453 return Unit->AddDie(Buffer);
1456 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1458 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1459 DIE *Die = ConstructPointerType(Unit, Name);
1460 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1463 /// ConstructPointerType - Construct a new pointer type.
1465 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1466 DIE Buffer(DW_TAG_pointer_type);
1467 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1468 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1469 return Unit->AddDie(Buffer);
1472 /// AddType - Add a new type attribute to the specified entity.
1474 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1476 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1478 // Check for pre-existence.
1479 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1481 // If it exists then use the existing value.
1483 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1487 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1488 // FIXME - Not sure why programs and variables are coming through here.
1489 // Short cut for handling subprogram types (not really a TyDesc.)
1490 AddPointerType(Entity, Unit, SubprogramTy->getName());
1491 } else if (GlobalVariableDesc *GlobalTy =
1492 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1493 // FIXME - Not sure why programs and variables are coming through here.
1494 // Short cut for handling global variable types (not really a TyDesc.)
1495 AddPointerType(Entity, Unit, GlobalTy->getName());
1498 Slot = NewDIEntry();
1501 DIE Buffer(DW_TAG_base_type);
1502 ConstructType(Buffer, TyDesc, Unit);
1504 // Add debug information entry to entity and unit.
1505 DIE *Die = Unit->AddDie(Buffer);
1506 SetDIEntry(Slot, Die);
1507 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1512 /// ConstructType - Adds all the required attributes to the type.
1514 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1515 // Get core information.
1516 const std::string &Name = TyDesc->getName();
1517 uint64_t Size = TyDesc->getSize() >> 3;
1519 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1520 // Fundamental types like int, float, bool
1521 Buffer.setTag(DW_TAG_base_type);
1522 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1523 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1525 unsigned Tag = DerivedTy->getTag();
1526 // FIXME - Workaround for templates.
1527 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1528 // Pointers, typedefs et al.
1530 // Map to main type, void will not have a type.
1531 if (TypeDesc *FromTy = DerivedTy->getFromType())
1532 AddType(&Buffer, FromTy, Unit);
1533 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1535 unsigned Tag = CompTy->getTag();
1537 // Set tag accordingly.
1538 if (Tag == DW_TAG_vector_type)
1539 Buffer.setTag(DW_TAG_array_type);
1543 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1546 case DW_TAG_vector_type:
1547 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1549 case DW_TAG_array_type: {
1550 // Add element type.
1551 if (TypeDesc *FromTy = CompTy->getFromType())
1552 AddType(&Buffer, FromTy, Unit);
1554 // Don't emit size attribute.
1557 // Construct an anonymous type for index type.
1558 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1561 // Add subranges to array type.
1562 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1563 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1564 int64_t Lo = SRD->getLo();
1565 int64_t Hi = SRD->getHi();
1566 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1568 // If a range is available.
1570 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1571 // Only add low if non-zero.
1572 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1573 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1576 Buffer.AddChild(Subrange);
1580 case DW_TAG_structure_type:
1581 case DW_TAG_union_type: {
1582 // Add elements to structure type.
1583 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1584 DebugInfoDesc *Element = Elements[i];
1586 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1587 // Add field or base class.
1589 unsigned Tag = MemberDesc->getTag();
1591 // Extract the basic information.
1592 const std::string &Name = MemberDesc->getName();
1593 uint64_t Size = MemberDesc->getSize();
1594 uint64_t Align = MemberDesc->getAlign();
1595 uint64_t Offset = MemberDesc->getOffset();
1597 // Construct member debug information entry.
1598 DIE *Member = new DIE(Tag);
1600 // Add name if not "".
1602 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1603 // Add location if available.
1604 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1606 // Most of the time the field info is the same as the members.
1607 uint64_t FieldSize = Size;
1608 uint64_t FieldAlign = Align;
1609 uint64_t FieldOffset = Offset;
1611 // Set the member type.
1612 TypeDesc *FromTy = MemberDesc->getFromType();
1613 AddType(Member, FromTy, Unit);
1615 // Walk up typedefs until a real size is found.
1617 if (FromTy->getTag() != DW_TAG_typedef) {
1618 FieldSize = FromTy->getSize();
1619 FieldAlign = FromTy->getSize();
1623 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1626 // Unless we have a bit field.
1627 if (Tag == DW_TAG_member && FieldSize != Size) {
1628 // Construct the alignment mask.
1629 uint64_t AlignMask = ~(FieldAlign - 1);
1630 // Determine the high bit + 1 of the declared size.
1631 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1632 // Work backwards to determine the base offset of the field.
1633 FieldOffset = HiMark - FieldSize;
1634 // Now normalize offset to the field.
1635 Offset -= FieldOffset;
1637 // Maybe we need to work from the other end.
1638 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1640 // Add size and offset.
1641 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1642 AddUInt(Member, DW_AT_bit_size, 0, Size);
1643 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1646 // Add computation for offset.
1647 DIEBlock *Block = new DIEBlock();
1648 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1649 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1650 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1652 // Add accessibility (public default unless is base class.
1653 if (MemberDesc->isProtected()) {
1654 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1655 } else if (MemberDesc->isPrivate()) {
1656 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1657 } else if (Tag == DW_TAG_inheritance) {
1658 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1661 Buffer.AddChild(Member);
1662 } else if (GlobalVariableDesc *StaticDesc =
1663 dyn_cast<GlobalVariableDesc>(Element)) {
1664 // Add static member.
1666 // Construct member debug information entry.
1667 DIE *Static = new DIE(DW_TAG_variable);
1669 // Add name and mangled name.
1670 const std::string &Name = StaticDesc->getName();
1671 const std::string &LinkageName = StaticDesc->getLinkageName();
1672 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1673 if (!LinkageName.empty()) {
1674 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1679 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1682 if (TypeDesc *StaticTy = StaticDesc->getType())
1683 AddType(Static, StaticTy, Unit);
1686 if (!StaticDesc->isStatic())
1687 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1688 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1690 Buffer.AddChild(Static);
1691 } else if (SubprogramDesc *MethodDesc =
1692 dyn_cast<SubprogramDesc>(Element)) {
1693 // Add member function.
1695 // Construct member debug information entry.
1696 DIE *Method = new DIE(DW_TAG_subprogram);
1698 // Add name and mangled name.
1699 const std::string &Name = MethodDesc->getName();
1700 const std::string &LinkageName = MethodDesc->getLinkageName();
1702 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1703 bool IsCTor = TyDesc->getName() == Name;
1705 if (!LinkageName.empty()) {
1706 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1711 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1714 if (CompositeTypeDesc *MethodTy =
1715 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1716 // Get argument information.
1717 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1722 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1726 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1727 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1728 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1729 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1730 Method->AddChild(Arg);
1735 if (!MethodDesc->isStatic())
1736 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1737 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1739 Buffer.AddChild(Method);
1744 case DW_TAG_enumeration_type: {
1745 // Add enumerators to enumeration type.
1746 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1747 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1748 const std::string &Name = ED->getName();
1749 int64_t Value = ED->getValue();
1750 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1751 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1752 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1753 Buffer.AddChild(Enumerator);
1758 case DW_TAG_subroutine_type: {
1759 // Add prototype flag.
1760 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1762 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1765 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1766 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1767 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1768 Buffer.AddChild(Arg);
1777 // Add size if non-zero (derived types don't have a size.)
1778 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1779 // Add name if not anonymous or intermediate type.
1780 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1781 // Add source line info if available.
1782 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1785 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1787 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1788 // Construct debug information entry.
1789 DIE *Die = new DIE(DW_TAG_compile_unit);
1790 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
1791 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
1792 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1793 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1794 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1795 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1797 // Construct compile unit.
1798 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1800 // Add Unit to compile unit map.
1801 DescToUnitMap[UnitDesc] = Unit;
1806 /// GetBaseCompileUnit - Get the main compile unit.
1808 CompileUnit *GetBaseCompileUnit() const {
1809 CompileUnit *Unit = CompileUnits[0];
1810 assert(Unit && "Missing compile unit.");
1814 /// FindCompileUnit - Get the compile unit for the given descriptor.
1816 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1817 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1818 assert(Unit && "Missing compile unit.");
1822 /// NewGlobalVariable - Add a new global variable DIE.
1824 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1825 // Get the compile unit context.
1826 CompileUnitDesc *UnitDesc =
1827 static_cast<CompileUnitDesc *>(GVD->getContext());
1828 CompileUnit *Unit = GetBaseCompileUnit();
1830 // Check for pre-existence.
1831 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1832 if (Slot) return Slot;
1834 // Get the global variable itself.
1835 GlobalVariable *GV = GVD->getGlobalVariable();
1837 const std::string &Name = GVD->getName();
1838 const std::string &FullName = GVD->getFullName();
1839 const std::string &LinkageName = GVD->getLinkageName();
1840 // Create the global's variable DIE.
1841 DIE *VariableDie = new DIE(DW_TAG_variable);
1842 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1843 if (!LinkageName.empty()) {
1844 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1847 AddType(VariableDie, GVD->getType(), Unit);
1848 if (!GVD->isStatic())
1849 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1851 // Add source line info if available.
1852 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1855 DIEBlock *Block = new DIEBlock();
1856 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1857 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1858 AddBlock(VariableDie, DW_AT_location, 0, Block);
1863 // Add to context owner.
1864 Unit->getDie()->AddChild(VariableDie);
1866 // Expose as global.
1867 // FIXME - need to check external flag.
1868 Unit->AddGlobal(FullName, VariableDie);
1873 /// NewSubprogram - Add a new subprogram DIE.
1875 DIE *NewSubprogram(SubprogramDesc *SPD) {
1876 // Get the compile unit context.
1877 CompileUnitDesc *UnitDesc =
1878 static_cast<CompileUnitDesc *>(SPD->getContext());
1879 CompileUnit *Unit = GetBaseCompileUnit();
1881 // Check for pre-existence.
1882 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1883 if (Slot) return Slot;
1885 // Gather the details (simplify add attribute code.)
1886 const std::string &Name = SPD->getName();
1887 const std::string &FullName = SPD->getFullName();
1888 const std::string &LinkageName = SPD->getLinkageName();
1890 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1891 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1892 if (!LinkageName.empty()) {
1893 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1896 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1897 if (!SPD->isStatic())
1898 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1899 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1901 // Add source line info if available.
1902 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1905 Slot = SubprogramDie;
1907 // Add to context owner.
1908 Unit->getDie()->AddChild(SubprogramDie);
1910 // Expose as global.
1911 Unit->AddGlobal(FullName, SubprogramDie);
1913 return SubprogramDie;
1916 /// NewScopeVariable - Create a new scope variable.
1918 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1919 // Get the descriptor.
1920 VariableDesc *VD = DV->getDesc();
1922 // Translate tag to proper Dwarf tag. The result variable is dropped for
1925 switch (VD->getTag()) {
1926 case DW_TAG_return_variable: return NULL;
1927 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1928 case DW_TAG_auto_variable: // fall thru
1929 default: Tag = DW_TAG_variable; break;
1932 // Define variable debug information entry.
1933 DIE *VariableDie = new DIE(Tag);
1934 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1936 // Add source line info if available.
1937 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1939 // Add variable type.
1940 AddType(VariableDie, VD->getType(), Unit);
1942 // Add variable address.
1943 MachineLocation Location;
1944 Location.set(RI->getFrameRegister(*MF),
1945 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1946 AddAddress(VariableDie, DW_AT_location, Location);
1951 /// ConstructScope - Construct the components of a scope.
1953 void ConstructScope(DebugScope *ParentScope,
1954 unsigned ParentStartID, unsigned ParentEndID,
1955 DIE *ParentDie, CompileUnit *Unit) {
1956 // Add variables to scope.
1957 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1958 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1959 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1960 if (VariableDie) ParentDie->AddChild(VariableDie);
1963 // Add nested scopes.
1964 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1965 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1966 // Define the Scope debug information entry.
1967 DebugScope *Scope = Scopes[j];
1968 // FIXME - Ignore inlined functions for the time being.
1969 if (!Scope->getParent()) continue;
1971 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1972 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1974 // Ignore empty scopes.
1975 if (StartID == EndID && StartID != 0) continue;
1976 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1978 if (StartID == ParentStartID && EndID == ParentEndID) {
1979 // Just add stuff to the parent scope.
1980 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1982 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1984 // Add the scope bounds.
1986 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1987 DWLabel("label", StartID));
1989 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1990 DWLabel("func_begin", SubprogramCount));
1993 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1994 DWLabel("label", EndID));
1996 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1997 DWLabel("func_end", SubprogramCount));
2000 // Add the scope contents.
2001 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2002 ParentDie->AddChild(ScopeDie);
2007 /// ConstructRootScope - Construct the scope for the subprogram.
2009 void ConstructRootScope(DebugScope *RootScope) {
2010 // Exit if there is no root scope.
2011 if (!RootScope) return;
2013 // Get the subprogram debug information entry.
2014 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2016 // Get the compile unit context.
2017 CompileUnit *Unit = GetBaseCompileUnit();
2019 // Get the subprogram die.
2020 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2021 assert(SPDie && "Missing subprogram descriptor");
2023 // Add the function bounds.
2024 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2025 DWLabel("func_begin", SubprogramCount));
2026 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2027 DWLabel("func_end", SubprogramCount));
2028 MachineLocation Location(RI->getFrameRegister(*MF));
2029 AddAddress(SPDie, DW_AT_frame_base, Location);
2031 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2034 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2036 void ConstructDefaultScope(MachineFunction *MF) {
2037 // Find the correct subprogram descriptor.
2038 std::vector<SubprogramDesc *> Subprograms;
2039 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2041 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2042 SubprogramDesc *SPD = Subprograms[i];
2044 if (SPD->getName() == MF->getFunction()->getName()) {
2045 // Get the compile unit context.
2046 CompileUnit *Unit = GetBaseCompileUnit();
2048 // Get the subprogram die.
2049 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2050 assert(SPDie && "Missing subprogram descriptor");
2052 // Add the function bounds.
2053 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2054 DWLabel("func_begin", SubprogramCount));
2055 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2056 DWLabel("func_end", SubprogramCount));
2058 MachineLocation Location(RI->getFrameRegister(*MF));
2059 AddAddress(SPDie, DW_AT_frame_base, Location);
2064 // FIXME: This is causing an abort because C++ mangled names are compared
2065 // with their unmangled counterparts. See PR2885. Don't do this assert.
2066 assert(0 && "Couldn't find DIE for machine function!");
2070 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2071 /// tools to recognize the object file contains Dwarf information.
2072 void EmitInitial() {
2073 // Check to see if we already emitted intial headers.
2074 if (didInitial) return;
2077 // Dwarf sections base addresses.
2078 if (TAI->doesDwarfRequireFrameSection()) {
2079 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2080 EmitLabel("section_debug_frame", 0);
2082 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2083 EmitLabel("section_info", 0);
2084 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2085 EmitLabel("section_abbrev", 0);
2086 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2087 EmitLabel("section_aranges", 0);
2088 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2089 EmitLabel("section_macinfo", 0);
2090 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2091 EmitLabel("section_line", 0);
2092 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2093 EmitLabel("section_loc", 0);
2094 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2095 EmitLabel("section_pubnames", 0);
2096 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2097 EmitLabel("section_str", 0);
2098 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2099 EmitLabel("section_ranges", 0);
2101 Asm->SwitchToSection(TAI->getTextSection());
2102 EmitLabel("text_begin", 0);
2103 Asm->SwitchToSection(TAI->getDataSection());
2104 EmitLabel("data_begin", 0);
2107 /// EmitDIE - Recusively Emits a debug information entry.
2109 void EmitDIE(DIE *Die) {
2110 // Get the abbreviation for this DIE.
2111 unsigned AbbrevNumber = Die->getAbbrevNumber();
2112 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2116 // Emit the code (index) for the abbreviation.
2117 Asm->EmitULEB128Bytes(AbbrevNumber);
2120 Asm->EOL(std::string("Abbrev [" +
2121 utostr(AbbrevNumber) +
2122 "] 0x" + utohexstr(Die->getOffset()) +
2123 ":0x" + utohexstr(Die->getSize()) + " " +
2124 TagString(Abbrev->getTag())));
2128 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2129 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2131 // Emit the DIE attribute values.
2132 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2133 unsigned Attr = AbbrevData[i].getAttribute();
2134 unsigned Form = AbbrevData[i].getForm();
2135 assert(Form && "Too many attributes for DIE (check abbreviation)");
2138 case DW_AT_sibling: {
2139 Asm->EmitInt32(Die->SiblingOffset());
2143 // Emit an attribute using the defined form.
2144 Values[i]->EmitValue(*this, Form);
2149 Asm->EOL(AttributeString(Attr));
2152 // Emit the DIE children if any.
2153 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2154 const std::vector<DIE *> &Children = Die->getChildren();
2156 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2157 EmitDIE(Children[j]);
2160 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2164 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2166 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2167 // Get the children.
2168 const std::vector<DIE *> &Children = Die->getChildren();
2170 // If not last sibling and has children then add sibling offset attribute.
2171 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2173 // Record the abbreviation.
2174 AssignAbbrevNumber(Die->getAbbrev());
2176 // Get the abbreviation for this DIE.
2177 unsigned AbbrevNumber = Die->getAbbrevNumber();
2178 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2181 Die->setOffset(Offset);
2183 // Start the size with the size of abbreviation code.
2184 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2186 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2187 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2189 // Size the DIE attribute values.
2190 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2191 // Size attribute value.
2192 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2195 // Size the DIE children if any.
2196 if (!Children.empty()) {
2197 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2198 "Children flag not set");
2200 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2201 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2204 // End of children marker.
2205 Offset += sizeof(int8_t);
2208 Die->setSize(Offset - Die->getOffset());
2212 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2214 void SizeAndOffsets() {
2215 // Process base compile unit.
2216 CompileUnit *Unit = GetBaseCompileUnit();
2217 // Compute size of compile unit header
2218 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2219 sizeof(int16_t) + // DWARF version number
2220 sizeof(int32_t) + // Offset Into Abbrev. Section
2221 sizeof(int8_t); // Pointer Size (in bytes)
2222 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2225 /// EmitDebugInfo - Emit the debug info section.
2227 void EmitDebugInfo() {
2228 // Start debug info section.
2229 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2231 CompileUnit *Unit = GetBaseCompileUnit();
2232 DIE *Die = Unit->getDie();
2233 // Emit the compile units header.
2234 EmitLabel("info_begin", Unit->getID());
2235 // Emit size of content not including length itself
2236 unsigned ContentSize = Die->getSize() +
2237 sizeof(int16_t) + // DWARF version number
2238 sizeof(int32_t) + // Offset Into Abbrev. Section
2239 sizeof(int8_t) + // Pointer Size (in bytes)
2240 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2242 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2243 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2244 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2245 Asm->EOL("Offset Into Abbrev. Section");
2246 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2249 // FIXME - extra padding for gdb bug.
2250 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2251 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2252 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2253 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2254 EmitLabel("info_end", Unit->getID());
2259 /// EmitAbbreviations - Emit the abbreviation section.
2261 void EmitAbbreviations() const {
2262 // Check to see if it is worth the effort.
2263 if (!Abbreviations.empty()) {
2264 // Start the debug abbrev section.
2265 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2267 EmitLabel("abbrev_begin", 0);
2269 // For each abbrevation.
2270 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2271 // Get abbreviation data
2272 const DIEAbbrev *Abbrev = Abbreviations[i];
2274 // Emit the abbrevations code (base 1 index.)
2275 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2276 Asm->EOL("Abbreviation Code");
2278 // Emit the abbreviations data.
2279 Abbrev->Emit(*this);
2284 // Mark end of abbreviations.
2285 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2287 EmitLabel("abbrev_end", 0);
2293 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2294 /// the line matrix.
2296 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2297 // Define last address of section.
2298 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2299 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2300 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2301 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2303 // Mark end of matrix.
2304 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2305 Asm->EmitULEB128Bytes(1); Asm->EOL();
2306 Asm->EmitInt8(1); Asm->EOL();
2309 /// EmitDebugLines - Emit source line information.
2311 void EmitDebugLines() {
2312 // If the target is using .loc/.file, the assembler will be emitting the
2313 // .debug_line table automatically.
2314 if (TAI->hasDotLocAndDotFile())
2317 // Minimum line delta, thus ranging from -10..(255-10).
2318 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2319 // Maximum line delta, thus ranging from -10..(255-10).
2320 const int MaxLineDelta = 255 + MinLineDelta;
2322 // Start the dwarf line section.
2323 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2325 // Construct the section header.
2327 EmitDifference("line_end", 0, "line_begin", 0, true);
2328 Asm->EOL("Length of Source Line Info");
2329 EmitLabel("line_begin", 0);
2331 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2333 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2334 Asm->EOL("Prolog Length");
2335 EmitLabel("line_prolog_begin", 0);
2337 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2339 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2341 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2343 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2345 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2347 // Line number standard opcode encodings argument count
2348 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2349 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2350 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2351 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2352 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2353 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2354 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2355 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2356 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2358 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2359 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2361 // Emit directories.
2362 for (unsigned DirectoryID = 1, NDID = Directories.size();
2363 DirectoryID <= NDID; ++DirectoryID) {
2364 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2366 Asm->EmitInt8(0); Asm->EOL("End of directories");
2369 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2370 SourceID <= NSID; ++SourceID) {
2371 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2372 Asm->EmitString(SourceFile.getName());
2374 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2375 Asm->EOL("Directory #");
2376 Asm->EmitULEB128Bytes(0);
2377 Asm->EOL("Mod date");
2378 Asm->EmitULEB128Bytes(0);
2379 Asm->EOL("File size");
2381 Asm->EmitInt8(0); Asm->EOL("End of files");
2383 EmitLabel("line_prolog_end", 0);
2385 // A sequence for each text section.
2386 unsigned SecSrcLinesSize = SectionSourceLines.size();
2388 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2389 // Isolate current sections line info.
2390 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2393 const Section* S = SectionMap[j + 1];
2394 Asm->EOL(std::string("Section ") + S->getName());
2398 // Dwarf assumes we start with first line of first source file.
2399 unsigned Source = 1;
2402 // Construct rows of the address, source, line, column matrix.
2403 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2404 const SourceLineInfo &LineInfo = LineInfos[i];
2405 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2406 if (!LabelID) continue;
2408 unsigned SourceID = LineInfo.getSourceID();
2409 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2410 unsigned DirectoryID = SourceFile.getDirectoryID();
2412 Asm->EOL(Directories[DirectoryID]
2413 + SourceFile.getName()
2415 + utostr_32(LineInfo.getLine()));
2419 // Define the line address.
2420 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2421 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2422 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2423 EmitReference("label", LabelID); Asm->EOL("Location label");
2425 // If change of source, then switch to the new source.
2426 if (Source != LineInfo.getSourceID()) {
2427 Source = LineInfo.getSourceID();
2428 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2429 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2432 // If change of line.
2433 if (Line != LineInfo.getLine()) {
2434 // Determine offset.
2435 int Offset = LineInfo.getLine() - Line;
2436 int Delta = Offset - MinLineDelta;
2439 Line = LineInfo.getLine();
2441 // If delta is small enough and in range...
2442 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2443 // ... then use fast opcode.
2444 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2446 // ... otherwise use long hand.
2447 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2448 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2449 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2452 // Copy the previous row (different address or source)
2453 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2457 EmitEndOfLineMatrix(j + 1);
2460 if (SecSrcLinesSize == 0)
2461 // Because we're emitting a debug_line section, we still need a line
2462 // table. The linker and friends expect it to exist. If there's nothing to
2463 // put into it, emit an empty table.
2464 EmitEndOfLineMatrix(1);
2466 EmitLabel("line_end", 0);
2471 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2473 void EmitCommonDebugFrame() {
2474 if (!TAI->doesDwarfRequireFrameSection())
2478 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2479 TargetFrameInfo::StackGrowsUp ?
2480 TD->getPointerSize() : -TD->getPointerSize();
2482 // Start the dwarf frame section.
2483 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2485 EmitLabel("debug_frame_common", 0);
2486 EmitDifference("debug_frame_common_end", 0,
2487 "debug_frame_common_begin", 0, true);
2488 Asm->EOL("Length of Common Information Entry");
2490 EmitLabel("debug_frame_common_begin", 0);
2491 Asm->EmitInt32((int)DW_CIE_ID);
2492 Asm->EOL("CIE Identifier Tag");
2493 Asm->EmitInt8(DW_CIE_VERSION);
2494 Asm->EOL("CIE Version");
2495 Asm->EmitString("");
2496 Asm->EOL("CIE Augmentation");
2497 Asm->EmitULEB128Bytes(1);
2498 Asm->EOL("CIE Code Alignment Factor");
2499 Asm->EmitSLEB128Bytes(stackGrowth);
2500 Asm->EOL("CIE Data Alignment Factor");
2501 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2502 Asm->EOL("CIE RA Column");
2504 std::vector<MachineMove> Moves;
2505 RI->getInitialFrameState(Moves);
2507 EmitFrameMoves(NULL, 0, Moves, false);
2509 Asm->EmitAlignment(2, 0, 0, false);
2510 EmitLabel("debug_frame_common_end", 0);
2515 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2517 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2518 if (!TAI->doesDwarfRequireFrameSection())
2521 // Start the dwarf frame section.
2522 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2524 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2525 "debug_frame_begin", DebugFrameInfo.Number, true);
2526 Asm->EOL("Length of Frame Information Entry");
2528 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2530 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2532 Asm->EOL("FDE CIE offset");
2534 EmitReference("func_begin", DebugFrameInfo.Number);
2535 Asm->EOL("FDE initial location");
2536 EmitDifference("func_end", DebugFrameInfo.Number,
2537 "func_begin", DebugFrameInfo.Number);
2538 Asm->EOL("FDE address range");
2540 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2542 Asm->EmitAlignment(2, 0, 0, false);
2543 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2548 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2550 void EmitDebugPubNames() {
2551 // Start the dwarf pubnames section.
2552 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2554 CompileUnit *Unit = GetBaseCompileUnit();
2556 EmitDifference("pubnames_end", Unit->getID(),
2557 "pubnames_begin", Unit->getID(), true);
2558 Asm->EOL("Length of Public Names Info");
2560 EmitLabel("pubnames_begin", Unit->getID());
2562 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2564 EmitSectionOffset("info_begin", "section_info",
2565 Unit->getID(), 0, true, false);
2566 Asm->EOL("Offset of Compilation Unit Info");
2568 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2569 Asm->EOL("Compilation Unit Length");
2571 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2573 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2576 const std::string &Name = GI->first;
2577 DIE * Entity = GI->second;
2579 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2580 Asm->EmitString(Name); Asm->EOL("External Name");
2583 Asm->EmitInt32(0); Asm->EOL("End Mark");
2584 EmitLabel("pubnames_end", Unit->getID());
2589 /// EmitDebugStr - Emit visible names into a debug str section.
2591 void EmitDebugStr() {
2592 // Check to see if it is worth the effort.
2593 if (!StringPool.empty()) {
2594 // Start the dwarf str section.
2595 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2597 // For each of strings in the string pool.
2598 for (unsigned StringID = 1, N = StringPool.size();
2599 StringID <= N; ++StringID) {
2600 // Emit a label for reference from debug information entries.
2601 EmitLabel("string", StringID);
2602 // Emit the string itself.
2603 const std::string &String = StringPool[StringID];
2604 Asm->EmitString(String); Asm->EOL();
2611 /// EmitDebugLoc - Emit visible names into a debug loc section.
2613 void EmitDebugLoc() {
2614 // Start the dwarf loc section.
2615 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2620 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2622 void EmitDebugARanges() {
2623 // Start the dwarf aranges section.
2624 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2628 CompileUnit *Unit = GetBaseCompileUnit();
2630 // Don't include size of length
2631 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2633 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2635 EmitReference("info_begin", Unit->getID());
2636 Asm->EOL("Offset of Compilation Unit Info");
2638 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2640 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2642 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2643 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2646 EmitReference("text_begin", 0); Asm->EOL("Address");
2647 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2649 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2650 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2656 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2658 void EmitDebugRanges() {
2659 // Start the dwarf ranges section.
2660 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2665 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2667 void EmitDebugMacInfo() {
2668 // Start the dwarf macinfo section.
2669 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2674 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2676 void ConstructCompileUnitDIEs() {
2677 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2679 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2680 unsigned ID = MMI->RecordSource(CUW[i]);
2681 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2682 CompileUnits.push_back(Unit);
2686 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2687 /// global variables.
2688 void ConstructGlobalDIEs() {
2689 std::vector<GlobalVariableDesc *> GlobalVariables;
2690 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
2692 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2693 GlobalVariableDesc *GVD = GlobalVariables[i];
2694 NewGlobalVariable(GVD);
2698 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2700 void ConstructSubprogramDIEs() {
2701 std::vector<SubprogramDesc *> Subprograms;
2702 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2704 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2705 SubprogramDesc *SPD = Subprograms[i];
2711 //===--------------------------------------------------------------------===//
2712 // Main entry points.
2714 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2715 : Dwarf(OS, A, T, "dbg")
2717 , AbbreviationsSet(InitAbbreviationsSetSize)
2719 , ValuesSet(InitValuesSetSize)
2724 , SectionSourceLines()
2729 virtual ~DwarfDebug() {
2730 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2731 delete CompileUnits[i];
2732 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2736 /// SetModuleInfo - Set machine module information when it's known that pass
2737 /// manager has created it. Set by the target AsmPrinter.
2738 void SetModuleInfo(MachineModuleInfo *mmi) {
2739 // Make sure initial declarations are made.
2740 if (!MMI && mmi->hasDebugInfo()) {
2744 // Create all the compile unit DIEs.
2745 ConstructCompileUnitDIEs();
2747 // Create DIEs for each of the externally visible global variables.
2748 ConstructGlobalDIEs();
2750 // Create DIEs for each of the externally visible subprograms.
2751 ConstructSubprogramDIEs();
2753 // Prime section data.
2754 SectionMap.insert(TAI->getTextSection());
2756 // Print out .file directives to specify files for .loc directives. These
2757 // are printed out early so that they precede any .loc directives.
2758 if (TAI->hasDotLocAndDotFile()) {
2759 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2760 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2761 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2762 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2763 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2764 assert(AppendOk && "Could not append filename to directory!");
2765 Asm->EmitFile(i, FullPath.toString());
2770 // Emit initial sections
2775 /// BeginModule - Emit all Dwarf sections that should come prior to the
2777 void BeginModule(Module *M) {
2781 /// EndModule - Emit all Dwarf sections that should come after the content.
2784 if (!ShouldEmitDwarf()) return;
2786 // Standard sections final addresses.
2787 Asm->SwitchToSection(TAI->getTextSection());
2788 EmitLabel("text_end", 0);
2789 Asm->SwitchToSection(TAI->getDataSection());
2790 EmitLabel("data_end", 0);
2792 // End text sections.
2793 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2794 Asm->SwitchToSection(SectionMap[i]);
2795 EmitLabel("section_end", i);
2798 // Emit common frame information.
2799 EmitCommonDebugFrame();
2801 // Emit function debug frame information
2802 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2803 E = DebugFrames.end(); I != E; ++I)
2804 EmitFunctionDebugFrame(*I);
2806 // Compute DIE offsets and sizes.
2809 // Emit all the DIEs into a debug info section
2812 // Corresponding abbreviations into a abbrev section.
2813 EmitAbbreviations();
2815 // Emit source line correspondence into a debug line section.
2818 // Emit info into a debug pubnames section.
2819 EmitDebugPubNames();
2821 // Emit info into a debug str section.
2824 // Emit info into a debug loc section.
2827 // Emit info into a debug aranges section.
2830 // Emit info into a debug ranges section.
2833 // Emit info into a debug macinfo section.
2837 /// BeginFunction - Gather pre-function debug information. Assumes being
2838 /// emitted immediately after the function entry point.
2839 void BeginFunction(MachineFunction *MF) {
2842 if (!ShouldEmitDwarf()) return;
2844 // Begin accumulating function debug information.
2845 MMI->BeginFunction(MF);
2847 // Assumes in correct section after the entry point.
2848 EmitLabel("func_begin", ++SubprogramCount);
2850 // Emit label for the implicitly defined dbg.stoppoint at the start of
2852 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2853 if (!LineInfos.empty()) {
2854 const SourceLineInfo &LineInfo = LineInfos[0];
2855 Asm->printLabel(LineInfo.getLabelID());
2859 /// EndFunction - Gather and emit post-function debug information.
2861 void EndFunction(MachineFunction *MF) {
2862 if (!ShouldEmitDwarf()) return;
2864 // Define end label for subprogram.
2865 EmitLabel("func_end", SubprogramCount);
2867 // Get function line info.
2868 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2870 if (!LineInfos.empty()) {
2871 // Get section line info.
2872 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2873 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2874 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2875 // Append the function info to section info.
2876 SectionLineInfos.insert(SectionLineInfos.end(),
2877 LineInfos.begin(), LineInfos.end());
2880 // Construct scopes for subprogram.
2881 if (MMI->getRootScope())
2882 ConstructRootScope(MMI->getRootScope());
2884 // FIXME: This is wrong. We are essentially getting past a problem with
2885 // debug information not being able to handle unreachable blocks that have
2886 // debug information in them. In particular, those unreachable blocks that
2887 // have "region end" info in them. That situation results in the "root
2888 // scope" not being created. If that's the case, then emit a "default"
2889 // scope, i.e., one that encompasses the whole function. This isn't
2890 // desirable. And a better way of handling this (and all of the debugging
2891 // information) needs to be explored.
2892 ConstructDefaultScope(MF);
2894 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2895 MMI->getFrameMoves()));
2899 //===----------------------------------------------------------------------===//
2900 /// DwarfException - Emits Dwarf exception handling directives.
2902 class DwarfException : public Dwarf {
2905 struct FunctionEHFrameInfo {
2908 unsigned PersonalityIndex;
2910 bool hasLandingPads;
2911 std::vector<MachineMove> Moves;
2912 const Function * function;
2914 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2916 const std::vector<MachineMove> &M,
2918 FnName(FN), Number(Num), PersonalityIndex(P),
2919 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2922 std::vector<FunctionEHFrameInfo> EHFrames;
2924 /// shouldEmitTable - Per-function flag to indicate if EH tables should
2926 bool shouldEmitTable;
2928 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
2929 /// should be emitted.
2930 bool shouldEmitMoves;
2932 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
2933 /// should be emitted.
2934 bool shouldEmitTableModule;
2936 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
2937 /// should be emitted.
2938 bool shouldEmitMovesModule;
2940 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2942 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2943 // Size and sign of stack growth.
2945 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2946 TargetFrameInfo::StackGrowsUp ?
2947 TD->getPointerSize() : -TD->getPointerSize();
2949 // Begin eh frame section.
2950 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2951 O << "EH_frame" << Index << ":\n";
2952 EmitLabel("section_eh_frame", Index);
2954 // Define base labels.
2955 EmitLabel("eh_frame_common", Index);
2957 // Define the eh frame length.
2958 EmitDifference("eh_frame_common_end", Index,
2959 "eh_frame_common_begin", Index, true);
2960 Asm->EOL("Length of Common Information Entry");
2963 EmitLabel("eh_frame_common_begin", Index);
2964 Asm->EmitInt32((int)0);
2965 Asm->EOL("CIE Identifier Tag");
2966 Asm->EmitInt8(DW_CIE_VERSION);
2967 Asm->EOL("CIE Version");
2969 // The personality presence indicates that language specific information
2970 // will show up in the eh frame.
2971 Asm->EmitString(Personality ? "zPLR" : "zR");
2972 Asm->EOL("CIE Augmentation");
2974 // Round out reader.
2975 Asm->EmitULEB128Bytes(1);
2976 Asm->EOL("CIE Code Alignment Factor");
2977 Asm->EmitSLEB128Bytes(stackGrowth);
2978 Asm->EOL("CIE Data Alignment Factor");
2979 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2980 Asm->EOL("CIE Return Address Column");
2982 // If there is a personality, we need to indicate the functions location.
2984 Asm->EmitULEB128Bytes(7);
2985 Asm->EOL("Augmentation Size");
2987 if (TAI->getNeedsIndirectEncoding()) {
2988 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2989 Asm->EOL("Personality (pcrel sdata4 indirect)");
2991 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2992 Asm->EOL("Personality (pcrel sdata4)");
2995 PrintRelDirective(true);
2996 O << TAI->getPersonalityPrefix();
2997 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2998 O << TAI->getPersonalitySuffix();
2999 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3000 O << "-" << TAI->getPCSymbol();
3001 Asm->EOL("Personality");
3003 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3004 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3005 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3006 Asm->EOL("FDE Encoding (pcrel sdata4)");
3008 Asm->EmitULEB128Bytes(1);
3009 Asm->EOL("Augmentation Size");
3010 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3011 Asm->EOL("FDE Encoding (pcrel sdata4)");
3014 // Indicate locations of general callee saved registers in frame.
3015 std::vector<MachineMove> Moves;
3016 RI->getInitialFrameState(Moves);
3017 EmitFrameMoves(NULL, 0, Moves, true);
3019 // On Darwin the linker honors the alignment of eh_frame, which means it
3020 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3021 // you get holes which confuse readers of eh_frame.
3022 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3024 EmitLabel("eh_frame_common_end", Index);
3029 /// EmitEHFrame - Emit function exception frame information.
3031 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3032 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3034 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3036 // Externally visible entry into the functions eh frame info.
3037 // If the corresponding function is static, this should not be
3038 // externally visible.
3039 if (linkage != Function::InternalLinkage) {
3040 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3041 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3044 // If corresponding function is weak definition, this should be too.
3045 if ((linkage == Function::WeakLinkage ||
3046 linkage == Function::LinkOnceLinkage) &&
3047 TAI->getWeakDefDirective())
3048 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3050 // If there are no calls then you can't unwind. This may mean we can
3051 // omit the EH Frame, but some environments do not handle weak absolute
3053 // If UnwindTablesMandatory is set we cannot do this optimization; the
3054 // unwind info is to be available for non-EH uses.
3055 if (!EHFrameInfo.hasCalls &&
3056 !UnwindTablesMandatory &&
3057 ((linkage != Function::WeakLinkage &&
3058 linkage != Function::LinkOnceLinkage) ||
3059 !TAI->getWeakDefDirective() ||
3060 TAI->getSupportsWeakOmittedEHFrame()))
3062 O << EHFrameInfo.FnName << " = 0\n";
3063 // This name has no connection to the function, so it might get
3064 // dead-stripped when the function is not, erroneously. Prohibit
3065 // dead-stripping unconditionally.
3066 if (const char *UsedDirective = TAI->getUsedDirective())
3067 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3069 O << EHFrameInfo.FnName << ":\n";
3072 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3073 "eh_frame_begin", EHFrameInfo.Number, true);
3074 Asm->EOL("Length of Frame Information Entry");
3076 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3078 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3079 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3081 Asm->EOL("FDE CIE offset");
3083 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3084 Asm->EOL("FDE initial location");
3085 EmitDifference("eh_func_end", EHFrameInfo.Number,
3086 "eh_func_begin", EHFrameInfo.Number, true);
3087 Asm->EOL("FDE address range");
3089 // If there is a personality and landing pads then point to the language
3090 // specific data area in the exception table.
3091 if (EHFrameInfo.PersonalityIndex) {
3092 Asm->EmitULEB128Bytes(4);
3093 Asm->EOL("Augmentation size");
3095 if (EHFrameInfo.hasLandingPads)
3096 EmitReference("exception", EHFrameInfo.Number, true, true);
3098 Asm->EmitInt32((int)0);
3099 Asm->EOL("Language Specific Data Area");
3101 Asm->EmitULEB128Bytes(0);
3102 Asm->EOL("Augmentation size");
3105 // Indicate locations of function specific callee saved registers in
3107 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3109 // On Darwin the linker honors the alignment of eh_frame, which means it
3110 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3111 // you get holes which confuse readers of eh_frame.
3112 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3114 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3116 // If the function is marked used, this table should be also. We cannot
3117 // make the mark unconditional in this case, since retaining the table
3118 // also retains the function in this case, and there is code around
3119 // that depends on unused functions (calling undefined externals) being
3120 // dead-stripped to link correctly. Yes, there really is.
3121 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3122 if (const char *UsedDirective = TAI->getUsedDirective())
3123 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3127 /// EmitExceptionTable - Emit landing pads and actions.
3129 /// The general organization of the table is complex, but the basic concepts
3130 /// are easy. First there is a header which describes the location and
3131 /// organization of the three components that follow.
3132 /// 1. The landing pad site information describes the range of code covered
3133 /// by the try. In our case it's an accumulation of the ranges covered
3134 /// by the invokes in the try. There is also a reference to the landing
3135 /// pad that handles the exception once processed. Finally an index into
3136 /// the actions table.
3137 /// 2. The action table, in our case, is composed of pairs of type ids
3138 /// and next action offset. Starting with the action index from the
3139 /// landing pad site, each type Id is checked for a match to the current
3140 /// exception. If it matches then the exception and type id are passed
3141 /// on to the landing pad. Otherwise the next action is looked up. This
3142 /// chain is terminated with a next action of zero. If no type id is
3143 /// found the the frame is unwound and handling continues.
3144 /// 3. Type id table contains references to all the C++ typeinfo for all
3145 /// catches in the function. This tables is reversed indexed base 1.
3147 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3148 static unsigned SharedTypeIds(const LandingPadInfo *L,
3149 const LandingPadInfo *R) {
3150 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3151 unsigned LSize = LIds.size(), RSize = RIds.size();
3152 unsigned MinSize = LSize < RSize ? LSize : RSize;
3155 for (; Count != MinSize; ++Count)
3156 if (LIds[Count] != RIds[Count])
3162 /// PadLT - Order landing pads lexicographically by type id.
3163 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3164 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3165 unsigned LSize = LIds.size(), RSize = RIds.size();
3166 unsigned MinSize = LSize < RSize ? LSize : RSize;
3168 for (unsigned i = 0; i != MinSize; ++i)
3169 if (LIds[i] != RIds[i])
3170 return LIds[i] < RIds[i];
3172 return LSize < RSize;
3176 static inline unsigned getEmptyKey() { return -1U; }
3177 static inline unsigned getTombstoneKey() { return -2U; }
3178 static unsigned getHashValue(const unsigned &Key) { return Key; }
3179 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3180 static bool isPod() { return true; }
3183 /// ActionEntry - Structure describing an entry in the actions table.
3184 struct ActionEntry {
3185 int ValueForTypeID; // The value to write - may not be equal to the type id.
3187 struct ActionEntry *Previous;
3190 /// PadRange - Structure holding a try-range and the associated landing pad.
3192 // The index of the landing pad.
3194 // The index of the begin and end labels in the landing pad's label lists.
3195 unsigned RangeIndex;
3198 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3200 /// CallSiteEntry - Structure describing an entry in the call-site table.
3201 struct CallSiteEntry {
3202 // The 'try-range' is BeginLabel .. EndLabel.
3203 unsigned BeginLabel; // zero indicates the start of the function.
3204 unsigned EndLabel; // zero indicates the end of the function.
3205 // The landing pad starts at PadLabel.
3206 unsigned PadLabel; // zero indicates that there is no landing pad.
3210 void EmitExceptionTable() {
3211 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3212 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3213 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3214 if (PadInfos.empty()) return;
3216 // Sort the landing pads in order of their type ids. This is used to fold
3217 // duplicate actions.
3218 SmallVector<const LandingPadInfo *, 64> LandingPads;
3219 LandingPads.reserve(PadInfos.size());
3220 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3221 LandingPads.push_back(&PadInfos[i]);
3222 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3224 // Negative type ids index into FilterIds, positive type ids index into
3225 // TypeInfos. The value written for a positive type id is just the type
3226 // id itself. For a negative type id, however, the value written is the
3227 // (negative) byte offset of the corresponding FilterIds entry. The byte
3228 // offset is usually equal to the type id, because the FilterIds entries
3229 // are written using a variable width encoding which outputs one byte per
3230 // entry as long as the value written is not too large, but can differ.
3231 // This kind of complication does not occur for positive type ids because
3232 // type infos are output using a fixed width encoding.
3233 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3234 SmallVector<int, 16> FilterOffsets;
3235 FilterOffsets.reserve(FilterIds.size());
3237 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3238 E = FilterIds.end(); I != E; ++I) {
3239 FilterOffsets.push_back(Offset);
3240 Offset -= TargetAsmInfo::getULEB128Size(*I);
3243 // Compute the actions table and gather the first action index for each
3244 // landing pad site.
3245 SmallVector<ActionEntry, 32> Actions;
3246 SmallVector<unsigned, 64> FirstActions;
3247 FirstActions.reserve(LandingPads.size());
3249 int FirstAction = 0;
3250 unsigned SizeActions = 0;
3251 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3252 const LandingPadInfo *LP = LandingPads[i];
3253 const std::vector<int> &TypeIds = LP->TypeIds;
3254 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3255 unsigned SizeSiteActions = 0;
3257 if (NumShared < TypeIds.size()) {
3258 unsigned SizeAction = 0;
3259 ActionEntry *PrevAction = 0;
3262 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3263 assert(Actions.size());
3264 PrevAction = &Actions.back();
3265 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3266 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3267 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3269 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3270 SizeAction += -PrevAction->NextAction;
3271 PrevAction = PrevAction->Previous;
3275 // Compute the actions.
3276 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3277 int TypeID = TypeIds[I];
3278 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3279 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3280 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3282 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3283 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3284 SizeSiteActions += SizeAction;
3286 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3287 Actions.push_back(Action);
3289 PrevAction = &Actions.back();
3292 // Record the first action of the landing pad site.
3293 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3294 } // else identical - re-use previous FirstAction
3296 FirstActions.push_back(FirstAction);
3298 // Compute this sites contribution to size.
3299 SizeActions += SizeSiteActions;
3302 // Compute the call-site table. The entry for an invoke has a try-range
3303 // containing the call, a non-zero landing pad and an appropriate action.
3304 // The entry for an ordinary call has a try-range containing the call and
3305 // zero for the landing pad and the action. Calls marked 'nounwind' have
3306 // no entry and must not be contained in the try-range of any entry - they
3307 // form gaps in the table. Entries must be ordered by try-range address.
3308 SmallVector<CallSiteEntry, 64> CallSites;
3310 RangeMapType PadMap;
3311 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3312 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3313 // try-ranges for them need be deduced.
3314 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3315 const LandingPadInfo *LandingPad = LandingPads[i];
3316 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3317 unsigned BeginLabel = LandingPad->BeginLabels[j];
3318 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3319 PadRange P = { i, j };
3320 PadMap[BeginLabel] = P;
3324 // The end label of the previous invoke or nounwind try-range.
3325 unsigned LastLabel = 0;
3327 // Whether there is a potentially throwing instruction (currently this means
3328 // an ordinary call) between the end of the previous try-range and now.
3329 bool SawPotentiallyThrowing = false;
3331 // Whether the last callsite entry was for an invoke.
3332 bool PreviousIsInvoke = false;
3334 // Visit all instructions in order of address.
3335 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3337 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3339 if (!MI->isLabel()) {
3340 SawPotentiallyThrowing |= MI->getDesc().isCall();
3344 unsigned BeginLabel = MI->getOperand(0).getImm();
3345 assert(BeginLabel && "Invalid label!");
3347 // End of the previous try-range?
3348 if (BeginLabel == LastLabel)
3349 SawPotentiallyThrowing = false;
3351 // Beginning of a new try-range?
3352 RangeMapType::iterator L = PadMap.find(BeginLabel);
3353 if (L == PadMap.end())
3354 // Nope, it was just some random label.
3357 PadRange P = L->second;
3358 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3360 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3361 "Inconsistent landing pad map!");
3363 // If some instruction between the previous try-range and this one may
3364 // throw, create a call-site entry with no landing pad for the region
3365 // between the try-ranges.
3366 if (SawPotentiallyThrowing) {
3367 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3368 CallSites.push_back(Site);
3369 PreviousIsInvoke = false;
3372 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3373 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3375 if (LandingPad->LandingPadLabel) {
3376 // This try-range is for an invoke.
3377 CallSiteEntry Site = {BeginLabel, LastLabel,
3378 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3380 // Try to merge with the previous call-site.
3381 if (PreviousIsInvoke) {
3382 CallSiteEntry &Prev = CallSites.back();
3383 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3384 // Extend the range of the previous entry.
3385 Prev.EndLabel = Site.EndLabel;
3390 // Otherwise, create a new call-site.
3391 CallSites.push_back(Site);
3392 PreviousIsInvoke = true;
3395 PreviousIsInvoke = false;
3399 // If some instruction between the previous try-range and the end of the
3400 // function may throw, create a call-site entry with no landing pad for the
3401 // region following the try-range.
3402 if (SawPotentiallyThrowing) {
3403 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3404 CallSites.push_back(Site);
3410 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3411 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3412 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3413 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3416 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3417 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3420 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3421 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3423 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3424 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3425 SizeSites + SizeActions + SizeTypes;
3427 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3428 sizeof(int8_t) + // TType format
3429 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3432 unsigned SizeAlign = (4 - TotalSize) & 3;
3434 // Begin the exception table.
3435 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3436 Asm->EmitAlignment(2, 0, 0, false);
3437 O << "GCC_except_table" << SubprogramCount << ":\n";
3438 for (unsigned i = 0; i != SizeAlign; ++i) {
3440 Asm->EOL("Padding");
3442 EmitLabel("exception", SubprogramCount);
3445 Asm->EmitInt8(DW_EH_PE_omit);
3446 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3447 Asm->EmitInt8(DW_EH_PE_absptr);
3448 Asm->EOL("TType format (DW_EH_PE_absptr)");
3449 Asm->EmitULEB128Bytes(TypeOffset);
3450 Asm->EOL("TType base offset");
3451 Asm->EmitInt8(DW_EH_PE_udata4);
3452 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3453 Asm->EmitULEB128Bytes(SizeSites);
3454 Asm->EOL("Call-site table length");
3456 // Emit the landing pad site information.
3457 for (unsigned i = 0; i < CallSites.size(); ++i) {
3458 CallSiteEntry &S = CallSites[i];
3459 const char *BeginTag;
3460 unsigned BeginNumber;
3462 if (!S.BeginLabel) {
3463 BeginTag = "eh_func_begin";
3464 BeginNumber = SubprogramCount;
3467 BeginNumber = S.BeginLabel;
3470 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3472 Asm->EOL("Region start");
3475 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3478 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3480 Asm->EOL("Region length");
3485 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3487 Asm->EOL("Landing pad");
3489 Asm->EmitULEB128Bytes(S.Action);
3493 // Emit the actions.
3494 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3495 ActionEntry &Action = Actions[I];
3497 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3498 Asm->EOL("TypeInfo index");
3499 Asm->EmitSLEB128Bytes(Action.NextAction);
3500 Asm->EOL("Next action");
3503 // Emit the type ids.
3504 for (unsigned M = TypeInfos.size(); M; --M) {
3505 GlobalVariable *GV = TypeInfos[M - 1];
3507 PrintRelDirective();
3510 O << Asm->getGlobalLinkName(GV);
3514 Asm->EOL("TypeInfo");
3517 // Emit the filter typeids.
3518 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3519 unsigned TypeID = FilterIds[j];
3520 Asm->EmitULEB128Bytes(TypeID);
3521 Asm->EOL("Filter TypeInfo index");
3524 Asm->EmitAlignment(2, 0, 0, false);
3528 //===--------------------------------------------------------------------===//
3529 // Main entry points.
3531 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3532 : Dwarf(OS, A, T, "eh")
3533 , shouldEmitTable(false)
3534 , shouldEmitMoves(false)
3535 , shouldEmitTableModule(false)
3536 , shouldEmitMovesModule(false)
3539 virtual ~DwarfException() {}
3541 /// SetModuleInfo - Set machine module information when it's known that pass
3542 /// manager has created it. Set by the target AsmPrinter.
3543 void SetModuleInfo(MachineModuleInfo *mmi) {
3547 /// BeginModule - Emit all exception information that should come prior to the
3549 void BeginModule(Module *M) {
3553 /// EndModule - Emit all exception information that should come after the
3556 if (shouldEmitMovesModule || shouldEmitTableModule) {
3557 const std::vector<Function *> Personalities = MMI->getPersonalities();
3558 for (unsigned i =0; i < Personalities.size(); ++i)
3559 EmitCommonEHFrame(Personalities[i], i);
3561 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3562 E = EHFrames.end(); I != E; ++I)
3567 /// BeginFunction - Gather pre-function exception information. Assumes being
3568 /// emitted immediately after the function entry point.
3569 void BeginFunction(MachineFunction *MF) {
3571 shouldEmitTable = shouldEmitMoves = false;
3572 if (MMI && TAI->doesSupportExceptionHandling()) {
3574 // Map all labels and get rid of any dead landing pads.
3575 MMI->TidyLandingPads();
3576 // If any landing pads survive, we need an EH table.
3577 if (MMI->getLandingPads().size())
3578 shouldEmitTable = true;
3580 // See if we need frame move info.
3581 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3582 shouldEmitMoves = true;
3584 if (shouldEmitMoves || shouldEmitTable)
3585 // Assumes in correct section after the entry point.
3586 EmitLabel("eh_func_begin", ++SubprogramCount);
3588 shouldEmitTableModule |= shouldEmitTable;
3589 shouldEmitMovesModule |= shouldEmitMoves;
3592 /// EndFunction - Gather and emit post-function exception information.
3594 void EndFunction() {
3595 if (shouldEmitMoves || shouldEmitTable) {
3596 EmitLabel("eh_func_end", SubprogramCount);
3597 EmitExceptionTable();
3599 // Save EH frame information
3601 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3603 MMI->getPersonalityIndex(),
3604 MF->getFrameInfo()->hasCalls(),
3605 !MMI->getLandingPads().empty(),
3606 MMI->getFrameMoves(),
3607 MF->getFunction()));
3612 } // End of namespace llvm
3614 //===----------------------------------------------------------------------===//
3616 /// Emit - Print the abbreviation using the specified Dwarf writer.
3618 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3619 // Emit its Dwarf tag type.
3620 DD.getAsm()->EmitULEB128Bytes(Tag);
3621 DD.getAsm()->EOL(TagString(Tag));
3623 // Emit whether it has children DIEs.
3624 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3625 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3627 // For each attribute description.
3628 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3629 const DIEAbbrevData &AttrData = Data[i];
3631 // Emit attribute type.
3632 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3633 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3636 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3637 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3640 // Mark end of abbreviation.
3641 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3642 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3646 void DIEAbbrev::print(std::ostream &O) {
3647 O << "Abbreviation @"
3648 << std::hex << (intptr_t)this << std::dec
3652 << ChildrenString(ChildrenFlag)
3655 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3657 << AttributeString(Data[i].getAttribute())
3659 << FormEncodingString(Data[i].getForm())
3663 void DIEAbbrev::dump() { print(cerr); }
3666 //===----------------------------------------------------------------------===//
3669 void DIEValue::dump() {
3674 //===----------------------------------------------------------------------===//
3676 /// EmitValue - Emit integer of appropriate size.
3678 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3680 case DW_FORM_flag: // Fall thru
3681 case DW_FORM_ref1: // Fall thru
3682 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3683 case DW_FORM_ref2: // Fall thru
3684 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3685 case DW_FORM_ref4: // Fall thru
3686 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3687 case DW_FORM_ref8: // Fall thru
3688 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3689 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3690 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3691 default: assert(0 && "DIE Value form not supported yet"); break;
3695 /// SizeOf - Determine size of integer value in bytes.
3697 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3699 case DW_FORM_flag: // Fall thru
3700 case DW_FORM_ref1: // Fall thru
3701 case DW_FORM_data1: return sizeof(int8_t);
3702 case DW_FORM_ref2: // Fall thru
3703 case DW_FORM_data2: return sizeof(int16_t);
3704 case DW_FORM_ref4: // Fall thru
3705 case DW_FORM_data4: return sizeof(int32_t);
3706 case DW_FORM_ref8: // Fall thru
3707 case DW_FORM_data8: return sizeof(int64_t);
3708 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
3709 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
3710 default: assert(0 && "DIE Value form not supported yet"); break;
3715 //===----------------------------------------------------------------------===//
3717 /// EmitValue - Emit string value.
3719 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3720 DD.getAsm()->EmitString(String);
3723 //===----------------------------------------------------------------------===//
3725 /// EmitValue - Emit label value.
3727 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3728 bool IsSmall = Form == DW_FORM_data4;
3729 DD.EmitReference(Label, false, IsSmall);
3732 /// SizeOf - Determine size of label value in bytes.
3734 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3735 if (Form == DW_FORM_data4) return 4;
3736 return DD.getTargetData()->getPointerSize();
3739 //===----------------------------------------------------------------------===//
3741 /// EmitValue - Emit label value.
3743 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3744 bool IsSmall = Form == DW_FORM_data4;
3745 DD.EmitReference(Label, false, IsSmall);
3748 /// SizeOf - Determine size of label value in bytes.
3750 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3751 if (Form == DW_FORM_data4) return 4;
3752 return DD.getTargetData()->getPointerSize();
3755 //===----------------------------------------------------------------------===//
3757 /// EmitValue - Emit delta value.
3759 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
3760 bool IsSmall = Form == DW_FORM_data4;
3761 DD.EmitSectionOffset(Label.Tag, Section.Tag,
3762 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
3765 /// SizeOf - Determine size of delta value in bytes.
3767 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3768 if (Form == DW_FORM_data4) return 4;
3769 return DD.getTargetData()->getPointerSize();
3772 //===----------------------------------------------------------------------===//
3774 /// EmitValue - Emit delta value.
3776 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3777 bool IsSmall = Form == DW_FORM_data4;
3778 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3781 /// SizeOf - Determine size of delta value in bytes.
3783 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3784 if (Form == DW_FORM_data4) return 4;
3785 return DD.getTargetData()->getPointerSize();
3788 //===----------------------------------------------------------------------===//
3790 /// EmitValue - Emit debug information entry offset.
3792 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3793 DD.getAsm()->EmitInt32(Entry->getOffset());
3796 //===----------------------------------------------------------------------===//
3798 /// ComputeSize - calculate the size of the block.
3800 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3802 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3804 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3805 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3811 /// EmitValue - Emit block data.
3813 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3815 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3816 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3817 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3818 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3819 default: assert(0 && "Improper form for block"); break;
3822 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3824 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3826 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3830 /// SizeOf - Determine size of block data in bytes.
3832 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3834 case DW_FORM_block1: return Size + sizeof(int8_t);
3835 case DW_FORM_block2: return Size + sizeof(int16_t);
3836 case DW_FORM_block4: return Size + sizeof(int32_t);
3837 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
3838 default: assert(0 && "Improper form for block"); break;
3843 //===----------------------------------------------------------------------===//
3844 /// DIE Implementation
3847 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3851 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3853 void DIE::AddSiblingOffset() {
3854 DIEInteger *DI = new DIEInteger(0);
3855 Values.insert(Values.begin(), DI);
3856 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3859 /// Profile - Used to gather unique data for the value folding set.
3861 void DIE::Profile(FoldingSetNodeID &ID) {
3864 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3865 ID.AddPointer(Children[i]);
3867 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3868 ID.AddPointer(Values[j]);
3872 void DIE::print(std::ostream &O, unsigned IncIndent) {
3873 static unsigned IndentCount = 0;
3874 IndentCount += IncIndent;
3875 const std::string Indent(IndentCount, ' ');
3876 bool isBlock = Abbrev.getTag() == 0;
3881 << "0x" << std::hex << (intptr_t)this << std::dec
3882 << ", Offset: " << Offset
3883 << ", Size: " << Size
3887 << TagString(Abbrev.getTag())
3889 << ChildrenString(Abbrev.getChildrenFlag());
3891 O << "Size: " << Size;
3895 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
3898 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3902 O << AttributeString(Data[i].getAttribute());
3904 O << "Blk[" << i << "]";
3907 << FormEncodingString(Data[i].getForm())
3909 Values[i]->print(O);
3914 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3915 Children[j]->print(O, 4);
3918 if (!isBlock) O << "\n";
3919 IndentCount -= IncIndent;
3927 //===----------------------------------------------------------------------===//
3928 /// DwarfWriter Implementation
3931 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
3932 const TargetAsmInfo *T) {
3933 DE = new DwarfException(OS, A, T);
3934 DD = new DwarfDebug(OS, A, T);
3937 DwarfWriter::~DwarfWriter() {
3942 /// SetModuleInfo - Set machine module info when it's known that pass manager
3943 /// has created it. Set by the target AsmPrinter.
3944 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3945 DD->SetModuleInfo(MMI);
3946 DE->SetModuleInfo(MMI);
3949 /// BeginModule - Emit all Dwarf sections that should come prior to the
3951 void DwarfWriter::BeginModule(Module *M) {
3956 /// EndModule - Emit all Dwarf sections that should come after the content.
3958 void DwarfWriter::EndModule() {
3963 /// BeginFunction - Gather pre-function debug information. Assumes being
3964 /// emitted immediately after the function entry point.
3965 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3966 DE->BeginFunction(MF);
3967 DD->BeginFunction(MF);
3970 /// EndFunction - Gather and emit post-function debug information.
3972 void DwarfWriter::EndFunction(MachineFunction *MF) {
3973 DD->EndFunction(MF);
3976 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
3977 // Clear function debug information.