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;
53 static TimerGroup *DwarfTimerGroup = 0;
54 static TimerGroup *getDwarfTimerGroup() {
55 if (DwarfTimerGroup) return DwarfTimerGroup;
56 return DwarfTimerGroup = new TimerGroup("Dwarf Exception and Debugging");
59 } // end anonymous namespace
63 //===----------------------------------------------------------------------===//
65 /// Configuration values for initial hash set sizes (log2).
67 static const unsigned InitDiesSetSize = 9; // log2(512)
68 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
69 static const unsigned InitValuesSetSize = 9; // log2(512)
71 //===----------------------------------------------------------------------===//
72 /// Forward declarations.
77 //===----------------------------------------------------------------------===//
80 /// getGlobalVariable - Return either a direct or cast Global value.
82 static GlobalVariable *getGlobalVariable(Value *V) {
83 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
85 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
86 if (CE->getOpcode() == Instruction::BitCast) {
87 return dyn_cast<GlobalVariable>(CE->getOperand(0));
88 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
89 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
90 if (!CE->getOperand(i)->isNullValue())
93 return dyn_cast<GlobalVariable>(CE->getOperand(0));
99 //===----------------------------------------------------------------------===//
100 /// DWLabel - Labels are used to track locations in the assembler file.
101 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
102 /// where the tag is a category of label (Ex. location) and number is a value
103 /// unique in that category.
106 /// Tag - Label category tag. Should always be a staticly declared C string.
110 /// Number - Value to make label unique.
114 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
116 void Profile(FoldingSetNodeID &ID) const {
118 ID.AddInteger(Number);
122 void print(std::ostream *O) const {
125 void print(std::ostream &O) const {
127 if (Number) O << Number;
132 //===----------------------------------------------------------------------===//
133 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
134 /// Dwarf abbreviation.
135 class DIEAbbrevData {
137 /// Attribute - Dwarf attribute code.
141 /// Form - Dwarf form code.
146 DIEAbbrevData(unsigned A, unsigned F)
152 unsigned getAttribute() const { return Attribute; }
153 unsigned getForm() const { return Form; }
155 /// Profile - Used to gather unique data for the abbreviation folding set.
157 void Profile(FoldingSetNodeID &ID)const {
158 ID.AddInteger(Attribute);
163 //===----------------------------------------------------------------------===//
164 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
165 /// information object.
166 class DIEAbbrev : public FoldingSetNode {
168 /// Tag - Dwarf tag code.
172 /// Unique number for node.
176 /// ChildrenFlag - Dwarf children flag.
178 unsigned ChildrenFlag;
180 /// Data - Raw data bytes for abbreviation.
182 SmallVector<DIEAbbrevData, 8> Data;
186 DIEAbbrev(unsigned T, unsigned C)
194 unsigned getTag() const { return Tag; }
195 unsigned getNumber() const { return Number; }
196 unsigned getChildrenFlag() const { return ChildrenFlag; }
197 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
198 void setTag(unsigned T) { Tag = T; }
199 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
200 void setNumber(unsigned N) { Number = N; }
202 /// AddAttribute - Adds another set of attribute information to the
204 void AddAttribute(unsigned Attribute, unsigned Form) {
205 Data.push_back(DIEAbbrevData(Attribute, Form));
208 /// AddFirstAttribute - Adds a set of attribute information to the front
209 /// of the abbreviation.
210 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
211 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
214 /// Profile - Used to gather unique data for the abbreviation folding set.
216 void Profile(FoldingSetNodeID &ID) {
218 ID.AddInteger(ChildrenFlag);
220 // For each attribute description.
221 for (unsigned i = 0, N = Data.size(); i < N; ++i)
225 /// Emit - Print the abbreviation using the specified Dwarf writer.
227 void Emit(const DwarfDebug &DD) const;
230 void print(std::ostream *O) {
233 void print(std::ostream &O);
238 //===----------------------------------------------------------------------===//
239 /// DIE - A structured debug information entry. Has an abbreviation which
240 /// describes it's organization.
241 class DIE : public FoldingSetNode {
243 /// Abbrev - Buffer for constructing abbreviation.
247 /// Offset - Offset in debug info section.
251 /// Size - Size of instance + children.
257 std::vector<DIE *> Children;
259 /// Attributes values.
261 SmallVector<DIEValue*, 32> Values;
264 explicit DIE(unsigned Tag)
265 : Abbrev(Tag, DW_CHILDREN_no)
274 DIEAbbrev &getAbbrev() { return Abbrev; }
275 unsigned getAbbrevNumber() const {
276 return Abbrev.getNumber();
278 unsigned getTag() const { return Abbrev.getTag(); }
279 unsigned getOffset() const { return Offset; }
280 unsigned getSize() const { return Size; }
281 const std::vector<DIE *> &getChildren() const { return Children; }
282 SmallVector<DIEValue*, 32> &getValues() { return Values; }
283 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
284 void setOffset(unsigned O) { Offset = O; }
285 void setSize(unsigned S) { Size = S; }
287 /// AddValue - Add a value and attributes to a DIE.
289 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
290 Abbrev.AddAttribute(Attribute, Form);
291 Values.push_back(Value);
294 /// SiblingOffset - Return the offset of the debug information entry's
296 unsigned SiblingOffset() const { return Offset + Size; }
298 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
300 void AddSiblingOffset();
302 /// AddChild - Add a child to the DIE.
304 void AddChild(DIE *Child) {
305 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
306 Children.push_back(Child);
309 /// Detach - Detaches objects connected to it after copying.
315 /// Profile - Used to gather unique data for the value folding set.
317 void Profile(FoldingSetNodeID &ID) ;
320 void print(std::ostream *O, unsigned IncIndent = 0) {
321 if (O) print(*O, IncIndent);
323 void print(std::ostream &O, unsigned IncIndent = 0);
328 //===----------------------------------------------------------------------===//
329 /// DIEValue - A debug information entry value.
331 class DIEValue : public FoldingSetNode {
344 /// Type - Type of data stored in the value.
348 explicit DIEValue(unsigned T)
351 virtual ~DIEValue() {}
354 unsigned getType() const { return Type; }
356 // Implement isa/cast/dyncast.
357 static bool classof(const DIEValue *) { return true; }
359 /// EmitValue - Emit value via the Dwarf writer.
361 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
363 /// SizeOf - Return the size of a value in bytes.
365 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
367 /// Profile - Used to gather unique data for the value folding set.
369 virtual void Profile(FoldingSetNodeID &ID) = 0;
372 void print(std::ostream *O) {
375 virtual void print(std::ostream &O) = 0;
380 //===----------------------------------------------------------------------===//
381 /// DWInteger - An integer value DIE.
383 class DIEInteger : public DIEValue {
388 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
390 // Implement isa/cast/dyncast.
391 static bool classof(const DIEInteger *) { return true; }
392 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
394 /// BestForm - Choose the best form for integer.
396 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
398 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
399 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
400 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
402 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
403 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
404 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
406 return DW_FORM_data8;
409 /// EmitValue - Emit integer of appropriate size.
411 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
413 /// SizeOf - Determine size of integer value in bytes.
415 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
417 /// Profile - Used to gather unique data for the value folding set.
419 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
420 ID.AddInteger(isInteger);
421 ID.AddInteger(Integer);
423 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
426 virtual void print(std::ostream &O) {
427 O << "Int: " << (int64_t)Integer
428 << " 0x" << std::hex << Integer << std::dec;
433 //===----------------------------------------------------------------------===//
434 /// DIEString - A string value DIE.
436 class DIEString : public DIEValue {
438 const std::string String;
440 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
442 // Implement isa/cast/dyncast.
443 static bool classof(const DIEString *) { return true; }
444 static bool classof(const DIEValue *S) { return S->Type == isString; }
446 /// EmitValue - Emit string value.
448 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
450 /// SizeOf - Determine size of string value in bytes.
452 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
453 return String.size() + sizeof(char); // sizeof('\0');
456 /// Profile - Used to gather unique data for the value folding set.
458 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
459 ID.AddInteger(isString);
460 ID.AddString(String);
462 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
465 virtual void print(std::ostream &O) {
466 O << "Str: \"" << String << "\"";
471 //===----------------------------------------------------------------------===//
472 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
474 class DIEDwarfLabel : public DIEValue {
479 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
481 // Implement isa/cast/dyncast.
482 static bool classof(const DIEDwarfLabel *) { return true; }
483 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
485 /// EmitValue - Emit label value.
487 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
489 /// SizeOf - Determine size of label value in bytes.
491 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
493 /// Profile - Used to gather unique data for the value folding set.
495 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
496 ID.AddInteger(isLabel);
499 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
502 virtual void print(std::ostream &O) {
510 //===----------------------------------------------------------------------===//
511 /// DIEObjectLabel - A label to an object in code or data.
513 class DIEObjectLabel : public DIEValue {
515 const std::string Label;
517 explicit DIEObjectLabel(const std::string &L)
518 : DIEValue(isAsIsLabel), Label(L) {}
520 // Implement isa/cast/dyncast.
521 static bool classof(const DIEObjectLabel *) { return true; }
522 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
524 /// EmitValue - Emit label value.
526 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
528 /// SizeOf - Determine size of label value in bytes.
530 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
532 /// Profile - Used to gather unique data for the value folding set.
534 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
535 ID.AddInteger(isAsIsLabel);
538 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
541 virtual void print(std::ostream &O) {
542 O << "Obj: " << Label;
547 //===----------------------------------------------------------------------===//
548 /// DIESectionOffset - A section offset DIE.
550 class DIESectionOffset : public DIEValue {
553 const DWLabel Section;
557 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
558 bool isEH = false, bool useSet = true)
559 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
560 IsEH(isEH), UseSet(useSet) {}
562 // Implement isa/cast/dyncast.
563 static bool classof(const DIESectionOffset *) { return true; }
564 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
566 /// EmitValue - Emit section offset.
568 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
570 /// SizeOf - Determine size of section offset value in bytes.
572 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
574 /// Profile - Used to gather unique data for the value folding set.
576 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
577 const DWLabel &Section) {
578 ID.AddInteger(isSectionOffset);
581 // IsEH and UseSet are specific to the Label/Section that we will emit
582 // the offset for; so Label/Section are enough for uniqueness.
584 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
587 virtual void print(std::ostream &O) {
592 O << "-" << IsEH << "-" << UseSet;
597 //===----------------------------------------------------------------------===//
598 /// DIEDelta - A simple label difference DIE.
600 class DIEDelta : public DIEValue {
602 const DWLabel LabelHi;
603 const DWLabel LabelLo;
605 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
606 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
608 // Implement isa/cast/dyncast.
609 static bool classof(const DIEDelta *) { return true; }
610 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
612 /// EmitValue - Emit delta value.
614 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
616 /// SizeOf - Determine size of delta value in bytes.
618 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
620 /// Profile - Used to gather unique data for the value folding set.
622 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
623 const DWLabel &LabelLo) {
624 ID.AddInteger(isDelta);
628 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
631 virtual void print(std::ostream &O) {
640 //===----------------------------------------------------------------------===//
641 /// DIEntry - A pointer to another debug information entry. An instance of this
642 /// class can also be used as a proxy for a debug information entry not yet
643 /// defined (ie. types.)
644 class DIEntry : public DIEValue {
648 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
650 // Implement isa/cast/dyncast.
651 static bool classof(const DIEntry *) { return true; }
652 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
654 /// EmitValue - Emit debug information entry offset.
656 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
658 /// SizeOf - Determine size of debug information entry in bytes.
660 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
661 return sizeof(int32_t);
664 /// Profile - Used to gather unique data for the value folding set.
666 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
667 ID.AddInteger(isEntry);
668 ID.AddPointer(Entry);
670 virtual void Profile(FoldingSetNodeID &ID) {
671 ID.AddInteger(isEntry);
674 ID.AddPointer(Entry);
681 virtual void print(std::ostream &O) {
682 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
687 //===----------------------------------------------------------------------===//
688 /// DIEBlock - A block of values. Primarily used for location expressions.
690 class DIEBlock : public DIEValue, public DIE {
692 unsigned Size; // Size in bytes excluding size header.
702 // Implement isa/cast/dyncast.
703 static bool classof(const DIEBlock *) { return true; }
704 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
706 /// ComputeSize - calculate the size of the block.
708 unsigned ComputeSize(DwarfDebug &DD);
710 /// BestForm - Choose the best form for data.
712 unsigned BestForm() const {
713 if ((unsigned char)Size == Size) return DW_FORM_block1;
714 if ((unsigned short)Size == Size) return DW_FORM_block2;
715 if ((unsigned int)Size == Size) return DW_FORM_block4;
716 return DW_FORM_block;
719 /// EmitValue - Emit block data.
721 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
723 /// SizeOf - Determine size of block data in bytes.
725 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
728 /// Profile - Used to gather unique data for the value folding set.
730 virtual void Profile(FoldingSetNodeID &ID) {
731 ID.AddInteger(isBlock);
736 virtual void print(std::ostream &O) {
743 //===----------------------------------------------------------------------===//
744 /// CompileUnit - This dwarf writer support class manages information associate
745 /// with a source file.
748 /// ID - File identifier for source.
752 /// Die - Compile unit debug information entry.
756 /// GVToDieMap - Tracks the mapping of unit level debug informaton
757 /// variables to debug information entries.
758 std::map<GlobalVariable *, DIE *> GVToDieMap;
760 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
761 /// descriptors to debug information entries using a DIEntry proxy.
762 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
764 /// Globals - A map of globally visible named entities for this unit.
766 std::map<std::string, DIE *> Globals;
768 /// DiesSet - Used to uniquely define dies within the compile unit.
770 FoldingSet<DIE> DiesSet;
773 CompileUnit(unsigned I, DIE *D)
774 : ID(I), Die(D), GVToDieMap(),
775 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
783 unsigned getID() const { return ID; }
784 DIE* getDie() const { return Die; }
785 std::map<std::string, DIE *> &getGlobals() { return Globals; }
787 /// hasContent - Return true if this compile unit has something to write out.
789 bool hasContent() const {
790 return !Die->getChildren().empty();
793 /// AddGlobal - Add a new global entity to the compile unit.
795 void AddGlobal(const std::string &Name, DIE *Die) {
799 /// getDieMapSlotFor - Returns the debug information entry map slot for the
800 /// specified debug variable.
801 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
802 return GVToDieMap[GV];
805 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
806 /// specified debug variable.
807 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
808 return GVToDIEntryMap[GV];
811 /// AddDie - Adds or interns the DIE to the compile unit.
813 DIE *AddDie(DIE &Buffer) {
817 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
820 Die = new DIE(Buffer);
821 DiesSet.InsertNode(Die, Where);
822 this->Die->AddChild(Die);
830 //===----------------------------------------------------------------------===//
831 /// Dwarf - Emits general Dwarf directives.
835 //===--------------------------------------------------------------------===//
836 // Core attributes used by the Dwarf writer.
840 /// O - Stream to .s file.
844 /// Asm - Target of Dwarf emission.
848 /// TAI - Target asm information.
849 const TargetAsmInfo *TAI;
851 /// TD - Target data.
852 const TargetData *TD;
854 /// RI - Register Information.
855 const TargetRegisterInfo *RI;
857 /// M - Current module.
861 /// MF - Current machine function.
865 /// MMI - Collected machine module information.
867 MachineModuleInfo *MMI;
869 /// SubprogramCount - The running count of functions being compiled.
871 unsigned SubprogramCount;
873 /// Flavor - A unique string indicating what dwarf producer this is, used to
875 const char * const Flavor;
878 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
883 , TD(Asm->TM.getTargetData())
884 , RI(Asm->TM.getRegisterInfo())
895 //===--------------------------------------------------------------------===//
898 AsmPrinter *getAsm() const { return Asm; }
899 MachineModuleInfo *getMMI() const { return MMI; }
900 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
901 const TargetData *getTargetData() const { return TD; }
903 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
905 if (isInSection && TAI->getDwarfSectionOffsetDirective())
906 O << TAI->getDwarfSectionOffsetDirective();
907 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
908 O << TAI->getData32bitsDirective();
910 O << TAI->getData64bitsDirective();
913 /// PrintLabelName - Print label name in form used by Dwarf writer.
915 void PrintLabelName(DWLabel Label) const {
916 PrintLabelName(Label.Tag, Label.Number);
918 void PrintLabelName(const char *Tag, unsigned Number) const {
919 O << TAI->getPrivateGlobalPrefix() << Tag;
920 if (Number) O << Number;
923 void PrintLabelName(const char *Tag, unsigned Number,
924 const char *Suffix) const {
925 O << TAI->getPrivateGlobalPrefix() << Tag;
926 if (Number) O << Number;
930 /// EmitLabel - Emit location label for internal use by Dwarf.
932 void EmitLabel(DWLabel Label) const {
933 EmitLabel(Label.Tag, Label.Number);
935 void EmitLabel(const char *Tag, unsigned Number) const {
936 PrintLabelName(Tag, Number);
940 /// EmitReference - Emit a reference to a label.
942 void EmitReference(DWLabel Label, bool IsPCRelative = false,
943 bool Force32Bit = false) const {
944 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
946 void EmitReference(const char *Tag, unsigned Number,
947 bool IsPCRelative = false, bool Force32Bit = false) const {
948 PrintRelDirective(Force32Bit);
949 PrintLabelName(Tag, Number);
951 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
953 void EmitReference(const std::string &Name, bool IsPCRelative = false,
954 bool Force32Bit = false) const {
955 PrintRelDirective(Force32Bit);
959 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
962 /// EmitDifference - Emit the difference between two labels. Some
963 /// assemblers do not behave with absolute expressions with data directives,
964 /// so there is an option (needsSet) to use an intermediary set expression.
965 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
966 bool IsSmall = false) {
967 EmitDifference(LabelHi.Tag, LabelHi.Number,
968 LabelLo.Tag, LabelLo.Number,
971 void EmitDifference(const char *TagHi, unsigned NumberHi,
972 const char *TagLo, unsigned NumberLo,
973 bool IsSmall = false) {
974 if (TAI->needsSet()) {
976 PrintLabelName("set", SetCounter, Flavor);
978 PrintLabelName(TagHi, NumberHi);
980 PrintLabelName(TagLo, NumberLo);
983 PrintRelDirective(IsSmall);
984 PrintLabelName("set", SetCounter, Flavor);
987 PrintRelDirective(IsSmall);
989 PrintLabelName(TagHi, NumberHi);
991 PrintLabelName(TagLo, NumberLo);
995 void EmitSectionOffset(const char* Label, const char* Section,
996 unsigned LabelNumber, unsigned SectionNumber,
997 bool IsSmall = false, bool isEH = false,
998 bool useSet = true) {
999 bool printAbsolute = false;
1001 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1003 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1005 if (TAI->needsSet() && useSet) {
1007 PrintLabelName("set", SetCounter, Flavor);
1009 PrintLabelName(Label, LabelNumber);
1011 if (!printAbsolute) {
1013 PrintLabelName(Section, SectionNumber);
1017 PrintRelDirective(IsSmall);
1019 PrintLabelName("set", SetCounter, Flavor);
1022 PrintRelDirective(IsSmall, true);
1024 PrintLabelName(Label, LabelNumber);
1026 if (!printAbsolute) {
1028 PrintLabelName(Section, SectionNumber);
1033 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1035 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1036 const std::vector<MachineMove> &Moves, bool isEH) {
1038 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1039 TargetFrameInfo::StackGrowsUp ?
1040 TD->getPointerSize() : -TD->getPointerSize();
1041 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1043 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1044 const MachineMove &Move = Moves[i];
1045 unsigned LabelID = Move.getLabelID();
1048 LabelID = MMI->MappedLabel(LabelID);
1050 // Throw out move if the label is invalid.
1051 if (!LabelID) continue;
1054 const MachineLocation &Dst = Move.getDestination();
1055 const MachineLocation &Src = Move.getSource();
1057 // Advance row if new location.
1058 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1059 Asm->EmitInt8(DW_CFA_advance_loc4);
1060 Asm->EOL("DW_CFA_advance_loc4");
1061 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1064 BaseLabelID = LabelID;
1065 BaseLabel = "label";
1069 // If advancing cfa.
1070 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1072 if (Src.getReg() == MachineLocation::VirtualFP) {
1073 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1074 Asm->EOL("DW_CFA_def_cfa_offset");
1076 Asm->EmitInt8(DW_CFA_def_cfa);
1077 Asm->EOL("DW_CFA_def_cfa");
1078 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1079 Asm->EOL("Register");
1082 int Offset = -Src.getOffset();
1084 Asm->EmitULEB128Bytes(Offset);
1087 assert(0 && "Machine move no supported yet.");
1089 } else if (Src.isReg() &&
1090 Src.getReg() == MachineLocation::VirtualFP) {
1092 Asm->EmitInt8(DW_CFA_def_cfa_register);
1093 Asm->EOL("DW_CFA_def_cfa_register");
1094 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1095 Asm->EOL("Register");
1097 assert(0 && "Machine move no supported yet.");
1100 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1101 int Offset = Dst.getOffset() / stackGrowth;
1104 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1105 Asm->EOL("DW_CFA_offset_extended_sf");
1106 Asm->EmitULEB128Bytes(Reg);
1108 Asm->EmitSLEB128Bytes(Offset);
1110 } else if (Reg < 64) {
1111 Asm->EmitInt8(DW_CFA_offset + Reg);
1113 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1116 Asm->EmitULEB128Bytes(Offset);
1119 Asm->EmitInt8(DW_CFA_offset_extended);
1120 Asm->EOL("DW_CFA_offset_extended");
1121 Asm->EmitULEB128Bytes(Reg);
1123 Asm->EmitULEB128Bytes(Offset);
1132 //===----------------------------------------------------------------------===//
1133 /// SrcLineInfo - This class is used to record source line correspondence.
1136 unsigned Line; // Source line number.
1137 unsigned Column; // Source column.
1138 unsigned SourceID; // Source ID number.
1139 unsigned LabelID; // Label in code ID number.
1141 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1142 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1145 unsigned getLine() const { return Line; }
1146 unsigned getColumn() const { return Column; }
1147 unsigned getSourceID() const { return SourceID; }
1148 unsigned getLabelID() const { return LabelID; }
1151 //===----------------------------------------------------------------------===//
1152 /// DbgVariable - This class is used to track local variable information.
1155 DIVariable Var; // Variable Descriptor.
1156 unsigned FrameIndex; // Variable frame index.
1158 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1161 DIVariable getVariable() const { return Var; }
1162 unsigned getFrameIndex() const { return FrameIndex; }
1165 //===----------------------------------------------------------------------===//
1166 /// DbgScope - This class is used to track scope information.
1169 DbgScope *Parent; // Parent to this scope.
1170 DIDescriptor Desc; // Debug info descriptor for scope.
1171 // Either subprogram or block.
1172 unsigned StartLabelID; // Label ID of the beginning of scope.
1173 unsigned EndLabelID; // Label ID of the end of scope.
1174 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1175 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1177 DbgScope(DbgScope *P, DIDescriptor D)
1178 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1181 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1182 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1186 DbgScope *getParent() const { return Parent; }
1187 DIDescriptor getDesc() const { return Desc; }
1188 unsigned getStartLabelID() const { return StartLabelID; }
1189 unsigned getEndLabelID() const { return EndLabelID; }
1190 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1191 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1192 void setStartLabelID(unsigned S) { StartLabelID = S; }
1193 void setEndLabelID(unsigned E) { EndLabelID = E; }
1195 /// AddScope - Add a scope to the scope.
1197 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1199 /// AddVariable - Add a variable to the scope.
1201 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1204 //===----------------------------------------------------------------------===//
1205 /// DwarfDebug - Emits Dwarf debug directives.
1207 class DwarfDebug : public Dwarf {
1208 //===--------------------------------------------------------------------===//
1209 // Attributes used to construct specific Dwarf sections.
1212 /// CompileUnitMap - A map of global variables representing compile units to
1214 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1216 /// CompileUnits - All the compile units in this module.
1218 SmallVector<CompileUnit *, 8> CompileUnits;
1220 /// MainCU - Some platform prefers one compile unit per .o file. In such
1221 /// cases, all dies are inserted in MainCU.
1222 CompileUnit *MainCU;
1224 /// AbbreviationsSet - Used to uniquely define abbreviations.
1226 FoldingSet<DIEAbbrev> AbbreviationsSet;
1228 /// Abbreviations - A list of all the unique abbreviations in use.
1230 std::vector<DIEAbbrev *> Abbreviations;
1232 /// DirectoryIdMap - Directory name to directory id map.
1234 StringMap<unsigned> DirectoryIdMap;
1236 /// DirectoryNames - A list of directory names.
1237 SmallVector<std::string, 8> DirectoryNames;
1239 /// SourceFileIdMap - Source file name to source file id map.
1241 StringMap<unsigned> SourceFileIdMap;
1243 /// SourceFileNames - A list of source file names.
1244 SmallVector<std::string, 8> SourceFileNames;
1246 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1247 /// id mapped to a unique id.
1248 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1250 /// SourceIds - Reverse map from source id to directory id + file id pair.
1252 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1254 /// Lines - List of of source line correspondence.
1255 std::vector<SrcLineInfo> Lines;
1257 /// ValuesSet - Used to uniquely define values.
1259 FoldingSet<DIEValue> ValuesSet;
1261 /// Values - A list of all the unique values in use.
1263 std::vector<DIEValue *> Values;
1265 /// StringPool - A UniqueVector of strings used by indirect references.
1267 UniqueVector<std::string> StringPool;
1269 /// SectionMap - Provides a unique id per text section.
1271 UniqueVector<const Section*> SectionMap;
1273 /// SectionSourceLines - Tracks line numbers per text section.
1275 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1277 /// didInitial - Flag to indicate if initial emission has been done.
1281 /// shouldEmit - Flag to indicate if debug information should be emitted.
1285 // RootDbgScope - Top level scope for the current function.
1287 DbgScope *RootDbgScope;
1289 /// DbgScopeMap - Tracks the scopes in the current function.
1290 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1292 /// DebugTimer - Timer for the Dwarf debug writer.
1295 struct FunctionDebugFrameInfo {
1297 std::vector<MachineMove> Moves;
1299 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1300 Number(Num), Moves(M) { }
1303 std::vector<FunctionDebugFrameInfo> DebugFrames;
1306 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
1309 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
1312 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1314 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1315 // Profile the node so that we can make it unique.
1316 FoldingSetNodeID ID;
1319 // Check the set for priors.
1320 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1322 // If it's newly added.
1323 if (InSet == &Abbrev) {
1324 // Add to abbreviation list.
1325 Abbreviations.push_back(&Abbrev);
1326 // Assign the vector position + 1 as its number.
1327 Abbrev.setNumber(Abbreviations.size());
1329 // Assign existing abbreviation number.
1330 Abbrev.setNumber(InSet->getNumber());
1334 /// NewString - Add a string to the constant pool and returns a label.
1336 DWLabel NewString(const std::string &String) {
1337 unsigned StringID = StringPool.insert(String);
1338 return DWLabel("string", StringID);
1341 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1343 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1347 FoldingSetNodeID ID;
1348 DIEntry::Profile(ID, Entry);
1350 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1352 if (Value) return Value;
1354 Value = new DIEntry(Entry);
1355 ValuesSet.InsertNode(Value, Where);
1357 Value = new DIEntry(Entry);
1360 Values.push_back(Value);
1364 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1366 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1367 Value->Entry = Entry;
1368 // Add to values set if not already there. If it is, we merely have a
1369 // duplicate in the values list (no harm.)
1370 ValuesSet.GetOrInsertNode(Value);
1373 /// AddUInt - Add an unsigned integer attribute data and value.
1375 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1376 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1378 FoldingSetNodeID ID;
1379 DIEInteger::Profile(ID, Integer);
1381 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1383 Value = new DIEInteger(Integer);
1384 ValuesSet.InsertNode(Value, Where);
1385 Values.push_back(Value);
1388 Die->AddValue(Attribute, Form, Value);
1391 /// AddSInt - Add an signed integer attribute data and value.
1393 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1394 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1396 FoldingSetNodeID ID;
1397 DIEInteger::Profile(ID, (uint64_t)Integer);
1399 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1401 Value = new DIEInteger(Integer);
1402 ValuesSet.InsertNode(Value, Where);
1403 Values.push_back(Value);
1406 Die->AddValue(Attribute, Form, Value);
1409 /// AddString - Add a string attribute data and value.
1411 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1412 const std::string &String) {
1413 FoldingSetNodeID ID;
1414 DIEString::Profile(ID, String);
1416 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1418 Value = new DIEString(String);
1419 ValuesSet.InsertNode(Value, Where);
1420 Values.push_back(Value);
1423 Die->AddValue(Attribute, Form, Value);
1426 /// AddLabel - Add a Dwarf label attribute data and value.
1428 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1429 const DWLabel &Label) {
1430 FoldingSetNodeID ID;
1431 DIEDwarfLabel::Profile(ID, Label);
1433 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1435 Value = new DIEDwarfLabel(Label);
1436 ValuesSet.InsertNode(Value, Where);
1437 Values.push_back(Value);
1440 Die->AddValue(Attribute, Form, Value);
1443 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1445 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1446 const std::string &Label) {
1447 FoldingSetNodeID ID;
1448 DIEObjectLabel::Profile(ID, Label);
1450 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1452 Value = new DIEObjectLabel(Label);
1453 ValuesSet.InsertNode(Value, Where);
1454 Values.push_back(Value);
1457 Die->AddValue(Attribute, Form, Value);
1460 /// AddSectionOffset - Add a section offset label attribute data and value.
1462 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1463 const DWLabel &Label, const DWLabel &Section,
1464 bool isEH = false, bool useSet = true) {
1465 FoldingSetNodeID ID;
1466 DIESectionOffset::Profile(ID, Label, Section);
1468 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1470 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1471 ValuesSet.InsertNode(Value, Where);
1472 Values.push_back(Value);
1475 Die->AddValue(Attribute, Form, Value);
1478 /// AddDelta - Add a label delta attribute data and value.
1480 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1481 const DWLabel &Hi, const DWLabel &Lo) {
1482 FoldingSetNodeID ID;
1483 DIEDelta::Profile(ID, Hi, Lo);
1485 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1487 Value = new DIEDelta(Hi, Lo);
1488 ValuesSet.InsertNode(Value, Where);
1489 Values.push_back(Value);
1492 Die->AddValue(Attribute, Form, Value);
1495 /// AddDIEntry - Add a DIE attribute data and value.
1497 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1498 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1501 /// AddBlock - Add block data.
1503 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1504 Block->ComputeSize(*this);
1505 FoldingSetNodeID ID;
1508 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1511 ValuesSet.InsertNode(Value, Where);
1512 Values.push_back(Value);
1514 // Already exists, reuse the previous one.
1516 Block = cast<DIEBlock>(Value);
1519 Die->AddValue(Attribute, Block->BestForm(), Value);
1522 /// AddSourceLine - Add location information to specified debug information
1524 void AddSourceLine(DIE *Die, const DIVariable *V) {
1525 unsigned FileID = 0;
1526 unsigned Line = V->getLineNumber();
1527 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1528 FileID = Unit->getID();
1529 assert (FileID && "Invalid file id");
1530 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1531 AddUInt(Die, DW_AT_decl_line, 0, Line);
1534 /// AddSourceLine - Add location information to specified debug information
1536 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1537 unsigned FileID = 0;
1538 unsigned Line = G->getLineNumber();
1539 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1540 FileID = Unit->getID();
1541 assert (FileID && "Invalid file id");
1542 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1543 AddUInt(Die, DW_AT_decl_line, 0, Line);
1546 void AddSourceLine(DIE *Die, const DIType *Ty) {
1547 unsigned FileID = 0;
1548 unsigned Line = Ty->getLineNumber();
1549 DICompileUnit CU = Ty->getCompileUnit();
1552 CompileUnit *Unit = FindCompileUnit(CU);
1553 FileID = Unit->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 /// AddAddress - Add an address attribute to a die based on the location
1561 void AddAddress(DIE *Die, unsigned Attribute,
1562 const MachineLocation &Location) {
1563 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1564 DIEBlock *Block = new DIEBlock();
1566 if (Location.isReg()) {
1568 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1570 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1571 AddUInt(Block, 0, DW_FORM_udata, Reg);
1575 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1577 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1578 AddUInt(Block, 0, DW_FORM_udata, Reg);
1580 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1583 AddBlock(Die, Attribute, 0, Block);
1586 /// AddType - Add a new type attribute to the specified entity.
1587 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1591 // Check for pre-existence.
1592 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1593 // If it exists then use the existing value.
1595 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1600 Slot = NewDIEntry();
1603 DIE Buffer(DW_TAG_base_type);
1604 if (Ty.isBasicType(Ty.getTag()))
1605 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1606 else if (Ty.isDerivedType(Ty.getTag()))
1607 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1609 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1610 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1613 // Add debug information entry to entity and appropriate context.
1615 DIDescriptor Context = Ty.getContext();
1616 if (!Context.isNull())
1617 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1620 DIE *Child = new DIE(Buffer);
1621 Die->AddChild(Child);
1623 SetDIEntry(Slot, Child);
1625 Die = DW_Unit->AddDie(Buffer);
1626 SetDIEntry(Slot, Die);
1629 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1632 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1633 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1636 // Get core information.
1639 Buffer.setTag(DW_TAG_base_type);
1640 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1641 // Add name if not anonymous or intermediate type.
1643 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1644 uint64_t Size = BTy.getSizeInBits() >> 3;
1645 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1648 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1649 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1650 DIDerivedType DTy) {
1652 // Get core information.
1655 uint64_t Size = DTy.getSizeInBits() >> 3;
1656 unsigned Tag = DTy.getTag();
1658 // FIXME - Workaround for templates.
1659 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1663 // Map to main type, void will not have a type.
1664 DIType FromTy = DTy.getTypeDerivedFrom();
1665 AddType(DW_Unit, &Buffer, FromTy);
1667 // Add name if not anonymous or intermediate type.
1669 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1671 // Add size if non-zero (derived types might be zero-sized.)
1673 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1675 // Add source line info if available and TyDesc is not a forward
1677 if (!DTy.isForwardDecl())
1678 AddSourceLine(&Buffer, &DTy);
1681 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1682 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1683 DICompositeType CTy) {
1684 // Get core information.
1688 uint64_t Size = CTy.getSizeInBits() >> 3;
1689 unsigned Tag = CTy.getTag();
1693 case DW_TAG_vector_type:
1694 case DW_TAG_array_type:
1695 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1697 case DW_TAG_enumeration_type:
1699 DIArray Elements = CTy.getTypeArray();
1700 // Add enumerators to enumeration type.
1701 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1702 DIE *ElemDie = NULL;
1703 DIEnumerator Enum(Elements.getElement(i).getGV());
1704 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1705 Buffer.AddChild(ElemDie);
1709 case DW_TAG_subroutine_type:
1711 // Add prototype flag.
1712 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1713 DIArray Elements = CTy.getTypeArray();
1715 DIDescriptor RTy = Elements.getElement(0);
1716 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1719 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1720 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1721 DIDescriptor Ty = Elements.getElement(i);
1722 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1723 Buffer.AddChild(Arg);
1727 case DW_TAG_structure_type:
1728 case DW_TAG_union_type:
1730 // Add elements to structure type.
1731 DIArray Elements = CTy.getTypeArray();
1733 // A forward struct declared type may not have elements available.
1734 if (Elements.isNull())
1737 // Add elements to structure type.
1738 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1739 DIDescriptor Element = Elements.getElement(i);
1740 DIE *ElemDie = NULL;
1741 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1742 ElemDie = CreateSubprogramDIE(DW_Unit,
1743 DISubprogram(Element.getGV()));
1744 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1745 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1746 DIGlobalVariable(Element.getGV()));
1748 ElemDie = CreateMemberDIE(DW_Unit,
1749 DIDerivedType(Element.getGV()));
1750 Buffer.AddChild(ElemDie);
1752 unsigned RLang = CTy.getRunTimeLang();
1754 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1761 // Add name if not anonymous or intermediate type.
1763 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1765 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1766 || Tag == DW_TAG_union_type) {
1767 // Add size if non-zero (derived types might be zero-sized.)
1769 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1771 // Add zero size if it is not a forward declaration.
1772 if (CTy.isForwardDecl())
1773 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1775 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1778 // Add source line info if available.
1779 if (!CTy.isForwardDecl())
1780 AddSourceLine(&Buffer, &CTy);
1784 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1785 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1786 int64_t L = SR.getLo();
1787 int64_t H = SR.getHi();
1788 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1790 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1792 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1793 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1795 Buffer.AddChild(DW_Subrange);
1798 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1799 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1800 DICompositeType *CTy) {
1801 Buffer.setTag(DW_TAG_array_type);
1802 if (CTy->getTag() == DW_TAG_vector_type)
1803 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1805 // Emit derived type.
1806 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1807 DIArray Elements = CTy->getTypeArray();
1809 // Construct an anonymous type for index type.
1810 DIE IdxBuffer(DW_TAG_base_type);
1811 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1812 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1813 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1815 // Add subranges to array type.
1816 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1817 DIDescriptor Element = Elements.getElement(i);
1818 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1819 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1823 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1824 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1826 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1829 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1830 int64_t Value = ETy->getEnumValue();
1831 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1835 /// CreateGlobalVariableDIE - Create new DIE using GV.
1836 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1838 DIE *GVDie = new DIE(DW_TAG_variable);
1840 GV.getDisplayName(Name);
1841 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1842 std::string LinkageName;
1843 GV.getLinkageName(LinkageName);
1844 if (!LinkageName.empty())
1845 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1846 AddType(DW_Unit, GVDie, GV.getType());
1847 if (!GV.isLocalToUnit())
1848 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1849 AddSourceLine(GVDie, &GV);
1853 /// CreateMemberDIE - Create new member DIE.
1854 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1855 DIE *MemberDie = new DIE(DT.getTag());
1859 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1861 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1863 AddSourceLine(MemberDie, &DT);
1865 uint64_t Size = DT.getSizeInBits();
1866 uint64_t FieldSize = DT.getOriginalTypeSize();
1868 if (Size != FieldSize) {
1870 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1871 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1873 uint64_t Offset = DT.getOffsetInBits();
1874 uint64_t FieldOffset = Offset;
1875 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1876 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1877 FieldOffset = (HiMark - FieldSize);
1878 Offset -= FieldOffset;
1879 // Maybe we need to work from the other end.
1880 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1881 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1883 DIEBlock *Block = new DIEBlock();
1884 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1885 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1886 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1888 if (DT.isProtected())
1889 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1890 else if (DT.isPrivate())
1891 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1896 /// CreateSubprogramDIE - Create new DIE using SP.
1897 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1898 const DISubprogram &SP,
1899 bool IsConstructor = false) {
1900 DIE *SPDie = new DIE(DW_TAG_subprogram);
1903 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1904 std::string LinkageName;
1905 SP.getLinkageName(LinkageName);
1906 if (!LinkageName.empty())
1907 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1909 AddSourceLine(SPDie, &SP);
1911 DICompositeType SPTy = SP.getType();
1912 DIArray Args = SPTy.getTypeArray();
1915 if (!IsConstructor) {
1917 AddType(DW_Unit, SPDie, SPTy);
1919 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1922 if (!SP.isDefinition()) {
1923 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1925 // Do not add arguments for subprogram definition. They will be
1926 // handled through RecordVariable.
1928 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1929 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1930 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1931 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1932 SPDie->AddChild(Arg);
1936 unsigned Lang = SP.getCompileUnit().getLanguage();
1937 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1938 || Lang == DW_LANG_ObjC)
1939 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1941 if (!SP.isLocalToUnit())
1942 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1946 /// FindCompileUnit - Get the compile unit for the given descriptor.
1948 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1949 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1950 assert(DW_Unit && "Missing compile unit.");
1954 /// NewDbgScopeVariable - Create a new scope variable.
1956 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1957 // Get the descriptor.
1958 const DIVariable &VD = DV->getVariable();
1960 // Translate tag to proper Dwarf tag. The result variable is dropped for
1963 switch (VD.getTag()) {
1964 case DW_TAG_return_variable: return NULL;
1965 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1966 case DW_TAG_auto_variable: // fall thru
1967 default: Tag = DW_TAG_variable; break;
1970 // Define variable debug information entry.
1971 DIE *VariableDie = new DIE(Tag);
1974 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1976 // Add source line info if available.
1977 AddSourceLine(VariableDie, &VD);
1979 // Add variable type.
1980 AddType(Unit, VariableDie, VD.getType());
1982 // Add variable address.
1983 MachineLocation Location;
1984 Location.set(RI->getFrameRegister(*MF),
1985 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1986 AddAddress(VariableDie, DW_AT_location, Location);
1991 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1993 DbgScope *getOrCreateScope(GlobalVariable *V) {
1994 DbgScope *&Slot = DbgScopeMap[V];
1995 if (Slot) return Slot;
1997 // FIXME - breaks down when the context is an inlined function.
1998 DIDescriptor ParentDesc;
1999 DIDescriptor Desc(V);
2001 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
2003 ParentDesc = Block.getContext();
2006 DbgScope *Parent = ParentDesc.isNull() ?
2007 NULL : getOrCreateScope(ParentDesc.getGV());
2008 Slot = new DbgScope(Parent, Desc);
2011 Parent->AddScope(Slot);
2012 } else if (RootDbgScope) {
2013 // FIXME - Add inlined function scopes to the root so we can delete them
2014 // later. Long term, handle inlined functions properly.
2015 RootDbgScope->AddScope(Slot);
2017 // First function is top level function.
2018 RootDbgScope = Slot;
2024 /// ConstructDbgScope - Construct the components of a scope.
2026 void ConstructDbgScope(DbgScope *ParentScope,
2027 unsigned ParentStartID, unsigned ParentEndID,
2028 DIE *ParentDie, CompileUnit *Unit) {
2029 // Add variables to scope.
2030 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2031 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2032 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2033 if (VariableDie) ParentDie->AddChild(VariableDie);
2036 // Add nested scopes.
2037 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2038 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2039 // Define the Scope debug information entry.
2040 DbgScope *Scope = Scopes[j];
2041 // FIXME - Ignore inlined functions for the time being.
2042 if (!Scope->getParent()) continue;
2044 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2045 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2047 // Ignore empty scopes.
2048 if (StartID == EndID && StartID != 0) continue;
2049 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2051 if (StartID == ParentStartID && EndID == ParentEndID) {
2052 // Just add stuff to the parent scope.
2053 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2055 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2057 // Add the scope bounds.
2059 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2060 DWLabel("label", StartID));
2062 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2063 DWLabel("func_begin", SubprogramCount));
2066 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2067 DWLabel("label", EndID));
2069 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2070 DWLabel("func_end", SubprogramCount));
2073 // Add the scope contents.
2074 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2075 ParentDie->AddChild(ScopeDie);
2080 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2082 void ConstructRootDbgScope(DbgScope *RootScope) {
2083 // Exit if there is no root scope.
2084 if (!RootScope) return;
2085 DIDescriptor Desc = RootScope->getDesc();
2089 // Get the subprogram debug information entry.
2090 DISubprogram SPD(Desc.getGV());
2092 // Get the compile unit context.
2093 CompileUnit *Unit = MainCU;
2095 Unit = FindCompileUnit(SPD.getCompileUnit());
2097 // Get the subprogram die.
2098 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2099 assert(SPDie && "Missing subprogram descriptor");
2101 // Add the function bounds.
2102 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2103 DWLabel("func_begin", SubprogramCount));
2104 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2105 DWLabel("func_end", SubprogramCount));
2106 MachineLocation Location(RI->getFrameRegister(*MF));
2107 AddAddress(SPDie, DW_AT_frame_base, Location);
2109 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2112 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2114 void ConstructDefaultDbgScope(MachineFunction *MF) {
2115 const char *FnName = MF->getFunction()->getNameStart();
2117 std::map<std::string, DIE*> &Globals = MainCU->getGlobals();
2118 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2119 if (GI != Globals.end()) {
2120 DIE *SPDie = GI->second;
2122 // Add the function bounds.
2123 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2124 DWLabel("func_begin", SubprogramCount));
2125 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2126 DWLabel("func_end", SubprogramCount));
2128 MachineLocation Location(RI->getFrameRegister(*MF));
2129 AddAddress(SPDie, DW_AT_frame_base, Location);
2133 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2134 CompileUnit *Unit = CompileUnits[i];
2135 std::map<std::string, DIE*> &Globals = Unit->getGlobals();
2136 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2137 if (GI != Globals.end()) {
2138 DIE *SPDie = GI->second;
2140 // Add the function bounds.
2141 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2142 DWLabel("func_begin", SubprogramCount));
2143 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2144 DWLabel("func_end", SubprogramCount));
2146 MachineLocation Location(RI->getFrameRegister(*MF));
2147 AddAddress(SPDie, DW_AT_frame_base, Location);
2154 // FIXME: This is causing an abort because C++ mangled names are compared
2155 // with their unmangled counterparts. See PR2885. Don't do this assert.
2156 assert(0 && "Couldn't find DIE for machine function!");
2161 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2162 /// tools to recognize the object file contains Dwarf information.
2163 void EmitInitial() {
2164 // Check to see if we already emitted intial headers.
2165 if (didInitial) return;
2168 // Dwarf sections base addresses.
2169 if (TAI->doesDwarfRequireFrameSection()) {
2170 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2171 EmitLabel("section_debug_frame", 0);
2173 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2174 EmitLabel("section_info", 0);
2175 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2176 EmitLabel("section_abbrev", 0);
2177 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2178 EmitLabel("section_aranges", 0);
2179 if (TAI->doesSupportMacInfoSection()) {
2180 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2181 EmitLabel("section_macinfo", 0);
2183 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2184 EmitLabel("section_line", 0);
2185 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2186 EmitLabel("section_loc", 0);
2187 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2188 EmitLabel("section_pubnames", 0);
2189 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2190 EmitLabel("section_str", 0);
2191 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2192 EmitLabel("section_ranges", 0);
2194 Asm->SwitchToSection(TAI->getTextSection());
2195 EmitLabel("text_begin", 0);
2196 Asm->SwitchToSection(TAI->getDataSection());
2197 EmitLabel("data_begin", 0);
2200 /// EmitDIE - Recusively Emits a debug information entry.
2202 void EmitDIE(DIE *Die) {
2203 // Get the abbreviation for this DIE.
2204 unsigned AbbrevNumber = Die->getAbbrevNumber();
2205 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2209 // Emit the code (index) for the abbreviation.
2210 Asm->EmitULEB128Bytes(AbbrevNumber);
2213 Asm->EOL(std::string("Abbrev [" +
2214 utostr(AbbrevNumber) +
2215 "] 0x" + utohexstr(Die->getOffset()) +
2216 ":0x" + utohexstr(Die->getSize()) + " " +
2217 TagString(Abbrev->getTag())));
2221 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2222 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2224 // Emit the DIE attribute values.
2225 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2226 unsigned Attr = AbbrevData[i].getAttribute();
2227 unsigned Form = AbbrevData[i].getForm();
2228 assert(Form && "Too many attributes for DIE (check abbreviation)");
2231 case DW_AT_sibling: {
2232 Asm->EmitInt32(Die->SiblingOffset());
2236 // Emit an attribute using the defined form.
2237 Values[i]->EmitValue(*this, Form);
2242 Asm->EOL(AttributeString(Attr));
2245 // Emit the DIE children if any.
2246 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2247 const std::vector<DIE *> &Children = Die->getChildren();
2249 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2250 EmitDIE(Children[j]);
2253 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2257 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2259 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2260 // Get the children.
2261 const std::vector<DIE *> &Children = Die->getChildren();
2263 // If not last sibling and has children then add sibling offset attribute.
2264 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2266 // Record the abbreviation.
2267 AssignAbbrevNumber(Die->getAbbrev());
2269 // Get the abbreviation for this DIE.
2270 unsigned AbbrevNumber = Die->getAbbrevNumber();
2271 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2274 Die->setOffset(Offset);
2276 // Start the size with the size of abbreviation code.
2277 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2279 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2280 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2282 // Size the DIE attribute values.
2283 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2284 // Size attribute value.
2285 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2288 // Size the DIE children if any.
2289 if (!Children.empty()) {
2290 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2291 "Children flag not set");
2293 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2294 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2297 // End of children marker.
2298 Offset += sizeof(int8_t);
2301 Die->setSize(Offset - Die->getOffset());
2305 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2307 void SizeAndOffsets() {
2308 // Process base compile unit.
2310 // Compute size of compile unit header
2311 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2312 sizeof(int16_t) + // DWARF version number
2313 sizeof(int32_t) + // Offset Into Abbrev. Section
2314 sizeof(int8_t); // Pointer Size (in bytes)
2315 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2318 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2319 CompileUnit *Unit = CompileUnits[i];
2320 // Compute size of compile unit header
2321 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2322 sizeof(int16_t) + // DWARF version number
2323 sizeof(int32_t) + // Offset Into Abbrev. Section
2324 sizeof(int8_t); // Pointer Size (in bytes)
2325 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2329 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2331 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2332 DIE *Die = Unit->getDie();
2333 // Emit the compile units header.
2334 EmitLabel("info_begin", Unit->getID());
2335 // Emit size of content not including length itself
2336 unsigned ContentSize = Die->getSize() +
2337 sizeof(int16_t) + // DWARF version number
2338 sizeof(int32_t) + // Offset Into Abbrev. Section
2339 sizeof(int8_t) + // Pointer Size (in bytes)
2340 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2342 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2343 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2344 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2345 Asm->EOL("Offset Into Abbrev. Section");
2346 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2349 // FIXME - extra padding for gdb bug.
2350 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2351 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2352 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2353 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2354 EmitLabel("info_end", Unit->getID());
2359 void EmitDebugInfo() {
2360 // Start debug info section.
2361 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2364 EmitDebugInfoPerCU(MainCU);
2368 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2369 EmitDebugInfoPerCU(CompileUnits[i]);
2372 /// EmitAbbreviations - Emit the abbreviation section.
2374 void EmitAbbreviations() const {
2375 // Check to see if it is worth the effort.
2376 if (!Abbreviations.empty()) {
2377 // Start the debug abbrev section.
2378 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2380 EmitLabel("abbrev_begin", 0);
2382 // For each abbrevation.
2383 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2384 // Get abbreviation data
2385 const DIEAbbrev *Abbrev = Abbreviations[i];
2387 // Emit the abbrevations code (base 1 index.)
2388 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2389 Asm->EOL("Abbreviation Code");
2391 // Emit the abbreviations data.
2392 Abbrev->Emit(*this);
2397 // Mark end of abbreviations.
2398 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2400 EmitLabel("abbrev_end", 0);
2406 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2407 /// the line matrix.
2409 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2410 // Define last address of section.
2411 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2412 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2413 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2414 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2416 // Mark end of matrix.
2417 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2418 Asm->EmitULEB128Bytes(1); Asm->EOL();
2419 Asm->EmitInt8(1); Asm->EOL();
2422 /// EmitDebugLines - Emit source line information.
2424 void EmitDebugLines() {
2425 // If the target is using .loc/.file, the assembler will be emitting the
2426 // .debug_line table automatically.
2427 if (TAI->hasDotLocAndDotFile())
2430 // Minimum line delta, thus ranging from -10..(255-10).
2431 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2432 // Maximum line delta, thus ranging from -10..(255-10).
2433 const int MaxLineDelta = 255 + MinLineDelta;
2435 // Start the dwarf line section.
2436 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2438 // Construct the section header.
2440 EmitDifference("line_end", 0, "line_begin", 0, true);
2441 Asm->EOL("Length of Source Line Info");
2442 EmitLabel("line_begin", 0);
2444 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2446 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2447 Asm->EOL("Prolog Length");
2448 EmitLabel("line_prolog_begin", 0);
2450 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2452 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2454 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2456 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2458 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2460 // Line number standard opcode encodings argument count
2461 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2462 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2463 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2464 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2465 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2466 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2467 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2468 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2469 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2471 // Emit directories.
2472 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2473 Asm->EmitString(getSourceDirectoryName(DI));
2474 Asm->EOL("Directory");
2476 Asm->EmitInt8(0); Asm->EOL("End of directories");
2479 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2480 // Remember source id starts at 1.
2481 std::pair<unsigned, unsigned> Id = getSourceDirsectoryAndFileIds(SI);
2482 Asm->EmitString(getSourceFileName(Id.second));
2484 Asm->EmitULEB128Bytes(Id.first);
2485 Asm->EOL("Directory #");
2486 Asm->EmitULEB128Bytes(0);
2487 Asm->EOL("Mod date");
2488 Asm->EmitULEB128Bytes(0);
2489 Asm->EOL("File size");
2491 Asm->EmitInt8(0); Asm->EOL("End of files");
2493 EmitLabel("line_prolog_end", 0);
2495 // A sequence for each text section.
2496 unsigned SecSrcLinesSize = SectionSourceLines.size();
2498 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2499 // Isolate current sections line info.
2500 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2503 const Section* S = SectionMap[j + 1];
2504 O << '\t' << TAI->getCommentString() << " Section"
2505 << S->getName() << '\n';
2509 // Dwarf assumes we start with first line of first source file.
2510 unsigned Source = 1;
2513 // Construct rows of the address, source, line, column matrix.
2514 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2515 const SrcLineInfo &LineInfo = LineInfos[i];
2516 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2517 if (!LabelID) continue;
2522 std::pair<unsigned, unsigned> SourceID =
2523 getSourceDirsectoryAndFileIds(LineInfo.getSourceID());
2524 O << '\t' << TAI->getCommentString() << ' '
2525 << getSourceDirectoryName(SourceID.first) << ' '
2526 << getSourceFileName(SourceID.second)
2527 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2530 // Define the line address.
2531 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2532 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2533 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2534 EmitReference("label", LabelID); Asm->EOL("Location label");
2536 // If change of source, then switch to the new source.
2537 if (Source != LineInfo.getSourceID()) {
2538 Source = LineInfo.getSourceID();
2539 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2540 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2543 // If change of line.
2544 if (Line != LineInfo.getLine()) {
2545 // Determine offset.
2546 int Offset = LineInfo.getLine() - Line;
2547 int Delta = Offset - MinLineDelta;
2550 Line = LineInfo.getLine();
2552 // If delta is small enough and in range...
2553 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2554 // ... then use fast opcode.
2555 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2557 // ... otherwise use long hand.
2558 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2559 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2560 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2563 // Copy the previous row (different address or source)
2564 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2568 EmitEndOfLineMatrix(j + 1);
2571 if (SecSrcLinesSize == 0)
2572 // Because we're emitting a debug_line section, we still need a line
2573 // table. The linker and friends expect it to exist. If there's nothing to
2574 // put into it, emit an empty table.
2575 EmitEndOfLineMatrix(1);
2577 EmitLabel("line_end", 0);
2582 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2584 void EmitCommonDebugFrame() {
2585 if (!TAI->doesDwarfRequireFrameSection())
2589 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2590 TargetFrameInfo::StackGrowsUp ?
2591 TD->getPointerSize() : -TD->getPointerSize();
2593 // Start the dwarf frame section.
2594 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2596 EmitLabel("debug_frame_common", 0);
2597 EmitDifference("debug_frame_common_end", 0,
2598 "debug_frame_common_begin", 0, true);
2599 Asm->EOL("Length of Common Information Entry");
2601 EmitLabel("debug_frame_common_begin", 0);
2602 Asm->EmitInt32((int)DW_CIE_ID);
2603 Asm->EOL("CIE Identifier Tag");
2604 Asm->EmitInt8(DW_CIE_VERSION);
2605 Asm->EOL("CIE Version");
2606 Asm->EmitString("");
2607 Asm->EOL("CIE Augmentation");
2608 Asm->EmitULEB128Bytes(1);
2609 Asm->EOL("CIE Code Alignment Factor");
2610 Asm->EmitSLEB128Bytes(stackGrowth);
2611 Asm->EOL("CIE Data Alignment Factor");
2612 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2613 Asm->EOL("CIE RA Column");
2615 std::vector<MachineMove> Moves;
2616 RI->getInitialFrameState(Moves);
2618 EmitFrameMoves(NULL, 0, Moves, false);
2620 Asm->EmitAlignment(2, 0, 0, false);
2621 EmitLabel("debug_frame_common_end", 0);
2626 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2628 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2629 if (!TAI->doesDwarfRequireFrameSection())
2632 // Start the dwarf frame section.
2633 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2635 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2636 "debug_frame_begin", DebugFrameInfo.Number, true);
2637 Asm->EOL("Length of Frame Information Entry");
2639 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2641 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2643 Asm->EOL("FDE CIE offset");
2645 EmitReference("func_begin", DebugFrameInfo.Number);
2646 Asm->EOL("FDE initial location");
2647 EmitDifference("func_end", DebugFrameInfo.Number,
2648 "func_begin", DebugFrameInfo.Number);
2649 Asm->EOL("FDE address range");
2651 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2654 Asm->EmitAlignment(2, 0, 0, false);
2655 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2660 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2661 EmitDifference("pubnames_end", Unit->getID(),
2662 "pubnames_begin", Unit->getID(), true);
2663 Asm->EOL("Length of Public Names Info");
2665 EmitLabel("pubnames_begin", Unit->getID());
2667 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2669 EmitSectionOffset("info_begin", "section_info",
2670 Unit->getID(), 0, true, false);
2671 Asm->EOL("Offset of Compilation Unit Info");
2673 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2675 Asm->EOL("Compilation Unit Length");
2677 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2678 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2679 GE = Globals.end(); GI != GE; ++GI) {
2680 const std::string &Name = GI->first;
2681 DIE * Entity = GI->second;
2683 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2684 Asm->EmitString(Name); Asm->EOL("External Name");
2687 Asm->EmitInt32(0); Asm->EOL("End Mark");
2688 EmitLabel("pubnames_end", Unit->getID());
2693 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2695 void EmitDebugPubNames() {
2696 // Start the dwarf pubnames section.
2697 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2700 EmitDebugPubNamesPerCU(MainCU);
2704 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2705 EmitDebugPubNamesPerCU(CompileUnits[i]);
2708 /// EmitDebugStr - Emit visible names into a debug str section.
2710 void EmitDebugStr() {
2711 // Check to see if it is worth the effort.
2712 if (!StringPool.empty()) {
2713 // Start the dwarf str section.
2714 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2716 // For each of strings in the string pool.
2717 for (unsigned StringID = 1, N = StringPool.size();
2718 StringID <= N; ++StringID) {
2719 // Emit a label for reference from debug information entries.
2720 EmitLabel("string", StringID);
2721 // Emit the string itself.
2722 const std::string &String = StringPool[StringID];
2723 Asm->EmitString(String); Asm->EOL();
2730 /// EmitDebugLoc - Emit visible names into a debug loc section.
2732 void EmitDebugLoc() {
2733 // Start the dwarf loc section.
2734 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2739 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2741 void EmitDebugARanges() {
2742 // Start the dwarf aranges section.
2743 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2747 CompileUnit *Unit = GetBaseCompileUnit();
2749 // Don't include size of length
2750 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2752 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2754 EmitReference("info_begin", Unit->getID());
2755 Asm->EOL("Offset of Compilation Unit Info");
2757 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2759 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2761 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2762 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2765 EmitReference("text_begin", 0); Asm->EOL("Address");
2766 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2768 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2769 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2775 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2777 void EmitDebugRanges() {
2778 // Start the dwarf ranges section.
2779 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2784 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2786 void EmitDebugMacInfo() {
2787 if (TAI->doesSupportMacInfoSection()) {
2788 // Start the dwarf macinfo section.
2789 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2795 void ConstructCompileUnit(GlobalVariable *GV) {
2796 DICompileUnit DIUnit(GV);
2797 std::string Dir, FN, Prod;
2798 unsigned ID = getOrCreateSourceID(DIUnit.getDirectory(Dir),
2799 DIUnit.getFilename(FN));
2801 DIE *Die = new DIE(DW_TAG_compile_unit);
2802 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2803 DWLabel("section_line", 0), DWLabel("section_line", 0),
2805 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2806 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2807 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2809 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2810 if (DIUnit.isOptimized())
2811 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2813 DIUnit.getFlags(Flags);
2815 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2816 unsigned RVer = DIUnit.getRunTimeVersion();
2818 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2820 CompileUnit *Unit = new CompileUnit(ID, Die);
2821 if (DIUnit.isMain()) {
2822 assert(!MainCU && "Multiple main compile units are found!");
2825 CompileUnitMap[DIUnit.getGV()] = Unit;
2826 CompileUnits.push_back(Unit);
2829 /// ConstructCompileUnits - Create a compile unit DIEs.
2830 void ConstructCompileUnits() {
2831 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2834 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2835 "Malformed compile unit descriptor anchor type");
2836 Constant *RootC = cast<Constant>(*Root->use_begin());
2837 assert(RootC->hasNUsesOrMore(1) &&
2838 "Malformed compile unit descriptor anchor type");
2839 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2841 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2842 UUI != UUE; ++UUI) {
2843 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2844 ConstructCompileUnit(GV);
2848 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2849 DIGlobalVariable DI_GV(GV);
2850 CompileUnit *DW_Unit = MainCU;
2852 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2854 // Check for pre-existence.
2855 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2859 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2862 DIEBlock *Block = new DIEBlock();
2863 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2864 AddObjectLabel(Block, 0, DW_FORM_udata,
2865 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2866 AddBlock(VariableDie, DW_AT_location, 0, Block);
2870 // Add to context owner.
2871 DW_Unit->getDie()->AddChild(VariableDie);
2872 // Expose as global. FIXME - need to check external flag.
2874 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2878 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2879 /// visible global variables. Return true if at least one global DIE is
2881 bool ConstructGlobalVariableDIEs() {
2882 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2886 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2887 "Malformed global variable descriptor anchor type");
2888 Constant *RootC = cast<Constant>(*Root->use_begin());
2889 assert(RootC->hasNUsesOrMore(1) &&
2890 "Malformed global variable descriptor anchor type");
2892 bool Result = false;
2893 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2895 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2896 UUI != UUE; ++UUI) {
2897 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2898 Result |= ConstructGlobalVariableDIE(GV);
2903 bool ConstructSubprogram(GlobalVariable *GV) {
2904 DISubprogram SP(GV);
2905 CompileUnit *Unit = MainCU;
2907 Unit = FindCompileUnit(SP.getCompileUnit());
2909 // Check for pre-existence.
2910 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2914 if (!SP.isDefinition())
2915 // This is a method declaration which will be handled while
2916 // constructing class type.
2919 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2922 Slot = SubprogramDie;
2923 // Add to context owner.
2924 Unit->getDie()->AddChild(SubprogramDie);
2925 // Expose as global.
2927 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2931 /// ConstructSubprograms - Create DIEs for each of the externally visible
2932 /// subprograms. Return true if at least one subprogram DIE is created.
2933 bool ConstructSubprograms() {
2934 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2938 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2939 "Malformed subprogram descriptor anchor type");
2940 Constant *RootC = cast<Constant>(*Root->use_begin());
2941 assert(RootC->hasNUsesOrMore(1) &&
2942 "Malformed subprogram descriptor anchor type");
2944 bool Result = false;
2945 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2947 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2948 UUI != UUE; ++UUI) {
2949 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2950 Result |= ConstructSubprogram(GV);
2956 //===--------------------------------------------------------------------===//
2957 // Main entry points.
2959 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2960 : Dwarf(OS, A, T, "dbg"), MainCU(0),
2961 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
2962 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
2963 SectionSourceLines(), didInitial(false), shouldEmit(false),
2964 RootDbgScope(0), DebugTimer(0) {
2965 if (TimePassesIsEnabled)
2966 DebugTimer = new Timer("Dwarf Debug Writer",
2967 *getDwarfTimerGroup());
2969 virtual ~DwarfDebug() {
2970 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2976 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2977 /// This is inovked by the target AsmPrinter.
2978 void SetDebugInfo(MachineModuleInfo *mmi) {
2979 if (TimePassesIsEnabled)
2980 DebugTimer->startTimer();
2982 // Create all the compile unit DIEs.
2983 ConstructCompileUnits();
2985 if (CompileUnits.empty()) {
2986 if (TimePassesIsEnabled)
2987 DebugTimer->startTimer();
2992 // Create DIEs for each of the externally visible global variables.
2993 bool globalDIEs = ConstructGlobalVariableDIEs();
2995 // Create DIEs for each of the externally visible subprograms.
2996 bool subprogramDIEs = ConstructSubprograms();
2998 // If there is not any debug info available for any global variables
2999 // and any subprograms then there is not any debug info to emit.
3000 if (!globalDIEs && !subprogramDIEs) {
3001 if (TimePassesIsEnabled)
3002 DebugTimer->startTimer();
3009 MMI->setDebugInfoAvailability(true);
3011 // Prime section data.
3012 SectionMap.insert(TAI->getTextSection());
3014 // Print out .file directives to specify files for .loc directives. These
3015 // are printed out early so that they precede any .loc directives.
3016 if (TAI->hasDotLocAndDotFile()) {
3017 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3018 // Remember source id starts at 1.
3019 std::pair<unsigned, unsigned> Id = getSourceDirsectoryAndFileIds(i);
3020 sys::Path FullPath(getSourceDirectoryName(Id.first));
3022 FullPath.appendComponent(getSourceFileName(Id.second));
3023 assert(AppendOk && "Could not append filename to directory!");
3025 Asm->EmitFile(i, FullPath.toString());
3030 // Emit initial sections
3033 if (TimePassesIsEnabled)
3034 DebugTimer->stopTimer();
3037 /// BeginModule - Emit all Dwarf sections that should come prior to the
3039 void BeginModule(Module *M) {
3043 /// EndModule - Emit all Dwarf sections that should come after the content.
3046 if (!ShouldEmitDwarfDebug())
3049 if (TimePassesIsEnabled)
3050 DebugTimer->startTimer();
3052 // Standard sections final addresses.
3053 Asm->SwitchToSection(TAI->getTextSection());
3054 EmitLabel("text_end", 0);
3055 Asm->SwitchToSection(TAI->getDataSection());
3056 EmitLabel("data_end", 0);
3058 // End text sections.
3059 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3060 Asm->SwitchToSection(SectionMap[i]);
3061 EmitLabel("section_end", i);
3064 // Emit common frame information.
3065 EmitCommonDebugFrame();
3067 // Emit function debug frame information
3068 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3069 E = DebugFrames.end(); I != E; ++I)
3070 EmitFunctionDebugFrame(*I);
3072 // Compute DIE offsets and sizes.
3075 // Emit all the DIEs into a debug info section
3078 // Corresponding abbreviations into a abbrev section.
3079 EmitAbbreviations();
3081 // Emit source line correspondence into a debug line section.
3084 // Emit info into a debug pubnames section.
3085 EmitDebugPubNames();
3087 // Emit info into a debug str section.
3090 // Emit info into a debug loc section.
3093 // Emit info into a debug aranges section.
3096 // Emit info into a debug ranges section.
3099 // Emit info into a debug macinfo section.
3102 if (TimePassesIsEnabled)
3103 DebugTimer->stopTimer();
3106 /// BeginFunction - Gather pre-function debug information. Assumes being
3107 /// emitted immediately after the function entry point.
3108 void BeginFunction(MachineFunction *MF) {
3109 if (!ShouldEmitDwarfDebug()) return;
3111 if (TimePassesIsEnabled)
3112 DebugTimer->startTimer();
3116 // Begin accumulating function debug information.
3117 MMI->BeginFunction(MF);
3119 // Assumes in correct section after the entry point.
3120 EmitLabel("func_begin", ++SubprogramCount);
3122 // Emit label for the implicitly defined dbg.stoppoint at the start of
3124 if (!Lines.empty()) {
3125 const SrcLineInfo &LineInfo = Lines[0];
3126 Asm->printLabel(LineInfo.getLabelID());
3129 if (TimePassesIsEnabled)
3130 DebugTimer->stopTimer();
3133 /// EndFunction - Gather and emit post-function debug information.
3135 void EndFunction(MachineFunction *MF) {
3136 if (!ShouldEmitDwarfDebug()) return;
3138 if (TimePassesIsEnabled)
3139 DebugTimer->startTimer();
3141 // Define end label for subprogram.
3142 EmitLabel("func_end", SubprogramCount);
3144 // Get function line info.
3145 if (!Lines.empty()) {
3146 // Get section line info.
3147 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3148 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3149 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3150 // Append the function info to section info.
3151 SectionLineInfos.insert(SectionLineInfos.end(),
3152 Lines.begin(), Lines.end());
3155 // Construct scopes for subprogram.
3157 ConstructRootDbgScope(RootDbgScope);
3159 // FIXME: This is wrong. We are essentially getting past a problem with
3160 // debug information not being able to handle unreachable blocks that have
3161 // debug information in them. In particular, those unreachable blocks that
3162 // have "region end" info in them. That situation results in the "root
3163 // scope" not being created. If that's the case, then emit a "default"
3164 // scope, i.e., one that encompasses the whole function. This isn't
3165 // desirable. And a better way of handling this (and all of the debugging
3166 // information) needs to be explored.
3167 ConstructDefaultDbgScope(MF);
3169 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3170 MMI->getFrameMoves()));
3174 delete RootDbgScope;
3175 DbgScopeMap.clear();
3176 RootDbgScope = NULL;
3181 if (TimePassesIsEnabled)
3182 DebugTimer->stopTimer();
3185 /// ValidDebugInfo - Return true if V represents valid debug info value.
3186 bool ValidDebugInfo(Value *V) {
3193 GlobalVariable *GV = getGlobalVariable(V);
3197 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3200 if (TimePassesIsEnabled)
3201 DebugTimer->startTimer();
3203 DIDescriptor DI(GV);
3205 // Check current version. Allow Version6 for now.
3206 unsigned Version = DI.getVersion();
3207 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) {
3208 if (TimePassesIsEnabled)
3209 DebugTimer->stopTimer();
3214 unsigned Tag = DI.getTag();
3216 case DW_TAG_variable:
3217 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3219 case DW_TAG_compile_unit:
3220 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3222 case DW_TAG_subprogram:
3223 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3229 if (TimePassesIsEnabled)
3230 DebugTimer->stopTimer();
3235 /// RecordSourceLine - Records location information and associates it with a
3236 /// label. Returns a unique label ID used to generate a label and provide
3237 /// correspondence to the source line list.
3238 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3239 if (TimePassesIsEnabled)
3240 DebugTimer->startTimer();
3242 CompileUnit *Unit = CompileUnitMap[V];
3243 assert(Unit && "Unable to find CompileUnit");
3244 unsigned ID = MMI->NextLabelID();
3245 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3247 if (TimePassesIsEnabled)
3248 DebugTimer->stopTimer();
3253 /// RecordSourceLine - Records location information and associates it with a
3254 /// label. Returns a unique label ID used to generate a label and provide
3255 /// correspondence to the source line list.
3256 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3257 if (TimePassesIsEnabled)
3258 DebugTimer->startTimer();
3260 unsigned ID = MMI->NextLabelID();
3261 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3263 if (TimePassesIsEnabled)
3264 DebugTimer->stopTimer();
3269 unsigned getRecordSourceLineCount() {
3270 return Lines.size();
3273 /// getNumSourceDirectories - Return the number of source directories in the
3275 unsigned getNumSourceDirectories() const {
3276 return DirectoryNames.size();
3279 /// getSourceDirectoryName - Return the name of the directory corresponding
3281 const std::string &getSourceDirectoryName(unsigned Id) const {
3282 return DirectoryNames[Id - 1];
3285 /// getNumSourceFiles - Return the number of source files in the debug info.
3287 unsigned getNumSourceFiles() const {
3288 return SourceFileNames.size();
3291 /// getSourceFileName - Return the name of the source file corresponding
3293 const std::string &getSourceFileName(unsigned Id) const {
3294 return SourceFileNames[Id - 1];
3297 /// getNumSourceIds - Return the number of unique source ids.
3299 unsigned getNumSourceIds() const {
3300 return SourceIds.size();
3303 /// getSourceDirsectoryAndFileIds - Return the directory and file ids that
3304 /// maps to the source id. Source id starts at 1.
3305 std::pair<unsigned, unsigned>
3306 getSourceDirsectoryAndFileIds(unsigned SId) const {
3307 return SourceIds[SId-1];
3310 /// getOrCreateSourceID - Look up the source id with the given directory and
3311 /// source file names. If none currently exists, create a new id and insert it
3312 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
3314 unsigned getOrCreateSourceID(const std::string &DirName,
3315 const std::string &FileName) {
3316 if (TimePassesIsEnabled)
3317 DebugTimer->startTimer();
3320 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
3321 if (DI != DirectoryIdMap.end()) {
3322 DId = DI->getValue();
3324 DId = DirectoryNames.size() + 1;
3325 DirectoryIdMap[DirName] = DId;
3326 DirectoryNames.push_back(DirName);
3330 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
3331 if (FI != SourceFileIdMap.end()) {
3332 FId = FI->getValue();
3334 FId = SourceFileNames.size() + 1;
3335 SourceFileIdMap[FileName] = FId;
3336 SourceFileNames.push_back(FileName);
3339 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
3340 SourceIdMap.find(std::make_pair(DId, FId));
3342 if (SI != SourceIdMap.end()) {
3343 if (TimePassesIsEnabled)
3344 DebugTimer->stopTimer();
3349 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
3350 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
3351 SourceIds.push_back(std::make_pair(DId, FId));
3353 if (TimePassesIsEnabled)
3354 DebugTimer->stopTimer();
3359 /// RecordRegionStart - Indicate the start of a region.
3361 unsigned RecordRegionStart(GlobalVariable *V) {
3362 if (TimePassesIsEnabled)
3363 DebugTimer->startTimer();
3365 DbgScope *Scope = getOrCreateScope(V);
3366 unsigned ID = MMI->NextLabelID();
3367 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3369 if (TimePassesIsEnabled)
3370 DebugTimer->stopTimer();
3375 /// RecordRegionEnd - Indicate the end of a region.
3377 unsigned RecordRegionEnd(GlobalVariable *V) {
3378 if (TimePassesIsEnabled)
3379 DebugTimer->startTimer();
3381 DbgScope *Scope = getOrCreateScope(V);
3382 unsigned ID = MMI->NextLabelID();
3383 Scope->setEndLabelID(ID);
3385 if (TimePassesIsEnabled)
3386 DebugTimer->stopTimer();
3391 /// RecordVariable - Indicate the declaration of a local variable.
3393 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3394 if (TimePassesIsEnabled)
3395 DebugTimer->startTimer();
3397 DIDescriptor Desc(GV);
3398 DbgScope *Scope = NULL;
3400 if (Desc.getTag() == DW_TAG_variable) {
3401 // GV is a global variable.
3402 DIGlobalVariable DG(GV);
3403 Scope = getOrCreateScope(DG.getContext().getGV());
3405 // or GV is a local variable.
3407 Scope = getOrCreateScope(DV.getContext().getGV());
3410 assert(Scope && "Unable to find variable' scope");
3411 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3412 Scope->AddVariable(DV);
3414 if (TimePassesIsEnabled)
3415 DebugTimer->stopTimer();
3419 //===----------------------------------------------------------------------===//
3420 /// DwarfException - Emits Dwarf exception handling directives.
3422 class DwarfException : public Dwarf {
3423 struct FunctionEHFrameInfo {
3426 unsigned PersonalityIndex;
3428 bool hasLandingPads;
3429 std::vector<MachineMove> Moves;
3430 const Function * function;
3432 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3434 const std::vector<MachineMove> &M,
3436 FnName(FN), Number(Num), PersonalityIndex(P),
3437 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3440 std::vector<FunctionEHFrameInfo> EHFrames;
3442 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3444 bool shouldEmitTable;
3446 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3447 /// should be emitted.
3448 bool shouldEmitMoves;
3450 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3451 /// should be emitted.
3452 bool shouldEmitTableModule;
3454 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3455 /// should be emitted.
3456 bool shouldEmitMovesModule;
3458 /// ExceptionTimer - Timer for the Dwarf exception writer.
3459 Timer *ExceptionTimer;
3461 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3463 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3464 // Size and sign of stack growth.
3466 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3467 TargetFrameInfo::StackGrowsUp ?
3468 TD->getPointerSize() : -TD->getPointerSize();
3470 // Begin eh frame section.
3471 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3473 if (!TAI->doesRequireNonLocalEHFrameLabel())
3474 O << TAI->getEHGlobalPrefix();
3475 O << "EH_frame" << Index << ":\n";
3476 EmitLabel("section_eh_frame", Index);
3478 // Define base labels.
3479 EmitLabel("eh_frame_common", Index);
3481 // Define the eh frame length.
3482 EmitDifference("eh_frame_common_end", Index,
3483 "eh_frame_common_begin", Index, true);
3484 Asm->EOL("Length of Common Information Entry");
3487 EmitLabel("eh_frame_common_begin", Index);
3488 Asm->EmitInt32((int)0);
3489 Asm->EOL("CIE Identifier Tag");
3490 Asm->EmitInt8(DW_CIE_VERSION);
3491 Asm->EOL("CIE Version");
3493 // The personality presence indicates that language specific information
3494 // will show up in the eh frame.
3495 Asm->EmitString(Personality ? "zPLR" : "zR");
3496 Asm->EOL("CIE Augmentation");
3498 // Round out reader.
3499 Asm->EmitULEB128Bytes(1);
3500 Asm->EOL("CIE Code Alignment Factor");
3501 Asm->EmitSLEB128Bytes(stackGrowth);
3502 Asm->EOL("CIE Data Alignment Factor");
3503 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3504 Asm->EOL("CIE Return Address Column");
3506 // If there is a personality, we need to indicate the functions location.
3508 Asm->EmitULEB128Bytes(7);
3509 Asm->EOL("Augmentation Size");
3511 if (TAI->getNeedsIndirectEncoding()) {
3512 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3513 Asm->EOL("Personality (pcrel sdata4 indirect)");
3515 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3516 Asm->EOL("Personality (pcrel sdata4)");
3519 PrintRelDirective(true);
3520 O << TAI->getPersonalityPrefix();
3521 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3522 O << TAI->getPersonalitySuffix();
3523 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3524 O << "-" << TAI->getPCSymbol();
3525 Asm->EOL("Personality");
3527 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3528 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3530 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3531 Asm->EOL("FDE Encoding (pcrel sdata4)");
3533 Asm->EmitULEB128Bytes(1);
3534 Asm->EOL("Augmentation Size");
3536 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3537 Asm->EOL("FDE Encoding (pcrel sdata4)");
3540 // Indicate locations of general callee saved registers in frame.
3541 std::vector<MachineMove> Moves;
3542 RI->getInitialFrameState(Moves);
3543 EmitFrameMoves(NULL, 0, Moves, true);
3545 // On Darwin the linker honors the alignment of eh_frame, which means it
3546 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3547 // you get holes which confuse readers of eh_frame.
3548 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3550 EmitLabel("eh_frame_common_end", Index);
3555 /// EmitEHFrame - Emit function exception frame information.
3557 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3558 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3560 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3562 // Externally visible entry into the functions eh frame info.
3563 // If the corresponding function is static, this should not be
3564 // externally visible.
3565 if (linkage != Function::InternalLinkage &&
3566 linkage != Function::PrivateLinkage) {
3567 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3568 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3571 // If corresponding function is weak definition, this should be too.
3572 if ((linkage == Function::WeakAnyLinkage ||
3573 linkage == Function::WeakODRLinkage ||
3574 linkage == Function::LinkOnceAnyLinkage ||
3575 linkage == Function::LinkOnceODRLinkage) &&
3576 TAI->getWeakDefDirective())
3577 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3579 // If there are no calls then you can't unwind. This may mean we can
3580 // omit the EH Frame, but some environments do not handle weak absolute
3582 // If UnwindTablesMandatory is set we cannot do this optimization; the
3583 // unwind info is to be available for non-EH uses.
3584 if (!EHFrameInfo.hasCalls &&
3585 !UnwindTablesMandatory &&
3586 ((linkage != Function::WeakAnyLinkage &&
3587 linkage != Function::WeakODRLinkage &&
3588 linkage != Function::LinkOnceAnyLinkage &&
3589 linkage != Function::LinkOnceODRLinkage) ||
3590 !TAI->getWeakDefDirective() ||
3591 TAI->getSupportsWeakOmittedEHFrame()))
3593 O << EHFrameInfo.FnName << " = 0\n";
3594 // This name has no connection to the function, so it might get
3595 // dead-stripped when the function is not, erroneously. Prohibit
3596 // dead-stripping unconditionally.
3597 if (const char *UsedDirective = TAI->getUsedDirective())
3598 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3600 O << EHFrameInfo.FnName << ":\n";
3603 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3604 "eh_frame_begin", EHFrameInfo.Number, true);
3605 Asm->EOL("Length of Frame Information Entry");
3607 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3609 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3610 PrintRelDirective(true, true);
3611 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3613 if (!TAI->isAbsoluteEHSectionOffsets())
3614 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3616 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3617 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3621 Asm->EOL("FDE CIE offset");
3623 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3624 Asm->EOL("FDE initial location");
3625 EmitDifference("eh_func_end", EHFrameInfo.Number,
3626 "eh_func_begin", EHFrameInfo.Number, true);
3627 Asm->EOL("FDE address range");
3629 // If there is a personality and landing pads then point to the language
3630 // specific data area in the exception table.
3631 if (EHFrameInfo.PersonalityIndex) {
3632 Asm->EmitULEB128Bytes(4);
3633 Asm->EOL("Augmentation size");
3635 if (EHFrameInfo.hasLandingPads)
3636 EmitReference("exception", EHFrameInfo.Number, true, true);
3638 Asm->EmitInt32((int)0);
3639 Asm->EOL("Language Specific Data Area");
3641 Asm->EmitULEB128Bytes(0);
3642 Asm->EOL("Augmentation size");
3645 // Indicate locations of function specific callee saved registers in
3647 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3650 // On Darwin the linker honors the alignment of eh_frame, which means it
3651 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3652 // you get holes which confuse readers of eh_frame.
3653 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3655 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3657 // If the function is marked used, this table should be also. We cannot
3658 // make the mark unconditional in this case, since retaining the table
3659 // also retains the function in this case, and there is code around
3660 // that depends on unused functions (calling undefined externals) being
3661 // dead-stripped to link correctly. Yes, there really is.
3662 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3663 if (const char *UsedDirective = TAI->getUsedDirective())
3664 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3668 /// EmitExceptionTable - Emit landing pads and actions.
3670 /// The general organization of the table is complex, but the basic concepts
3671 /// are easy. First there is a header which describes the location and
3672 /// organization of the three components that follow.
3673 /// 1. The landing pad site information describes the range of code covered
3674 /// by the try. In our case it's an accumulation of the ranges covered
3675 /// by the invokes in the try. There is also a reference to the landing
3676 /// pad that handles the exception once processed. Finally an index into
3677 /// the actions table.
3678 /// 2. The action table, in our case, is composed of pairs of type ids
3679 /// and next action offset. Starting with the action index from the
3680 /// landing pad site, each type Id is checked for a match to the current
3681 /// exception. If it matches then the exception and type id are passed
3682 /// on to the landing pad. Otherwise the next action is looked up. This
3683 /// chain is terminated with a next action of zero. If no type id is
3684 /// found the the frame is unwound and handling continues.
3685 /// 3. Type id table contains references to all the C++ typeinfo for all
3686 /// catches in the function. This tables is reversed indexed base 1.
3688 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3689 static unsigned SharedTypeIds(const LandingPadInfo *L,
3690 const LandingPadInfo *R) {
3691 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3692 unsigned LSize = LIds.size(), RSize = RIds.size();
3693 unsigned MinSize = LSize < RSize ? LSize : RSize;
3696 for (; Count != MinSize; ++Count)
3697 if (LIds[Count] != RIds[Count])
3703 /// PadLT - Order landing pads lexicographically by type id.
3704 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3705 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3706 unsigned LSize = LIds.size(), RSize = RIds.size();
3707 unsigned MinSize = LSize < RSize ? LSize : RSize;
3709 for (unsigned i = 0; i != MinSize; ++i)
3710 if (LIds[i] != RIds[i])
3711 return LIds[i] < RIds[i];
3713 return LSize < RSize;
3717 static inline unsigned getEmptyKey() { return -1U; }
3718 static inline unsigned getTombstoneKey() { return -2U; }
3719 static unsigned getHashValue(const unsigned &Key) { return Key; }
3720 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3721 static bool isPod() { return true; }
3724 /// ActionEntry - Structure describing an entry in the actions table.
3725 struct ActionEntry {
3726 int ValueForTypeID; // The value to write - may not be equal to the type id.
3728 struct ActionEntry *Previous;
3731 /// PadRange - Structure holding a try-range and the associated landing pad.
3733 // The index of the landing pad.
3735 // The index of the begin and end labels in the landing pad's label lists.
3736 unsigned RangeIndex;
3739 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3741 /// CallSiteEntry - Structure describing an entry in the call-site table.
3742 struct CallSiteEntry {
3743 // The 'try-range' is BeginLabel .. EndLabel.
3744 unsigned BeginLabel; // zero indicates the start of the function.
3745 unsigned EndLabel; // zero indicates the end of the function.
3746 // The landing pad starts at PadLabel.
3747 unsigned PadLabel; // zero indicates that there is no landing pad.
3751 void EmitExceptionTable() {
3752 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3753 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3754 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3755 if (PadInfos.empty()) return;
3757 // Sort the landing pads in order of their type ids. This is used to fold
3758 // duplicate actions.
3759 SmallVector<const LandingPadInfo *, 64> LandingPads;
3760 LandingPads.reserve(PadInfos.size());
3761 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3762 LandingPads.push_back(&PadInfos[i]);
3763 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3765 // Negative type ids index into FilterIds, positive type ids index into
3766 // TypeInfos. The value written for a positive type id is just the type
3767 // id itself. For a negative type id, however, the value written is the
3768 // (negative) byte offset of the corresponding FilterIds entry. The byte
3769 // offset is usually equal to the type id, because the FilterIds entries
3770 // are written using a variable width encoding which outputs one byte per
3771 // entry as long as the value written is not too large, but can differ.
3772 // This kind of complication does not occur for positive type ids because
3773 // type infos are output using a fixed width encoding.
3774 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3775 SmallVector<int, 16> FilterOffsets;
3776 FilterOffsets.reserve(FilterIds.size());
3778 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3779 E = FilterIds.end(); I != E; ++I) {
3780 FilterOffsets.push_back(Offset);
3781 Offset -= TargetAsmInfo::getULEB128Size(*I);
3784 // Compute the actions table and gather the first action index for each
3785 // landing pad site.
3786 SmallVector<ActionEntry, 32> Actions;
3787 SmallVector<unsigned, 64> FirstActions;
3788 FirstActions.reserve(LandingPads.size());
3790 int FirstAction = 0;
3791 unsigned SizeActions = 0;
3792 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3793 const LandingPadInfo *LP = LandingPads[i];
3794 const std::vector<int> &TypeIds = LP->TypeIds;
3795 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3796 unsigned SizeSiteActions = 0;
3798 if (NumShared < TypeIds.size()) {
3799 unsigned SizeAction = 0;
3800 ActionEntry *PrevAction = 0;
3803 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3804 assert(Actions.size());
3805 PrevAction = &Actions.back();
3806 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3807 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3808 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3810 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3811 SizeAction += -PrevAction->NextAction;
3812 PrevAction = PrevAction->Previous;
3816 // Compute the actions.
3817 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3818 int TypeID = TypeIds[I];
3819 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3820 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3821 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3823 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3824 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3825 SizeSiteActions += SizeAction;
3827 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3828 Actions.push_back(Action);
3830 PrevAction = &Actions.back();
3833 // Record the first action of the landing pad site.
3834 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3835 } // else identical - re-use previous FirstAction
3837 FirstActions.push_back(FirstAction);
3839 // Compute this sites contribution to size.
3840 SizeActions += SizeSiteActions;
3843 // Compute the call-site table. The entry for an invoke has a try-range
3844 // containing the call, a non-zero landing pad and an appropriate action.
3845 // The entry for an ordinary call has a try-range containing the call and
3846 // zero for the landing pad and the action. Calls marked 'nounwind' have
3847 // no entry and must not be contained in the try-range of any entry - they
3848 // form gaps in the table. Entries must be ordered by try-range address.
3849 SmallVector<CallSiteEntry, 64> CallSites;
3851 RangeMapType PadMap;
3852 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3853 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3854 // try-ranges for them need be deduced.
3855 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3856 const LandingPadInfo *LandingPad = LandingPads[i];
3857 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3858 unsigned BeginLabel = LandingPad->BeginLabels[j];
3859 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3860 PadRange P = { i, j };
3861 PadMap[BeginLabel] = P;
3865 // The end label of the previous invoke or nounwind try-range.
3866 unsigned LastLabel = 0;
3868 // Whether there is a potentially throwing instruction (currently this means
3869 // an ordinary call) between the end of the previous try-range and now.
3870 bool SawPotentiallyThrowing = false;
3872 // Whether the last callsite entry was for an invoke.
3873 bool PreviousIsInvoke = false;
3875 // Visit all instructions in order of address.
3876 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3878 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3880 if (!MI->isLabel()) {
3881 SawPotentiallyThrowing |= MI->getDesc().isCall();
3885 unsigned BeginLabel = MI->getOperand(0).getImm();
3886 assert(BeginLabel && "Invalid label!");
3888 // End of the previous try-range?
3889 if (BeginLabel == LastLabel)
3890 SawPotentiallyThrowing = false;
3892 // Beginning of a new try-range?
3893 RangeMapType::iterator L = PadMap.find(BeginLabel);
3894 if (L == PadMap.end())
3895 // Nope, it was just some random label.
3898 PadRange P = L->second;
3899 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3901 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3902 "Inconsistent landing pad map!");
3904 // If some instruction between the previous try-range and this one may
3905 // throw, create a call-site entry with no landing pad for the region
3906 // between the try-ranges.
3907 if (SawPotentiallyThrowing) {
3908 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3909 CallSites.push_back(Site);
3910 PreviousIsInvoke = false;
3913 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3914 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3916 if (LandingPad->LandingPadLabel) {
3917 // This try-range is for an invoke.
3918 CallSiteEntry Site = {BeginLabel, LastLabel,
3919 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3921 // Try to merge with the previous call-site.
3922 if (PreviousIsInvoke) {
3923 CallSiteEntry &Prev = CallSites.back();
3924 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3925 // Extend the range of the previous entry.
3926 Prev.EndLabel = Site.EndLabel;
3931 // Otherwise, create a new call-site.
3932 CallSites.push_back(Site);
3933 PreviousIsInvoke = true;
3936 PreviousIsInvoke = false;
3940 // If some instruction between the previous try-range and the end of the
3941 // function may throw, create a call-site entry with no landing pad for the
3942 // region following the try-range.
3943 if (SawPotentiallyThrowing) {
3944 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3945 CallSites.push_back(Site);
3951 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3952 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3953 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3954 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3957 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3958 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3961 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3962 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3964 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3965 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3966 SizeSites + SizeActions + SizeTypes;
3968 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3969 sizeof(int8_t) + // TType format
3970 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3973 unsigned SizeAlign = (4 - TotalSize) & 3;
3975 // Begin the exception table.
3976 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3977 Asm->EmitAlignment(2, 0, 0, false);
3978 O << "GCC_except_table" << SubprogramCount << ":\n";
3979 for (unsigned i = 0; i != SizeAlign; ++i) {
3981 Asm->EOL("Padding");
3983 EmitLabel("exception", SubprogramCount);
3986 Asm->EmitInt8(DW_EH_PE_omit);
3987 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3988 Asm->EmitInt8(DW_EH_PE_absptr);
3989 Asm->EOL("TType format (DW_EH_PE_absptr)");
3990 Asm->EmitULEB128Bytes(TypeOffset);
3991 Asm->EOL("TType base offset");
3992 Asm->EmitInt8(DW_EH_PE_udata4);
3993 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3994 Asm->EmitULEB128Bytes(SizeSites);
3995 Asm->EOL("Call-site table length");
3997 // Emit the landing pad site information.
3998 for (unsigned i = 0; i < CallSites.size(); ++i) {
3999 CallSiteEntry &S = CallSites[i];
4000 const char *BeginTag;
4001 unsigned BeginNumber;
4003 if (!S.BeginLabel) {
4004 BeginTag = "eh_func_begin";
4005 BeginNumber = SubprogramCount;
4008 BeginNumber = S.BeginLabel;
4011 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4013 Asm->EOL("Region start");
4016 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4019 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4021 Asm->EOL("Region length");
4026 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4028 Asm->EOL("Landing pad");
4030 Asm->EmitULEB128Bytes(S.Action);
4034 // Emit the actions.
4035 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4036 ActionEntry &Action = Actions[I];
4038 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4039 Asm->EOL("TypeInfo index");
4040 Asm->EmitSLEB128Bytes(Action.NextAction);
4041 Asm->EOL("Next action");
4044 // Emit the type ids.
4045 for (unsigned M = TypeInfos.size(); M; --M) {
4046 GlobalVariable *GV = TypeInfos[M - 1];
4048 PrintRelDirective();
4051 O << Asm->getGlobalLinkName(GV);
4055 Asm->EOL("TypeInfo");
4058 // Emit the filter typeids.
4059 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4060 unsigned TypeID = FilterIds[j];
4061 Asm->EmitULEB128Bytes(TypeID);
4062 Asm->EOL("Filter TypeInfo index");
4065 Asm->EmitAlignment(2, 0, 0, false);
4069 //===--------------------------------------------------------------------===//
4070 // Main entry points.
4072 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4073 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4074 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4076 if (TimePassesIsEnabled)
4077 ExceptionTimer = new Timer("Dwarf Exception Writer",
4078 *getDwarfTimerGroup());
4081 virtual ~DwarfException() {
4082 delete ExceptionTimer;
4085 /// SetModuleInfo - Set machine module information when it's known that pass
4086 /// manager has created it. Set by the target AsmPrinter.
4087 void SetModuleInfo(MachineModuleInfo *mmi) {
4091 /// BeginModule - Emit all exception information that should come prior to the
4093 void BeginModule(Module *M) {
4097 /// EndModule - Emit all exception information that should come after the
4100 if (TimePassesIsEnabled)
4101 ExceptionTimer->startTimer();
4103 if (shouldEmitMovesModule || shouldEmitTableModule) {
4104 const std::vector<Function *> Personalities = MMI->getPersonalities();
4105 for (unsigned i = 0; i < Personalities.size(); ++i)
4106 EmitCommonEHFrame(Personalities[i], i);
4108 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4109 E = EHFrames.end(); I != E; ++I)
4113 if (TimePassesIsEnabled)
4114 ExceptionTimer->stopTimer();
4117 /// BeginFunction - Gather pre-function exception information. Assumes being
4118 /// emitted immediately after the function entry point.
4119 void BeginFunction(MachineFunction *MF) {
4120 if (TimePassesIsEnabled)
4121 ExceptionTimer->startTimer();
4124 shouldEmitTable = shouldEmitMoves = false;
4126 if (MMI && TAI->doesSupportExceptionHandling()) {
4127 // Map all labels and get rid of any dead landing pads.
4128 MMI->TidyLandingPads();
4130 // If any landing pads survive, we need an EH table.
4131 if (MMI->getLandingPads().size())
4132 shouldEmitTable = true;
4134 // See if we need frame move info.
4135 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4136 shouldEmitMoves = true;
4138 if (shouldEmitMoves || shouldEmitTable)
4139 // Assumes in correct section after the entry point.
4140 EmitLabel("eh_func_begin", ++SubprogramCount);
4143 shouldEmitTableModule |= shouldEmitTable;
4144 shouldEmitMovesModule |= shouldEmitMoves;
4146 if (TimePassesIsEnabled)
4147 ExceptionTimer->stopTimer();
4150 /// EndFunction - Gather and emit post-function exception information.
4152 void EndFunction() {
4153 if (TimePassesIsEnabled)
4154 ExceptionTimer->startTimer();
4156 if (shouldEmitMoves || shouldEmitTable) {
4157 EmitLabel("eh_func_end", SubprogramCount);
4158 EmitExceptionTable();
4160 // Save EH frame information
4162 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4164 MMI->getPersonalityIndex(),
4165 MF->getFrameInfo()->hasCalls(),
4166 !MMI->getLandingPads().empty(),
4167 MMI->getFrameMoves(),
4168 MF->getFunction()));
4171 if (TimePassesIsEnabled)
4172 ExceptionTimer->stopTimer();
4176 } // End of namespace llvm
4178 //===----------------------------------------------------------------------===//
4180 /// Emit - Print the abbreviation using the specified Dwarf writer.
4182 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4183 // Emit its Dwarf tag type.
4184 DD.getAsm()->EmitULEB128Bytes(Tag);
4185 DD.getAsm()->EOL(TagString(Tag));
4187 // Emit whether it has children DIEs.
4188 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4189 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4191 // For each attribute description.
4192 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4193 const DIEAbbrevData &AttrData = Data[i];
4195 // Emit attribute type.
4196 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4197 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4200 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4201 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4204 // Mark end of abbreviation.
4205 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4206 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4210 void DIEAbbrev::print(std::ostream &O) {
4211 O << "Abbreviation @"
4212 << std::hex << (intptr_t)this << std::dec
4216 << ChildrenString(ChildrenFlag)
4219 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4221 << AttributeString(Data[i].getAttribute())
4223 << FormEncodingString(Data[i].getForm())
4227 void DIEAbbrev::dump() { print(cerr); }
4230 //===----------------------------------------------------------------------===//
4233 void DIEValue::dump() {
4238 //===----------------------------------------------------------------------===//
4240 /// EmitValue - Emit integer of appropriate size.
4242 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4244 case DW_FORM_flag: // Fall thru
4245 case DW_FORM_ref1: // Fall thru
4246 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4247 case DW_FORM_ref2: // Fall thru
4248 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4249 case DW_FORM_ref4: // Fall thru
4250 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4251 case DW_FORM_ref8: // Fall thru
4252 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4253 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4254 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4255 default: assert(0 && "DIE Value form not supported yet"); break;
4259 /// SizeOf - Determine size of integer value in bytes.
4261 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4263 case DW_FORM_flag: // Fall thru
4264 case DW_FORM_ref1: // Fall thru
4265 case DW_FORM_data1: return sizeof(int8_t);
4266 case DW_FORM_ref2: // Fall thru
4267 case DW_FORM_data2: return sizeof(int16_t);
4268 case DW_FORM_ref4: // Fall thru
4269 case DW_FORM_data4: return sizeof(int32_t);
4270 case DW_FORM_ref8: // Fall thru
4271 case DW_FORM_data8: return sizeof(int64_t);
4272 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4273 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4274 default: assert(0 && "DIE Value form not supported yet"); break;
4279 //===----------------------------------------------------------------------===//
4281 /// EmitValue - Emit string value.
4283 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4284 DD.getAsm()->EmitString(String);
4287 //===----------------------------------------------------------------------===//
4289 /// EmitValue - Emit label value.
4291 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4292 bool IsSmall = Form == DW_FORM_data4;
4293 DD.EmitReference(Label, false, IsSmall);
4296 /// SizeOf - Determine size of label value in bytes.
4298 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4299 if (Form == DW_FORM_data4) return 4;
4300 return DD.getTargetData()->getPointerSize();
4303 //===----------------------------------------------------------------------===//
4305 /// EmitValue - Emit label value.
4307 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4308 bool IsSmall = Form == DW_FORM_data4;
4309 DD.EmitReference(Label, false, IsSmall);
4312 /// SizeOf - Determine size of label value in bytes.
4314 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4315 if (Form == DW_FORM_data4) return 4;
4316 return DD.getTargetData()->getPointerSize();
4319 //===----------------------------------------------------------------------===//
4321 /// EmitValue - Emit delta value.
4323 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4324 bool IsSmall = Form == DW_FORM_data4;
4325 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4326 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4329 /// SizeOf - Determine size of delta value in bytes.
4331 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4332 if (Form == DW_FORM_data4) return 4;
4333 return DD.getTargetData()->getPointerSize();
4336 //===----------------------------------------------------------------------===//
4338 /// EmitValue - Emit delta value.
4340 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4341 bool IsSmall = Form == DW_FORM_data4;
4342 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4345 /// SizeOf - Determine size of delta value in bytes.
4347 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4348 if (Form == DW_FORM_data4) return 4;
4349 return DD.getTargetData()->getPointerSize();
4352 //===----------------------------------------------------------------------===//
4354 /// EmitValue - Emit debug information entry offset.
4356 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4357 DD.getAsm()->EmitInt32(Entry->getOffset());
4360 //===----------------------------------------------------------------------===//
4362 /// ComputeSize - calculate the size of the block.
4364 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4366 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4368 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4369 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4375 /// EmitValue - Emit block data.
4377 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4379 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4380 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4381 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4382 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4383 default: assert(0 && "Improper form for block"); break;
4386 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4388 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4390 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4394 /// SizeOf - Determine size of block data in bytes.
4396 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4398 case DW_FORM_block1: return Size + sizeof(int8_t);
4399 case DW_FORM_block2: return Size + sizeof(int16_t);
4400 case DW_FORM_block4: return Size + sizeof(int32_t);
4401 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4402 default: assert(0 && "Improper form for block"); break;
4407 //===----------------------------------------------------------------------===//
4408 /// DIE Implementation
4411 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4415 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4417 void DIE::AddSiblingOffset() {
4418 DIEInteger *DI = new DIEInteger(0);
4419 Values.insert(Values.begin(), DI);
4420 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4423 /// Profile - Used to gather unique data for the value folding set.
4425 void DIE::Profile(FoldingSetNodeID &ID) {
4428 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4429 ID.AddPointer(Children[i]);
4431 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4432 ID.AddPointer(Values[j]);
4436 void DIE::print(std::ostream &O, unsigned IncIndent) {
4437 static unsigned IndentCount = 0;
4438 IndentCount += IncIndent;
4439 const std::string Indent(IndentCount, ' ');
4440 bool isBlock = Abbrev.getTag() == 0;
4445 << "0x" << std::hex << (intptr_t)this << std::dec
4446 << ", Offset: " << Offset
4447 << ", Size: " << Size
4451 << TagString(Abbrev.getTag())
4453 << ChildrenString(Abbrev.getChildrenFlag());
4455 O << "Size: " << Size;
4459 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4462 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4466 O << AttributeString(Data[i].getAttribute());
4468 O << "Blk[" << i << "]";
4471 << FormEncodingString(Data[i].getForm())
4473 Values[i]->print(O);
4478 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4479 Children[j]->print(O, 4);
4482 if (!isBlock) O << "\n";
4483 IndentCount -= IncIndent;
4491 //===----------------------------------------------------------------------===//
4492 /// DwarfWriter Implementation
4495 DwarfWriter::DwarfWriter()
4496 : ImmutablePass(&ID), DD(0), DE(0) {}
4498 DwarfWriter::~DwarfWriter() {
4501 delete DwarfTimerGroup; DwarfTimerGroup = 0;
4504 /// BeginModule - Emit all Dwarf sections that should come prior to the
4506 void DwarfWriter::BeginModule(Module *M,
4507 MachineModuleInfo *MMI,
4508 raw_ostream &OS, AsmPrinter *A,
4509 const TargetAsmInfo *T) {
4510 DE = new DwarfException(OS, A, T);
4511 DD = new DwarfDebug(OS, A, T);
4514 DD->SetDebugInfo(MMI);
4515 DE->SetModuleInfo(MMI);
4518 /// EndModule - Emit all Dwarf sections that should come after the content.
4520 void DwarfWriter::EndModule() {
4525 /// BeginFunction - Gather pre-function debug information. Assumes being
4526 /// emitted immediately after the function entry point.
4527 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4528 DE->BeginFunction(MF);
4529 DD->BeginFunction(MF);
4532 /// EndFunction - Gather and emit post-function debug information.
4534 void DwarfWriter::EndFunction(MachineFunction *MF) {
4535 DD->EndFunction(MF);
4538 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4539 // Clear function debug information.
4543 /// ValidDebugInfo - Return true if V represents valid debug info value.
4544 bool DwarfWriter::ValidDebugInfo(Value *V) {
4545 return DD && DD->ValidDebugInfo(V);
4548 /// RecordSourceLine - Records location information and associates it with a
4549 /// label. Returns a unique label ID used to generate a label and provide
4550 /// correspondence to the source line list.
4551 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4553 return DD->RecordSourceLine(Line, Col, Src);
4556 /// getOrCreateSourceID - Look up the source id with the given directory and
4557 /// source file names. If none currently exists, create a new id and insert it
4558 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
4560 unsigned DwarfWriter::getOrCreateSourceID(const std::string &DirName,
4561 const std::string &FileName) {
4562 return DD->getOrCreateSourceID(DirName, FileName);
4565 /// RecordRegionStart - Indicate the start of a region.
4566 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4567 return DD->RecordRegionStart(V);
4570 /// RecordRegionEnd - Indicate the end of a region.
4571 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4572 return DD->RecordRegionEnd(V);
4575 /// getRecordSourceLineCount - Count source lines.
4576 unsigned DwarfWriter::getRecordSourceLineCount() {
4577 return DD->getRecordSourceLineCount();
4580 /// RecordVariable - Indicate the declaration of a local variable.
4582 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4583 DD->RecordVariable(GV, FrameIndex);
4586 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4588 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4589 return DD->ShouldEmitDwarfDebug();