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) {
1441 DIE Buffer(DW_TAG_base_type);
1442 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1443 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1444 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1445 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1446 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1449 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1451 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1452 DIE *Die = ConstructPointerType(Unit, Name);
1453 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1456 /// ConstructPointerType - Construct a new pointer type.
1458 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1459 DIE Buffer(DW_TAG_pointer_type);
1460 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1461 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1462 return Unit->AddDie(Buffer);
1465 /// AddType - Add a new type attribute to the specified entity.
1467 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1469 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1471 // Check for pre-existence.
1472 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1474 // If it exists then use the existing value.
1476 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1480 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1481 // FIXME - Not sure why programs and variables are coming through here.
1482 // Short cut for handling subprogram types (not really a TyDesc.)
1483 AddPointerType(Entity, Unit, SubprogramTy->getName());
1484 } else if (GlobalVariableDesc *GlobalTy =
1485 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1486 // FIXME - Not sure why programs and variables are coming through here.
1487 // Short cut for handling global variable types (not really a TyDesc.)
1488 AddPointerType(Entity, Unit, GlobalTy->getName());
1491 Slot = NewDIEntry();
1494 DIE Buffer(DW_TAG_base_type);
1495 ConstructType(Buffer, TyDesc, Unit);
1497 // Add debug information entry to entity and unit.
1498 DIE *Die = Unit->AddDie(Buffer);
1499 SetDIEntry(Slot, Die);
1500 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1505 /// ConstructType - Adds all the required attributes to the type.
1507 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1508 // Get core information.
1509 const std::string &Name = TyDesc->getName();
1510 uint64_t Size = TyDesc->getSize() >> 3;
1512 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1513 // Fundamental types like int, float, bool
1514 Buffer.setTag(DW_TAG_base_type);
1515 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1516 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1518 unsigned Tag = DerivedTy->getTag();
1519 // FIXME - Workaround for templates.
1520 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1521 // Pointers, typedefs et al.
1523 // Map to main type, void will not have a type.
1524 if (TypeDesc *FromTy = DerivedTy->getFromType())
1525 AddType(&Buffer, FromTy, Unit);
1526 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1528 unsigned Tag = CompTy->getTag();
1530 // Set tag accordingly.
1531 if (Tag == DW_TAG_vector_type)
1532 Buffer.setTag(DW_TAG_array_type);
1536 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1539 case DW_TAG_vector_type:
1540 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1542 case DW_TAG_array_type: {
1543 // Add element type.
1544 if (TypeDesc *FromTy = CompTy->getFromType())
1545 AddType(&Buffer, FromTy, Unit);
1547 // Don't emit size attribute.
1550 // Construct an anonymous type for index type.
1551 DIE Buffer(DW_TAG_base_type);
1552 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
1553 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1554 DIE *IndexTy = Unit->AddDie(Buffer);
1556 // Add subranges to array type.
1557 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1558 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1559 int64_t Lo = SRD->getLo();
1560 int64_t Hi = SRD->getHi();
1561 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1563 // If a range is available.
1565 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1566 // Only add low if non-zero.
1567 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1568 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1571 Buffer.AddChild(Subrange);
1575 case DW_TAG_structure_type:
1576 case DW_TAG_union_type: {
1577 // Add elements to structure type.
1578 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1579 DebugInfoDesc *Element = Elements[i];
1581 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1582 // Add field or base class.
1583 unsigned Tag = MemberDesc->getTag();
1585 // Extract the basic information.
1586 const std::string &Name = MemberDesc->getName();
1587 uint64_t Size = MemberDesc->getSize();
1588 uint64_t Align = MemberDesc->getAlign();
1589 uint64_t Offset = MemberDesc->getOffset();
1591 // Construct member debug information entry.
1592 DIE *Member = new DIE(Tag);
1594 // Add name if not "".
1596 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1598 // Add location if available.
1599 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1601 // Most of the time the field info is the same as the members.
1602 uint64_t FieldSize = Size;
1603 uint64_t FieldAlign = Align;
1604 uint64_t FieldOffset = Offset;
1606 // Set the member type.
1607 TypeDesc *FromTy = MemberDesc->getFromType();
1608 AddType(Member, FromTy, Unit);
1610 // Walk up typedefs until a real size is found.
1612 if (FromTy->getTag() != DW_TAG_typedef) {
1613 FieldSize = FromTy->getSize();
1614 FieldAlign = FromTy->getAlign();
1618 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1621 // Unless we have a bit field.
1622 if (Tag == DW_TAG_member && FieldSize != Size) {
1623 // Construct the alignment mask.
1624 uint64_t AlignMask = ~(FieldAlign - 1);
1625 // Determine the high bit + 1 of the declared size.
1626 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1627 // Work backwards to determine the base offset of the field.
1628 FieldOffset = HiMark - FieldSize;
1629 // Now normalize offset to the field.
1630 Offset -= FieldOffset;
1632 // Maybe we need to work from the other end.
1633 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1635 // Add size and offset.
1636 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1637 AddUInt(Member, DW_AT_bit_size, 0, Size);
1638 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1641 // Add computation for offset.
1642 DIEBlock *Block = new DIEBlock();
1643 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1644 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1645 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1647 // Add accessibility (public default unless is base class.
1648 if (MemberDesc->isProtected()) {
1649 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1650 } else if (MemberDesc->isPrivate()) {
1651 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1652 } else if (Tag == DW_TAG_inheritance) {
1653 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1656 Buffer.AddChild(Member);
1657 } else if (GlobalVariableDesc *StaticDesc =
1658 dyn_cast<GlobalVariableDesc>(Element)) {
1659 // Add static member.
1661 // Construct member debug information entry.
1662 DIE *Static = new DIE(DW_TAG_variable);
1664 // Add name and mangled name.
1665 const std::string &Name = StaticDesc->getName();
1666 const std::string &LinkageName = StaticDesc->getLinkageName();
1667 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1668 if (!LinkageName.empty()) {
1669 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1674 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1677 if (TypeDesc *StaticTy = StaticDesc->getType())
1678 AddType(Static, StaticTy, Unit);
1681 if (!StaticDesc->isStatic())
1682 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1683 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1685 Buffer.AddChild(Static);
1686 } else if (SubprogramDesc *MethodDesc =
1687 dyn_cast<SubprogramDesc>(Element)) {
1688 // Add member function.
1690 // Construct member debug information entry.
1691 DIE *Method = new DIE(DW_TAG_subprogram);
1693 // Add name and mangled name.
1694 const std::string &Name = MethodDesc->getName();
1695 const std::string &LinkageName = MethodDesc->getLinkageName();
1697 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1698 bool IsCTor = TyDesc->getName() == Name;
1700 if (!LinkageName.empty()) {
1701 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1706 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1709 if (CompositeTypeDesc *MethodTy =
1710 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1711 // Get argument information.
1712 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1717 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1721 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
1722 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1723 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1724 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1725 Method->AddChild(Arg);
1730 if (!MethodDesc->isStatic())
1731 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1732 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1734 Buffer.AddChild(Method);
1739 case DW_TAG_enumeration_type: {
1740 // Add enumerators to enumeration type.
1741 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1742 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1743 const std::string &Name = ED->getName();
1744 int64_t Value = ED->getValue();
1745 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1746 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1747 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1748 Buffer.AddChild(Enumerator);
1753 case DW_TAG_subroutine_type: {
1754 // Add prototype flag.
1755 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1757 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1760 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
1761 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1762 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1763 Buffer.AddChild(Arg);
1772 // Add name if not anonymous or intermediate type.
1773 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1775 // Add size if non-zero (derived types might be zero-sized.)
1777 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1778 else if (isa<CompositeTypeDesc>(TyDesc)) {
1779 // If TyDesc is a composite type, then add size even if it's zero unless
1780 // it's a forward declaration.
1781 if (TyDesc->isForwardDecl())
1782 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1784 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1787 // Add source line info if available and TyDesc is not a forward
1789 if (!TyDesc->isForwardDecl())
1790 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1793 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1795 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1796 // Construct debug information entry.
1797 DIE *Die = new DIE(DW_TAG_compile_unit);
1798 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
1799 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
1800 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1801 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1802 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1803 if (!UnitDesc->getDirectory().empty())
1804 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1806 // Construct compile unit.
1807 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1809 // Add Unit to compile unit map.
1810 DescToUnitMap[UnitDesc] = Unit;
1815 /// GetBaseCompileUnit - Get the main compile unit.
1817 CompileUnit *GetBaseCompileUnit() const {
1818 CompileUnit *Unit = CompileUnits[0];
1819 assert(Unit && "Missing compile unit.");
1823 /// FindCompileUnit - Get the compile unit for the given descriptor.
1825 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1826 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1827 assert(Unit && "Missing compile unit.");
1831 /// NewGlobalVariable - Add a new global variable DIE.
1833 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1834 // Get the compile unit context.
1835 CompileUnitDesc *UnitDesc =
1836 static_cast<CompileUnitDesc *>(GVD->getContext());
1837 CompileUnit *Unit = GetBaseCompileUnit();
1839 // Check for pre-existence.
1840 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1841 if (Slot) return Slot;
1843 // Get the global variable itself.
1844 GlobalVariable *GV = GVD->getGlobalVariable();
1846 const std::string &Name = GVD->getName();
1847 const std::string &FullName = GVD->getFullName();
1848 const std::string &LinkageName = GVD->getLinkageName();
1849 // Create the global's variable DIE.
1850 DIE *VariableDie = new DIE(DW_TAG_variable);
1851 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1852 if (!LinkageName.empty()) {
1853 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1856 AddType(VariableDie, GVD->getType(), Unit);
1857 if (!GVD->isStatic())
1858 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1860 // Add source line info if available.
1861 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1864 DIEBlock *Block = new DIEBlock();
1865 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1866 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1867 AddBlock(VariableDie, DW_AT_location, 0, Block);
1872 // Add to context owner.
1873 Unit->getDie()->AddChild(VariableDie);
1875 // Expose as global.
1876 // FIXME - need to check external flag.
1877 Unit->AddGlobal(FullName, VariableDie);
1882 /// NewSubprogram - Add a new subprogram DIE.
1884 DIE *NewSubprogram(SubprogramDesc *SPD) {
1885 // Get the compile unit context.
1886 CompileUnitDesc *UnitDesc =
1887 static_cast<CompileUnitDesc *>(SPD->getContext());
1888 CompileUnit *Unit = GetBaseCompileUnit();
1890 // Check for pre-existence.
1891 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1892 if (Slot) return Slot;
1894 // Gather the details (simplify add attribute code.)
1895 const std::string &Name = SPD->getName();
1896 const std::string &FullName = SPD->getFullName();
1897 const std::string &LinkageName = SPD->getLinkageName();
1899 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1900 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1901 if (!LinkageName.empty()) {
1902 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1905 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1906 if (!SPD->isStatic())
1907 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1908 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1910 // Add source line info if available.
1911 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1914 Slot = SubprogramDie;
1916 // Add to context owner.
1917 Unit->getDie()->AddChild(SubprogramDie);
1919 // Expose as global.
1920 Unit->AddGlobal(FullName, SubprogramDie);
1922 return SubprogramDie;
1925 /// NewScopeVariable - Create a new scope variable.
1927 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1928 // Get the descriptor.
1929 VariableDesc *VD = DV->getDesc();
1931 // Translate tag to proper Dwarf tag. The result variable is dropped for
1934 switch (VD->getTag()) {
1935 case DW_TAG_return_variable: return NULL;
1936 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1937 case DW_TAG_auto_variable: // fall thru
1938 default: Tag = DW_TAG_variable; break;
1941 // Define variable debug information entry.
1942 DIE *VariableDie = new DIE(Tag);
1943 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1945 // Add source line info if available.
1946 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1948 // Add variable type.
1949 AddType(VariableDie, VD->getType(), Unit);
1951 // Add variable address.
1952 MachineLocation Location;
1953 Location.set(RI->getFrameRegister(*MF),
1954 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1955 AddAddress(VariableDie, DW_AT_location, Location);
1960 /// ConstructScope - Construct the components of a scope.
1962 void ConstructScope(DebugScope *ParentScope,
1963 unsigned ParentStartID, unsigned ParentEndID,
1964 DIE *ParentDie, CompileUnit *Unit) {
1965 // Add variables to scope.
1966 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1967 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1968 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1969 if (VariableDie) ParentDie->AddChild(VariableDie);
1972 // Add nested scopes.
1973 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1974 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1975 // Define the Scope debug information entry.
1976 DebugScope *Scope = Scopes[j];
1977 // FIXME - Ignore inlined functions for the time being.
1978 if (!Scope->getParent()) continue;
1980 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1981 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1983 // Ignore empty scopes.
1984 if (StartID == EndID && StartID != 0) continue;
1985 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1987 if (StartID == ParentStartID && EndID == ParentEndID) {
1988 // Just add stuff to the parent scope.
1989 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1991 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1993 // Add the scope bounds.
1995 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1996 DWLabel("label", StartID));
1998 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1999 DWLabel("func_begin", SubprogramCount));
2002 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2003 DWLabel("label", EndID));
2005 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2006 DWLabel("func_end", SubprogramCount));
2009 // Add the scope contents.
2010 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2011 ParentDie->AddChild(ScopeDie);
2016 /// ConstructRootScope - Construct the scope for the subprogram.
2018 void ConstructRootScope(DebugScope *RootScope) {
2019 // Exit if there is no root scope.
2020 if (!RootScope) return;
2022 // Get the subprogram debug information entry.
2023 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2025 // Get the compile unit context.
2026 CompileUnit *Unit = GetBaseCompileUnit();
2028 // Get the subprogram die.
2029 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2030 assert(SPDie && "Missing subprogram descriptor");
2032 // Add the function bounds.
2033 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2034 DWLabel("func_begin", SubprogramCount));
2035 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2036 DWLabel("func_end", SubprogramCount));
2037 MachineLocation Location(RI->getFrameRegister(*MF));
2038 AddAddress(SPDie, DW_AT_frame_base, Location);
2040 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2043 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2045 void ConstructDefaultScope(MachineFunction *MF) {
2046 // Find the correct subprogram descriptor.
2047 std::vector<SubprogramDesc *> Subprograms;
2048 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2050 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2051 SubprogramDesc *SPD = Subprograms[i];
2053 if (SPD->getName() == MF->getFunction()->getName()) {
2054 // Get the compile unit context.
2055 CompileUnit *Unit = GetBaseCompileUnit();
2057 // Get the subprogram die.
2058 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2059 assert(SPDie && "Missing subprogram descriptor");
2061 // Add the function bounds.
2062 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2063 DWLabel("func_begin", SubprogramCount));
2064 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2065 DWLabel("func_end", SubprogramCount));
2067 MachineLocation Location(RI->getFrameRegister(*MF));
2068 AddAddress(SPDie, DW_AT_frame_base, Location);
2073 // FIXME: This is causing an abort because C++ mangled names are compared
2074 // with their unmangled counterparts. See PR2885. Don't do this assert.
2075 assert(0 && "Couldn't find DIE for machine function!");
2079 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2080 /// tools to recognize the object file contains Dwarf information.
2081 void EmitInitial() {
2082 // Check to see if we already emitted intial headers.
2083 if (didInitial) return;
2086 // Dwarf sections base addresses.
2087 if (TAI->doesDwarfRequireFrameSection()) {
2088 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2089 EmitLabel("section_debug_frame", 0);
2091 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2092 EmitLabel("section_info", 0);
2093 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2094 EmitLabel("section_abbrev", 0);
2095 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2096 EmitLabel("section_aranges", 0);
2097 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2098 EmitLabel("section_macinfo", 0);
2099 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2100 EmitLabel("section_line", 0);
2101 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2102 EmitLabel("section_loc", 0);
2103 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2104 EmitLabel("section_pubnames", 0);
2105 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2106 EmitLabel("section_str", 0);
2107 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2108 EmitLabel("section_ranges", 0);
2110 Asm->SwitchToSection(TAI->getTextSection());
2111 EmitLabel("text_begin", 0);
2112 Asm->SwitchToSection(TAI->getDataSection());
2113 EmitLabel("data_begin", 0);
2116 /// EmitDIE - Recusively Emits a debug information entry.
2118 void EmitDIE(DIE *Die) {
2119 // Get the abbreviation for this DIE.
2120 unsigned AbbrevNumber = Die->getAbbrevNumber();
2121 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2125 // Emit the code (index) for the abbreviation.
2126 Asm->EmitULEB128Bytes(AbbrevNumber);
2129 Asm->EOL(std::string("Abbrev [" +
2130 utostr(AbbrevNumber) +
2131 "] 0x" + utohexstr(Die->getOffset()) +
2132 ":0x" + utohexstr(Die->getSize()) + " " +
2133 TagString(Abbrev->getTag())));
2137 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2138 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2140 // Emit the DIE attribute values.
2141 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2142 unsigned Attr = AbbrevData[i].getAttribute();
2143 unsigned Form = AbbrevData[i].getForm();
2144 assert(Form && "Too many attributes for DIE (check abbreviation)");
2147 case DW_AT_sibling: {
2148 Asm->EmitInt32(Die->SiblingOffset());
2152 // Emit an attribute using the defined form.
2153 Values[i]->EmitValue(*this, Form);
2158 Asm->EOL(AttributeString(Attr));
2161 // Emit the DIE children if any.
2162 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2163 const std::vector<DIE *> &Children = Die->getChildren();
2165 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2166 EmitDIE(Children[j]);
2169 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2173 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2175 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2176 // Get the children.
2177 const std::vector<DIE *> &Children = Die->getChildren();
2179 // If not last sibling and has children then add sibling offset attribute.
2180 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2182 // Record the abbreviation.
2183 AssignAbbrevNumber(Die->getAbbrev());
2185 // Get the abbreviation for this DIE.
2186 unsigned AbbrevNumber = Die->getAbbrevNumber();
2187 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2190 Die->setOffset(Offset);
2192 // Start the size with the size of abbreviation code.
2193 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2195 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2196 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2198 // Size the DIE attribute values.
2199 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2200 // Size attribute value.
2201 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2204 // Size the DIE children if any.
2205 if (!Children.empty()) {
2206 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2207 "Children flag not set");
2209 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2210 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2213 // End of children marker.
2214 Offset += sizeof(int8_t);
2217 Die->setSize(Offset - Die->getOffset());
2221 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2223 void SizeAndOffsets() {
2224 // Process base compile unit.
2225 CompileUnit *Unit = GetBaseCompileUnit();
2226 // Compute size of compile unit header
2227 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2228 sizeof(int16_t) + // DWARF version number
2229 sizeof(int32_t) + // Offset Into Abbrev. Section
2230 sizeof(int8_t); // Pointer Size (in bytes)
2231 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2234 /// EmitDebugInfo - Emit the debug info section.
2236 void EmitDebugInfo() {
2237 // Start debug info section.
2238 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2240 CompileUnit *Unit = GetBaseCompileUnit();
2241 DIE *Die = Unit->getDie();
2242 // Emit the compile units header.
2243 EmitLabel("info_begin", Unit->getID());
2244 // Emit size of content not including length itself
2245 unsigned ContentSize = Die->getSize() +
2246 sizeof(int16_t) + // DWARF version number
2247 sizeof(int32_t) + // Offset Into Abbrev. Section
2248 sizeof(int8_t) + // Pointer Size (in bytes)
2249 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2251 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2252 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2253 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2254 Asm->EOL("Offset Into Abbrev. Section");
2255 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2258 // FIXME - extra padding for gdb bug.
2259 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2260 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2261 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2262 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2263 EmitLabel("info_end", Unit->getID());
2268 /// EmitAbbreviations - Emit the abbreviation section.
2270 void EmitAbbreviations() const {
2271 // Check to see if it is worth the effort.
2272 if (!Abbreviations.empty()) {
2273 // Start the debug abbrev section.
2274 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2276 EmitLabel("abbrev_begin", 0);
2278 // For each abbrevation.
2279 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2280 // Get abbreviation data
2281 const DIEAbbrev *Abbrev = Abbreviations[i];
2283 // Emit the abbrevations code (base 1 index.)
2284 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2285 Asm->EOL("Abbreviation Code");
2287 // Emit the abbreviations data.
2288 Abbrev->Emit(*this);
2293 // Mark end of abbreviations.
2294 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2296 EmitLabel("abbrev_end", 0);
2302 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2303 /// the line matrix.
2305 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2306 // Define last address of section.
2307 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2308 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2309 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2310 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2312 // Mark end of matrix.
2313 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2314 Asm->EmitULEB128Bytes(1); Asm->EOL();
2315 Asm->EmitInt8(1); Asm->EOL();
2318 /// EmitDebugLines - Emit source line information.
2320 void EmitDebugLines() {
2321 // If the target is using .loc/.file, the assembler will be emitting the
2322 // .debug_line table automatically.
2323 if (TAI->hasDotLocAndDotFile())
2326 // Minimum line delta, thus ranging from -10..(255-10).
2327 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2328 // Maximum line delta, thus ranging from -10..(255-10).
2329 const int MaxLineDelta = 255 + MinLineDelta;
2331 // Start the dwarf line section.
2332 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2334 // Construct the section header.
2336 EmitDifference("line_end", 0, "line_begin", 0, true);
2337 Asm->EOL("Length of Source Line Info");
2338 EmitLabel("line_begin", 0);
2340 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2342 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2343 Asm->EOL("Prolog Length");
2344 EmitLabel("line_prolog_begin", 0);
2346 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2348 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2350 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2352 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2354 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2356 // Line number standard opcode encodings argument count
2357 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2358 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2359 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2360 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2361 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2362 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2363 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2364 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2365 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2367 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2368 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2370 // Emit directories.
2371 for (unsigned DirectoryID = 1, NDID = Directories.size();
2372 DirectoryID <= NDID; ++DirectoryID) {
2373 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2375 Asm->EmitInt8(0); Asm->EOL("End of directories");
2378 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2379 SourceID <= NSID; ++SourceID) {
2380 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2381 Asm->EmitString(SourceFile.getName());
2383 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2384 Asm->EOL("Directory #");
2385 Asm->EmitULEB128Bytes(0);
2386 Asm->EOL("Mod date");
2387 Asm->EmitULEB128Bytes(0);
2388 Asm->EOL("File size");
2390 Asm->EmitInt8(0); Asm->EOL("End of files");
2392 EmitLabel("line_prolog_end", 0);
2394 // A sequence for each text section.
2395 unsigned SecSrcLinesSize = SectionSourceLines.size();
2397 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2398 // Isolate current sections line info.
2399 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2402 const Section* S = SectionMap[j + 1];
2403 Asm->EOL(std::string("Section ") + S->getName());
2407 // Dwarf assumes we start with first line of first source file.
2408 unsigned Source = 1;
2411 // Construct rows of the address, source, line, column matrix.
2412 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2413 const SourceLineInfo &LineInfo = LineInfos[i];
2414 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2415 if (!LabelID) continue;
2417 unsigned SourceID = LineInfo.getSourceID();
2418 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2419 unsigned DirectoryID = SourceFile.getDirectoryID();
2421 Asm->EOL(Directories[DirectoryID]
2422 + SourceFile.getName()
2424 + utostr_32(LineInfo.getLine()));
2428 // Define the line address.
2429 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2430 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2431 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2432 EmitReference("label", LabelID); Asm->EOL("Location label");
2434 // If change of source, then switch to the new source.
2435 if (Source != LineInfo.getSourceID()) {
2436 Source = LineInfo.getSourceID();
2437 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2438 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2441 // If change of line.
2442 if (Line != LineInfo.getLine()) {
2443 // Determine offset.
2444 int Offset = LineInfo.getLine() - Line;
2445 int Delta = Offset - MinLineDelta;
2448 Line = LineInfo.getLine();
2450 // If delta is small enough and in range...
2451 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2452 // ... then use fast opcode.
2453 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2455 // ... otherwise use long hand.
2456 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2457 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2458 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2461 // Copy the previous row (different address or source)
2462 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2466 EmitEndOfLineMatrix(j + 1);
2469 if (SecSrcLinesSize == 0)
2470 // Because we're emitting a debug_line section, we still need a line
2471 // table. The linker and friends expect it to exist. If there's nothing to
2472 // put into it, emit an empty table.
2473 EmitEndOfLineMatrix(1);
2475 EmitLabel("line_end", 0);
2480 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2482 void EmitCommonDebugFrame() {
2483 if (!TAI->doesDwarfRequireFrameSection())
2487 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2488 TargetFrameInfo::StackGrowsUp ?
2489 TD->getPointerSize() : -TD->getPointerSize();
2491 // Start the dwarf frame section.
2492 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2494 EmitLabel("debug_frame_common", 0);
2495 EmitDifference("debug_frame_common_end", 0,
2496 "debug_frame_common_begin", 0, true);
2497 Asm->EOL("Length of Common Information Entry");
2499 EmitLabel("debug_frame_common_begin", 0);
2500 Asm->EmitInt32((int)DW_CIE_ID);
2501 Asm->EOL("CIE Identifier Tag");
2502 Asm->EmitInt8(DW_CIE_VERSION);
2503 Asm->EOL("CIE Version");
2504 Asm->EmitString("");
2505 Asm->EOL("CIE Augmentation");
2506 Asm->EmitULEB128Bytes(1);
2507 Asm->EOL("CIE Code Alignment Factor");
2508 Asm->EmitSLEB128Bytes(stackGrowth);
2509 Asm->EOL("CIE Data Alignment Factor");
2510 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2511 Asm->EOL("CIE RA Column");
2513 std::vector<MachineMove> Moves;
2514 RI->getInitialFrameState(Moves);
2516 EmitFrameMoves(NULL, 0, Moves, false);
2518 Asm->EmitAlignment(2, 0, 0, false);
2519 EmitLabel("debug_frame_common_end", 0);
2524 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2526 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2527 if (!TAI->doesDwarfRequireFrameSection())
2530 // Start the dwarf frame section.
2531 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2533 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2534 "debug_frame_begin", DebugFrameInfo.Number, true);
2535 Asm->EOL("Length of Frame Information Entry");
2537 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2539 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2541 Asm->EOL("FDE CIE offset");
2543 EmitReference("func_begin", DebugFrameInfo.Number);
2544 Asm->EOL("FDE initial location");
2545 EmitDifference("func_end", DebugFrameInfo.Number,
2546 "func_begin", DebugFrameInfo.Number);
2547 Asm->EOL("FDE address range");
2549 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2551 Asm->EmitAlignment(2, 0, 0, false);
2552 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2557 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2559 void EmitDebugPubNames() {
2560 // Start the dwarf pubnames section.
2561 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2563 CompileUnit *Unit = GetBaseCompileUnit();
2565 EmitDifference("pubnames_end", Unit->getID(),
2566 "pubnames_begin", Unit->getID(), true);
2567 Asm->EOL("Length of Public Names Info");
2569 EmitLabel("pubnames_begin", Unit->getID());
2571 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2573 EmitSectionOffset("info_begin", "section_info",
2574 Unit->getID(), 0, true, false);
2575 Asm->EOL("Offset of Compilation Unit Info");
2577 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2578 Asm->EOL("Compilation Unit Length");
2580 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2582 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2585 const std::string &Name = GI->first;
2586 DIE * Entity = GI->second;
2588 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2589 Asm->EmitString(Name); Asm->EOL("External Name");
2592 Asm->EmitInt32(0); Asm->EOL("End Mark");
2593 EmitLabel("pubnames_end", Unit->getID());
2598 /// EmitDebugStr - Emit visible names into a debug str section.
2600 void EmitDebugStr() {
2601 // Check to see if it is worth the effort.
2602 if (!StringPool.empty()) {
2603 // Start the dwarf str section.
2604 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2606 // For each of strings in the string pool.
2607 for (unsigned StringID = 1, N = StringPool.size();
2608 StringID <= N; ++StringID) {
2609 // Emit a label for reference from debug information entries.
2610 EmitLabel("string", StringID);
2611 // Emit the string itself.
2612 const std::string &String = StringPool[StringID];
2613 Asm->EmitString(String); Asm->EOL();
2620 /// EmitDebugLoc - Emit visible names into a debug loc section.
2622 void EmitDebugLoc() {
2623 // Start the dwarf loc section.
2624 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2629 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2631 void EmitDebugARanges() {
2632 // Start the dwarf aranges section.
2633 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2637 CompileUnit *Unit = GetBaseCompileUnit();
2639 // Don't include size of length
2640 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2642 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2644 EmitReference("info_begin", Unit->getID());
2645 Asm->EOL("Offset of Compilation Unit Info");
2647 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2649 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2651 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2652 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2655 EmitReference("text_begin", 0); Asm->EOL("Address");
2656 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2658 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2659 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2665 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2667 void EmitDebugRanges() {
2668 // Start the dwarf ranges section.
2669 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2674 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2676 void EmitDebugMacInfo() {
2677 // Start the dwarf macinfo section.
2678 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2683 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2685 void ConstructCompileUnitDIEs() {
2686 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2688 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2689 unsigned ID = MMI->RecordSource(CUW[i]);
2690 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2691 CompileUnits.push_back(Unit);
2695 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2696 /// global variables.
2697 void ConstructGlobalDIEs() {
2698 std::vector<GlobalVariableDesc *> GlobalVariables;
2699 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
2701 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2702 GlobalVariableDesc *GVD = GlobalVariables[i];
2703 NewGlobalVariable(GVD);
2707 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2709 void ConstructSubprogramDIEs() {
2710 std::vector<SubprogramDesc *> Subprograms;
2711 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2713 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2714 SubprogramDesc *SPD = Subprograms[i];
2720 //===--------------------------------------------------------------------===//
2721 // Main entry points.
2723 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2724 : Dwarf(OS, A, T, "dbg")
2726 , AbbreviationsSet(InitAbbreviationsSetSize)
2728 , ValuesSet(InitValuesSetSize)
2733 , SectionSourceLines()
2738 virtual ~DwarfDebug() {
2739 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2740 delete CompileUnits[i];
2741 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2745 /// SetModuleInfo - Set machine module information when it's known that pass
2746 /// manager has created it. Set by the target AsmPrinter.
2747 void SetModuleInfo(MachineModuleInfo *mmi) {
2748 // Make sure initial declarations are made.
2749 if (!MMI && mmi->hasDebugInfo()) {
2753 // Create all the compile unit DIEs.
2754 ConstructCompileUnitDIEs();
2756 // Create DIEs for each of the externally visible global variables.
2757 ConstructGlobalDIEs();
2759 // Create DIEs for each of the externally visible subprograms.
2760 ConstructSubprogramDIEs();
2762 // Prime section data.
2763 SectionMap.insert(TAI->getTextSection());
2765 // Print out .file directives to specify files for .loc directives. These
2766 // are printed out early so that they precede any .loc directives.
2767 if (TAI->hasDotLocAndDotFile()) {
2768 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2769 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2770 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2771 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2772 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2773 assert(AppendOk && "Could not append filename to directory!");
2775 Asm->EmitFile(i, FullPath.toString());
2780 // Emit initial sections
2785 /// BeginModule - Emit all Dwarf sections that should come prior to the
2787 void BeginModule(Module *M) {
2791 /// EndModule - Emit all Dwarf sections that should come after the content.
2794 if (!ShouldEmitDwarf()) return;
2796 // Standard sections final addresses.
2797 Asm->SwitchToSection(TAI->getTextSection());
2798 EmitLabel("text_end", 0);
2799 Asm->SwitchToSection(TAI->getDataSection());
2800 EmitLabel("data_end", 0);
2802 // End text sections.
2803 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2804 Asm->SwitchToSection(SectionMap[i]);
2805 EmitLabel("section_end", i);
2808 // Emit common frame information.
2809 EmitCommonDebugFrame();
2811 // Emit function debug frame information
2812 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2813 E = DebugFrames.end(); I != E; ++I)
2814 EmitFunctionDebugFrame(*I);
2816 // Compute DIE offsets and sizes.
2819 // Emit all the DIEs into a debug info section
2822 // Corresponding abbreviations into a abbrev section.
2823 EmitAbbreviations();
2825 // Emit source line correspondence into a debug line section.
2828 // Emit info into a debug pubnames section.
2829 EmitDebugPubNames();
2831 // Emit info into a debug str section.
2834 // Emit info into a debug loc section.
2837 // Emit info into a debug aranges section.
2840 // Emit info into a debug ranges section.
2843 // Emit info into a debug macinfo section.
2847 /// BeginFunction - Gather pre-function debug information. Assumes being
2848 /// emitted immediately after the function entry point.
2849 void BeginFunction(MachineFunction *MF) {
2852 if (!ShouldEmitDwarf()) return;
2854 // Begin accumulating function debug information.
2855 MMI->BeginFunction(MF);
2857 // Assumes in correct section after the entry point.
2858 EmitLabel("func_begin", ++SubprogramCount);
2860 // Emit label for the implicitly defined dbg.stoppoint at the start of
2862 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2863 if (!LineInfos.empty()) {
2864 const SourceLineInfo &LineInfo = LineInfos[0];
2865 Asm->printLabel(LineInfo.getLabelID());
2869 /// EndFunction - Gather and emit post-function debug information.
2871 void EndFunction(MachineFunction *MF) {
2872 if (!ShouldEmitDwarf()) return;
2874 // Define end label for subprogram.
2875 EmitLabel("func_end", SubprogramCount);
2877 // Get function line info.
2878 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2880 if (!LineInfos.empty()) {
2881 // Get section line info.
2882 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2883 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2884 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2885 // Append the function info to section info.
2886 SectionLineInfos.insert(SectionLineInfos.end(),
2887 LineInfos.begin(), LineInfos.end());
2890 // Construct scopes for subprogram.
2891 if (MMI->getRootScope())
2892 ConstructRootScope(MMI->getRootScope());
2894 // FIXME: This is wrong. We are essentially getting past a problem with
2895 // debug information not being able to handle unreachable blocks that have
2896 // debug information in them. In particular, those unreachable blocks that
2897 // have "region end" info in them. That situation results in the "root
2898 // scope" not being created. If that's the case, then emit a "default"
2899 // scope, i.e., one that encompasses the whole function. This isn't
2900 // desirable. And a better way of handling this (and all of the debugging
2901 // information) needs to be explored.
2902 ConstructDefaultScope(MF);
2904 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2905 MMI->getFrameMoves()));
2909 //===----------------------------------------------------------------------===//
2910 /// DwarfException - Emits Dwarf exception handling directives.
2912 class DwarfException : public Dwarf {
2915 struct FunctionEHFrameInfo {
2918 unsigned PersonalityIndex;
2920 bool hasLandingPads;
2921 std::vector<MachineMove> Moves;
2922 const Function * function;
2924 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2926 const std::vector<MachineMove> &M,
2928 FnName(FN), Number(Num), PersonalityIndex(P),
2929 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2932 std::vector<FunctionEHFrameInfo> EHFrames;
2934 /// shouldEmitTable - Per-function flag to indicate if EH tables should
2936 bool shouldEmitTable;
2938 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
2939 /// should be emitted.
2940 bool shouldEmitMoves;
2942 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
2943 /// should be emitted.
2944 bool shouldEmitTableModule;
2946 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
2947 /// should be emitted.
2948 bool shouldEmitMovesModule;
2950 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2952 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2953 // Size and sign of stack growth.
2955 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2956 TargetFrameInfo::StackGrowsUp ?
2957 TD->getPointerSize() : -TD->getPointerSize();
2959 // Begin eh frame section.
2960 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2962 if (!TAI->doesRequireNonLocalEHFrameLabel())
2963 O << TAI->getEHGlobalPrefix();
2964 O << "EH_frame" << Index << ":\n";
2965 EmitLabel("section_eh_frame", Index);
2967 // Define base labels.
2968 EmitLabel("eh_frame_common", Index);
2970 // Define the eh frame length.
2971 EmitDifference("eh_frame_common_end", Index,
2972 "eh_frame_common_begin", Index, true);
2973 Asm->EOL("Length of Common Information Entry");
2976 EmitLabel("eh_frame_common_begin", Index);
2977 Asm->EmitInt32((int)0);
2978 Asm->EOL("CIE Identifier Tag");
2979 Asm->EmitInt8(DW_CIE_VERSION);
2980 Asm->EOL("CIE Version");
2982 // The personality presence indicates that language specific information
2983 // will show up in the eh frame.
2984 Asm->EmitString(Personality ? "zPLR" : "zR");
2985 Asm->EOL("CIE Augmentation");
2987 // Round out reader.
2988 Asm->EmitULEB128Bytes(1);
2989 Asm->EOL("CIE Code Alignment Factor");
2990 Asm->EmitSLEB128Bytes(stackGrowth);
2991 Asm->EOL("CIE Data Alignment Factor");
2992 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2993 Asm->EOL("CIE Return Address Column");
2995 // If there is a personality, we need to indicate the functions location.
2997 Asm->EmitULEB128Bytes(7);
2998 Asm->EOL("Augmentation Size");
3000 if (TAI->getNeedsIndirectEncoding()) {
3001 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3002 Asm->EOL("Personality (pcrel sdata4 indirect)");
3004 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3005 Asm->EOL("Personality (pcrel sdata4)");
3008 PrintRelDirective(true);
3009 O << TAI->getPersonalityPrefix();
3010 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3011 O << TAI->getPersonalitySuffix();
3012 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3013 O << "-" << TAI->getPCSymbol();
3014 Asm->EOL("Personality");
3016 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3017 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3019 if (TAI->doesFDEEncodingRequireSData4()) {
3020 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3021 Asm->EOL("FDE Encoding (pcrel sdata4)");
3023 Asm->EmitInt8(DW_EH_PE_pcrel);
3024 Asm->EOL("FDE Encoding (pcrel)");
3027 Asm->EmitULEB128Bytes(1);
3028 Asm->EOL("Augmentation Size");
3030 if (TAI->doesFDEEncodingRequireSData4()) {
3031 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3032 Asm->EOL("FDE Encoding (pcrel sdata4)");
3034 Asm->EmitInt8(DW_EH_PE_pcrel);
3035 Asm->EOL("FDE Encoding (pcrel)");
3039 // Indicate locations of general callee saved registers in frame.
3040 std::vector<MachineMove> Moves;
3041 RI->getInitialFrameState(Moves);
3042 EmitFrameMoves(NULL, 0, Moves, true);
3044 // On Darwin the linker honors the alignment of eh_frame, which means it
3045 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3046 // you get holes which confuse readers of eh_frame.
3047 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3049 EmitLabel("eh_frame_common_end", Index);
3054 /// EmitEHFrame - Emit function exception frame information.
3056 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3057 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3059 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3061 // Externally visible entry into the functions eh frame info.
3062 // If the corresponding function is static, this should not be
3063 // externally visible.
3064 if (linkage != Function::InternalLinkage) {
3065 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3066 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3069 // If corresponding function is weak definition, this should be too.
3070 if ((linkage == Function::WeakLinkage ||
3071 linkage == Function::LinkOnceLinkage) &&
3072 TAI->getWeakDefDirective())
3073 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3075 // If there are no calls then you can't unwind. This may mean we can
3076 // omit the EH Frame, but some environments do not handle weak absolute
3078 // If UnwindTablesMandatory is set we cannot do this optimization; the
3079 // unwind info is to be available for non-EH uses.
3080 if (!EHFrameInfo.hasCalls &&
3081 !UnwindTablesMandatory &&
3082 ((linkage != Function::WeakLinkage &&
3083 linkage != Function::LinkOnceLinkage) ||
3084 !TAI->getWeakDefDirective() ||
3085 TAI->getSupportsWeakOmittedEHFrame()))
3087 O << EHFrameInfo.FnName << " = 0\n";
3088 // This name has no connection to the function, so it might get
3089 // dead-stripped when the function is not, erroneously. Prohibit
3090 // dead-stripping unconditionally.
3091 if (const char *UsedDirective = TAI->getUsedDirective())
3092 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3094 O << EHFrameInfo.FnName << ":\n";
3097 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3098 "eh_frame_begin", EHFrameInfo.Number, true);
3099 Asm->EOL("Length of Frame Information Entry");
3101 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3103 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3104 PrintRelDirective(true, true);
3105 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3107 if (!TAI->isAbsoluteEHSectionOffsets())
3108 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3110 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3111 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3115 Asm->EOL("FDE CIE offset");
3117 EmitReference("eh_func_begin", EHFrameInfo.Number, true,
3118 TAI->doesRequire32BitFDEReference());
3119 Asm->EOL("FDE initial location");
3120 EmitDifference("eh_func_end", EHFrameInfo.Number,
3121 "eh_func_begin", EHFrameInfo.Number,
3122 TAI->doesRequire32BitFDEReference());
3123 Asm->EOL("FDE address range");
3125 // If there is a personality and landing pads then point to the language
3126 // specific data area in the exception table.
3127 if (EHFrameInfo.PersonalityIndex) {
3128 Asm->EmitULEB128Bytes(4);
3129 Asm->EOL("Augmentation size");
3131 if (EHFrameInfo.hasLandingPads)
3132 EmitReference("exception", EHFrameInfo.Number, true, true);
3134 Asm->EmitInt32((int)0);
3135 Asm->EOL("Language Specific Data Area");
3137 Asm->EmitULEB128Bytes(0);
3138 Asm->EOL("Augmentation size");
3141 // Indicate locations of function specific callee saved registers in
3143 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3145 // On Darwin the linker honors the alignment of eh_frame, which means it
3146 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3147 // you get holes which confuse readers of eh_frame.
3148 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3150 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3152 // If the function is marked used, this table should be also. We cannot
3153 // make the mark unconditional in this case, since retaining the table
3154 // also retains the function in this case, and there is code around
3155 // that depends on unused functions (calling undefined externals) being
3156 // dead-stripped to link correctly. Yes, there really is.
3157 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3158 if (const char *UsedDirective = TAI->getUsedDirective())
3159 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3163 /// EmitExceptionTable - Emit landing pads and actions.
3165 /// The general organization of the table is complex, but the basic concepts
3166 /// are easy. First there is a header which describes the location and
3167 /// organization of the three components that follow.
3168 /// 1. The landing pad site information describes the range of code covered
3169 /// by the try. In our case it's an accumulation of the ranges covered
3170 /// by the invokes in the try. There is also a reference to the landing
3171 /// pad that handles the exception once processed. Finally an index into
3172 /// the actions table.
3173 /// 2. The action table, in our case, is composed of pairs of type ids
3174 /// and next action offset. Starting with the action index from the
3175 /// landing pad site, each type Id is checked for a match to the current
3176 /// exception. If it matches then the exception and type id are passed
3177 /// on to the landing pad. Otherwise the next action is looked up. This
3178 /// chain is terminated with a next action of zero. If no type id is
3179 /// found the the frame is unwound and handling continues.
3180 /// 3. Type id table contains references to all the C++ typeinfo for all
3181 /// catches in the function. This tables is reversed indexed base 1.
3183 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3184 static unsigned SharedTypeIds(const LandingPadInfo *L,
3185 const LandingPadInfo *R) {
3186 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3187 unsigned LSize = LIds.size(), RSize = RIds.size();
3188 unsigned MinSize = LSize < RSize ? LSize : RSize;
3191 for (; Count != MinSize; ++Count)
3192 if (LIds[Count] != RIds[Count])
3198 /// PadLT - Order landing pads lexicographically by type id.
3199 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3200 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3201 unsigned LSize = LIds.size(), RSize = RIds.size();
3202 unsigned MinSize = LSize < RSize ? LSize : RSize;
3204 for (unsigned i = 0; i != MinSize; ++i)
3205 if (LIds[i] != RIds[i])
3206 return LIds[i] < RIds[i];
3208 return LSize < RSize;
3212 static inline unsigned getEmptyKey() { return -1U; }
3213 static inline unsigned getTombstoneKey() { return -2U; }
3214 static unsigned getHashValue(const unsigned &Key) { return Key; }
3215 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3216 static bool isPod() { return true; }
3219 /// ActionEntry - Structure describing an entry in the actions table.
3220 struct ActionEntry {
3221 int ValueForTypeID; // The value to write - may not be equal to the type id.
3223 struct ActionEntry *Previous;
3226 /// PadRange - Structure holding a try-range and the associated landing pad.
3228 // The index of the landing pad.
3230 // The index of the begin and end labels in the landing pad's label lists.
3231 unsigned RangeIndex;
3234 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3236 /// CallSiteEntry - Structure describing an entry in the call-site table.
3237 struct CallSiteEntry {
3238 // The 'try-range' is BeginLabel .. EndLabel.
3239 unsigned BeginLabel; // zero indicates the start of the function.
3240 unsigned EndLabel; // zero indicates the end of the function.
3241 // The landing pad starts at PadLabel.
3242 unsigned PadLabel; // zero indicates that there is no landing pad.
3246 void EmitExceptionTable() {
3247 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3248 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3249 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3250 if (PadInfos.empty()) return;
3252 // Sort the landing pads in order of their type ids. This is used to fold
3253 // duplicate actions.
3254 SmallVector<const LandingPadInfo *, 64> LandingPads;
3255 LandingPads.reserve(PadInfos.size());
3256 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3257 LandingPads.push_back(&PadInfos[i]);
3258 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3260 // Negative type ids index into FilterIds, positive type ids index into
3261 // TypeInfos. The value written for a positive type id is just the type
3262 // id itself. For a negative type id, however, the value written is the
3263 // (negative) byte offset of the corresponding FilterIds entry. The byte
3264 // offset is usually equal to the type id, because the FilterIds entries
3265 // are written using a variable width encoding which outputs one byte per
3266 // entry as long as the value written is not too large, but can differ.
3267 // This kind of complication does not occur for positive type ids because
3268 // type infos are output using a fixed width encoding.
3269 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3270 SmallVector<int, 16> FilterOffsets;
3271 FilterOffsets.reserve(FilterIds.size());
3273 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3274 E = FilterIds.end(); I != E; ++I) {
3275 FilterOffsets.push_back(Offset);
3276 Offset -= TargetAsmInfo::getULEB128Size(*I);
3279 // Compute the actions table and gather the first action index for each
3280 // landing pad site.
3281 SmallVector<ActionEntry, 32> Actions;
3282 SmallVector<unsigned, 64> FirstActions;
3283 FirstActions.reserve(LandingPads.size());
3285 int FirstAction = 0;
3286 unsigned SizeActions = 0;
3287 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3288 const LandingPadInfo *LP = LandingPads[i];
3289 const std::vector<int> &TypeIds = LP->TypeIds;
3290 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3291 unsigned SizeSiteActions = 0;
3293 if (NumShared < TypeIds.size()) {
3294 unsigned SizeAction = 0;
3295 ActionEntry *PrevAction = 0;
3298 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3299 assert(Actions.size());
3300 PrevAction = &Actions.back();
3301 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3302 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3303 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3305 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3306 SizeAction += -PrevAction->NextAction;
3307 PrevAction = PrevAction->Previous;
3311 // Compute the actions.
3312 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3313 int TypeID = TypeIds[I];
3314 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3315 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3316 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3318 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3319 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3320 SizeSiteActions += SizeAction;
3322 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3323 Actions.push_back(Action);
3325 PrevAction = &Actions.back();
3328 // Record the first action of the landing pad site.
3329 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3330 } // else identical - re-use previous FirstAction
3332 FirstActions.push_back(FirstAction);
3334 // Compute this sites contribution to size.
3335 SizeActions += SizeSiteActions;
3338 // Compute the call-site table. The entry for an invoke has a try-range
3339 // containing the call, a non-zero landing pad and an appropriate action.
3340 // The entry for an ordinary call has a try-range containing the call and
3341 // zero for the landing pad and the action. Calls marked 'nounwind' have
3342 // no entry and must not be contained in the try-range of any entry - they
3343 // form gaps in the table. Entries must be ordered by try-range address.
3344 SmallVector<CallSiteEntry, 64> CallSites;
3346 RangeMapType PadMap;
3347 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3348 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3349 // try-ranges for them need be deduced.
3350 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3351 const LandingPadInfo *LandingPad = LandingPads[i];
3352 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3353 unsigned BeginLabel = LandingPad->BeginLabels[j];
3354 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3355 PadRange P = { i, j };
3356 PadMap[BeginLabel] = P;
3360 // The end label of the previous invoke or nounwind try-range.
3361 unsigned LastLabel = 0;
3363 // Whether there is a potentially throwing instruction (currently this means
3364 // an ordinary call) between the end of the previous try-range and now.
3365 bool SawPotentiallyThrowing = false;
3367 // Whether the last callsite entry was for an invoke.
3368 bool PreviousIsInvoke = false;
3370 // Visit all instructions in order of address.
3371 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3373 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3375 if (!MI->isLabel()) {
3376 SawPotentiallyThrowing |= MI->getDesc().isCall();
3380 unsigned BeginLabel = MI->getOperand(0).getImm();
3381 assert(BeginLabel && "Invalid label!");
3383 // End of the previous try-range?
3384 if (BeginLabel == LastLabel)
3385 SawPotentiallyThrowing = false;
3387 // Beginning of a new try-range?
3388 RangeMapType::iterator L = PadMap.find(BeginLabel);
3389 if (L == PadMap.end())
3390 // Nope, it was just some random label.
3393 PadRange P = L->second;
3394 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3396 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3397 "Inconsistent landing pad map!");
3399 // If some instruction between the previous try-range and this one may
3400 // throw, create a call-site entry with no landing pad for the region
3401 // between the try-ranges.
3402 if (SawPotentiallyThrowing) {
3403 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3404 CallSites.push_back(Site);
3405 PreviousIsInvoke = false;
3408 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3409 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3411 if (LandingPad->LandingPadLabel) {
3412 // This try-range is for an invoke.
3413 CallSiteEntry Site = {BeginLabel, LastLabel,
3414 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3416 // Try to merge with the previous call-site.
3417 if (PreviousIsInvoke) {
3418 CallSiteEntry &Prev = CallSites.back();
3419 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3420 // Extend the range of the previous entry.
3421 Prev.EndLabel = Site.EndLabel;
3426 // Otherwise, create a new call-site.
3427 CallSites.push_back(Site);
3428 PreviousIsInvoke = true;
3431 PreviousIsInvoke = false;
3435 // If some instruction between the previous try-range and the end of the
3436 // function may throw, create a call-site entry with no landing pad for the
3437 // region following the try-range.
3438 if (SawPotentiallyThrowing) {
3439 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3440 CallSites.push_back(Site);
3446 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3447 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3448 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3449 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3452 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3453 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3456 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3457 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3459 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3460 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3461 SizeSites + SizeActions + SizeTypes;
3463 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3464 sizeof(int8_t) + // TType format
3465 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3468 unsigned SizeAlign = (4 - TotalSize) & 3;
3470 // Begin the exception table.
3471 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3472 Asm->EmitAlignment(2, 0, 0, false);
3473 O << "GCC_except_table" << SubprogramCount << ":\n";
3474 for (unsigned i = 0; i != SizeAlign; ++i) {
3476 Asm->EOL("Padding");
3478 EmitLabel("exception", SubprogramCount);
3481 Asm->EmitInt8(DW_EH_PE_omit);
3482 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3483 Asm->EmitInt8(DW_EH_PE_absptr);
3484 Asm->EOL("TType format (DW_EH_PE_absptr)");
3485 Asm->EmitULEB128Bytes(TypeOffset);
3486 Asm->EOL("TType base offset");
3487 Asm->EmitInt8(DW_EH_PE_udata4);
3488 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3489 Asm->EmitULEB128Bytes(SizeSites);
3490 Asm->EOL("Call-site table length");
3492 // Emit the landing pad site information.
3493 for (unsigned i = 0; i < CallSites.size(); ++i) {
3494 CallSiteEntry &S = CallSites[i];
3495 const char *BeginTag;
3496 unsigned BeginNumber;
3498 if (!S.BeginLabel) {
3499 BeginTag = "eh_func_begin";
3500 BeginNumber = SubprogramCount;
3503 BeginNumber = S.BeginLabel;
3506 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3508 Asm->EOL("Region start");
3511 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3514 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3516 Asm->EOL("Region length");
3521 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3523 Asm->EOL("Landing pad");
3525 Asm->EmitULEB128Bytes(S.Action);
3529 // Emit the actions.
3530 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3531 ActionEntry &Action = Actions[I];
3533 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3534 Asm->EOL("TypeInfo index");
3535 Asm->EmitSLEB128Bytes(Action.NextAction);
3536 Asm->EOL("Next action");
3539 // Emit the type ids.
3540 for (unsigned M = TypeInfos.size(); M; --M) {
3541 GlobalVariable *GV = TypeInfos[M - 1];
3543 PrintRelDirective();
3546 O << Asm->getGlobalLinkName(GV);
3550 Asm->EOL("TypeInfo");
3553 // Emit the filter typeids.
3554 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3555 unsigned TypeID = FilterIds[j];
3556 Asm->EmitULEB128Bytes(TypeID);
3557 Asm->EOL("Filter TypeInfo index");
3560 Asm->EmitAlignment(2, 0, 0, false);
3564 //===--------------------------------------------------------------------===//
3565 // Main entry points.
3567 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3568 : Dwarf(OS, A, T, "eh")
3569 , shouldEmitTable(false)
3570 , shouldEmitMoves(false)
3571 , shouldEmitTableModule(false)
3572 , shouldEmitMovesModule(false)
3575 virtual ~DwarfException() {}
3577 /// SetModuleInfo - Set machine module information when it's known that pass
3578 /// manager has created it. Set by the target AsmPrinter.
3579 void SetModuleInfo(MachineModuleInfo *mmi) {
3583 /// BeginModule - Emit all exception information that should come prior to the
3585 void BeginModule(Module *M) {
3589 /// EndModule - Emit all exception information that should come after the
3592 if (shouldEmitMovesModule || shouldEmitTableModule) {
3593 const std::vector<Function *> Personalities = MMI->getPersonalities();
3594 for (unsigned i =0; i < Personalities.size(); ++i)
3595 EmitCommonEHFrame(Personalities[i], i);
3597 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3598 E = EHFrames.end(); I != E; ++I)
3603 /// BeginFunction - Gather pre-function exception information. Assumes being
3604 /// emitted immediately after the function entry point.
3605 void BeginFunction(MachineFunction *MF) {
3607 shouldEmitTable = shouldEmitMoves = false;
3608 if (MMI && TAI->doesSupportExceptionHandling()) {
3610 // Map all labels and get rid of any dead landing pads.
3611 MMI->TidyLandingPads();
3612 // If any landing pads survive, we need an EH table.
3613 if (MMI->getLandingPads().size())
3614 shouldEmitTable = true;
3616 // See if we need frame move info.
3617 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3618 shouldEmitMoves = true;
3620 if (shouldEmitMoves || shouldEmitTable)
3621 // Assumes in correct section after the entry point.
3622 EmitLabel("eh_func_begin", ++SubprogramCount);
3624 shouldEmitTableModule |= shouldEmitTable;
3625 shouldEmitMovesModule |= shouldEmitMoves;
3628 /// EndFunction - Gather and emit post-function exception information.
3630 void EndFunction() {
3631 if (shouldEmitMoves || shouldEmitTable) {
3632 EmitLabel("eh_func_end", SubprogramCount);
3633 EmitExceptionTable();
3635 // Save EH frame information
3637 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3639 MMI->getPersonalityIndex(),
3640 MF->getFrameInfo()->hasCalls(),
3641 !MMI->getLandingPads().empty(),
3642 MMI->getFrameMoves(),
3643 MF->getFunction()));
3648 } // End of namespace llvm
3650 //===----------------------------------------------------------------------===//
3652 /// Emit - Print the abbreviation using the specified Dwarf writer.
3654 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3655 // Emit its Dwarf tag type.
3656 DD.getAsm()->EmitULEB128Bytes(Tag);
3657 DD.getAsm()->EOL(TagString(Tag));
3659 // Emit whether it has children DIEs.
3660 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3661 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3663 // For each attribute description.
3664 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3665 const DIEAbbrevData &AttrData = Data[i];
3667 // Emit attribute type.
3668 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3669 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3672 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3673 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3676 // Mark end of abbreviation.
3677 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3678 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3682 void DIEAbbrev::print(std::ostream &O) {
3683 O << "Abbreviation @"
3684 << std::hex << (intptr_t)this << std::dec
3688 << ChildrenString(ChildrenFlag)
3691 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3693 << AttributeString(Data[i].getAttribute())
3695 << FormEncodingString(Data[i].getForm())
3699 void DIEAbbrev::dump() { print(cerr); }
3702 //===----------------------------------------------------------------------===//
3705 void DIEValue::dump() {
3710 //===----------------------------------------------------------------------===//
3712 /// EmitValue - Emit integer of appropriate size.
3714 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3716 case DW_FORM_flag: // Fall thru
3717 case DW_FORM_ref1: // Fall thru
3718 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3719 case DW_FORM_ref2: // Fall thru
3720 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3721 case DW_FORM_ref4: // Fall thru
3722 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3723 case DW_FORM_ref8: // Fall thru
3724 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3725 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3726 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3727 default: assert(0 && "DIE Value form not supported yet"); break;
3731 /// SizeOf - Determine size of integer value in bytes.
3733 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3735 case DW_FORM_flag: // Fall thru
3736 case DW_FORM_ref1: // Fall thru
3737 case DW_FORM_data1: return sizeof(int8_t);
3738 case DW_FORM_ref2: // Fall thru
3739 case DW_FORM_data2: return sizeof(int16_t);
3740 case DW_FORM_ref4: // Fall thru
3741 case DW_FORM_data4: return sizeof(int32_t);
3742 case DW_FORM_ref8: // Fall thru
3743 case DW_FORM_data8: return sizeof(int64_t);
3744 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
3745 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
3746 default: assert(0 && "DIE Value form not supported yet"); break;
3751 //===----------------------------------------------------------------------===//
3753 /// EmitValue - Emit string value.
3755 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3756 DD.getAsm()->EmitString(String);
3759 //===----------------------------------------------------------------------===//
3761 /// EmitValue - Emit label value.
3763 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3764 bool IsSmall = Form == DW_FORM_data4;
3765 DD.EmitReference(Label, false, IsSmall);
3768 /// SizeOf - Determine size of label value in bytes.
3770 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3771 if (Form == DW_FORM_data4) return 4;
3772 return DD.getTargetData()->getPointerSize();
3775 //===----------------------------------------------------------------------===//
3777 /// EmitValue - Emit label value.
3779 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3780 bool IsSmall = Form == DW_FORM_data4;
3781 DD.EmitReference(Label, false, IsSmall);
3784 /// SizeOf - Determine size of label value in bytes.
3786 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3787 if (Form == DW_FORM_data4) return 4;
3788 return DD.getTargetData()->getPointerSize();
3791 //===----------------------------------------------------------------------===//
3793 /// EmitValue - Emit delta value.
3795 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
3796 bool IsSmall = Form == DW_FORM_data4;
3797 DD.EmitSectionOffset(Label.Tag, Section.Tag,
3798 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
3801 /// SizeOf - Determine size of delta value in bytes.
3803 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3804 if (Form == DW_FORM_data4) return 4;
3805 return DD.getTargetData()->getPointerSize();
3808 //===----------------------------------------------------------------------===//
3810 /// EmitValue - Emit delta value.
3812 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3813 bool IsSmall = Form == DW_FORM_data4;
3814 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3817 /// SizeOf - Determine size of delta value in bytes.
3819 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3820 if (Form == DW_FORM_data4) return 4;
3821 return DD.getTargetData()->getPointerSize();
3824 //===----------------------------------------------------------------------===//
3826 /// EmitValue - Emit debug information entry offset.
3828 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3829 DD.getAsm()->EmitInt32(Entry->getOffset());
3832 //===----------------------------------------------------------------------===//
3834 /// ComputeSize - calculate the size of the block.
3836 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3838 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3840 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3841 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3847 /// EmitValue - Emit block data.
3849 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3851 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3852 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3853 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3854 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3855 default: assert(0 && "Improper form for block"); break;
3858 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3860 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3862 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3866 /// SizeOf - Determine size of block data in bytes.
3868 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3870 case DW_FORM_block1: return Size + sizeof(int8_t);
3871 case DW_FORM_block2: return Size + sizeof(int16_t);
3872 case DW_FORM_block4: return Size + sizeof(int32_t);
3873 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
3874 default: assert(0 && "Improper form for block"); break;
3879 //===----------------------------------------------------------------------===//
3880 /// DIE Implementation
3883 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3887 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3889 void DIE::AddSiblingOffset() {
3890 DIEInteger *DI = new DIEInteger(0);
3891 Values.insert(Values.begin(), DI);
3892 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3895 /// Profile - Used to gather unique data for the value folding set.
3897 void DIE::Profile(FoldingSetNodeID &ID) {
3900 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3901 ID.AddPointer(Children[i]);
3903 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3904 ID.AddPointer(Values[j]);
3908 void DIE::print(std::ostream &O, unsigned IncIndent) {
3909 static unsigned IndentCount = 0;
3910 IndentCount += IncIndent;
3911 const std::string Indent(IndentCount, ' ');
3912 bool isBlock = Abbrev.getTag() == 0;
3917 << "0x" << std::hex << (intptr_t)this << std::dec
3918 << ", Offset: " << Offset
3919 << ", Size: " << Size
3923 << TagString(Abbrev.getTag())
3925 << ChildrenString(Abbrev.getChildrenFlag());
3927 O << "Size: " << Size;
3931 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
3934 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3938 O << AttributeString(Data[i].getAttribute());
3940 O << "Blk[" << i << "]";
3943 << FormEncodingString(Data[i].getForm())
3945 Values[i]->print(O);
3950 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3951 Children[j]->print(O, 4);
3954 if (!isBlock) O << "\n";
3955 IndentCount -= IncIndent;
3963 //===----------------------------------------------------------------------===//
3964 /// DwarfWriter Implementation
3967 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
3968 const TargetAsmInfo *T) {
3969 DE = new DwarfException(OS, A, T);
3970 DD = new DwarfDebug(OS, A, T);
3973 DwarfWriter::~DwarfWriter() {
3978 /// SetModuleInfo - Set machine module info when it's known that pass manager
3979 /// has created it. Set by the target AsmPrinter.
3980 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3981 DD->SetModuleInfo(MMI);
3982 DE->SetModuleInfo(MMI);
3985 /// BeginModule - Emit all Dwarf sections that should come prior to the
3987 void DwarfWriter::BeginModule(Module *M) {
3992 /// EndModule - Emit all Dwarf sections that should come after the content.
3994 void DwarfWriter::EndModule() {
3999 /// BeginFunction - Gather pre-function debug information. Assumes being
4000 /// emitted immediately after the function entry point.
4001 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4002 DE->BeginFunction(MF);
4003 DD->BeginFunction(MF);
4006 /// EndFunction - Gather and emit post-function debug information.
4008 void DwarfWriter::EndFunction(MachineFunction *MF) {
4009 DD->EndFunction(MF);
4012 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4013 // Clear function debug information.