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"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/Analysis/DebugInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/FoldingSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringMap.h"
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
51 static TimerGroup &getDwarfTimerGroup() {
52 static TimerGroup DwarfTimerGroup("Dwarf Exception and Debugging");
53 return DwarfTimerGroup;
58 //===----------------------------------------------------------------------===//
60 /// Configuration values for initial hash set sizes (log2).
62 static const unsigned InitDiesSetSize = 9; // log2(512)
63 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
64 static const unsigned InitValuesSetSize = 9; // log2(512)
66 //===----------------------------------------------------------------------===//
67 /// Forward declarations.
72 //===----------------------------------------------------------------------===//
73 /// DWLabel - Labels are used to track locations in the assembler file.
74 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
75 /// where the tag is a category of label (Ex. location) and number is a value
76 /// unique in that category.
79 /// Tag - Label category tag. Should always be a staticly declared C string.
83 /// Number - Value to make label unique.
87 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
89 void Profile(FoldingSetNodeID &ID) const {
91 ID.AddInteger(Number);
95 void print(std::ostream *O) const {
98 void print(std::ostream &O) const {
100 if (Number) O << Number;
105 //===----------------------------------------------------------------------===//
106 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
107 /// Dwarf abbreviation.
108 class DIEAbbrevData {
109 /// Attribute - Dwarf attribute code.
113 /// Form - Dwarf form code.
117 DIEAbbrevData(unsigned A, unsigned F) : Attribute(A), Form(F) {}
120 unsigned getAttribute() const { return Attribute; }
121 unsigned getForm() const { return Form; }
123 /// Profile - Used to gather unique data for the abbreviation folding set.
125 void Profile(FoldingSetNodeID &ID)const {
126 ID.AddInteger(Attribute);
131 //===----------------------------------------------------------------------===//
132 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
133 /// information object.
134 class DIEAbbrev : public FoldingSetNode {
136 /// Tag - Dwarf tag code.
140 /// Unique number for node.
144 /// ChildrenFlag - Dwarf children flag.
146 unsigned ChildrenFlag;
148 /// Data - Raw data bytes for abbreviation.
150 SmallVector<DIEAbbrevData, 8> Data;
152 DIEAbbrev(unsigned T, unsigned C) : Tag(T), ChildrenFlag(C), Data() {}
153 virtual ~DIEAbbrev() {}
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), Offset(0), Size(0), Children(), Values() {}
231 DIEAbbrev &getAbbrev() { return Abbrev; }
232 unsigned getAbbrevNumber() const {
233 return Abbrev.getNumber();
235 unsigned getTag() const { return Abbrev.getTag(); }
236 unsigned getOffset() const { return Offset; }
237 unsigned getSize() const { return Size; }
238 const std::vector<DIE *> &getChildren() const { return Children; }
239 SmallVector<DIEValue*, 32> &getValues() { return Values; }
240 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
241 void setOffset(unsigned O) { Offset = O; }
242 void setSize(unsigned S) { Size = S; }
244 /// AddValue - Add a value and attributes to a DIE.
246 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
247 Abbrev.AddAttribute(Attribute, Form);
248 Values.push_back(Value);
251 /// SiblingOffset - Return the offset of the debug information entry's
253 unsigned SiblingOffset() const { return Offset + Size; }
255 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
257 void AddSiblingOffset();
259 /// AddChild - Add a child to the DIE.
261 void AddChild(DIE *Child) {
262 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
263 Children.push_back(Child);
266 /// Detach - Detaches objects connected to it after copying.
272 /// Profile - Used to gather unique data for the value folding set.
274 void Profile(FoldingSetNodeID &ID) ;
277 void print(std::ostream *O, unsigned IncIndent = 0) {
278 if (O) print(*O, IncIndent);
280 void print(std::ostream &O, unsigned IncIndent = 0);
285 //===----------------------------------------------------------------------===//
286 /// DIEValue - A debug information entry value.
288 class DIEValue : public FoldingSetNode {
301 /// Type - Type of data stored in the value.
305 explicit DIEValue(unsigned T) : Type(T) {}
306 virtual ~DIEValue() {}
309 unsigned getType() const { return Type; }
311 // Implement isa/cast/dyncast.
312 static bool classof(const DIEValue *) { return true; }
314 /// EmitValue - Emit value via the Dwarf writer.
316 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
318 /// SizeOf - Return the size of a value in bytes.
320 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
322 /// Profile - Used to gather unique data for the value folding set.
324 virtual void Profile(FoldingSetNodeID &ID) = 0;
327 void print(std::ostream *O) {
330 virtual void print(std::ostream &O) = 0;
335 //===----------------------------------------------------------------------===//
336 /// DWInteger - An integer value DIE.
338 class DIEInteger : public DIEValue {
343 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
345 // Implement isa/cast/dyncast.
346 static bool classof(const DIEInteger *) { return true; }
347 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
349 /// BestForm - Choose the best form for integer.
351 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
353 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
354 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
355 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
357 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
358 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
359 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
361 return DW_FORM_data8;
364 /// EmitValue - Emit integer of appropriate size.
366 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
368 /// SizeOf - Determine size of integer value in bytes.
370 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
372 /// Profile - Used to gather unique data for the value folding set.
374 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
375 ID.AddInteger(isInteger);
376 ID.AddInteger(Integer);
378 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
381 virtual void print(std::ostream &O) {
382 O << "Int: " << (int64_t)Integer
383 << " 0x" << std::hex << Integer << std::dec;
388 //===----------------------------------------------------------------------===//
389 /// DIEString - A string value DIE.
391 class DIEString : public DIEValue {
392 const std::string Str;
394 explicit DIEString(const std::string &S) : DIEValue(isString), Str(S) {}
396 // Implement isa/cast/dyncast.
397 static bool classof(const DIEString *) { return true; }
398 static bool classof(const DIEValue *S) { return S->Type == isString; }
400 /// EmitValue - Emit string value.
402 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
404 /// SizeOf - Determine size of string value in bytes.
406 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
407 return Str.size() + sizeof(char); // sizeof('\0');
410 /// Profile - Used to gather unique data for the value folding set.
412 static void Profile(FoldingSetNodeID &ID, const std::string &Str) {
413 ID.AddInteger(isString);
416 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Str); }
419 virtual void print(std::ostream &O) {
420 O << "Str: \"" << Str << "\"";
425 //===----------------------------------------------------------------------===//
426 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
428 class DIEDwarfLabel : public DIEValue {
431 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
433 // Implement isa/cast/dyncast.
434 static bool classof(const DIEDwarfLabel *) { return true; }
435 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
437 /// EmitValue - Emit label value.
439 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
441 /// SizeOf - Determine size of label value in bytes.
443 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
445 /// Profile - Used to gather unique data for the value folding set.
447 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
448 ID.AddInteger(isLabel);
451 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
454 virtual void print(std::ostream &O) {
461 //===----------------------------------------------------------------------===//
462 /// DIEObjectLabel - A label to an object in code or data.
464 class DIEObjectLabel : public DIEValue {
465 const std::string Label;
467 explicit DIEObjectLabel(const std::string &L)
468 : DIEValue(isAsIsLabel), Label(L) {}
470 // Implement isa/cast/dyncast.
471 static bool classof(const DIEObjectLabel *) { return true; }
472 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
474 /// EmitValue - Emit label value.
476 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
478 /// SizeOf - Determine size of label value in bytes.
480 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
482 /// Profile - Used to gather unique data for the value folding set.
484 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
485 ID.AddInteger(isAsIsLabel);
488 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
491 virtual void print(std::ostream &O) {
492 O << "Obj: " << Label;
497 //===----------------------------------------------------------------------===//
498 /// DIESectionOffset - A section offset DIE.
500 class DIESectionOffset : public DIEValue {
502 const DWLabel Section;
506 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
507 bool isEH = false, bool useSet = true)
508 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
509 IsEH(isEH), UseSet(useSet) {}
511 // Implement isa/cast/dyncast.
512 static bool classof(const DIESectionOffset *) { return true; }
513 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
515 /// EmitValue - Emit section offset.
517 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
519 /// SizeOf - Determine size of section offset value in bytes.
521 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
523 /// Profile - Used to gather unique data for the value folding set.
525 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
526 const DWLabel &Section) {
527 ID.AddInteger(isSectionOffset);
530 // IsEH and UseSet are specific to the Label/Section that we will emit
531 // the offset for; so Label/Section are enough for uniqueness.
533 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
536 virtual void print(std::ostream &O) {
541 O << "-" << IsEH << "-" << UseSet;
546 //===----------------------------------------------------------------------===//
547 /// DIEDelta - A simple label difference DIE.
549 class DIEDelta : public DIEValue {
550 const DWLabel LabelHi;
551 const DWLabel LabelLo;
553 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
554 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
556 // Implement isa/cast/dyncast.
557 static bool classof(const DIEDelta *) { return true; }
558 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
560 /// EmitValue - Emit delta value.
562 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
564 /// SizeOf - Determine size of delta value in bytes.
566 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
568 /// Profile - Used to gather unique data for the value folding set.
570 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
571 const DWLabel &LabelLo) {
572 ID.AddInteger(isDelta);
576 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
579 virtual void print(std::ostream &O) {
588 //===----------------------------------------------------------------------===//
589 /// DIEntry - A pointer to another debug information entry. An instance of this
590 /// class can also be used as a proxy for a debug information entry not yet
591 /// defined (ie. types.)
592 class DIEntry : public DIEValue {
595 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
597 void setEntry(DIE *E) { Entry = E; }
599 // Implement isa/cast/dyncast.
600 static bool classof(const DIEntry *) { return true; }
601 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
603 /// EmitValue - Emit debug information entry offset.
605 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
607 /// SizeOf - Determine size of debug information entry in bytes.
609 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
610 return sizeof(int32_t);
613 /// Profile - Used to gather unique data for the value folding set.
615 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
616 ID.AddInteger(isEntry);
617 ID.AddPointer(Entry);
619 virtual void Profile(FoldingSetNodeID &ID) {
620 ID.AddInteger(isEntry);
623 ID.AddPointer(Entry);
630 virtual void print(std::ostream &O) {
631 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
636 //===----------------------------------------------------------------------===//
637 /// DIEBlock - A block of values. Primarily used for location expressions.
639 class DIEBlock : public DIEValue, public DIE {
640 unsigned Size; // Size in bytes excluding size header.
643 : DIEValue(isBlock), DIE(0), Size(0) {}
644 virtual ~DIEBlock() {}
646 // Implement isa/cast/dyncast.
647 static bool classof(const DIEBlock *) { return true; }
648 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
650 /// ComputeSize - calculate the size of the block.
652 unsigned ComputeSize(DwarfDebug &DD);
654 /// BestForm - Choose the best form for data.
656 unsigned BestForm() const {
657 if ((unsigned char)Size == Size) return DW_FORM_block1;
658 if ((unsigned short)Size == Size) return DW_FORM_block2;
659 if ((unsigned int)Size == Size) return DW_FORM_block4;
660 return DW_FORM_block;
663 /// EmitValue - Emit block data.
665 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
667 /// SizeOf - Determine size of block data in bytes.
669 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
671 /// Profile - Used to gather unique data for the value folding set.
673 virtual void Profile(FoldingSetNodeID &ID) {
674 ID.AddInteger(isBlock);
679 virtual void print(std::ostream &O) {
686 //===----------------------------------------------------------------------===//
687 /// CompileUnit - This dwarf writer support class manages information associate
688 /// with a source file.
690 /// ID - File identifier for source.
694 /// Die - Compile unit debug information entry.
698 /// GVToDieMap - Tracks the mapping of unit level debug informaton
699 /// variables to debug information entries.
700 std::map<GlobalVariable *, DIE *> GVToDieMap;
702 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
703 /// descriptors to debug information entries using a DIEntry proxy.
704 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
706 /// Globals - A map of globally visible named entities for this unit.
708 StringMap<DIE*> Globals;
710 /// DiesSet - Used to uniquely define dies within the compile unit.
712 FoldingSet<DIE> DiesSet;
714 CompileUnit(unsigned I, DIE *D)
715 : ID(I), Die(D), GVToDieMap(),
716 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
724 unsigned getID() const { return ID; }
725 DIE* getDie() const { return Die; }
726 StringMap<DIE*> &getGlobals() { return Globals; }
728 /// hasContent - Return true if this compile unit has something to write out.
730 bool hasContent() const {
731 return !Die->getChildren().empty();
734 /// AddGlobal - Add a new global entity to the compile unit.
736 void AddGlobal(const std::string &Name, DIE *Die) {
740 /// getDieMapSlotFor - Returns the debug information entry map slot for the
741 /// specified debug variable.
742 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
743 return GVToDieMap[GV];
746 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
747 /// specified debug variable.
748 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
749 return GVToDIEntryMap[GV];
752 /// AddDie - Adds or interns the DIE to the compile unit.
754 DIE *AddDie(DIE &Buffer) {
758 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
761 Die = new DIE(Buffer);
762 DiesSet.InsertNode(Die, Where);
763 this->Die->AddChild(Die);
771 //===----------------------------------------------------------------------===//
772 /// Dwarf - Emits general Dwarf directives.
776 //===--------------------------------------------------------------------===//
777 // Core attributes used by the Dwarf writer.
781 /// O - Stream to .s file.
785 /// Asm - Target of Dwarf emission.
789 /// TAI - Target asm information.
790 const TargetAsmInfo *TAI;
792 /// TD - Target data.
793 const TargetData *TD;
795 /// RI - Register Information.
796 const TargetRegisterInfo *RI;
798 /// M - Current module.
802 /// MF - Current machine function.
806 /// MMI - Collected machine module information.
808 MachineModuleInfo *MMI;
810 /// SubprogramCount - The running count of functions being compiled.
812 unsigned SubprogramCount;
814 /// Flavor - A unique string indicating what dwarf producer this is, used to
816 const char * const Flavor;
819 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
824 , TD(Asm->TM.getTargetData())
825 , RI(Asm->TM.getRegisterInfo())
836 //===--------------------------------------------------------------------===//
839 const AsmPrinter *getAsm() const { return Asm; }
840 MachineModuleInfo *getMMI() const { return MMI; }
841 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
842 const TargetData *getTargetData() const { return TD; }
844 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
846 if (isInSection && TAI->getDwarfSectionOffsetDirective())
847 O << TAI->getDwarfSectionOffsetDirective();
848 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
849 O << TAI->getData32bitsDirective();
851 O << TAI->getData64bitsDirective();
854 /// PrintLabelName - Print label name in form used by Dwarf writer.
856 void PrintLabelName(DWLabel Label) const {
857 PrintLabelName(Label.Tag, Label.Number);
859 void PrintLabelName(const char *Tag, unsigned Number) const {
860 O << TAI->getPrivateGlobalPrefix() << Tag;
861 if (Number) O << Number;
864 void PrintLabelName(const char *Tag, unsigned Number,
865 const char *Suffix) const {
866 O << TAI->getPrivateGlobalPrefix() << Tag;
867 if (Number) O << Number;
871 /// EmitLabel - Emit location label for internal use by Dwarf.
873 void EmitLabel(DWLabel Label) const {
874 EmitLabel(Label.Tag, Label.Number);
876 void EmitLabel(const char *Tag, unsigned Number) const {
877 PrintLabelName(Tag, Number);
881 /// EmitReference - Emit a reference to a label.
883 void EmitReference(DWLabel Label, bool IsPCRelative = false,
884 bool Force32Bit = false) const {
885 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
887 void EmitReference(const char *Tag, unsigned Number,
888 bool IsPCRelative = false, bool Force32Bit = false) const {
889 PrintRelDirective(Force32Bit);
890 PrintLabelName(Tag, Number);
892 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
894 void EmitReference(const std::string &Name, bool IsPCRelative = false,
895 bool Force32Bit = false) const {
896 PrintRelDirective(Force32Bit);
900 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
903 /// EmitDifference - Emit the difference between two labels. Some
904 /// assemblers do not behave with absolute expressions with data directives,
905 /// so there is an option (needsSet) to use an intermediary set expression.
906 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
907 bool IsSmall = false) {
908 EmitDifference(LabelHi.Tag, LabelHi.Number,
909 LabelLo.Tag, LabelLo.Number,
912 void EmitDifference(const char *TagHi, unsigned NumberHi,
913 const char *TagLo, unsigned NumberLo,
914 bool IsSmall = false) {
915 if (TAI->needsSet()) {
917 PrintLabelName("set", SetCounter, Flavor);
919 PrintLabelName(TagHi, NumberHi);
921 PrintLabelName(TagLo, NumberLo);
924 PrintRelDirective(IsSmall);
925 PrintLabelName("set", SetCounter, Flavor);
928 PrintRelDirective(IsSmall);
930 PrintLabelName(TagHi, NumberHi);
932 PrintLabelName(TagLo, NumberLo);
936 void EmitSectionOffset(const char* Label, const char* Section,
937 unsigned LabelNumber, unsigned SectionNumber,
938 bool IsSmall = false, bool isEH = false,
939 bool useSet = true) {
940 bool printAbsolute = false;
942 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
944 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
946 if (TAI->needsSet() && useSet) {
948 PrintLabelName("set", SetCounter, Flavor);
950 PrintLabelName(Label, LabelNumber);
952 if (!printAbsolute) {
954 PrintLabelName(Section, SectionNumber);
958 PrintRelDirective(IsSmall);
960 PrintLabelName("set", SetCounter, Flavor);
963 PrintRelDirective(IsSmall, true);
965 PrintLabelName(Label, LabelNumber);
967 if (!printAbsolute) {
969 PrintLabelName(Section, SectionNumber);
974 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
976 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
977 const std::vector<MachineMove> &Moves, bool isEH) {
979 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
980 TargetFrameInfo::StackGrowsUp ?
981 TD->getPointerSize() : -TD->getPointerSize();
982 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
984 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
985 const MachineMove &Move = Moves[i];
986 unsigned LabelID = Move.getLabelID();
989 LabelID = MMI->MappedLabel(LabelID);
991 // Throw out move if the label is invalid.
992 if (!LabelID) continue;
995 const MachineLocation &Dst = Move.getDestination();
996 const MachineLocation &Src = Move.getSource();
998 // Advance row if new location.
999 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1000 Asm->EmitInt8(DW_CFA_advance_loc4);
1001 Asm->EOL("DW_CFA_advance_loc4");
1002 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1005 BaseLabelID = LabelID;
1006 BaseLabel = "label";
1010 // If advancing cfa.
1011 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1013 if (Src.getReg() == MachineLocation::VirtualFP) {
1014 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1015 Asm->EOL("DW_CFA_def_cfa_offset");
1017 Asm->EmitInt8(DW_CFA_def_cfa);
1018 Asm->EOL("DW_CFA_def_cfa");
1019 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1020 Asm->EOL("Register");
1023 int Offset = -Src.getOffset();
1025 Asm->EmitULEB128Bytes(Offset);
1028 assert(0 && "Machine move no supported yet.");
1030 } else if (Src.isReg() &&
1031 Src.getReg() == MachineLocation::VirtualFP) {
1033 Asm->EmitInt8(DW_CFA_def_cfa_register);
1034 Asm->EOL("DW_CFA_def_cfa_register");
1035 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1036 Asm->EOL("Register");
1038 assert(0 && "Machine move no supported yet.");
1041 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1042 int Offset = Dst.getOffset() / stackGrowth;
1045 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1046 Asm->EOL("DW_CFA_offset_extended_sf");
1047 Asm->EmitULEB128Bytes(Reg);
1049 Asm->EmitSLEB128Bytes(Offset);
1051 } else if (Reg < 64) {
1052 Asm->EmitInt8(DW_CFA_offset + Reg);
1053 if (Asm->isVerbose())
1054 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1057 Asm->EmitULEB128Bytes(Offset);
1060 Asm->EmitInt8(DW_CFA_offset_extended);
1061 Asm->EOL("DW_CFA_offset_extended");
1062 Asm->EmitULEB128Bytes(Reg);
1064 Asm->EmitULEB128Bytes(Offset);
1073 //===----------------------------------------------------------------------===//
1074 /// SrcLineInfo - This class is used to record source line correspondence.
1077 unsigned Line; // Source line number.
1078 unsigned Column; // Source column.
1079 unsigned SourceID; // Source ID number.
1080 unsigned LabelID; // Label in code ID number.
1082 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1083 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1086 unsigned getLine() const { return Line; }
1087 unsigned getColumn() const { return Column; }
1088 unsigned getSourceID() const { return SourceID; }
1089 unsigned getLabelID() const { return LabelID; }
1092 //===----------------------------------------------------------------------===//
1093 /// DbgVariable - This class is used to track local variable information.
1096 DIVariable Var; // Variable Descriptor.
1097 unsigned FrameIndex; // Variable frame index.
1099 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1102 DIVariable getVariable() const { return Var; }
1103 unsigned getFrameIndex() const { return FrameIndex; }
1106 //===----------------------------------------------------------------------===//
1107 /// DbgScope - This class is used to track scope information.
1110 DbgScope *Parent; // Parent to this scope.
1111 DIDescriptor Desc; // Debug info descriptor for scope.
1112 // Either subprogram or block.
1113 unsigned StartLabelID; // Label ID of the beginning of scope.
1114 unsigned EndLabelID; // Label ID of the end of scope.
1115 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1116 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1118 DbgScope(DbgScope *P, DIDescriptor D)
1119 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1121 virtual ~DbgScope() {
1122 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1123 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1127 DbgScope *getParent() const { return Parent; }
1128 DIDescriptor getDesc() const { return Desc; }
1129 unsigned getStartLabelID() const { return StartLabelID; }
1130 unsigned getEndLabelID() const { return EndLabelID; }
1131 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1132 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1133 void setStartLabelID(unsigned S) { StartLabelID = S; }
1134 void setEndLabelID(unsigned E) { EndLabelID = E; }
1136 /// AddScope - Add a scope to the scope.
1138 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1140 /// AddVariable - Add a variable to the scope.
1142 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1144 virtual bool isInlinedSubroutine() { return false; }
1145 virtual unsigned getLine() { assert ( 0 && "Unexpected scope!"); return 0; }
1146 virtual unsigned getColumn() { assert ( 0 && "Unexpected scope!"); return 0; }
1147 virtual unsigned getFile() { assert ( 0 && "Unexpected scope!"); return 0; }
1155 void DbgScope::dump() const {
1156 static unsigned IndentLevel = 0;
1157 std::string Indent(IndentLevel, ' ');
1159 cerr << Indent; Desc.dump();
1160 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
1164 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
1165 if (Scopes[i] != this)
1172 //===----------------------------------------------------------------------===//
1173 /// DbgInlinedSubroutineScope - This class is used to track inlined subroutine
1174 /// scope information.
1176 class DbgInlinedSubroutineScope : public DbgScope {
1181 DbgInlinedSubroutineScope(DbgScope *P, DIDescriptor D,
1182 unsigned S, unsigned L, unsigned C)
1183 : DbgScope(P, D), Src(S), Line(L), Col(C)
1186 unsigned getLine() { return Line; }
1187 unsigned getColumn() { return Col; }
1188 unsigned getFile() { return Src; }
1189 bool isInlinedSubroutine() { return true; }
1192 //===----------------------------------------------------------------------===//
1193 /// DwarfDebug - Emits Dwarf debug directives.
1195 class DwarfDebug : public Dwarf {
1196 //===--------------------------------------------------------------------===//
1197 // Attributes used to construct specific Dwarf sections.
1200 /// CompileUnitMap - A map of global variables representing compile units to
1202 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1204 /// CompileUnits - All the compile units in this module.
1206 SmallVector<CompileUnit *, 8> CompileUnits;
1208 /// MainCU - Some platform prefers one compile unit per .o file. In such
1209 /// cases, all dies are inserted in MainCU.
1210 CompileUnit *MainCU;
1212 /// AbbreviationsSet - Used to uniquely define abbreviations.
1214 FoldingSet<DIEAbbrev> AbbreviationsSet;
1216 /// Abbreviations - A list of all the unique abbreviations in use.
1218 std::vector<DIEAbbrev *> Abbreviations;
1220 /// DirectoryIdMap - Directory name to directory id map.
1222 StringMap<unsigned> DirectoryIdMap;
1224 /// DirectoryNames - A list of directory names.
1225 SmallVector<std::string, 8> DirectoryNames;
1227 /// SourceFileIdMap - Source file name to source file id map.
1229 StringMap<unsigned> SourceFileIdMap;
1231 /// SourceFileNames - A list of source file names.
1232 SmallVector<std::string, 8> SourceFileNames;
1234 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1235 /// id mapped to a unique id.
1236 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1238 /// SourceIds - Reverse map from source id to directory id + file id pair.
1240 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1242 /// Lines - List of of source line correspondence.
1243 std::vector<SrcLineInfo> Lines;
1245 /// ValuesSet - Used to uniquely define values.
1247 FoldingSet<DIEValue> ValuesSet;
1249 /// Values - A list of all the unique values in use.
1251 std::vector<DIEValue *> Values;
1253 /// StringPool - A UniqueVector of strings used by indirect references.
1255 UniqueVector<std::string> StringPool;
1257 /// SectionMap - Provides a unique id per text section.
1259 UniqueVector<const Section*> SectionMap;
1261 /// SectionSourceLines - Tracks line numbers per text section.
1263 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1265 /// didInitial - Flag to indicate if initial emission has been done.
1269 /// shouldEmit - Flag to indicate if debug information should be emitted.
1273 // FunctionDbgScope - Top level scope for the current function.
1275 DbgScope *FunctionDbgScope;
1277 /// DbgScopeMap - Tracks the scopes in the current function.
1278 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1280 /// DbgInlinedScopeMap - Tracks inlined scopes in the current function.
1281 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> > DbgInlinedScopeMap;
1283 /// InlineInfo - Keep track of inlined functions and their location.
1284 /// This information is used to populate debug_inlined section.
1285 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> > InlineInfo;
1287 /// InlinedVariableScopes - Scopes information for the inlined subroutine
1289 DenseMap<const MachineInstr *, DbgScope *> InlinedVariableScopes;
1291 /// DebugTimer - Timer for the Dwarf debug writer.
1294 struct FunctionDebugFrameInfo {
1296 std::vector<MachineMove> Moves;
1298 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1299 Number(Num), Moves(M) { }
1302 std::vector<FunctionDebugFrameInfo> DebugFrames;
1305 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1306 /// maps to the source id. Source id starts at 1.
1307 std::pair<unsigned, unsigned>
1308 getSourceDirectoryAndFileIds(unsigned SId) const {
1309 return SourceIds[SId-1];
1312 /// getNumSourceDirectories - Return the number of source directories in the
1314 unsigned getNumSourceDirectories() const {
1315 return DirectoryNames.size();
1318 /// getSourceDirectoryName - Return the name of the directory corresponding
1320 const std::string &getSourceDirectoryName(unsigned Id) const {
1321 return DirectoryNames[Id - 1];
1324 /// getSourceFileName - Return the name of the source file corresponding
1326 const std::string &getSourceFileName(unsigned Id) const {
1327 return SourceFileNames[Id - 1];
1330 /// getNumSourceIds - Return the number of unique source ids.
1331 unsigned getNumSourceIds() const {
1332 return SourceIds.size();
1335 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1337 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1338 // Profile the node so that we can make it unique.
1339 FoldingSetNodeID ID;
1342 // Check the set for priors.
1343 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1345 // If it's newly added.
1346 if (InSet == &Abbrev) {
1347 // Add to abbreviation list.
1348 Abbreviations.push_back(&Abbrev);
1349 // Assign the vector position + 1 as its number.
1350 Abbrev.setNumber(Abbreviations.size());
1352 // Assign existing abbreviation number.
1353 Abbrev.setNumber(InSet->getNumber());
1357 /// NewString - Add a string to the constant pool and returns a label.
1359 DWLabel NewString(const std::string &String) {
1360 unsigned StringID = StringPool.insert(String);
1361 return DWLabel("string", StringID);
1364 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1366 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1370 FoldingSetNodeID ID;
1371 DIEntry::Profile(ID, Entry);
1373 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1375 if (Value) return Value;
1377 Value = new DIEntry(Entry);
1378 ValuesSet.InsertNode(Value, Where);
1380 Value = new DIEntry(Entry);
1383 Values.push_back(Value);
1387 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1389 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1390 Value->setEntry(Entry);
1391 // Add to values set if not already there. If it is, we merely have a
1392 // duplicate in the values list (no harm.)
1393 ValuesSet.GetOrInsertNode(Value);
1396 /// AddUInt - Add an unsigned integer attribute data and value.
1398 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1399 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1401 FoldingSetNodeID ID;
1402 DIEInteger::Profile(ID, Integer);
1404 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1406 Value = new DIEInteger(Integer);
1407 ValuesSet.InsertNode(Value, Where);
1408 Values.push_back(Value);
1411 Die->AddValue(Attribute, Form, Value);
1414 /// AddSInt - Add an signed integer attribute data and value.
1416 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1417 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1419 FoldingSetNodeID ID;
1420 DIEInteger::Profile(ID, (uint64_t)Integer);
1422 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1424 Value = new DIEInteger(Integer);
1425 ValuesSet.InsertNode(Value, Where);
1426 Values.push_back(Value);
1429 Die->AddValue(Attribute, Form, Value);
1432 /// AddString - Add a string attribute data and value.
1434 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1435 const std::string &String) {
1436 FoldingSetNodeID ID;
1437 DIEString::Profile(ID, String);
1439 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1441 Value = new DIEString(String);
1442 ValuesSet.InsertNode(Value, Where);
1443 Values.push_back(Value);
1446 Die->AddValue(Attribute, Form, Value);
1449 /// AddLabel - Add a Dwarf label attribute data and value.
1451 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1452 const DWLabel &Label) {
1453 FoldingSetNodeID ID;
1454 DIEDwarfLabel::Profile(ID, Label);
1456 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1458 Value = new DIEDwarfLabel(Label);
1459 ValuesSet.InsertNode(Value, Where);
1460 Values.push_back(Value);
1463 Die->AddValue(Attribute, Form, Value);
1466 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1468 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1469 const std::string &Label) {
1470 FoldingSetNodeID ID;
1471 DIEObjectLabel::Profile(ID, Label);
1473 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1475 Value = new DIEObjectLabel(Label);
1476 ValuesSet.InsertNode(Value, Where);
1477 Values.push_back(Value);
1480 Die->AddValue(Attribute, Form, Value);
1483 /// AddSectionOffset - Add a section offset label attribute data and value.
1485 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1486 const DWLabel &Label, const DWLabel &Section,
1487 bool isEH = false, bool useSet = true) {
1488 FoldingSetNodeID ID;
1489 DIESectionOffset::Profile(ID, Label, Section);
1491 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1493 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1494 ValuesSet.InsertNode(Value, Where);
1495 Values.push_back(Value);
1498 Die->AddValue(Attribute, Form, Value);
1501 /// AddDelta - Add a label delta attribute data and value.
1503 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1504 const DWLabel &Hi, const DWLabel &Lo) {
1505 FoldingSetNodeID ID;
1506 DIEDelta::Profile(ID, Hi, Lo);
1508 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1510 Value = new DIEDelta(Hi, Lo);
1511 ValuesSet.InsertNode(Value, Where);
1512 Values.push_back(Value);
1515 Die->AddValue(Attribute, Form, Value);
1518 /// AddDIEntry - Add a DIE attribute data and value.
1520 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1521 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1524 /// AddBlock - Add block data.
1526 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1527 Block->ComputeSize(*this);
1528 FoldingSetNodeID ID;
1531 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1534 ValuesSet.InsertNode(Value, Where);
1535 Values.push_back(Value);
1537 // Already exists, reuse the previous one.
1539 Block = cast<DIEBlock>(Value);
1542 Die->AddValue(Attribute, Block->BestForm(), Value);
1545 /// AddSourceLine - Add location information to specified debug information
1547 void AddSourceLine(DIE *Die, const DIVariable *V) {
1548 // If there is no compile unit specified, don't add a line #.
1549 if (V->getCompileUnit().isNull())
1552 unsigned Line = V->getLineNumber();
1553 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
1554 assert(FileID && "Invalid file id");
1555 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1556 AddUInt(Die, DW_AT_decl_line, 0, Line);
1559 /// AddSourceLine - Add location information to specified debug information
1561 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1562 // If there is no compile unit specified, don't add a line #.
1563 if (G->getCompileUnit().isNull())
1565 unsigned Line = G->getLineNumber();
1566 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
1567 assert(FileID && "Invalid file id");
1568 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1569 AddUInt(Die, DW_AT_decl_line, 0, Line);
1572 void AddSourceLine(DIE *Die, const DIType *Ty) {
1573 // If there is no compile unit specified, don't add a line #.
1574 DICompileUnit CU = Ty->getCompileUnit();
1578 unsigned Line = Ty->getLineNumber();
1579 unsigned FileID = FindCompileUnit(CU).getID();
1580 assert(FileID && "Invalid file id");
1581 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1582 AddUInt(Die, DW_AT_decl_line, 0, Line);
1585 /// AddAddress - Add an address attribute to a die based on the location
1587 void AddAddress(DIE *Die, unsigned Attribute,
1588 const MachineLocation &Location) {
1589 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1590 DIEBlock *Block = new DIEBlock();
1592 if (Location.isReg()) {
1594 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1596 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1597 AddUInt(Block, 0, DW_FORM_udata, Reg);
1601 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1603 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1604 AddUInt(Block, 0, DW_FORM_udata, Reg);
1606 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1609 AddBlock(Die, Attribute, 0, Block);
1612 /// AddType - Add a new type attribute to the specified entity.
1613 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1617 // Check for pre-existence.
1618 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1619 // If it exists then use the existing value.
1621 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1626 Slot = NewDIEntry();
1629 DIE Buffer(DW_TAG_base_type);
1630 if (Ty.isBasicType(Ty.getTag()))
1631 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1632 else if (Ty.isDerivedType(Ty.getTag()))
1633 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1635 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1636 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1639 // Add debug information entry to entity and appropriate context.
1641 DIDescriptor Context = Ty.getContext();
1642 if (!Context.isNull())
1643 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1646 DIE *Child = new DIE(Buffer);
1647 Die->AddChild(Child);
1649 SetDIEntry(Slot, Child);
1651 Die = DW_Unit->AddDie(Buffer);
1652 SetDIEntry(Slot, Die);
1655 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1658 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1659 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1662 // Get core information.
1665 Buffer.setTag(DW_TAG_base_type);
1666 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1667 // Add name if not anonymous or intermediate type.
1669 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1670 uint64_t Size = BTy.getSizeInBits() >> 3;
1671 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1674 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1675 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1676 DIDerivedType DTy) {
1678 // Get core information.
1681 uint64_t Size = DTy.getSizeInBits() >> 3;
1682 unsigned Tag = DTy.getTag();
1684 // FIXME - Workaround for templates.
1685 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1689 // Map to main type, void will not have a type.
1690 DIType FromTy = DTy.getTypeDerivedFrom();
1691 AddType(DW_Unit, &Buffer, FromTy);
1693 // Add name if not anonymous or intermediate type.
1695 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1697 // Add size if non-zero (derived types might be zero-sized.)
1699 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1701 // Add source line info if available and TyDesc is not a forward
1703 if (!DTy.isForwardDecl())
1704 AddSourceLine(&Buffer, &DTy);
1707 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1708 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1709 DICompositeType CTy) {
1710 // Get core information.
1714 uint64_t Size = CTy.getSizeInBits() >> 3;
1715 unsigned Tag = CTy.getTag();
1719 case DW_TAG_vector_type:
1720 case DW_TAG_array_type:
1721 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1723 case DW_TAG_enumeration_type:
1725 DIArray Elements = CTy.getTypeArray();
1726 // Add enumerators to enumeration type.
1727 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1728 DIE *ElemDie = NULL;
1729 DIEnumerator Enum(Elements.getElement(i).getGV());
1730 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1731 Buffer.AddChild(ElemDie);
1735 case DW_TAG_subroutine_type:
1738 DIArray Elements = CTy.getTypeArray();
1739 DIDescriptor RTy = Elements.getElement(0);
1740 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1742 // Add prototype flag.
1743 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1746 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1747 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1748 DIDescriptor Ty = Elements.getElement(i);
1749 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1750 Buffer.AddChild(Arg);
1754 case DW_TAG_structure_type:
1755 case DW_TAG_union_type:
1756 case DW_TAG_class_type:
1758 // Add elements to structure type.
1759 DIArray Elements = CTy.getTypeArray();
1761 // A forward struct declared type may not have elements available.
1762 if (Elements.isNull())
1765 // Add elements to structure type.
1766 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1767 DIDescriptor Element = Elements.getElement(i);
1768 DIE *ElemDie = NULL;
1769 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1770 ElemDie = CreateSubprogramDIE(DW_Unit,
1771 DISubprogram(Element.getGV()));
1772 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1773 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1774 DIGlobalVariable(Element.getGV()));
1776 ElemDie = CreateMemberDIE(DW_Unit,
1777 DIDerivedType(Element.getGV()));
1778 Buffer.AddChild(ElemDie);
1780 unsigned RLang = CTy.getRunTimeLang();
1782 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1789 // Add name if not anonymous or intermediate type.
1791 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1793 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1794 || Tag == DW_TAG_union_type) {
1795 // Add size if non-zero (derived types might be zero-sized.)
1797 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1799 // Add zero size if it is not a forward declaration.
1800 if (CTy.isForwardDecl())
1801 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1803 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1806 // Add source line info if available.
1807 if (!CTy.isForwardDecl())
1808 AddSourceLine(&Buffer, &CTy);
1812 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1813 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1814 int64_t L = SR.getLo();
1815 int64_t H = SR.getHi();
1816 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1818 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1820 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1821 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1823 Buffer.AddChild(DW_Subrange);
1826 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1827 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1828 DICompositeType *CTy) {
1829 Buffer.setTag(DW_TAG_array_type);
1830 if (CTy->getTag() == DW_TAG_vector_type)
1831 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1833 // Emit derived type.
1834 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1835 DIArray Elements = CTy->getTypeArray();
1837 // Construct an anonymous type for index type.
1838 DIE IdxBuffer(DW_TAG_base_type);
1839 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1840 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1841 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1843 // Add subranges to array type.
1844 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1845 DIDescriptor Element = Elements.getElement(i);
1846 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1847 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1851 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1852 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1854 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1857 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1858 int64_t Value = ETy->getEnumValue();
1859 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1863 /// CreateGlobalVariableDIE - Create new DIE using GV.
1864 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1866 DIE *GVDie = new DIE(DW_TAG_variable);
1868 GV.getDisplayName(Name);
1869 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1870 std::string LinkageName;
1871 GV.getLinkageName(LinkageName);
1872 if (!LinkageName.empty())
1873 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1874 AddType(DW_Unit, GVDie, GV.getType());
1875 if (!GV.isLocalToUnit())
1876 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1877 AddSourceLine(GVDie, &GV);
1881 /// CreateMemberDIE - Create new member DIE.
1882 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1883 DIE *MemberDie = new DIE(DT.getTag());
1887 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1889 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1891 AddSourceLine(MemberDie, &DT);
1893 uint64_t Size = DT.getSizeInBits();
1894 uint64_t FieldSize = DT.getOriginalTypeSize();
1896 if (Size != FieldSize) {
1898 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1899 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1901 uint64_t Offset = DT.getOffsetInBits();
1902 uint64_t FieldOffset = Offset;
1903 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1904 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1905 FieldOffset = (HiMark - FieldSize);
1906 Offset -= FieldOffset;
1907 // Maybe we need to work from the other end.
1908 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1909 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1911 DIEBlock *Block = new DIEBlock();
1912 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1913 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1914 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1916 if (DT.isProtected())
1917 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1918 else if (DT.isPrivate())
1919 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1924 /// CreateSubprogramDIE - Create new DIE using SP.
1925 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1926 const DISubprogram &SP,
1927 bool IsConstructor = false) {
1928 DIE *SPDie = new DIE(DW_TAG_subprogram);
1932 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1934 std::string LinkageName;
1935 SP.getLinkageName(LinkageName);
1937 if (!LinkageName.empty())
1938 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1940 AddSourceLine(SPDie, &SP);
1942 DICompositeType SPTy = SP.getType();
1943 DIArray Args = SPTy.getTypeArray();
1945 // Add prototyped tag, if C or ObjC.
1946 unsigned Lang = SP.getCompileUnit().getLanguage();
1947 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89 || Lang == DW_LANG_ObjC)
1948 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1951 unsigned SPTag = SPTy.getTag();
1952 if (!IsConstructor) {
1953 if (Args.isNull() || SPTag != DW_TAG_subroutine_type)
1954 AddType(DW_Unit, SPDie, SPTy);
1956 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1959 if (!SP.isDefinition()) {
1960 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1961 // Add arguments. Do not add arguments for subprogram definition. They
1962 // will be handled through RecordVariable.
1963 if (SPTag == DW_TAG_subroutine_type)
1964 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1965 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1966 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1967 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ??
1968 SPDie->AddChild(Arg);
1972 if (!SP.isLocalToUnit())
1973 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1975 // DW_TAG_inlined_subroutine may refer to this DIE.
1976 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
1981 /// FindCompileUnit - Get the compile unit for the given descriptor.
1983 CompileUnit &FindCompileUnit(DICompileUnit Unit) const {
1984 DenseMap<Value *, CompileUnit *>::const_iterator I =
1985 CompileUnitMap.find(Unit.getGV());
1986 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1990 /// NewDbgScopeVariable - Create a new scope variable.
1992 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1993 // Get the descriptor.
1994 const DIVariable &VD = DV->getVariable();
1996 // Translate tag to proper Dwarf tag. The result variable is dropped for
1999 switch (VD.getTag()) {
2000 case DW_TAG_return_variable: return NULL;
2001 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2002 case DW_TAG_auto_variable: // fall thru
2003 default: Tag = DW_TAG_variable; break;
2006 // Define variable debug information entry.
2007 DIE *VariableDie = new DIE(Tag);
2010 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2012 // Add source line info if available.
2013 AddSourceLine(VariableDie, &VD);
2015 // Add variable type.
2016 AddType(Unit, VariableDie, VD.getType());
2018 // Add variable address.
2019 MachineLocation Location;
2020 Location.set(RI->getFrameRegister(*MF),
2021 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2022 AddAddress(VariableDie, DW_AT_location, Location);
2027 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2029 DbgScope *getOrCreateScope(GlobalVariable *V) {
2030 DbgScope *&Slot = DbgScopeMap[V];
2031 if (Slot) return Slot;
2033 DbgScope *Parent = NULL;
2036 if (!Block.isNull()) {
2037 DIDescriptor ParentDesc = Block.getContext();
2039 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
2042 Slot = new DbgScope(Parent, DIDescriptor(V));
2045 Parent->AddScope(Slot);
2047 // First function is top level function.
2048 FunctionDbgScope = Slot;
2053 /// createInlinedSubroutineScope - Returns the scope associated with the
2054 /// inlined subroutine.
2056 DbgScope *createInlinedSubroutineScope(DISubprogram SP, unsigned Src,
2057 unsigned Line, unsigned Col) {
2059 new DbgInlinedSubroutineScope(NULL, SP, Src, Line, Col);
2061 // FIXME - Add inlined function scopes to the root so we can delete them
2063 assert (FunctionDbgScope && "Function scope info missing!");
2064 FunctionDbgScope->AddScope(Scope);
2068 /// ConstructDbgScope - Construct the components of a scope.
2070 void ConstructDbgScope(DbgScope *ParentScope,
2071 unsigned ParentStartID, unsigned ParentEndID,
2072 DIE *ParentDie, CompileUnit *Unit) {
2073 // Add variables to scope.
2074 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2075 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2076 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2077 if (VariableDie) ParentDie->AddChild(VariableDie);
2080 // Add nested scopes.
2081 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2082 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2083 // Define the Scope debug information entry.
2084 DbgScope *Scope = Scopes[j];
2086 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2087 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2089 // Ignore empty scopes.
2090 // Do not ignore inlined scope even if it does not have any
2091 // variables or scopes.
2092 if (StartID == EndID && StartID != 0) continue;
2093 if (!Scope->isInlinedSubroutine()
2094 && Scope->getScopes().empty() && Scope->getVariables().empty())
2097 if (StartID == ParentStartID && EndID == ParentEndID) {
2098 // Just add stuff to the parent scope.
2099 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2101 DIE *ScopeDie = NULL;
2102 if (MainCU && TAI->doesDwarfUsesInlineInfoSection()
2103 && Scope->isInlinedSubroutine()) {
2104 ScopeDie = new DIE(DW_TAG_inlined_subroutine);
2105 DIE *Origin = MainCU->getDieMapSlotFor(Scope->getDesc().getGV());
2106 AddDIEntry(ScopeDie, DW_AT_abstract_origin, DW_FORM_ref4, Origin);
2107 AddUInt(ScopeDie, DW_AT_call_file, 0, Scope->getFile());
2108 AddUInt(ScopeDie, DW_AT_call_line, 0, Scope->getLine());
2109 AddUInt(ScopeDie, DW_AT_call_column, 0, Scope->getColumn());
2111 ScopeDie = new DIE(DW_TAG_lexical_block);
2114 // Add the scope bounds.
2116 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2117 DWLabel("label", StartID));
2119 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2120 DWLabel("func_begin", SubprogramCount));
2123 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2124 DWLabel("label", EndID));
2126 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2127 DWLabel("func_end", SubprogramCount));
2129 // Add the scope contents.
2130 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2131 ParentDie->AddChild(ScopeDie);
2136 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
2138 void ConstructFunctionDbgScope(DbgScope *RootScope) {
2139 // Exit if there is no root scope.
2140 if (!RootScope) return;
2141 DIDescriptor Desc = RootScope->getDesc();
2145 // Get the subprogram debug information entry.
2146 DISubprogram SPD(Desc.getGV());
2148 // Get the compile unit context.
2149 CompileUnit *Unit = MainCU;
2151 Unit = &FindCompileUnit(SPD.getCompileUnit());
2153 // Get the subprogram die.
2154 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2155 assert(SPDie && "Missing subprogram descriptor");
2157 // Add the function bounds.
2158 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2159 DWLabel("func_begin", SubprogramCount));
2160 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2161 DWLabel("func_end", SubprogramCount));
2162 MachineLocation Location(RI->getFrameRegister(*MF));
2163 AddAddress(SPDie, DW_AT_frame_base, Location);
2165 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2168 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2170 void ConstructDefaultDbgScope(MachineFunction *MF) {
2171 const char *FnName = MF->getFunction()->getNameStart();
2173 StringMap<DIE*> &Globals = MainCU->getGlobals();
2174 StringMap<DIE*>::iterator GI = Globals.find(FnName);
2175 if (GI != Globals.end()) {
2176 DIE *SPDie = GI->second;
2178 // Add the function bounds.
2179 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2180 DWLabel("func_begin", SubprogramCount));
2181 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2182 DWLabel("func_end", SubprogramCount));
2184 MachineLocation Location(RI->getFrameRegister(*MF));
2185 AddAddress(SPDie, DW_AT_frame_base, Location);
2189 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2190 CompileUnit *Unit = CompileUnits[i];
2191 StringMap<DIE*> &Globals = Unit->getGlobals();
2192 StringMap<DIE*>::iterator GI = Globals.find(FnName);
2193 if (GI != Globals.end()) {
2194 DIE *SPDie = GI->second;
2196 // Add the function bounds.
2197 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2198 DWLabel("func_begin", SubprogramCount));
2199 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2200 DWLabel("func_end", SubprogramCount));
2202 MachineLocation Location(RI->getFrameRegister(*MF));
2203 AddAddress(SPDie, DW_AT_frame_base, Location);
2210 // FIXME: This is causing an abort because C++ mangled names are compared
2211 // with their unmangled counterparts. See PR2885. Don't do this assert.
2212 assert(0 && "Couldn't find DIE for machine function!");
2217 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2218 /// tools to recognize the object file contains Dwarf information.
2219 void EmitInitial() {
2220 // Check to see if we already emitted intial headers.
2221 if (didInitial) return;
2224 // Dwarf sections base addresses.
2225 if (TAI->doesDwarfRequireFrameSection()) {
2226 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2227 EmitLabel("section_debug_frame", 0);
2229 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2230 EmitLabel("section_info", 0);
2231 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2232 EmitLabel("section_abbrev", 0);
2233 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2234 EmitLabel("section_aranges", 0);
2235 if (TAI->doesSupportMacInfoSection()) {
2236 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2237 EmitLabel("section_macinfo", 0);
2239 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2240 EmitLabel("section_line", 0);
2241 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2242 EmitLabel("section_loc", 0);
2243 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2244 EmitLabel("section_pubnames", 0);
2245 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2246 EmitLabel("section_str", 0);
2247 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2248 EmitLabel("section_ranges", 0);
2250 Asm->SwitchToSection(TAI->getTextSection());
2251 EmitLabel("text_begin", 0);
2252 Asm->SwitchToSection(TAI->getDataSection());
2253 EmitLabel("data_begin", 0);
2256 /// EmitDIE - Recusively Emits a debug information entry.
2258 void EmitDIE(DIE *Die) {
2259 // Get the abbreviation for this DIE.
2260 unsigned AbbrevNumber = Die->getAbbrevNumber();
2261 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2265 // Emit the code (index) for the abbreviation.
2266 Asm->EmitULEB128Bytes(AbbrevNumber);
2268 if (Asm->isVerbose())
2269 Asm->EOL(std::string("Abbrev [" +
2270 utostr(AbbrevNumber) +
2271 "] 0x" + utohexstr(Die->getOffset()) +
2272 ":0x" + utohexstr(Die->getSize()) + " " +
2273 TagString(Abbrev->getTag())));
2277 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2278 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2280 // Emit the DIE attribute values.
2281 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2282 unsigned Attr = AbbrevData[i].getAttribute();
2283 unsigned Form = AbbrevData[i].getForm();
2284 assert(Form && "Too many attributes for DIE (check abbreviation)");
2287 case DW_AT_sibling: {
2288 Asm->EmitInt32(Die->SiblingOffset());
2292 // Emit an attribute using the defined form.
2293 Values[i]->EmitValue(*this, Form);
2298 Asm->EOL(AttributeString(Attr));
2301 // Emit the DIE children if any.
2302 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2303 const std::vector<DIE *> &Children = Die->getChildren();
2305 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2306 EmitDIE(Children[j]);
2309 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2313 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2315 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2316 // Get the children.
2317 const std::vector<DIE *> &Children = Die->getChildren();
2319 // If not last sibling and has children then add sibling offset attribute.
2320 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2322 // Record the abbreviation.
2323 AssignAbbrevNumber(Die->getAbbrev());
2325 // Get the abbreviation for this DIE.
2326 unsigned AbbrevNumber = Die->getAbbrevNumber();
2327 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2330 Die->setOffset(Offset);
2332 // Start the size with the size of abbreviation code.
2333 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2335 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2336 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2338 // Size the DIE attribute values.
2339 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2340 // Size attribute value.
2341 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2344 // Size the DIE children if any.
2345 if (!Children.empty()) {
2346 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2347 "Children flag not set");
2349 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2350 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2353 // End of children marker.
2354 Offset += sizeof(int8_t);
2357 Die->setSize(Offset - Die->getOffset());
2361 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2363 void SizeAndOffsets() {
2364 // Process base compile unit.
2366 // Compute size of compile unit header
2367 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2368 sizeof(int16_t) + // DWARF version number
2369 sizeof(int32_t) + // Offset Into Abbrev. Section
2370 sizeof(int8_t); // Pointer Size (in bytes)
2371 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2374 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2375 CompileUnit *Unit = CompileUnits[i];
2376 // Compute size of compile unit header
2377 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2378 sizeof(int16_t) + // DWARF version number
2379 sizeof(int32_t) + // Offset Into Abbrev. Section
2380 sizeof(int8_t); // Pointer Size (in bytes)
2381 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2385 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2387 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2388 DIE *Die = Unit->getDie();
2389 // Emit the compile units header.
2390 EmitLabel("info_begin", Unit->getID());
2391 // Emit size of content not including length itself
2392 unsigned ContentSize = Die->getSize() +
2393 sizeof(int16_t) + // DWARF version number
2394 sizeof(int32_t) + // Offset Into Abbrev. Section
2395 sizeof(int8_t) + // Pointer Size (in bytes)
2396 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2398 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2399 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2400 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2401 Asm->EOL("Offset Into Abbrev. Section");
2402 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2405 // FIXME - extra padding for gdb bug.
2406 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2407 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2408 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2409 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2410 EmitLabel("info_end", Unit->getID());
2415 void EmitDebugInfo() {
2416 // Start debug info section.
2417 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2420 EmitDebugInfoPerCU(MainCU);
2424 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2425 EmitDebugInfoPerCU(CompileUnits[i]);
2428 /// EmitAbbreviations - Emit the abbreviation section.
2430 void EmitAbbreviations() const {
2431 // Check to see if it is worth the effort.
2432 if (!Abbreviations.empty()) {
2433 // Start the debug abbrev section.
2434 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2436 EmitLabel("abbrev_begin", 0);
2438 // For each abbrevation.
2439 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2440 // Get abbreviation data
2441 const DIEAbbrev *Abbrev = Abbreviations[i];
2443 // Emit the abbrevations code (base 1 index.)
2444 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2445 Asm->EOL("Abbreviation Code");
2447 // Emit the abbreviations data.
2448 Abbrev->Emit(*this);
2453 // Mark end of abbreviations.
2454 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2456 EmitLabel("abbrev_end", 0);
2462 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2463 /// the line matrix.
2465 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2466 // Define last address of section.
2467 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2468 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2469 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2470 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2472 // Mark end of matrix.
2473 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2474 Asm->EmitULEB128Bytes(1); Asm->EOL();
2475 Asm->EmitInt8(1); Asm->EOL();
2478 /// EmitDebugLines - Emit source line information.
2480 void EmitDebugLines() {
2481 // If the target is using .loc/.file, the assembler will be emitting the
2482 // .debug_line table automatically.
2483 if (TAI->hasDotLocAndDotFile())
2486 // Minimum line delta, thus ranging from -10..(255-10).
2487 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2488 // Maximum line delta, thus ranging from -10..(255-10).
2489 const int MaxLineDelta = 255 + MinLineDelta;
2491 // Start the dwarf line section.
2492 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2494 // Construct the section header.
2496 EmitDifference("line_end", 0, "line_begin", 0, true);
2497 Asm->EOL("Length of Source Line Info");
2498 EmitLabel("line_begin", 0);
2500 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2502 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2503 Asm->EOL("Prolog Length");
2504 EmitLabel("line_prolog_begin", 0);
2506 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2508 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2510 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2512 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2514 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2516 // Line number standard opcode encodings argument count
2517 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2518 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2519 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2520 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2521 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2522 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2523 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2524 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2525 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2527 // Emit directories.
2528 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2529 Asm->EmitString(getSourceDirectoryName(DI));
2530 Asm->EOL("Directory");
2532 Asm->EmitInt8(0); Asm->EOL("End of directories");
2535 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2536 // Remember source id starts at 1.
2537 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2538 Asm->EmitString(getSourceFileName(Id.second));
2540 Asm->EmitULEB128Bytes(Id.first);
2541 Asm->EOL("Directory #");
2542 Asm->EmitULEB128Bytes(0);
2543 Asm->EOL("Mod date");
2544 Asm->EmitULEB128Bytes(0);
2545 Asm->EOL("File size");
2547 Asm->EmitInt8(0); Asm->EOL("End of files");
2549 EmitLabel("line_prolog_end", 0);
2551 // A sequence for each text section.
2552 unsigned SecSrcLinesSize = SectionSourceLines.size();
2554 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2555 // Isolate current sections line info.
2556 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2558 if (Asm->isVerbose()) {
2559 const Section* S = SectionMap[j + 1];
2560 O << '\t' << TAI->getCommentString() << " Section"
2561 << S->getName() << '\n';
2565 // Dwarf assumes we start with first line of first source file.
2566 unsigned Source = 1;
2569 // Construct rows of the address, source, line, column matrix.
2570 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2571 const SrcLineInfo &LineInfo = LineInfos[i];
2572 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2573 if (!LabelID) continue;
2575 if (!Asm->isVerbose())
2578 std::pair<unsigned, unsigned> SourceID =
2579 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2580 O << '\t' << TAI->getCommentString() << ' '
2581 << getSourceDirectoryName(SourceID.first) << ' '
2582 << getSourceFileName(SourceID.second)
2583 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2586 // Define the line address.
2587 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2588 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2589 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2590 EmitReference("label", LabelID); Asm->EOL("Location label");
2592 // If change of source, then switch to the new source.
2593 if (Source != LineInfo.getSourceID()) {
2594 Source = LineInfo.getSourceID();
2595 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2596 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2599 // If change of line.
2600 if (Line != LineInfo.getLine()) {
2601 // Determine offset.
2602 int Offset = LineInfo.getLine() - Line;
2603 int Delta = Offset - MinLineDelta;
2606 Line = LineInfo.getLine();
2608 // If delta is small enough and in range...
2609 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2610 // ... then use fast opcode.
2611 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2613 // ... otherwise use long hand.
2614 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2615 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2616 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2619 // Copy the previous row (different address or source)
2620 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2624 EmitEndOfLineMatrix(j + 1);
2627 if (SecSrcLinesSize == 0)
2628 // Because we're emitting a debug_line section, we still need a line
2629 // table. The linker and friends expect it to exist. If there's nothing to
2630 // put into it, emit an empty table.
2631 EmitEndOfLineMatrix(1);
2633 EmitLabel("line_end", 0);
2638 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2640 void EmitCommonDebugFrame() {
2641 if (!TAI->doesDwarfRequireFrameSection())
2645 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2646 TargetFrameInfo::StackGrowsUp ?
2647 TD->getPointerSize() : -TD->getPointerSize();
2649 // Start the dwarf frame section.
2650 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2652 EmitLabel("debug_frame_common", 0);
2653 EmitDifference("debug_frame_common_end", 0,
2654 "debug_frame_common_begin", 0, true);
2655 Asm->EOL("Length of Common Information Entry");
2657 EmitLabel("debug_frame_common_begin", 0);
2658 Asm->EmitInt32((int)DW_CIE_ID);
2659 Asm->EOL("CIE Identifier Tag");
2660 Asm->EmitInt8(DW_CIE_VERSION);
2661 Asm->EOL("CIE Version");
2662 Asm->EmitString("");
2663 Asm->EOL("CIE Augmentation");
2664 Asm->EmitULEB128Bytes(1);
2665 Asm->EOL("CIE Code Alignment Factor");
2666 Asm->EmitSLEB128Bytes(stackGrowth);
2667 Asm->EOL("CIE Data Alignment Factor");
2668 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2669 Asm->EOL("CIE RA Column");
2671 std::vector<MachineMove> Moves;
2672 RI->getInitialFrameState(Moves);
2674 EmitFrameMoves(NULL, 0, Moves, false);
2676 Asm->EmitAlignment(2, 0, 0, false);
2677 EmitLabel("debug_frame_common_end", 0);
2682 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2684 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2685 if (!TAI->doesDwarfRequireFrameSection())
2688 // Start the dwarf frame section.
2689 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2691 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2692 "debug_frame_begin", DebugFrameInfo.Number, true);
2693 Asm->EOL("Length of Frame Information Entry");
2695 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2697 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2699 Asm->EOL("FDE CIE offset");
2701 EmitReference("func_begin", DebugFrameInfo.Number);
2702 Asm->EOL("FDE initial location");
2703 EmitDifference("func_end", DebugFrameInfo.Number,
2704 "func_begin", DebugFrameInfo.Number);
2705 Asm->EOL("FDE address range");
2707 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2710 Asm->EmitAlignment(2, 0, 0, false);
2711 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2716 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2717 EmitDifference("pubnames_end", Unit->getID(),
2718 "pubnames_begin", Unit->getID(), true);
2719 Asm->EOL("Length of Public Names Info");
2721 EmitLabel("pubnames_begin", Unit->getID());
2723 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2725 EmitSectionOffset("info_begin", "section_info",
2726 Unit->getID(), 0, true, false);
2727 Asm->EOL("Offset of Compilation Unit Info");
2729 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2731 Asm->EOL("Compilation Unit Length");
2733 StringMap<DIE*> &Globals = Unit->getGlobals();
2734 for (StringMap<DIE*>::const_iterator
2735 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2736 const char *Name = GI->getKeyData();
2737 DIE * Entity = GI->second;
2739 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2740 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2743 Asm->EmitInt32(0); Asm->EOL("End Mark");
2744 EmitLabel("pubnames_end", Unit->getID());
2749 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2751 void EmitDebugPubNames() {
2752 // Start the dwarf pubnames section.
2753 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2756 EmitDebugPubNamesPerCU(MainCU);
2760 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2761 EmitDebugPubNamesPerCU(CompileUnits[i]);
2764 /// EmitDebugStr - Emit visible names into a debug str section.
2766 void EmitDebugStr() {
2767 // Check to see if it is worth the effort.
2768 if (!StringPool.empty()) {
2769 // Start the dwarf str section.
2770 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2772 // For each of strings in the string pool.
2773 for (unsigned StringID = 1, N = StringPool.size();
2774 StringID <= N; ++StringID) {
2775 // Emit a label for reference from debug information entries.
2776 EmitLabel("string", StringID);
2777 // Emit the string itself.
2778 const std::string &String = StringPool[StringID];
2779 Asm->EmitString(String); Asm->EOL();
2786 /// EmitDebugLoc - Emit visible names into a debug loc section.
2788 void EmitDebugLoc() {
2789 // Start the dwarf loc section.
2790 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2795 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2797 void EmitDebugARanges() {
2798 // Start the dwarf aranges section.
2799 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2803 CompileUnit *Unit = GetBaseCompileUnit();
2805 // Don't include size of length
2806 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2808 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2810 EmitReference("info_begin", Unit->getID());
2811 Asm->EOL("Offset of Compilation Unit Info");
2813 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2815 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2817 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2818 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2821 EmitReference("text_begin", 0); Asm->EOL("Address");
2822 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2824 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2825 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2831 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2833 void EmitDebugRanges() {
2834 // Start the dwarf ranges section.
2835 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2840 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2842 void EmitDebugMacInfo() {
2843 if (TAI->doesSupportMacInfoSection()) {
2844 // Start the dwarf macinfo section.
2845 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2851 /// EmitDebugInlineInfo - Emit inline info using following format.
2853 /// 1. length of section
2854 /// 2. Dwarf version number
2855 /// 3. address size.
2857 /// Entries (one "entry" for each function that was inlined):
2859 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2860 /// otherwise offset into __debug_str for regular function name.
2861 /// 2. offset into __debug_str section for regular function name.
2862 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2863 /// instances for the function.
2865 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2866 /// inlined instance; the die_offset points to the inlined_subroutine die in
2867 /// the __debug_info section, and the low_pc is the starting address for the
2868 /// inlining instance.
2869 void EmitDebugInlineInfo() {
2870 if (!TAI->doesDwarfUsesInlineInfoSection())
2876 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2878 EmitDifference("debug_inlined_end", 1,
2879 "debug_inlined_begin", 1, true);
2880 Asm->EOL("Length of Debug Inlined Information Entry");
2882 EmitLabel("debug_inlined_begin", 1);
2884 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2885 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2887 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2888 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2889 GlobalVariable *GV = I->first;
2890 SmallVector<unsigned, 4> &Labels = I->second;
2891 DISubprogram SP(GV);
2895 SP.getLinkageName(LName);
2898 Asm->EmitString(LName.empty() ? Name : LName);
2899 Asm->EOL("MIPS linkage name");
2901 Asm->EmitString(Name); Asm->EOL("Function name");
2903 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2905 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2906 LE = Labels.end(); LI != LE; ++LI) {
2907 DIE *SP = MainCU->getDieMapSlotFor(GV);
2908 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2910 if (TD->getPointerSize() == sizeof(int32_t))
2911 O << TAI->getData32bitsDirective();
2913 O << TAI->getData64bitsDirective();
2914 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2918 EmitLabel("debug_inlined_end", 1);
2922 /// GetOrCreateSourceID - Look up the source id with the given directory and
2923 /// source file names. If none currently exists, create a new id and insert it
2924 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2926 unsigned GetOrCreateSourceID(const std::string &DirName,
2927 const std::string &FileName) {
2929 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2930 if (DI != DirectoryIdMap.end()) {
2931 DId = DI->getValue();
2933 DId = DirectoryNames.size() + 1;
2934 DirectoryIdMap[DirName] = DId;
2935 DirectoryNames.push_back(DirName);
2939 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2940 if (FI != SourceFileIdMap.end()) {
2941 FId = FI->getValue();
2943 FId = SourceFileNames.size() + 1;
2944 SourceFileIdMap[FileName] = FId;
2945 SourceFileNames.push_back(FileName);
2948 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2949 SourceIdMap.find(std::make_pair(DId, FId));
2950 if (SI != SourceIdMap.end())
2953 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2954 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2955 SourceIds.push_back(std::make_pair(DId, FId));
2960 void ConstructCompileUnit(GlobalVariable *GV) {
2961 DICompileUnit DIUnit(GV);
2962 std::string Dir, FN, Prod;
2963 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2964 DIUnit.getFilename(FN));
2966 DIE *Die = new DIE(DW_TAG_compile_unit);
2967 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2968 DWLabel("section_line", 0), DWLabel("section_line", 0),
2970 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2971 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2972 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2974 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2975 if (DIUnit.isOptimized())
2976 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2978 DIUnit.getFlags(Flags);
2980 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2981 unsigned RVer = DIUnit.getRunTimeVersion();
2983 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2985 CompileUnit *Unit = new CompileUnit(ID, Die);
2986 if (DIUnit.isMain()) {
2987 assert(!MainCU && "Multiple main compile units are found!");
2990 CompileUnitMap[DIUnit.getGV()] = Unit;
2991 CompileUnits.push_back(Unit);
2994 /// ConstructCompileUnits - Create a compile unit DIEs.
2995 void ConstructCompileUnits() {
2996 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2999 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3000 "Malformed compile unit descriptor anchor type");
3001 Constant *RootC = cast<Constant>(*Root->use_begin());
3002 assert(RootC->hasNUsesOrMore(1) &&
3003 "Malformed compile unit descriptor anchor type");
3004 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3006 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3007 UUI != UUE; ++UUI) {
3008 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3009 ConstructCompileUnit(GV);
3013 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
3014 DIGlobalVariable DI_GV(GV);
3015 CompileUnit *DW_Unit = MainCU;
3017 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
3019 // Check for pre-existence.
3020 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
3024 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
3027 DIEBlock *Block = new DIEBlock();
3028 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3030 AddObjectLabel(Block, 0, DW_FORM_udata,
3031 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
3032 AddBlock(VariableDie, DW_AT_location, 0, Block);
3037 // Add to context owner.
3038 DW_Unit->getDie()->AddChild(VariableDie);
3040 // Expose as global. FIXME - need to check external flag.
3042 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
3046 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
3047 /// visible global variables. Return true if at least one global DIE is
3049 bool ConstructGlobalVariableDIEs() {
3050 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
3054 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3055 "Malformed global variable descriptor anchor type");
3056 Constant *RootC = cast<Constant>(*Root->use_begin());
3057 assert(RootC->hasNUsesOrMore(1) &&
3058 "Malformed global variable descriptor anchor type");
3060 bool Result = false;
3061 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3063 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3065 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
3070 bool ConstructSubprogram(GlobalVariable *GV) {
3071 DISubprogram SP(GV);
3072 CompileUnit *Unit = MainCU;
3074 Unit = &FindCompileUnit(SP.getCompileUnit());
3076 // Check for pre-existence.
3077 DIE *&Slot = Unit->getDieMapSlotFor(GV);
3081 if (!SP.isDefinition())
3082 // This is a method declaration which will be handled while
3083 // constructing class type.
3086 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
3089 Slot = SubprogramDie;
3090 // Add to context owner.
3091 Unit->getDie()->AddChild(SubprogramDie);
3092 // Expose as global.
3094 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
3098 /// ConstructSubprograms - Create DIEs for each of the externally visible
3099 /// subprograms. Return true if at least one subprogram DIE is created.
3100 bool ConstructSubprograms() {
3101 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
3105 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3106 "Malformed subprogram descriptor anchor type");
3107 Constant *RootC = cast<Constant>(*Root->use_begin());
3108 assert(RootC->hasNUsesOrMore(1) &&
3109 "Malformed subprogram descriptor anchor type");
3111 bool Result = false;
3112 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3114 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3116 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
3122 //===--------------------------------------------------------------------===//
3123 // Main entry points.
3125 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3126 : Dwarf(OS, A, T, "dbg"), MainCU(0),
3127 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
3128 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
3129 SectionSourceLines(), didInitial(false), shouldEmit(false),
3130 FunctionDbgScope(0), DebugTimer(0) {
3131 if (TimePassesIsEnabled)
3132 DebugTimer = new Timer("Dwarf Debug Writer",
3133 getDwarfTimerGroup());
3135 virtual ~DwarfDebug() {
3136 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3142 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3144 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
3146 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3147 /// This is inovked by the target AsmPrinter.
3148 void SetDebugInfo(MachineModuleInfo *mmi) {
3149 if (TimePassesIsEnabled)
3150 DebugTimer->startTimer();
3152 // Create all the compile unit DIEs.
3153 ConstructCompileUnits();
3155 if (CompileUnits.empty()) {
3156 if (TimePassesIsEnabled)
3157 DebugTimer->stopTimer();
3162 // Create DIEs for each of the externally visible global variables.
3163 bool globalDIEs = ConstructGlobalVariableDIEs();
3165 // Create DIEs for each of the externally visible subprograms.
3166 bool subprogramDIEs = ConstructSubprograms();
3168 // If there is not any debug info available for any global variables
3169 // and any subprograms then there is not any debug info to emit.
3170 if (!globalDIEs && !subprogramDIEs) {
3171 if (TimePassesIsEnabled)
3172 DebugTimer->stopTimer();
3179 MMI->setDebugInfoAvailability(true);
3181 // Prime section data.
3182 SectionMap.insert(TAI->getTextSection());
3184 // Print out .file directives to specify files for .loc directives. These
3185 // are printed out early so that they precede any .loc directives.
3186 if (TAI->hasDotLocAndDotFile()) {
3187 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3188 // Remember source id starts at 1.
3189 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3190 sys::Path FullPath(getSourceDirectoryName(Id.first));
3192 FullPath.appendComponent(getSourceFileName(Id.second));
3193 assert(AppendOk && "Could not append filename to directory!");
3195 Asm->EmitFile(i, FullPath.toString());
3200 // Emit initial sections
3203 if (TimePassesIsEnabled)
3204 DebugTimer->stopTimer();
3207 /// BeginModule - Emit all Dwarf sections that should come prior to the
3209 void BeginModule(Module *M) {
3213 /// EndModule - Emit all Dwarf sections that should come after the content.
3216 if (!ShouldEmitDwarfDebug())
3219 if (TimePassesIsEnabled)
3220 DebugTimer->startTimer();
3222 // Standard sections final addresses.
3223 Asm->SwitchToSection(TAI->getTextSection());
3224 EmitLabel("text_end", 0);
3225 Asm->SwitchToSection(TAI->getDataSection());
3226 EmitLabel("data_end", 0);
3228 // End text sections.
3229 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3230 Asm->SwitchToSection(SectionMap[i]);
3231 EmitLabel("section_end", i);
3234 // Emit common frame information.
3235 EmitCommonDebugFrame();
3237 // Emit function debug frame information
3238 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3239 E = DebugFrames.end(); I != E; ++I)
3240 EmitFunctionDebugFrame(*I);
3242 // Compute DIE offsets and sizes.
3245 // Emit all the DIEs into a debug info section
3248 // Corresponding abbreviations into a abbrev section.
3249 EmitAbbreviations();
3251 // Emit source line correspondence into a debug line section.
3254 // Emit info into a debug pubnames section.
3255 EmitDebugPubNames();
3257 // Emit info into a debug str section.
3260 // Emit info into a debug loc section.
3263 // Emit info into a debug aranges section.
3266 // Emit info into a debug ranges section.
3269 // Emit info into a debug macinfo section.
3272 // Emit inline info.
3273 EmitDebugInlineInfo();
3275 if (TimePassesIsEnabled)
3276 DebugTimer->stopTimer();
3279 /// BeginFunction - Gather pre-function debug information. Assumes being
3280 /// emitted immediately after the function entry point.
3281 void BeginFunction(MachineFunction *MF) {
3284 if (!ShouldEmitDwarfDebug()) return;
3286 if (TimePassesIsEnabled)
3287 DebugTimer->startTimer();
3289 // Begin accumulating function debug information.
3290 MMI->BeginFunction(MF);
3292 // Assumes in correct section after the entry point.
3293 EmitLabel("func_begin", ++SubprogramCount);
3295 // Emit label for the implicitly defined dbg.stoppoint at the start of
3297 DebugLoc FDL = MF->getDefaultDebugLoc();
3298 if (!FDL.isUnknown()) {
3299 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
3300 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
3301 DICompileUnit(DLT.CompileUnit));
3302 Asm->printLabel(LabelID);
3305 if (TimePassesIsEnabled)
3306 DebugTimer->stopTimer();
3309 /// EndFunction - Gather and emit post-function debug information.
3311 void EndFunction(MachineFunction *MF) {
3312 if (!ShouldEmitDwarfDebug()) return;
3314 if (TimePassesIsEnabled)
3315 DebugTimer->startTimer();
3317 // Define end label for subprogram.
3318 EmitLabel("func_end", SubprogramCount);
3320 // Get function line info.
3321 if (!Lines.empty()) {
3322 // Get section line info.
3323 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3324 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3325 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3326 // Append the function info to section info.
3327 SectionLineInfos.insert(SectionLineInfos.end(),
3328 Lines.begin(), Lines.end());
3331 // Construct scopes for subprogram.
3332 if (FunctionDbgScope)
3333 ConstructFunctionDbgScope(FunctionDbgScope);
3335 // FIXME: This is wrong. We are essentially getting past a problem with
3336 // debug information not being able to handle unreachable blocks that have
3337 // debug information in them. In particular, those unreachable blocks that
3338 // have "region end" info in them. That situation results in the "root
3339 // scope" not being created. If that's the case, then emit a "default"
3340 // scope, i.e., one that encompasses the whole function. This isn't
3341 // desirable. And a better way of handling this (and all of the debugging
3342 // information) needs to be explored.
3343 ConstructDefaultDbgScope(MF);
3345 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3346 MMI->getFrameMoves()));
3349 if (FunctionDbgScope) {
3350 delete FunctionDbgScope;
3351 DbgScopeMap.clear();
3352 DbgInlinedScopeMap.clear();
3353 InlinedVariableScopes.clear();
3354 FunctionDbgScope = NULL;
3359 if (TimePassesIsEnabled)
3360 DebugTimer->stopTimer();
3363 /// RecordSourceLine - Records location information and associates it with a
3364 /// label. Returns a unique label ID used to generate a label and provide
3365 /// correspondence to the source line list.
3366 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3367 if (TimePassesIsEnabled)
3368 DebugTimer->startTimer();
3370 CompileUnit *Unit = CompileUnitMap[V];
3371 assert(Unit && "Unable to find CompileUnit");
3372 unsigned ID = MMI->NextLabelID();
3373 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3375 if (TimePassesIsEnabled)
3376 DebugTimer->stopTimer();
3381 /// RecordSourceLine - Records location information and associates it with a
3382 /// label. Returns a unique label ID used to generate a label and provide
3383 /// correspondence to the source line list.
3384 unsigned RecordSourceLine(unsigned Line, unsigned Col, DICompileUnit CU) {
3385 if (TimePassesIsEnabled)
3386 DebugTimer->startTimer();
3388 std::string Dir, Fn;
3389 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
3390 CU.getFilename(Fn));
3391 unsigned ID = MMI->NextLabelID();
3392 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3394 if (TimePassesIsEnabled)
3395 DebugTimer->stopTimer();
3400 /// getRecordSourceLineCount - Return the number of source lines in the debug
3402 unsigned getRecordSourceLineCount() const {
3403 return Lines.size();
3406 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3407 /// timed. Look up the source id with the given directory and source file
3408 /// names. If none currently exists, create a new id and insert it in the
3409 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3411 unsigned getOrCreateSourceID(const std::string &DirName,
3412 const std::string &FileName) {
3413 if (TimePassesIsEnabled)
3414 DebugTimer->startTimer();
3416 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3418 if (TimePassesIsEnabled)
3419 DebugTimer->stopTimer();
3424 /// RecordRegionStart - Indicate the start of a region.
3425 unsigned RecordRegionStart(GlobalVariable *V) {
3426 if (TimePassesIsEnabled)
3427 DebugTimer->startTimer();
3429 DbgScope *Scope = getOrCreateScope(V);
3430 unsigned ID = MMI->NextLabelID();
3431 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3433 if (TimePassesIsEnabled)
3434 DebugTimer->stopTimer();
3439 /// RecordRegionEnd - Indicate the end of a region.
3440 unsigned RecordRegionEnd(GlobalVariable *V) {
3441 if (TimePassesIsEnabled)
3442 DebugTimer->startTimer();
3444 DbgScope *Scope = getOrCreateScope(V);
3445 unsigned ID = MMI->NextLabelID();
3446 Scope->setEndLabelID(ID);
3448 if (TimePassesIsEnabled)
3449 DebugTimer->stopTimer();
3454 /// RecordVariable - Indicate the declaration of a local variable.
3455 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
3456 const MachineInstr *MI) {
3457 if (TimePassesIsEnabled)
3458 DebugTimer->startTimer();
3460 DIDescriptor Desc(GV);
3461 DbgScope *Scope = NULL;
3463 if (Desc.getTag() == DW_TAG_variable) {
3464 // GV is a global variable.
3465 DIGlobalVariable DG(GV);
3466 Scope = getOrCreateScope(DG.getContext().getGV());
3468 DenseMap<const MachineInstr *, DbgScope *>::iterator
3469 SI = InlinedVariableScopes.find(MI);
3471 if (SI != InlinedVariableScopes.end()) {
3472 // or GV is an inlined local variable.
3475 // or GV is a local variable.
3477 Scope = getOrCreateScope(DV.getContext().getGV());
3481 assert(Scope && "Unable to find variable' scope");
3482 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3483 Scope->AddVariable(DV);
3485 if (TimePassesIsEnabled)
3486 DebugTimer->stopTimer();
3489 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
3490 unsigned RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
3491 unsigned Line, unsigned Col) {
3492 unsigned LabelID = MMI->NextLabelID();
3494 if (!TAI->doesDwarfUsesInlineInfoSection())
3497 if (TimePassesIsEnabled)
3498 DebugTimer->startTimer();
3500 std::string Dir, Fn;
3501 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
3502 CU.getFilename(Fn));
3503 DbgScope *Scope = createInlinedSubroutineScope(SP, Src, Line, Col);
3504 Scope->setStartLabelID(LabelID);
3505 MMI->RecordUsedDbgLabel(LabelID);
3506 GlobalVariable *GV = SP.getGV();
3508 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3509 SI = DbgInlinedScopeMap.find(GV);
3511 if (SI == DbgInlinedScopeMap.end())
3512 DbgInlinedScopeMap[GV].push_back(Scope);
3514 SI->second.push_back(Scope);
3516 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
3517 I = InlineInfo.find(GV);
3518 if (I == InlineInfo.end())
3519 InlineInfo[GV].push_back(LabelID);
3521 I->second.push_back(LabelID);
3523 if (TimePassesIsEnabled)
3524 DebugTimer->stopTimer();
3529 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
3530 unsigned RecordInlinedFnEnd(DISubprogram &SP) {
3531 if (!TAI->doesDwarfUsesInlineInfoSection())
3534 if (TimePassesIsEnabled)
3535 DebugTimer->startTimer();
3537 GlobalVariable *GV = SP.getGV();
3538 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3539 I = DbgInlinedScopeMap.find(GV);
3541 if (I == DbgInlinedScopeMap.end()) {
3542 if (TimePassesIsEnabled)
3543 DebugTimer->stopTimer();
3548 SmallVector<DbgScope *, 2> &Scopes = I->second;
3549 assert(!Scopes.empty() && "We should have at least one debug scope!");
3550 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
3551 unsigned ID = MMI->NextLabelID();
3553 MMI->RecordUsedDbgLabel(ID);
3554 Scope->setEndLabelID(ID);
3556 if (TimePassesIsEnabled)
3557 DebugTimer->stopTimer();
3562 /// RecordVariableScope - Record scope for the variable declared by
3563 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
3564 /// Record scopes for only inlined subroutine variables. Other
3565 /// variables' scopes are determined during RecordVariable().
3566 void RecordVariableScope(DIVariable &DV, const MachineInstr *DeclareMI) {
3567 if (TimePassesIsEnabled)
3568 DebugTimer->startTimer();
3570 DISubprogram SP(DV.getContext().getGV());
3573 if (TimePassesIsEnabled)
3574 DebugTimer->stopTimer();
3579 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3580 I = DbgInlinedScopeMap.find(SP.getGV());
3581 if (I != DbgInlinedScopeMap.end())
3582 InlinedVariableScopes[DeclareMI] = I->second.back();
3584 if (TimePassesIsEnabled)
3585 DebugTimer->stopTimer();
3589 //===----------------------------------------------------------------------===//
3590 /// DwarfException - Emits Dwarf exception handling directives.
3592 class DwarfException : public Dwarf {
3593 struct FunctionEHFrameInfo {
3596 unsigned PersonalityIndex;
3598 bool hasLandingPads;
3599 std::vector<MachineMove> Moves;
3600 const Function * function;
3602 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3604 const std::vector<MachineMove> &M,
3606 FnName(FN), Number(Num), PersonalityIndex(P),
3607 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3610 std::vector<FunctionEHFrameInfo> EHFrames;
3612 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3614 bool shouldEmitTable;
3616 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3617 /// should be emitted.
3618 bool shouldEmitMoves;
3620 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3621 /// should be emitted.
3622 bool shouldEmitTableModule;
3624 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3625 /// should be emitted.
3626 bool shouldEmitMovesModule;
3628 /// ExceptionTimer - Timer for the Dwarf exception writer.
3629 Timer *ExceptionTimer;
3631 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3633 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3634 // Size and sign of stack growth.
3636 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3637 TargetFrameInfo::StackGrowsUp ?
3638 TD->getPointerSize() : -TD->getPointerSize();
3640 // Begin eh frame section.
3641 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3643 if (!TAI->doesRequireNonLocalEHFrameLabel())
3644 O << TAI->getEHGlobalPrefix();
3645 O << "EH_frame" << Index << ":\n";
3646 EmitLabel("section_eh_frame", Index);
3648 // Define base labels.
3649 EmitLabel("eh_frame_common", Index);
3651 // Define the eh frame length.
3652 EmitDifference("eh_frame_common_end", Index,
3653 "eh_frame_common_begin", Index, true);
3654 Asm->EOL("Length of Common Information Entry");
3657 EmitLabel("eh_frame_common_begin", Index);
3658 Asm->EmitInt32((int)0);
3659 Asm->EOL("CIE Identifier Tag");
3660 Asm->EmitInt8(DW_CIE_VERSION);
3661 Asm->EOL("CIE Version");
3663 // The personality presence indicates that language specific information
3664 // will show up in the eh frame.
3665 Asm->EmitString(Personality ? "zPLR" : "zR");
3666 Asm->EOL("CIE Augmentation");
3668 // Round out reader.
3669 Asm->EmitULEB128Bytes(1);
3670 Asm->EOL("CIE Code Alignment Factor");
3671 Asm->EmitSLEB128Bytes(stackGrowth);
3672 Asm->EOL("CIE Data Alignment Factor");
3673 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3674 Asm->EOL("CIE Return Address Column");
3676 // If there is a personality, we need to indicate the functions location.
3678 Asm->EmitULEB128Bytes(7);
3679 Asm->EOL("Augmentation Size");
3681 if (TAI->getNeedsIndirectEncoding()) {
3682 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3683 Asm->EOL("Personality (pcrel sdata4 indirect)");
3685 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3686 Asm->EOL("Personality (pcrel sdata4)");
3689 PrintRelDirective(true);
3690 O << TAI->getPersonalityPrefix();
3691 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3692 O << TAI->getPersonalitySuffix();
3693 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3694 O << "-" << TAI->getPCSymbol();
3695 Asm->EOL("Personality");
3697 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3698 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3700 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3701 Asm->EOL("FDE Encoding (pcrel sdata4)");
3703 Asm->EmitULEB128Bytes(1);
3704 Asm->EOL("Augmentation Size");
3706 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3707 Asm->EOL("FDE Encoding (pcrel sdata4)");
3710 // Indicate locations of general callee saved registers in frame.
3711 std::vector<MachineMove> Moves;
3712 RI->getInitialFrameState(Moves);
3713 EmitFrameMoves(NULL, 0, Moves, true);
3715 // On Darwin the linker honors the alignment of eh_frame, which means it
3716 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3717 // you get holes which confuse readers of eh_frame.
3718 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3720 EmitLabel("eh_frame_common_end", Index);
3725 /// EmitEHFrame - Emit function exception frame information.
3727 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3728 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3730 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
3731 "Should not emit 'available externally' functions at all");
3733 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3735 // Externally visible entry into the functions eh frame info.
3736 // If the corresponding function is static, this should not be
3737 // externally visible.
3738 if (linkage != Function::InternalLinkage &&
3739 linkage != Function::PrivateLinkage) {
3740 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3741 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3744 // If corresponding function is weak definition, this should be too.
3745 if ((linkage == Function::WeakAnyLinkage ||
3746 linkage == Function::WeakODRLinkage ||
3747 linkage == Function::LinkOnceAnyLinkage ||
3748 linkage == Function::LinkOnceODRLinkage) &&
3749 TAI->getWeakDefDirective())
3750 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3752 // If there are no calls then you can't unwind. This may mean we can
3753 // omit the EH Frame, but some environments do not handle weak absolute
3755 // If UnwindTablesMandatory is set we cannot do this optimization; the
3756 // unwind info is to be available for non-EH uses.
3757 if (!EHFrameInfo.hasCalls &&
3758 !UnwindTablesMandatory &&
3759 ((linkage != Function::WeakAnyLinkage &&
3760 linkage != Function::WeakODRLinkage &&
3761 linkage != Function::LinkOnceAnyLinkage &&
3762 linkage != Function::LinkOnceODRLinkage) ||
3763 !TAI->getWeakDefDirective() ||
3764 TAI->getSupportsWeakOmittedEHFrame()))
3766 O << EHFrameInfo.FnName << " = 0\n";
3767 // This name has no connection to the function, so it might get
3768 // dead-stripped when the function is not, erroneously. Prohibit
3769 // dead-stripping unconditionally.
3770 if (const char *UsedDirective = TAI->getUsedDirective())
3771 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3773 O << EHFrameInfo.FnName << ":\n";
3776 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3777 "eh_frame_begin", EHFrameInfo.Number, true);
3778 Asm->EOL("Length of Frame Information Entry");
3780 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3782 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3783 PrintRelDirective(true, true);
3784 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3786 if (!TAI->isAbsoluteEHSectionOffsets())
3787 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3789 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3790 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3794 Asm->EOL("FDE CIE offset");
3796 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3797 Asm->EOL("FDE initial location");
3798 EmitDifference("eh_func_end", EHFrameInfo.Number,
3799 "eh_func_begin", EHFrameInfo.Number, true);
3800 Asm->EOL("FDE address range");
3802 // If there is a personality and landing pads then point to the language
3803 // specific data area in the exception table.
3804 if (EHFrameInfo.PersonalityIndex) {
3805 Asm->EmitULEB128Bytes(4);
3806 Asm->EOL("Augmentation size");
3808 if (EHFrameInfo.hasLandingPads)
3809 EmitReference("exception", EHFrameInfo.Number, true, true);
3811 Asm->EmitInt32((int)0);
3812 Asm->EOL("Language Specific Data Area");
3814 Asm->EmitULEB128Bytes(0);
3815 Asm->EOL("Augmentation size");
3818 // Indicate locations of function specific callee saved registers in
3820 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3823 // On Darwin the linker honors the alignment of eh_frame, which means it
3824 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3825 // you get holes which confuse readers of eh_frame.
3826 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3828 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3830 // If the function is marked used, this table should be also. We cannot
3831 // make the mark unconditional in this case, since retaining the table
3832 // also retains the function in this case, and there is code around
3833 // that depends on unused functions (calling undefined externals) being
3834 // dead-stripped to link correctly. Yes, there really is.
3835 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3836 if (const char *UsedDirective = TAI->getUsedDirective())
3837 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3841 /// EmitExceptionTable - Emit landing pads and actions.
3843 /// The general organization of the table is complex, but the basic concepts
3844 /// are easy. First there is a header which describes the location and
3845 /// organization of the three components that follow.
3846 /// 1. The landing pad site information describes the range of code covered
3847 /// by the try. In our case it's an accumulation of the ranges covered
3848 /// by the invokes in the try. There is also a reference to the landing
3849 /// pad that handles the exception once processed. Finally an index into
3850 /// the actions table.
3851 /// 2. The action table, in our case, is composed of pairs of type ids
3852 /// and next action offset. Starting with the action index from the
3853 /// landing pad site, each type Id is checked for a match to the current
3854 /// exception. If it matches then the exception and type id are passed
3855 /// on to the landing pad. Otherwise the next action is looked up. This
3856 /// chain is terminated with a next action of zero. If no type id is
3857 /// found the the frame is unwound and handling continues.
3858 /// 3. Type id table contains references to all the C++ typeinfo for all
3859 /// catches in the function. This tables is reversed indexed base 1.
3861 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3862 static unsigned SharedTypeIds(const LandingPadInfo *L,
3863 const LandingPadInfo *R) {
3864 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3865 unsigned LSize = LIds.size(), RSize = RIds.size();
3866 unsigned MinSize = LSize < RSize ? LSize : RSize;
3869 for (; Count != MinSize; ++Count)
3870 if (LIds[Count] != RIds[Count])
3876 /// PadLT - Order landing pads lexicographically by type id.
3877 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3878 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3879 unsigned LSize = LIds.size(), RSize = RIds.size();
3880 unsigned MinSize = LSize < RSize ? LSize : RSize;
3882 for (unsigned i = 0; i != MinSize; ++i)
3883 if (LIds[i] != RIds[i])
3884 return LIds[i] < RIds[i];
3886 return LSize < RSize;
3890 static inline unsigned getEmptyKey() { return -1U; }
3891 static inline unsigned getTombstoneKey() { return -2U; }
3892 static unsigned getHashValue(const unsigned &Key) { return Key; }
3893 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3894 static bool isPod() { return true; }
3897 /// ActionEntry - Structure describing an entry in the actions table.
3898 struct ActionEntry {
3899 int ValueForTypeID; // The value to write - may not be equal to the type id.
3901 struct ActionEntry *Previous;
3904 /// PadRange - Structure holding a try-range and the associated landing pad.
3906 // The index of the landing pad.
3908 // The index of the begin and end labels in the landing pad's label lists.
3909 unsigned RangeIndex;
3912 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3914 /// CallSiteEntry - Structure describing an entry in the call-site table.
3915 struct CallSiteEntry {
3916 // The 'try-range' is BeginLabel .. EndLabel.
3917 unsigned BeginLabel; // zero indicates the start of the function.
3918 unsigned EndLabel; // zero indicates the end of the function.
3919 // The landing pad starts at PadLabel.
3920 unsigned PadLabel; // zero indicates that there is no landing pad.
3924 void EmitExceptionTable() {
3925 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3926 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3927 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3928 if (PadInfos.empty()) return;
3930 // Sort the landing pads in order of their type ids. This is used to fold
3931 // duplicate actions.
3932 SmallVector<const LandingPadInfo *, 64> LandingPads;
3933 LandingPads.reserve(PadInfos.size());
3934 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3935 LandingPads.push_back(&PadInfos[i]);
3936 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3938 // Negative type ids index into FilterIds, positive type ids index into
3939 // TypeInfos. The value written for a positive type id is just the type
3940 // id itself. For a negative type id, however, the value written is the
3941 // (negative) byte offset of the corresponding FilterIds entry. The byte
3942 // offset is usually equal to the type id, because the FilterIds entries
3943 // are written using a variable width encoding which outputs one byte per
3944 // entry as long as the value written is not too large, but can differ.
3945 // This kind of complication does not occur for positive type ids because
3946 // type infos are output using a fixed width encoding.
3947 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3948 SmallVector<int, 16> FilterOffsets;
3949 FilterOffsets.reserve(FilterIds.size());
3951 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3952 E = FilterIds.end(); I != E; ++I) {
3953 FilterOffsets.push_back(Offset);
3954 Offset -= TargetAsmInfo::getULEB128Size(*I);
3957 // Compute the actions table and gather the first action index for each
3958 // landing pad site.
3959 SmallVector<ActionEntry, 32> Actions;
3960 SmallVector<unsigned, 64> FirstActions;
3961 FirstActions.reserve(LandingPads.size());
3963 int FirstAction = 0;
3964 unsigned SizeActions = 0;
3965 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3966 const LandingPadInfo *LP = LandingPads[i];
3967 const std::vector<int> &TypeIds = LP->TypeIds;
3968 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3969 unsigned SizeSiteActions = 0;
3971 if (NumShared < TypeIds.size()) {
3972 unsigned SizeAction = 0;
3973 ActionEntry *PrevAction = 0;
3976 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3977 assert(Actions.size());
3978 PrevAction = &Actions.back();
3979 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3980 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3981 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3983 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3984 SizeAction += -PrevAction->NextAction;
3985 PrevAction = PrevAction->Previous;
3989 // Compute the actions.
3990 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3991 int TypeID = TypeIds[I];
3992 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3993 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3994 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3996 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3997 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3998 SizeSiteActions += SizeAction;
4000 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4001 Actions.push_back(Action);
4003 PrevAction = &Actions.back();
4006 // Record the first action of the landing pad site.
4007 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4008 } // else identical - re-use previous FirstAction
4010 FirstActions.push_back(FirstAction);
4012 // Compute this sites contribution to size.
4013 SizeActions += SizeSiteActions;
4016 // Compute the call-site table. The entry for an invoke has a try-range
4017 // containing the call, a non-zero landing pad and an appropriate action.
4018 // The entry for an ordinary call has a try-range containing the call and
4019 // zero for the landing pad and the action. Calls marked 'nounwind' have
4020 // no entry and must not be contained in the try-range of any entry - they
4021 // form gaps in the table. Entries must be ordered by try-range address.
4022 SmallVector<CallSiteEntry, 64> CallSites;
4024 RangeMapType PadMap;
4025 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4026 // by try-range labels when lowered). Ordinary calls do not, so appropriate
4027 // try-ranges for them need be deduced.
4028 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4029 const LandingPadInfo *LandingPad = LandingPads[i];
4030 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4031 unsigned BeginLabel = LandingPad->BeginLabels[j];
4032 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4033 PadRange P = { i, j };
4034 PadMap[BeginLabel] = P;
4038 // The end label of the previous invoke or nounwind try-range.
4039 unsigned LastLabel = 0;
4041 // Whether there is a potentially throwing instruction (currently this means
4042 // an ordinary call) between the end of the previous try-range and now.
4043 bool SawPotentiallyThrowing = false;
4045 // Whether the last callsite entry was for an invoke.
4046 bool PreviousIsInvoke = false;
4048 // Visit all instructions in order of address.
4049 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4051 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4053 if (!MI->isLabel()) {
4054 SawPotentiallyThrowing |= MI->getDesc().isCall();
4058 unsigned BeginLabel = MI->getOperand(0).getImm();
4059 assert(BeginLabel && "Invalid label!");
4061 // End of the previous try-range?
4062 if (BeginLabel == LastLabel)
4063 SawPotentiallyThrowing = false;
4065 // Beginning of a new try-range?
4066 RangeMapType::iterator L = PadMap.find(BeginLabel);
4067 if (L == PadMap.end())
4068 // Nope, it was just some random label.
4071 PadRange P = L->second;
4072 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4074 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4075 "Inconsistent landing pad map!");
4077 // If some instruction between the previous try-range and this one may
4078 // throw, create a call-site entry with no landing pad for the region
4079 // between the try-ranges.
4080 if (SawPotentiallyThrowing) {
4081 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4082 CallSites.push_back(Site);
4083 PreviousIsInvoke = false;
4086 LastLabel = LandingPad->EndLabels[P.RangeIndex];
4087 assert(BeginLabel && LastLabel && "Invalid landing pad!");
4089 if (LandingPad->LandingPadLabel) {
4090 // This try-range is for an invoke.
4091 CallSiteEntry Site = {BeginLabel, LastLabel,
4092 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4094 // Try to merge with the previous call-site.
4095 if (PreviousIsInvoke) {
4096 CallSiteEntry &Prev = CallSites.back();
4097 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4098 // Extend the range of the previous entry.
4099 Prev.EndLabel = Site.EndLabel;
4104 // Otherwise, create a new call-site.
4105 CallSites.push_back(Site);
4106 PreviousIsInvoke = true;
4109 PreviousIsInvoke = false;
4113 // If some instruction between the previous try-range and the end of the
4114 // function may throw, create a call-site entry with no landing pad for the
4115 // region following the try-range.
4116 if (SawPotentiallyThrowing) {
4117 CallSiteEntry Site = {LastLabel, 0, 0, 0};
4118 CallSites.push_back(Site);
4124 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
4125 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4126 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4127 unsigned SizeSites = CallSites.size() * (SiteStartSize +
4130 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4131 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4134 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4135 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4137 unsigned TypeOffset = sizeof(int8_t) + // Call site format
4138 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4139 SizeSites + SizeActions + SizeTypes;
4141 unsigned TotalSize = sizeof(int8_t) + // LPStart format
4142 sizeof(int8_t) + // TType format
4143 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4146 unsigned SizeAlign = (4 - TotalSize) & 3;
4148 // Begin the exception table.
4149 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4150 Asm->EmitAlignment(2, 0, 0, false);
4151 O << "GCC_except_table" << SubprogramCount << ":\n";
4152 for (unsigned i = 0; i != SizeAlign; ++i) {
4154 Asm->EOL("Padding");
4156 EmitLabel("exception", SubprogramCount);
4159 Asm->EmitInt8(DW_EH_PE_omit);
4160 Asm->EOL("LPStart format (DW_EH_PE_omit)");
4161 Asm->EmitInt8(DW_EH_PE_absptr);
4162 Asm->EOL("TType format (DW_EH_PE_absptr)");
4163 Asm->EmitULEB128Bytes(TypeOffset);
4164 Asm->EOL("TType base offset");
4165 Asm->EmitInt8(DW_EH_PE_udata4);
4166 Asm->EOL("Call site format (DW_EH_PE_udata4)");
4167 Asm->EmitULEB128Bytes(SizeSites);
4168 Asm->EOL("Call-site table length");
4170 // Emit the landing pad site information.
4171 for (unsigned i = 0; i < CallSites.size(); ++i) {
4172 CallSiteEntry &S = CallSites[i];
4173 const char *BeginTag;
4174 unsigned BeginNumber;
4176 if (!S.BeginLabel) {
4177 BeginTag = "eh_func_begin";
4178 BeginNumber = SubprogramCount;
4181 BeginNumber = S.BeginLabel;
4184 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4186 Asm->EOL("Region start");
4189 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4192 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4194 Asm->EOL("Region length");
4199 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4201 Asm->EOL("Landing pad");
4203 Asm->EmitULEB128Bytes(S.Action);
4207 // Emit the actions.
4208 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4209 ActionEntry &Action = Actions[I];
4211 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4212 Asm->EOL("TypeInfo index");
4213 Asm->EmitSLEB128Bytes(Action.NextAction);
4214 Asm->EOL("Next action");
4217 // Emit the type ids.
4218 for (unsigned M = TypeInfos.size(); M; --M) {
4219 GlobalVariable *GV = TypeInfos[M - 1];
4221 PrintRelDirective();
4225 O << Asm->getGlobalLinkName(GV, GLN);
4230 Asm->EOL("TypeInfo");
4233 // Emit the filter typeids.
4234 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4235 unsigned TypeID = FilterIds[j];
4236 Asm->EmitULEB128Bytes(TypeID);
4237 Asm->EOL("Filter TypeInfo index");
4240 Asm->EmitAlignment(2, 0, 0, false);
4244 //===--------------------------------------------------------------------===//
4245 // Main entry points.
4247 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4248 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4249 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4251 if (TimePassesIsEnabled)
4252 ExceptionTimer = new Timer("Dwarf Exception Writer",
4253 getDwarfTimerGroup());
4256 virtual ~DwarfException() {
4257 delete ExceptionTimer;
4260 /// SetModuleInfo - Set machine module information when it's known that pass
4261 /// manager has created it. Set by the target AsmPrinter.
4262 void SetModuleInfo(MachineModuleInfo *mmi) {
4266 /// BeginModule - Emit all exception information that should come prior to the
4268 void BeginModule(Module *M) {
4272 /// EndModule - Emit all exception information that should come after the
4275 if (TimePassesIsEnabled)
4276 ExceptionTimer->startTimer();
4278 if (shouldEmitMovesModule || shouldEmitTableModule) {
4279 const std::vector<Function *> Personalities = MMI->getPersonalities();
4280 for (unsigned i = 0; i < Personalities.size(); ++i)
4281 EmitCommonEHFrame(Personalities[i], i);
4283 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4284 E = EHFrames.end(); I != E; ++I)
4288 if (TimePassesIsEnabled)
4289 ExceptionTimer->stopTimer();
4292 /// BeginFunction - Gather pre-function exception information. Assumes being
4293 /// emitted immediately after the function entry point.
4294 void BeginFunction(MachineFunction *MF) {
4295 if (TimePassesIsEnabled)
4296 ExceptionTimer->startTimer();
4299 shouldEmitTable = shouldEmitMoves = false;
4301 if (MMI && TAI->doesSupportExceptionHandling()) {
4302 // Map all labels and get rid of any dead landing pads.
4303 MMI->TidyLandingPads();
4305 // If any landing pads survive, we need an EH table.
4306 if (MMI->getLandingPads().size())
4307 shouldEmitTable = true;
4309 // See if we need frame move info.
4310 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4311 shouldEmitMoves = true;
4313 if (shouldEmitMoves || shouldEmitTable)
4314 // Assumes in correct section after the entry point.
4315 EmitLabel("eh_func_begin", ++SubprogramCount);
4318 shouldEmitTableModule |= shouldEmitTable;
4319 shouldEmitMovesModule |= shouldEmitMoves;
4321 if (TimePassesIsEnabled)
4322 ExceptionTimer->stopTimer();
4325 /// EndFunction - Gather and emit post-function exception information.
4327 void EndFunction() {
4328 if (TimePassesIsEnabled)
4329 ExceptionTimer->startTimer();
4331 if (shouldEmitMoves || shouldEmitTable) {
4332 EmitLabel("eh_func_end", SubprogramCount);
4333 EmitExceptionTable();
4335 // Save EH frame information
4338 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF, Name),
4340 MMI->getPersonalityIndex(),
4341 MF->getFrameInfo()->hasCalls(),
4342 !MMI->getLandingPads().empty(),
4343 MMI->getFrameMoves(),
4344 MF->getFunction()));
4347 if (TimePassesIsEnabled)
4348 ExceptionTimer->stopTimer();
4352 } // End of namespace llvm
4354 //===----------------------------------------------------------------------===//
4356 /// Emit - Print the abbreviation using the specified Dwarf writer.
4358 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4359 // Emit its Dwarf tag type.
4360 DD.getAsm()->EmitULEB128Bytes(Tag);
4361 DD.getAsm()->EOL(TagString(Tag));
4363 // Emit whether it has children DIEs.
4364 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4365 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4367 // For each attribute description.
4368 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4369 const DIEAbbrevData &AttrData = Data[i];
4371 // Emit attribute type.
4372 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4373 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4376 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4377 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4380 // Mark end of abbreviation.
4381 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4382 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4386 void DIEAbbrev::print(std::ostream &O) {
4387 O << "Abbreviation @"
4388 << std::hex << (intptr_t)this << std::dec
4392 << ChildrenString(ChildrenFlag)
4395 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4397 << AttributeString(Data[i].getAttribute())
4399 << FormEncodingString(Data[i].getForm())
4403 void DIEAbbrev::dump() { print(cerr); }
4406 //===----------------------------------------------------------------------===//
4409 void DIEValue::dump() {
4414 //===----------------------------------------------------------------------===//
4416 /// EmitValue - Emit integer of appropriate size.
4418 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4420 case DW_FORM_flag: // Fall thru
4421 case DW_FORM_ref1: // Fall thru
4422 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4423 case DW_FORM_ref2: // Fall thru
4424 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4425 case DW_FORM_ref4: // Fall thru
4426 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4427 case DW_FORM_ref8: // Fall thru
4428 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4429 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4430 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4431 default: assert(0 && "DIE Value form not supported yet"); break;
4435 /// SizeOf - Determine size of integer value in bytes.
4437 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4439 case DW_FORM_flag: // Fall thru
4440 case DW_FORM_ref1: // Fall thru
4441 case DW_FORM_data1: return sizeof(int8_t);
4442 case DW_FORM_ref2: // Fall thru
4443 case DW_FORM_data2: return sizeof(int16_t);
4444 case DW_FORM_ref4: // Fall thru
4445 case DW_FORM_data4: return sizeof(int32_t);
4446 case DW_FORM_ref8: // Fall thru
4447 case DW_FORM_data8: return sizeof(int64_t);
4448 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4449 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4450 default: assert(0 && "DIE Value form not supported yet"); break;
4455 //===----------------------------------------------------------------------===//
4457 /// EmitValue - Emit string value.
4459 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4460 DD.getAsm()->EmitString(Str);
4463 //===----------------------------------------------------------------------===//
4465 /// EmitValue - Emit label value.
4467 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4468 bool IsSmall = Form == DW_FORM_data4;
4469 DD.EmitReference(Label, false, IsSmall);
4472 /// SizeOf - Determine size of label value in bytes.
4474 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4475 if (Form == DW_FORM_data4) return 4;
4476 return DD.getTargetData()->getPointerSize();
4479 //===----------------------------------------------------------------------===//
4481 /// EmitValue - Emit label value.
4483 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4484 bool IsSmall = Form == DW_FORM_data4;
4485 DD.EmitReference(Label, false, IsSmall);
4488 /// SizeOf - Determine size of label value in bytes.
4490 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4491 if (Form == DW_FORM_data4) return 4;
4492 return DD.getTargetData()->getPointerSize();
4495 //===----------------------------------------------------------------------===//
4497 /// EmitValue - Emit delta value.
4499 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4500 bool IsSmall = Form == DW_FORM_data4;
4501 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4502 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4505 /// SizeOf - Determine size of delta value in bytes.
4507 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4508 if (Form == DW_FORM_data4) return 4;
4509 return DD.getTargetData()->getPointerSize();
4512 //===----------------------------------------------------------------------===//
4514 /// EmitValue - Emit delta value.
4516 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4517 bool IsSmall = Form == DW_FORM_data4;
4518 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4521 /// SizeOf - Determine size of delta value in bytes.
4523 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4524 if (Form == DW_FORM_data4) return 4;
4525 return DD.getTargetData()->getPointerSize();
4528 //===----------------------------------------------------------------------===//
4530 /// EmitValue - Emit debug information entry offset.
4532 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4533 DD.getAsm()->EmitInt32(Entry->getOffset());
4536 //===----------------------------------------------------------------------===//
4538 /// ComputeSize - calculate the size of the block.
4540 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4542 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4544 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4545 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4551 /// EmitValue - Emit block data.
4553 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4555 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4556 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4557 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4558 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4559 default: assert(0 && "Improper form for block"); break;
4562 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4564 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4566 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4570 /// SizeOf - Determine size of block data in bytes.
4572 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4574 case DW_FORM_block1: return Size + sizeof(int8_t);
4575 case DW_FORM_block2: return Size + sizeof(int16_t);
4576 case DW_FORM_block4: return Size + sizeof(int32_t);
4577 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4578 default: assert(0 && "Improper form for block"); break;
4583 //===----------------------------------------------------------------------===//
4584 /// DIE Implementation
4587 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4591 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4593 void DIE::AddSiblingOffset() {
4594 DIEInteger *DI = new DIEInteger(0);
4595 Values.insert(Values.begin(), DI);
4596 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4599 /// Profile - Used to gather unique data for the value folding set.
4601 void DIE::Profile(FoldingSetNodeID &ID) {
4604 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4605 ID.AddPointer(Children[i]);
4607 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4608 ID.AddPointer(Values[j]);
4612 void DIE::print(std::ostream &O, unsigned IncIndent) {
4613 static unsigned IndentCount = 0;
4614 IndentCount += IncIndent;
4615 const std::string Indent(IndentCount, ' ');
4616 bool isBlock = Abbrev.getTag() == 0;
4621 << "0x" << std::hex << (intptr_t)this << std::dec
4622 << ", Offset: " << Offset
4623 << ", Size: " << Size
4627 << TagString(Abbrev.getTag())
4629 << ChildrenString(Abbrev.getChildrenFlag());
4631 O << "Size: " << Size;
4635 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4638 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4642 O << AttributeString(Data[i].getAttribute());
4644 O << "Blk[" << i << "]";
4647 << FormEncodingString(Data[i].getForm())
4649 Values[i]->print(O);
4654 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4655 Children[j]->print(O, 4);
4658 if (!isBlock) O << "\n";
4659 IndentCount -= IncIndent;
4667 //===----------------------------------------------------------------------===//
4668 /// DwarfWriter Implementation
4671 DwarfWriter::DwarfWriter()
4672 : ImmutablePass(&ID), DD(0), DE(0) {}
4674 DwarfWriter::~DwarfWriter() {
4679 /// BeginModule - Emit all Dwarf sections that should come prior to the
4681 void DwarfWriter::BeginModule(Module *M,
4682 MachineModuleInfo *MMI,
4683 raw_ostream &OS, AsmPrinter *A,
4684 const TargetAsmInfo *T) {
4685 DE = new DwarfException(OS, A, T);
4686 DD = new DwarfDebug(OS, A, T);
4689 DD->SetDebugInfo(MMI);
4690 DE->SetModuleInfo(MMI);
4693 /// EndModule - Emit all Dwarf sections that should come after the content.
4695 void DwarfWriter::EndModule() {
4700 /// BeginFunction - Gather pre-function debug information. Assumes being
4701 /// emitted immediately after the function entry point.
4702 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4703 DE->BeginFunction(MF);
4704 DD->BeginFunction(MF);
4707 /// EndFunction - Gather and emit post-function debug information.
4709 void DwarfWriter::EndFunction(MachineFunction *MF) {
4710 DD->EndFunction(MF);
4713 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4714 // Clear function debug information.
4718 /// RecordSourceLine - Records location information and associates it with a
4719 /// label. Returns a unique label ID used to generate a label and provide
4720 /// correspondence to the source line list.
4721 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4723 return DD->RecordSourceLine(Line, Col, CU);
4726 /// RecordRegionStart - Indicate the start of a region.
4727 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4728 return DD->RecordRegionStart(V);
4731 /// RecordRegionEnd - Indicate the end of a region.
4732 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4733 return DD->RecordRegionEnd(V);
4736 /// getRecordSourceLineCount - Count source lines.
4737 unsigned DwarfWriter::getRecordSourceLineCount() {
4738 return DD->getRecordSourceLineCount();
4741 /// RecordVariable - Indicate the declaration of a local variable.
4743 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
4744 const MachineInstr *MI) {
4745 DD->RecordVariable(GV, FrameIndex, MI);
4748 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4750 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4751 return DD && DD->ShouldEmitDwarfDebug();
4754 //// RecordInlinedFnStart - Global variable GV is inlined at the location marked
4755 //// by LabelID label.
4756 unsigned DwarfWriter::RecordInlinedFnStart(DISubprogram SP, DICompileUnit CU,
4757 unsigned Line, unsigned Col) {
4758 return DD->RecordInlinedFnStart(SP, CU, Line, Col);
4761 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
4762 unsigned DwarfWriter::RecordInlinedFnEnd(DISubprogram SP) {
4763 return DD->RecordInlinedFnEnd(SP);
4766 /// RecordVariableScope - Record scope for the variable declared by
4767 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
4768 void DwarfWriter::RecordVariableScope(DIVariable &DV,
4769 const MachineInstr *DeclareMI) {
4770 DD->RecordVariableScope(DV, DeclareMI);