1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/DataTypes.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/System/Path.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
53 //===----------------------------------------------------------------------===//
55 /// Configuration values for initial hash set sizes (log2).
57 static const unsigned InitDiesSetSize = 9; // log2(512)
58 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
59 static const unsigned InitValuesSetSize = 9; // log2(512)
61 //===----------------------------------------------------------------------===//
62 /// Forward declarations.
67 //===----------------------------------------------------------------------===//
70 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
71 /// specified value in their initializer somewhere.
73 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
74 // Scan though value users.
75 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
76 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
77 // If the user is a GlobalVariable then add to result.
79 } else if (Constant *C = dyn_cast<Constant>(*I)) {
80 // If the user is a constant variable then scan its users.
81 getGlobalVariablesUsing(C, Result);
86 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
87 /// named GlobalVariable.
89 getGlobalVariablesUsing(Module &M, const std::string &RootName,
90 std::vector<GlobalVariable*> &Result) {
91 std::vector<const Type*> FieldTypes;
92 FieldTypes.push_back(Type::Int32Ty);
93 FieldTypes.push_back(Type::Int32Ty);
95 // Get the GlobalVariable root.
96 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
97 StructType::get(FieldTypes));
99 // If present and linkonce then scan for users.
100 if (UseRoot && UseRoot->hasLinkOnceLinkage())
101 getGlobalVariablesUsing(UseRoot, Result);
104 /// getGlobalVariable - Return either a direct or cast Global value.
106 static GlobalVariable *getGlobalVariable(Value *V) {
107 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
109 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
110 if (CE->getOpcode() == Instruction::BitCast) {
111 return dyn_cast<GlobalVariable>(CE->getOperand(0));
112 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
113 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
114 if (!CE->getOperand(i)->isNullValue())
117 return dyn_cast<GlobalVariable>(CE->getOperand(0));
123 //===----------------------------------------------------------------------===//
124 /// DWLabel - Labels are used to track locations in the assembler file.
125 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
126 /// where the tag is a category of label (Ex. location) and number is a value
127 /// unique in that category.
130 /// Tag - Label category tag. Should always be a staticly declared C string.
134 /// Number - Value to make label unique.
138 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
140 void Profile(FoldingSetNodeID &ID) const {
141 ID.AddString(std::string(Tag));
142 ID.AddInteger(Number);
146 void print(std::ostream *O) const {
149 void print(std::ostream &O) const {
151 if (Number) O << Number;
156 //===----------------------------------------------------------------------===//
157 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
158 /// Dwarf abbreviation.
159 class DIEAbbrevData {
161 /// Attribute - Dwarf attribute code.
165 /// Form - Dwarf form code.
170 DIEAbbrevData(unsigned A, unsigned F)
176 unsigned getAttribute() const { return Attribute; }
177 unsigned getForm() const { return Form; }
179 /// Profile - Used to gather unique data for the abbreviation folding set.
181 void Profile(FoldingSetNodeID &ID)const {
182 ID.AddInteger(Attribute);
187 //===----------------------------------------------------------------------===//
188 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
189 /// information object.
190 class DIEAbbrev : public FoldingSetNode {
192 /// Tag - Dwarf tag code.
196 /// Unique number for node.
200 /// ChildrenFlag - Dwarf children flag.
202 unsigned ChildrenFlag;
204 /// Data - Raw data bytes for abbreviation.
206 SmallVector<DIEAbbrevData, 8> Data;
210 DIEAbbrev(unsigned T, unsigned C)
218 unsigned getTag() const { return Tag; }
219 unsigned getNumber() const { return Number; }
220 unsigned getChildrenFlag() const { return ChildrenFlag; }
221 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
222 void setTag(unsigned T) { Tag = T; }
223 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
224 void setNumber(unsigned N) { Number = N; }
226 /// AddAttribute - Adds another set of attribute information to the
228 void AddAttribute(unsigned Attribute, unsigned Form) {
229 Data.push_back(DIEAbbrevData(Attribute, Form));
232 /// AddFirstAttribute - Adds a set of attribute information to the front
233 /// of the abbreviation.
234 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
235 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
238 /// Profile - Used to gather unique data for the abbreviation folding set.
240 void Profile(FoldingSetNodeID &ID) {
242 ID.AddInteger(ChildrenFlag);
244 // For each attribute description.
245 for (unsigned i = 0, N = Data.size(); i < N; ++i)
249 /// Emit - Print the abbreviation using the specified Dwarf writer.
251 void Emit(const DwarfDebug &DD) const;
254 void print(std::ostream *O) {
257 void print(std::ostream &O);
262 //===----------------------------------------------------------------------===//
263 /// DIE - A structured debug information entry. Has an abbreviation which
264 /// describes it's organization.
265 class DIE : public FoldingSetNode {
267 /// Abbrev - Buffer for constructing abbreviation.
271 /// Offset - Offset in debug info section.
275 /// Size - Size of instance + children.
281 std::vector<DIE *> Children;
283 /// Attributes values.
285 SmallVector<DIEValue*, 32> Values;
288 explicit DIE(unsigned Tag)
289 : Abbrev(Tag, DW_CHILDREN_no)
298 DIEAbbrev &getAbbrev() { return Abbrev; }
299 unsigned getAbbrevNumber() const {
300 return Abbrev.getNumber();
302 unsigned getTag() const { return Abbrev.getTag(); }
303 unsigned getOffset() const { return Offset; }
304 unsigned getSize() const { return Size; }
305 const std::vector<DIE *> &getChildren() const { return Children; }
306 SmallVector<DIEValue*, 32> &getValues() { return Values; }
307 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
308 void setOffset(unsigned O) { Offset = O; }
309 void setSize(unsigned S) { Size = S; }
311 /// AddValue - Add a value and attributes to a DIE.
313 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
314 Abbrev.AddAttribute(Attribute, Form);
315 Values.push_back(Value);
318 /// SiblingOffset - Return the offset of the debug information entry's
320 unsigned SiblingOffset() const { return Offset + Size; }
322 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
324 void AddSiblingOffset();
326 /// AddChild - Add a child to the DIE.
328 void AddChild(DIE *Child) {
329 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
330 Children.push_back(Child);
333 /// Detach - Detaches objects connected to it after copying.
339 /// Profile - Used to gather unique data for the value folding set.
341 void Profile(FoldingSetNodeID &ID) ;
344 void print(std::ostream *O, unsigned IncIndent = 0) {
345 if (O) print(*O, IncIndent);
347 void print(std::ostream &O, unsigned IncIndent = 0);
352 //===----------------------------------------------------------------------===//
353 /// DIEValue - A debug information entry value.
355 class DIEValue : public FoldingSetNode {
368 /// Type - Type of data stored in the value.
372 explicit DIEValue(unsigned T)
375 virtual ~DIEValue() {}
378 unsigned getType() const { return Type; }
380 // Implement isa/cast/dyncast.
381 static bool classof(const DIEValue *) { return true; }
383 /// EmitValue - Emit value via the Dwarf writer.
385 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
387 /// SizeOf - Return the size of a value in bytes.
389 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
391 /// Profile - Used to gather unique data for the value folding set.
393 virtual void Profile(FoldingSetNodeID &ID) = 0;
396 void print(std::ostream *O) {
399 virtual void print(std::ostream &O) = 0;
404 //===----------------------------------------------------------------------===//
405 /// DWInteger - An integer value DIE.
407 class DIEInteger : public DIEValue {
412 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
414 // Implement isa/cast/dyncast.
415 static bool classof(const DIEInteger *) { return true; }
416 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
418 /// BestForm - Choose the best form for integer.
420 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
422 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
423 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
424 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
426 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
427 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
428 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
430 return DW_FORM_data8;
433 /// EmitValue - Emit integer of appropriate size.
435 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
437 /// SizeOf - Determine size of integer value in bytes.
439 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
441 /// Profile - Used to gather unique data for the value folding set.
443 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
444 ID.AddInteger(isInteger);
445 ID.AddInteger(Integer);
447 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
450 virtual void print(std::ostream &O) {
451 O << "Int: " << (int64_t)Integer
452 << " 0x" << std::hex << Integer << std::dec;
457 //===----------------------------------------------------------------------===//
458 /// DIEString - A string value DIE.
460 class DIEString : public DIEValue {
462 const std::string String;
464 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
466 // Implement isa/cast/dyncast.
467 static bool classof(const DIEString *) { return true; }
468 static bool classof(const DIEValue *S) { return S->Type == isString; }
470 /// EmitValue - Emit string value.
472 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
474 /// SizeOf - Determine size of string value in bytes.
476 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
477 return String.size() + sizeof(char); // sizeof('\0');
480 /// Profile - Used to gather unique data for the value folding set.
482 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
483 ID.AddInteger(isString);
484 ID.AddString(String);
486 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
489 virtual void print(std::ostream &O) {
490 O << "Str: \"" << String << "\"";
495 //===----------------------------------------------------------------------===//
496 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
498 class DIEDwarfLabel : public DIEValue {
503 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
505 // Implement isa/cast/dyncast.
506 static bool classof(const DIEDwarfLabel *) { return true; }
507 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
509 /// EmitValue - Emit label value.
511 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
513 /// SizeOf - Determine size of label value in bytes.
515 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
517 /// Profile - Used to gather unique data for the value folding set.
519 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
520 ID.AddInteger(isLabel);
523 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
526 virtual void print(std::ostream &O) {
534 //===----------------------------------------------------------------------===//
535 /// DIEObjectLabel - A label to an object in code or data.
537 class DIEObjectLabel : public DIEValue {
539 const std::string Label;
541 explicit DIEObjectLabel(const std::string &L)
542 : DIEValue(isAsIsLabel), Label(L) {}
544 // Implement isa/cast/dyncast.
545 static bool classof(const DIEObjectLabel *) { return true; }
546 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
548 /// EmitValue - Emit label value.
550 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
552 /// SizeOf - Determine size of label value in bytes.
554 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
556 /// Profile - Used to gather unique data for the value folding set.
558 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
559 ID.AddInteger(isAsIsLabel);
562 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
565 virtual void print(std::ostream &O) {
566 O << "Obj: " << Label;
571 //===----------------------------------------------------------------------===//
572 /// DIESectionOffset - A section offset DIE.
574 class DIESectionOffset : public DIEValue {
577 const DWLabel Section;
581 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
582 bool isEH = false, bool useSet = true)
583 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
584 IsEH(isEH), UseSet(useSet) {}
586 // Implement isa/cast/dyncast.
587 static bool classof(const DIESectionOffset *) { return true; }
588 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
590 /// EmitValue - Emit section offset.
592 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
594 /// SizeOf - Determine size of section offset value in bytes.
596 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
598 /// Profile - Used to gather unique data for the value folding set.
600 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
601 const DWLabel &Section) {
602 ID.AddInteger(isSectionOffset);
605 // IsEH and UseSet are specific to the Label/Section that we will emit
606 // the offset for; so Label/Section are enough for uniqueness.
608 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
611 virtual void print(std::ostream &O) {
616 O << "-" << IsEH << "-" << UseSet;
621 //===----------------------------------------------------------------------===//
622 /// DIEDelta - A simple label difference DIE.
624 class DIEDelta : public DIEValue {
626 const DWLabel LabelHi;
627 const DWLabel LabelLo;
629 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
630 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
632 // Implement isa/cast/dyncast.
633 static bool classof(const DIEDelta *) { return true; }
634 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
636 /// EmitValue - Emit delta value.
638 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
640 /// SizeOf - Determine size of delta value in bytes.
642 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
644 /// Profile - Used to gather unique data for the value folding set.
646 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
647 const DWLabel &LabelLo) {
648 ID.AddInteger(isDelta);
652 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
655 virtual void print(std::ostream &O) {
664 //===----------------------------------------------------------------------===//
665 /// DIEntry - A pointer to another debug information entry. An instance of this
666 /// class can also be used as a proxy for a debug information entry not yet
667 /// defined (ie. types.)
668 class DIEntry : public DIEValue {
672 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
674 // Implement isa/cast/dyncast.
675 static bool classof(const DIEntry *) { return true; }
676 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
678 /// EmitValue - Emit debug information entry offset.
680 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
682 /// SizeOf - Determine size of debug information entry in bytes.
684 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
685 return sizeof(int32_t);
688 /// Profile - Used to gather unique data for the value folding set.
690 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
691 ID.AddInteger(isEntry);
692 ID.AddPointer(Entry);
694 virtual void Profile(FoldingSetNodeID &ID) {
695 ID.AddInteger(isEntry);
698 ID.AddPointer(Entry);
705 virtual void print(std::ostream &O) {
706 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
711 //===----------------------------------------------------------------------===//
712 /// DIEBlock - A block of values. Primarily used for location expressions.
714 class DIEBlock : public DIEValue, public DIE {
716 unsigned Size; // Size in bytes excluding size header.
726 // Implement isa/cast/dyncast.
727 static bool classof(const DIEBlock *) { return true; }
728 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
730 /// ComputeSize - calculate the size of the block.
732 unsigned ComputeSize(DwarfDebug &DD);
734 /// BestForm - Choose the best form for data.
736 unsigned BestForm() const {
737 if ((unsigned char)Size == Size) return DW_FORM_block1;
738 if ((unsigned short)Size == Size) return DW_FORM_block2;
739 if ((unsigned int)Size == Size) return DW_FORM_block4;
740 return DW_FORM_block;
743 /// EmitValue - Emit block data.
745 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
747 /// SizeOf - Determine size of block data in bytes.
749 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
752 /// Profile - Used to gather unique data for the value folding set.
754 virtual void Profile(FoldingSetNodeID &ID) {
755 ID.AddInteger(isBlock);
760 virtual void print(std::ostream &O) {
767 //===----------------------------------------------------------------------===//
768 /// CompileUnit - This dwarf writer support class manages information associate
769 /// with a source file.
772 /// ID - File identifier for source.
776 /// Die - Compile unit debug information entry.
780 /// GVToDieMap - Tracks the mapping of unit level debug informaton
781 /// variables to debug information entries.
782 std::map<GlobalVariable *, DIE *> GVToDieMap;
784 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
785 /// descriptors to debug information entries using a DIEntry proxy.
786 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
788 /// Globals - A map of globally visible named entities for this unit.
790 std::map<std::string, DIE *> Globals;
792 /// DiesSet - Used to uniquely define dies within the compile unit.
794 FoldingSet<DIE> DiesSet;
797 CompileUnit(unsigned I, DIE *D)
798 : ID(I), Die(D), GVToDieMap(),
799 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
807 unsigned getID() const { return ID; }
808 DIE* getDie() const { return Die; }
809 std::map<std::string, DIE *> &getGlobals() { return Globals; }
811 /// hasContent - Return true if this compile unit has something to write out.
813 bool hasContent() const {
814 return !Die->getChildren().empty();
817 /// AddGlobal - Add a new global entity to the compile unit.
819 void AddGlobal(const std::string &Name, DIE *Die) {
823 /// getDieMapSlotFor - Returns the debug information entry map slot for the
824 /// specified debug variable.
825 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
826 return GVToDieMap[GV];
829 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
830 /// specified debug variable.
831 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
832 return GVToDIEntryMap[GV];
835 /// AddDie - Adds or interns the DIE to the compile unit.
837 DIE *AddDie(DIE &Buffer) {
841 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
844 Die = new DIE(Buffer);
845 DiesSet.InsertNode(Die, Where);
846 this->Die->AddChild(Die);
854 //===----------------------------------------------------------------------===//
855 /// Dwarf - Emits general Dwarf directives.
859 //===--------------------------------------------------------------------===//
860 // Core attributes used by the Dwarf writer.
864 /// O - Stream to .s file.
868 /// Asm - Target of Dwarf emission.
872 /// TAI - Target asm information.
873 const TargetAsmInfo *TAI;
875 /// TD - Target data.
876 const TargetData *TD;
878 /// RI - Register Information.
879 const TargetRegisterInfo *RI;
881 /// M - Current module.
885 /// MF - Current machine function.
889 /// MMI - Collected machine module information.
891 MachineModuleInfo *MMI;
893 /// SubprogramCount - The running count of functions being compiled.
895 unsigned SubprogramCount;
897 /// Flavor - A unique string indicating what dwarf producer this is, used to
899 const char * const Flavor;
902 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
907 , TD(Asm->TM.getTargetData())
908 , RI(Asm->TM.getRegisterInfo())
919 //===--------------------------------------------------------------------===//
922 AsmPrinter *getAsm() const { return Asm; }
923 MachineModuleInfo *getMMI() const { return MMI; }
924 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
925 const TargetData *getTargetData() const { return TD; }
927 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
929 if (isInSection && TAI->getDwarfSectionOffsetDirective())
930 O << TAI->getDwarfSectionOffsetDirective();
931 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
932 O << TAI->getData32bitsDirective();
934 O << TAI->getData64bitsDirective();
937 /// PrintLabelName - Print label name in form used by Dwarf writer.
939 void PrintLabelName(DWLabel Label) const {
940 PrintLabelName(Label.Tag, Label.Number);
942 void PrintLabelName(const char *Tag, unsigned Number) const {
943 O << TAI->getPrivateGlobalPrefix() << Tag;
944 if (Number) O << Number;
947 void PrintLabelName(const char *Tag, unsigned Number,
948 const char *Suffix) const {
949 O << TAI->getPrivateGlobalPrefix() << Tag;
950 if (Number) O << Number;
954 /// EmitLabel - Emit location label for internal use by Dwarf.
956 void EmitLabel(DWLabel Label) const {
957 EmitLabel(Label.Tag, Label.Number);
959 void EmitLabel(const char *Tag, unsigned Number) const {
960 PrintLabelName(Tag, Number);
964 /// EmitReference - Emit a reference to a label.
966 void EmitReference(DWLabel Label, bool IsPCRelative = false,
967 bool Force32Bit = false) const {
968 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
970 void EmitReference(const char *Tag, unsigned Number,
971 bool IsPCRelative = false, bool Force32Bit = false) const {
972 PrintRelDirective(Force32Bit);
973 PrintLabelName(Tag, Number);
975 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
977 void EmitReference(const std::string &Name, bool IsPCRelative = false,
978 bool Force32Bit = false) const {
979 PrintRelDirective(Force32Bit);
983 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
986 /// EmitDifference - Emit the difference between two labels. Some
987 /// assemblers do not behave with absolute expressions with data directives,
988 /// so there is an option (needsSet) to use an intermediary set expression.
989 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
990 bool IsSmall = false) {
991 EmitDifference(LabelHi.Tag, LabelHi.Number,
992 LabelLo.Tag, LabelLo.Number,
995 void EmitDifference(const char *TagHi, unsigned NumberHi,
996 const char *TagLo, unsigned NumberLo,
997 bool IsSmall = false) {
998 if (TAI->needsSet()) {
1000 PrintLabelName("set", SetCounter, Flavor);
1002 PrintLabelName(TagHi, NumberHi);
1004 PrintLabelName(TagLo, NumberLo);
1007 PrintRelDirective(IsSmall);
1008 PrintLabelName("set", SetCounter, Flavor);
1011 PrintRelDirective(IsSmall);
1013 PrintLabelName(TagHi, NumberHi);
1015 PrintLabelName(TagLo, NumberLo);
1019 void EmitSectionOffset(const char* Label, const char* Section,
1020 unsigned LabelNumber, unsigned SectionNumber,
1021 bool IsSmall = false, bool isEH = false,
1022 bool useSet = true) {
1023 bool printAbsolute = false;
1025 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1027 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1029 if (TAI->needsSet() && useSet) {
1031 PrintLabelName("set", SetCounter, Flavor);
1033 PrintLabelName(Label, LabelNumber);
1035 if (!printAbsolute) {
1037 PrintLabelName(Section, SectionNumber);
1041 PrintRelDirective(IsSmall);
1043 PrintLabelName("set", SetCounter, Flavor);
1046 PrintRelDirective(IsSmall, true);
1048 PrintLabelName(Label, LabelNumber);
1050 if (!printAbsolute) {
1052 PrintLabelName(Section, SectionNumber);
1057 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1059 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1060 const std::vector<MachineMove> &Moves, bool isEH) {
1062 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1063 TargetFrameInfo::StackGrowsUp ?
1064 TD->getPointerSize() : -TD->getPointerSize();
1065 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1067 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1068 const MachineMove &Move = Moves[i];
1069 unsigned LabelID = Move.getLabelID();
1072 LabelID = MMI->MappedLabel(LabelID);
1074 // Throw out move if the label is invalid.
1075 if (!LabelID) continue;
1078 const MachineLocation &Dst = Move.getDestination();
1079 const MachineLocation &Src = Move.getSource();
1081 // Advance row if new location.
1082 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1083 Asm->EmitInt8(DW_CFA_advance_loc4);
1084 Asm->EOL("DW_CFA_advance_loc4");
1085 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1088 BaseLabelID = LabelID;
1089 BaseLabel = "label";
1093 // If advancing cfa.
1094 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1096 if (Src.getReg() == MachineLocation::VirtualFP) {
1097 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1098 Asm->EOL("DW_CFA_def_cfa_offset");
1100 Asm->EmitInt8(DW_CFA_def_cfa);
1101 Asm->EOL("DW_CFA_def_cfa");
1102 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1103 Asm->EOL("Register");
1106 int Offset = -Src.getOffset();
1108 Asm->EmitULEB128Bytes(Offset);
1111 assert(0 && "Machine move no supported yet.");
1113 } else if (Src.isReg() &&
1114 Src.getReg() == MachineLocation::VirtualFP) {
1116 Asm->EmitInt8(DW_CFA_def_cfa_register);
1117 Asm->EOL("DW_CFA_def_cfa_register");
1118 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1119 Asm->EOL("Register");
1121 assert(0 && "Machine move no supported yet.");
1124 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1125 int Offset = Dst.getOffset() / stackGrowth;
1128 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1129 Asm->EOL("DW_CFA_offset_extended_sf");
1130 Asm->EmitULEB128Bytes(Reg);
1132 Asm->EmitSLEB128Bytes(Offset);
1134 } else if (Reg < 64) {
1135 Asm->EmitInt8(DW_CFA_offset + Reg);
1137 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1140 Asm->EmitULEB128Bytes(Offset);
1143 Asm->EmitInt8(DW_CFA_offset_extended);
1144 Asm->EOL("DW_CFA_offset_extended");
1145 Asm->EmitULEB128Bytes(Reg);
1147 Asm->EmitULEB128Bytes(Offset);
1156 //===----------------------------------------------------------------------===//
1157 /// SrcLineInfo - This class is used to record source line correspondence.
1160 unsigned Line; // Source line number.
1161 unsigned Column; // Source column.
1162 unsigned SourceID; // Source ID number.
1163 unsigned LabelID; // Label in code ID number.
1165 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1166 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1169 unsigned getLine() const { return Line; }
1170 unsigned getColumn() const { return Column; }
1171 unsigned getSourceID() const { return SourceID; }
1172 unsigned getLabelID() const { return LabelID; }
1175 //===----------------------------------------------------------------------===//
1176 /// SrcFileInfo - This class is used to track source information.
1179 unsigned DirectoryID; // Directory ID number.
1180 std::string Name; // File name (not including directory.)
1182 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1185 unsigned getDirectoryID() const { return DirectoryID; }
1186 const std::string &getName() const { return Name; }
1188 /// operator== - Used by UniqueVector to locate entry.
1190 bool operator==(const SrcFileInfo &SI) const {
1191 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1194 /// operator< - Used by UniqueVector to locate entry.
1196 bool operator<(const SrcFileInfo &SI) const {
1197 return getDirectoryID() < SI.getDirectoryID() ||
1198 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1202 //===----------------------------------------------------------------------===//
1203 /// DbgVariable - This class is used to track local variable information.
1206 DIVariable Var; // Variable Descriptor.
1207 unsigned FrameIndex; // Variable frame index.
1209 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1212 DIVariable getVariable() const { return Var; }
1213 unsigned getFrameIndex() const { return FrameIndex; }
1216 //===----------------------------------------------------------------------===//
1217 /// DbgScope - This class is used to track scope information.
1220 DbgScope *Parent; // Parent to this scope.
1221 DIDescriptor Desc; // Debug info descriptor for scope.
1222 // Either subprogram or block.
1223 unsigned StartLabelID; // Label ID of the beginning of scope.
1224 unsigned EndLabelID; // Label ID of the end of scope.
1225 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1226 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1228 DbgScope(DbgScope *P, DIDescriptor D)
1229 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1232 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1233 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1237 DbgScope *getParent() const { return Parent; }
1238 DIDescriptor getDesc() const { return Desc; }
1239 unsigned getStartLabelID() const { return StartLabelID; }
1240 unsigned getEndLabelID() const { return EndLabelID; }
1241 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1242 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1243 void setStartLabelID(unsigned S) { StartLabelID = S; }
1244 void setEndLabelID(unsigned E) { EndLabelID = E; }
1246 /// AddScope - Add a scope to the scope.
1248 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1250 /// AddVariable - Add a variable to the scope.
1252 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1255 //===----------------------------------------------------------------------===//
1256 /// DwarfDebug - Emits Dwarf debug directives.
1258 class DwarfDebug : public Dwarf {
1259 //===--------------------------------------------------------------------===//
1260 // Attributes used to construct specific Dwarf sections.
1263 /// DW_CUs - All the compile units involved in this build. The index
1264 /// of each entry in this vector corresponds to the sources in MMI.
1265 DenseMap<Value *, CompileUnit *> DW_CUs;
1267 /// MainCU - Some platform prefers one compile unit per .o file. In such
1268 /// cases, all dies are inserted in MainCU.
1269 CompileUnit *MainCU;
1270 /// AbbreviationsSet - Used to uniquely define abbreviations.
1272 FoldingSet<DIEAbbrev> AbbreviationsSet;
1274 /// Abbreviations - A list of all the unique abbreviations in use.
1276 std::vector<DIEAbbrev *> Abbreviations;
1278 /// Directories - Uniquing vector for directories.
1279 UniqueVector<std::string> Directories;
1281 /// SourceFiles - Uniquing vector for source files.
1282 UniqueVector<SrcFileInfo> SrcFiles;
1284 /// Lines - List of of source line correspondence.
1285 std::vector<SrcLineInfo> Lines;
1287 /// ValuesSet - Used to uniquely define values.
1289 FoldingSet<DIEValue> ValuesSet;
1291 /// Values - A list of all the unique values in use.
1293 std::vector<DIEValue *> Values;
1295 /// StringPool - A UniqueVector of strings used by indirect references.
1297 UniqueVector<std::string> StringPool;
1299 /// SectionMap - Provides a unique id per text section.
1301 UniqueVector<const Section*> SectionMap;
1303 /// SectionSourceLines - Tracks line numbers per text section.
1305 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1307 /// didInitial - Flag to indicate if initial emission has been done.
1311 /// shouldEmit - Flag to indicate if debug information should be emitted.
1315 // RootDbgScope - Top level scope for the current function.
1317 DbgScope *RootDbgScope;
1319 // DbgScopeMap - Tracks the scopes in the current function.
1320 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1322 struct FunctionDebugFrameInfo {
1324 std::vector<MachineMove> Moves;
1326 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1327 Number(Num), Moves(M) { }
1330 std::vector<FunctionDebugFrameInfo> DebugFrames;
1334 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1336 bool ShouldEmitDwarf() const { return shouldEmit; }
1338 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1340 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1341 // Profile the node so that we can make it unique.
1342 FoldingSetNodeID ID;
1345 // Check the set for priors.
1346 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1348 // If it's newly added.
1349 if (InSet == &Abbrev) {
1350 // Add to abbreviation list.
1351 Abbreviations.push_back(&Abbrev);
1352 // Assign the vector position + 1 as its number.
1353 Abbrev.setNumber(Abbreviations.size());
1355 // Assign existing abbreviation number.
1356 Abbrev.setNumber(InSet->getNumber());
1360 /// NewString - Add a string to the constant pool and returns a label.
1362 DWLabel NewString(const std::string &String) {
1363 unsigned StringID = StringPool.insert(String);
1364 return DWLabel("string", StringID);
1367 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1369 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1373 FoldingSetNodeID ID;
1374 DIEntry::Profile(ID, Entry);
1376 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1378 if (Value) return Value;
1380 Value = new DIEntry(Entry);
1381 ValuesSet.InsertNode(Value, Where);
1383 Value = new DIEntry(Entry);
1386 Values.push_back(Value);
1390 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1392 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1393 Value->Entry = Entry;
1394 // Add to values set if not already there. If it is, we merely have a
1395 // duplicate in the values list (no harm.)
1396 ValuesSet.GetOrInsertNode(Value);
1399 /// AddUInt - Add an unsigned integer attribute data and value.
1401 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1402 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1404 FoldingSetNodeID ID;
1405 DIEInteger::Profile(ID, Integer);
1407 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1409 Value = new DIEInteger(Integer);
1410 ValuesSet.InsertNode(Value, Where);
1411 Values.push_back(Value);
1414 Die->AddValue(Attribute, Form, Value);
1417 /// AddSInt - Add an signed integer attribute data and value.
1419 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1420 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1422 FoldingSetNodeID ID;
1423 DIEInteger::Profile(ID, (uint64_t)Integer);
1425 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1427 Value = new DIEInteger(Integer);
1428 ValuesSet.InsertNode(Value, Where);
1429 Values.push_back(Value);
1432 Die->AddValue(Attribute, Form, Value);
1435 /// AddString - Add a std::string attribute data and value.
1437 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1438 const std::string &String) {
1439 FoldingSetNodeID ID;
1440 DIEString::Profile(ID, String);
1442 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1444 Value = new DIEString(String);
1445 ValuesSet.InsertNode(Value, Where);
1446 Values.push_back(Value);
1449 Die->AddValue(Attribute, Form, Value);
1452 /// AddLabel - Add a Dwarf label attribute data and value.
1454 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1455 const DWLabel &Label) {
1456 FoldingSetNodeID ID;
1457 DIEDwarfLabel::Profile(ID, Label);
1459 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1461 Value = new DIEDwarfLabel(Label);
1462 ValuesSet.InsertNode(Value, Where);
1463 Values.push_back(Value);
1466 Die->AddValue(Attribute, Form, Value);
1469 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1471 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1472 const std::string &Label) {
1473 FoldingSetNodeID ID;
1474 DIEObjectLabel::Profile(ID, Label);
1476 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1478 Value = new DIEObjectLabel(Label);
1479 ValuesSet.InsertNode(Value, Where);
1480 Values.push_back(Value);
1483 Die->AddValue(Attribute, Form, Value);
1486 /// AddSectionOffset - Add a section offset label attribute data and value.
1488 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1489 const DWLabel &Label, const DWLabel &Section,
1490 bool isEH = false, bool useSet = true) {
1491 FoldingSetNodeID ID;
1492 DIESectionOffset::Profile(ID, Label, Section);
1494 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1496 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1497 ValuesSet.InsertNode(Value, Where);
1498 Values.push_back(Value);
1501 Die->AddValue(Attribute, Form, Value);
1504 /// AddDelta - Add a label delta attribute data and value.
1506 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1507 const DWLabel &Hi, const DWLabel &Lo) {
1508 FoldingSetNodeID ID;
1509 DIEDelta::Profile(ID, Hi, Lo);
1511 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1513 Value = new DIEDelta(Hi, Lo);
1514 ValuesSet.InsertNode(Value, Where);
1515 Values.push_back(Value);
1518 Die->AddValue(Attribute, Form, Value);
1521 /// AddDIEntry - Add a DIE attribute data and value.
1523 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1524 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1527 /// AddBlock - Add block data.
1529 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1530 Block->ComputeSize(*this);
1531 FoldingSetNodeID ID;
1534 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1537 ValuesSet.InsertNode(Value, Where);
1538 Values.push_back(Value);
1540 // Already exists, reuse the previous one.
1542 Block = cast<DIEBlock>(Value);
1545 Die->AddValue(Attribute, Block->BestForm(), Value);
1550 /// AddSourceLine - Add location information to specified debug information
1552 void AddSourceLine(DIE *Die, const DIVariable *V) {
1553 unsigned FileID = 0;
1554 unsigned Line = V->getLineNumber();
1555 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1556 FileID = Unit->getID();
1557 assert (FileID && "Invalid file id");
1558 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1559 AddUInt(Die, DW_AT_decl_line, 0, Line);
1562 /// AddSourceLine - Add location information to specified debug information
1564 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1565 unsigned FileID = 0;
1566 unsigned Line = G->getLineNumber();
1567 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1568 FileID = Unit->getID();
1569 assert (FileID && "Invalid file id");
1570 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1571 AddUInt(Die, DW_AT_decl_line, 0, Line);
1574 void AddSourceLine(DIE *Die, const DIType *Ty) {
1575 unsigned FileID = 0;
1576 unsigned Line = Ty->getLineNumber();
1577 DICompileUnit CU = Ty->getCompileUnit();
1580 CompileUnit *Unit = FindCompileUnit(CU);
1581 FileID = Unit->getID();
1582 assert (FileID && "Invalid file id");
1583 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1584 AddUInt(Die, DW_AT_decl_line, 0, Line);
1587 /// AddAddress - Add an address attribute to a die based on the location
1589 void AddAddress(DIE *Die, unsigned Attribute,
1590 const MachineLocation &Location) {
1591 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1592 DIEBlock *Block = new DIEBlock();
1594 if (Location.isReg()) {
1596 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1598 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1599 AddUInt(Block, 0, DW_FORM_udata, Reg);
1603 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1605 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1606 AddUInt(Block, 0, DW_FORM_udata, Reg);
1608 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1611 AddBlock(Die, Attribute, 0, Block);
1614 /// AddType - Add a new type attribute to the specified entity.
1615 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1619 // Check for pre-existence.
1620 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1621 // If it exists then use the existing value.
1623 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1628 Slot = NewDIEntry();
1631 DIE Buffer(DW_TAG_base_type);
1632 if (Ty.isBasicType(Ty.getTag()))
1633 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1634 else if (Ty.isDerivedType(Ty.getTag()))
1635 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1637 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1638 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1641 // Add debug information entry to entity and appropriate context.
1643 DIDescriptor Context = Ty.getContext();
1644 if (!Context.isNull())
1645 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1648 DIE *Child = new DIE(Buffer);
1649 Die->AddChild(Child);
1651 SetDIEntry(Slot, Child);
1653 Die = DW_Unit->AddDie(Buffer);
1654 SetDIEntry(Slot, Die);
1657 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1660 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1661 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1664 // Get core information.
1665 const std::string &Name = BTy.getName();
1666 Buffer.setTag(DW_TAG_base_type);
1667 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1668 // Add name if not anonymous or intermediate type.
1670 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1671 uint64_t Size = BTy.getSizeInBits() >> 3;
1672 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1675 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1676 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1677 DIDerivedType DTy) {
1679 // Get core information.
1680 const std::string &Name = DTy.getName();
1681 uint64_t Size = DTy.getSizeInBits() >> 3;
1682 unsigned Tag = DTy.getTag();
1683 // FIXME - Workaround for templates.
1684 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1687 // Map to main type, void will not have a type.
1688 DIType FromTy = DTy.getTypeDerivedFrom();
1689 AddType(DW_Unit, &Buffer, FromTy);
1691 // Add name if not anonymous or intermediate type.
1692 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1694 // Add size if non-zero (derived types might be zero-sized.)
1696 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1698 // Add source line info if available and TyDesc is not a forward
1700 if (!DTy.isForwardDecl())
1701 AddSourceLine(&Buffer, &DTy);
1704 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1705 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1706 DICompositeType CTy) {
1708 // Get core information.
1709 const std::string &Name = CTy.getName();
1710 uint64_t Size = CTy.getSizeInBits() >> 3;
1711 unsigned Tag = CTy.getTag();
1714 case DW_TAG_vector_type:
1715 case DW_TAG_array_type:
1716 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1718 case DW_TAG_enumeration_type:
1720 DIArray Elements = CTy.getTypeArray();
1721 // Add enumerators to enumeration type.
1722 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1723 DIE *ElemDie = NULL;
1724 DIEnumerator Enum(Elements.getElement(i).getGV());
1725 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1726 Buffer.AddChild(ElemDie);
1730 case DW_TAG_subroutine_type:
1732 // Add prototype flag.
1733 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1734 DIArray Elements = CTy.getTypeArray();
1736 DIDescriptor RTy = Elements.getElement(0);
1737 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1740 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1741 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1742 DIDescriptor Ty = Elements.getElement(i);
1743 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1744 Buffer.AddChild(Arg);
1748 case DW_TAG_structure_type:
1749 case DW_TAG_union_type:
1751 // Add elements to structure type.
1752 DIArray Elements = CTy.getTypeArray();
1754 // A forward struct declared type may not have elements available.
1755 if (Elements.isNull())
1758 // Add elements to structure type.
1759 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1760 DIDescriptor Element = Elements.getElement(i);
1761 DIE *ElemDie = NULL;
1762 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1763 ElemDie = CreateSubprogramDIE(DW_Unit,
1764 DISubprogram(Element.getGV()));
1765 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1766 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1767 DIGlobalVariable(Element.getGV()));
1769 ElemDie = CreateMemberDIE(DW_Unit,
1770 DIDerivedType(Element.getGV()));
1771 Buffer.AddChild(ElemDie);
1773 unsigned RLang = CTy.getRunTimeLang();
1775 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1782 // Add name if not anonymous or intermediate type.
1783 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1785 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1786 || Tag == DW_TAG_union_type) {
1787 // Add size if non-zero (derived types might be zero-sized.)
1789 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1791 // Add zero size if it is not a forward declaration.
1792 if (CTy.isForwardDecl())
1793 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1795 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1798 // Add source line info if available.
1799 if (!CTy.isForwardDecl())
1800 AddSourceLine(&Buffer, &CTy);
1804 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1805 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1806 int64_t L = SR.getLo();
1807 int64_t H = SR.getHi();
1808 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1810 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1812 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1813 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1815 Buffer.AddChild(DW_Subrange);
1818 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1819 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1820 DICompositeType *CTy) {
1821 Buffer.setTag(DW_TAG_array_type);
1822 if (CTy->getTag() == DW_TAG_vector_type)
1823 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1825 // Emit derived type.
1826 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1827 DIArray Elements = CTy->getTypeArray();
1829 // Construct an anonymous type for index type.
1830 DIE IdxBuffer(DW_TAG_base_type);
1831 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1832 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1833 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1835 // Add subranges to array type.
1836 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1837 DIDescriptor Element = Elements.getElement(i);
1838 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1839 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1843 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1844 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1846 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1847 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1848 int64_t Value = ETy->getEnumValue();
1849 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1853 /// CreateGlobalVariableDIE - Create new DIE using GV.
1854 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1856 DIE *GVDie = new DIE(DW_TAG_variable);
1857 AddString(GVDie, DW_AT_name, DW_FORM_string, GV.getName());
1858 const std::string &LinkageName = GV.getLinkageName();
1859 if (!LinkageName.empty())
1860 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1861 AddType(DW_Unit, GVDie, GV.getType());
1862 if (!GV.isLocalToUnit())
1863 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1864 AddSourceLine(GVDie, &GV);
1868 /// CreateMemberDIE - Create new member DIE.
1869 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1870 DIE *MemberDie = new DIE(DT.getTag());
1871 std::string Name = DT.getName();
1873 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1875 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1877 AddSourceLine(MemberDie, &DT);
1879 uint64_t Size = DT.getSizeInBits();
1880 uint64_t FieldSize = DT.getOriginalTypeSize();
1882 if (Size != FieldSize) {
1884 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1885 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1887 uint64_t Offset = DT.getOffsetInBits();
1888 uint64_t FieldOffset = Offset;
1889 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1890 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1891 FieldOffset = (HiMark - FieldSize);
1892 Offset -= FieldOffset;
1893 // Maybe we need to work from the other end.
1894 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1895 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1897 DIEBlock *Block = new DIEBlock();
1898 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1899 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1900 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1902 if (DT.isProtected())
1903 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1904 else if (DT.isPrivate())
1905 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1910 /// CreateSubprogramDIE - Create new DIE using SP.
1911 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1912 const DISubprogram &SP,
1913 bool IsConstructor = false) {
1914 DIE *SPDie = new DIE(DW_TAG_subprogram);
1915 AddString(SPDie, DW_AT_name, DW_FORM_string, SP.getName());
1916 const std::string &LinkageName = SP.getLinkageName();
1917 if (!LinkageName.empty())
1918 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1920 AddSourceLine(SPDie, &SP);
1922 DICompositeType SPTy = SP.getType();
1923 DIArray Args = SPTy.getTypeArray();
1927 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1929 if (!SP.isDefinition()) {
1930 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1932 // Do not add arguments for subprogram definition. They will be
1933 // handled through RecordVariable.
1935 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1936 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1937 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1938 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1939 SPDie->AddChild(Arg);
1943 if (!SP.isLocalToUnit())
1944 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1948 /// FindCompileUnit - Get the compile unit for the given descriptor.
1950 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1951 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
1952 assert(DW_Unit && "Missing compile unit.");
1956 /// NewDbgScopeVariable - Create a new scope variable.
1958 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1959 // Get the descriptor.
1960 const DIVariable &VD = DV->getVariable();
1962 // Translate tag to proper Dwarf tag. The result variable is dropped for
1965 switch (VD.getTag()) {
1966 case DW_TAG_return_variable: return NULL;
1967 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1968 case DW_TAG_auto_variable: // fall thru
1969 default: Tag = DW_TAG_variable; break;
1972 // Define variable debug information entry.
1973 DIE *VariableDie = new DIE(Tag);
1974 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD.getName());
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];
1996 // FIXME - breaks down when the context is an inlined function.
1997 DIDescriptor ParentDesc;
1998 DIDescriptor Desc(V);
1999 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
2001 ParentDesc = Block.getContext();
2003 DbgScope *Parent = ParentDesc.isNull() ?
2004 NULL : getOrCreateScope(ParentDesc.getGV());
2005 Slot = new DbgScope(Parent, Desc);
2007 Parent->AddScope(Slot);
2008 } else if (RootDbgScope) {
2009 // FIXME - Add inlined function scopes to the root so we can delete
2010 // them later. Long term, handle inlined functions properly.
2011 RootDbgScope->AddScope(Slot);
2013 // First function is top level function.
2014 RootDbgScope = Slot;
2020 /// ConstructDbgScope - Construct the components of a scope.
2022 void ConstructDbgScope(DbgScope *ParentScope,
2023 unsigned ParentStartID, unsigned ParentEndID,
2024 DIE *ParentDie, CompileUnit *Unit) {
2025 // Add variables to scope.
2026 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2027 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2028 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2029 if (VariableDie) ParentDie->AddChild(VariableDie);
2032 // Add nested scopes.
2033 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2034 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2035 // Define the Scope debug information entry.
2036 DbgScope *Scope = Scopes[j];
2037 // FIXME - Ignore inlined functions for the time being.
2038 if (!Scope->getParent()) continue;
2040 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2041 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2043 // Ignore empty scopes.
2044 if (StartID == EndID && StartID != 0) continue;
2045 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2047 if (StartID == ParentStartID && EndID == ParentEndID) {
2048 // Just add stuff to the parent scope.
2049 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2051 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2053 // Add the scope bounds.
2055 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2056 DWLabel("label", StartID));
2058 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2059 DWLabel("func_begin", SubprogramCount));
2062 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2063 DWLabel("label", EndID));
2065 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2066 DWLabel("func_end", SubprogramCount));
2069 // Add the scope contents.
2070 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2071 ParentDie->AddChild(ScopeDie);
2076 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2078 void ConstructRootDbgScope(DbgScope *RootScope) {
2079 // Exit if there is no root scope.
2080 if (!RootScope) return;
2081 DIDescriptor Desc = RootScope->getDesc();
2085 // Get the subprogram debug information entry.
2086 DISubprogram SPD(Desc.getGV());
2088 // Get the compile unit context.
2089 CompileUnit *Unit = MainCU;
2091 Unit = FindCompileUnit(SPD.getCompileUnit());
2093 // Get the subprogram die.
2094 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2095 assert(SPDie && "Missing subprogram descriptor");
2097 // Add the function bounds.
2098 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2099 DWLabel("func_begin", SubprogramCount));
2100 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2101 DWLabel("func_end", SubprogramCount));
2102 MachineLocation Location(RI->getFrameRegister(*MF));
2103 AddAddress(SPDie, DW_AT_frame_base, Location);
2105 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2108 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2110 void ConstructDefaultDbgScope(MachineFunction *MF) {
2111 // Find the correct subprogram descriptor.
2112 std::string SPName = "llvm.dbg.subprograms";
2113 std::vector<GlobalVariable*> Result;
2114 getGlobalVariablesUsing(*M, SPName, Result);
2116 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2117 E = Result.end(); I != E; ++I) {
2118 DISubprogram SPD(*I);
2120 if (SPD.getName() == MF->getFunction()->getName()) {
2121 // Get the compile unit context.
2122 CompileUnit *Unit = MainCU;
2124 Unit = FindCompileUnit(SPD.getCompileUnit());
2126 // Get the subprogram die.
2127 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2128 assert(SPDie && "Missing subprogram descriptor");
2130 // Add the function bounds.
2131 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2132 DWLabel("func_begin", SubprogramCount));
2133 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2134 DWLabel("func_end", SubprogramCount));
2136 MachineLocation Location(RI->getFrameRegister(*MF));
2137 AddAddress(SPDie, DW_AT_frame_base, Location);
2142 // FIXME: This is causing an abort because C++ mangled names are compared
2143 // with their unmangled counterparts. See PR2885. Don't do this assert.
2144 assert(0 && "Couldn't find DIE for machine function!");
2148 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2149 /// tools to recognize the object file contains Dwarf information.
2150 void EmitInitial() {
2151 // Check to see if we already emitted intial headers.
2152 if (didInitial) return;
2155 // Dwarf sections base addresses.
2156 if (TAI->doesDwarfRequireFrameSection()) {
2157 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2158 EmitLabel("section_debug_frame", 0);
2160 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2161 EmitLabel("section_info", 0);
2162 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2163 EmitLabel("section_abbrev", 0);
2164 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2165 EmitLabel("section_aranges", 0);
2166 if (TAI->doesSupportMacInfoSection()) {
2167 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2168 EmitLabel("section_macinfo", 0);
2170 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2171 EmitLabel("section_line", 0);
2172 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2173 EmitLabel("section_loc", 0);
2174 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2175 EmitLabel("section_pubnames", 0);
2176 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2177 EmitLabel("section_str", 0);
2178 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2179 EmitLabel("section_ranges", 0);
2181 Asm->SwitchToSection(TAI->getTextSection());
2182 EmitLabel("text_begin", 0);
2183 Asm->SwitchToSection(TAI->getDataSection());
2184 EmitLabel("data_begin", 0);
2187 /// EmitDIE - Recusively Emits a debug information entry.
2189 void EmitDIE(DIE *Die) {
2190 // Get the abbreviation for this DIE.
2191 unsigned AbbrevNumber = Die->getAbbrevNumber();
2192 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2196 // Emit the code (index) for the abbreviation.
2197 Asm->EmitULEB128Bytes(AbbrevNumber);
2200 Asm->EOL(std::string("Abbrev [" +
2201 utostr(AbbrevNumber) +
2202 "] 0x" + utohexstr(Die->getOffset()) +
2203 ":0x" + utohexstr(Die->getSize()) + " " +
2204 TagString(Abbrev->getTag())));
2208 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2209 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2211 // Emit the DIE attribute values.
2212 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2213 unsigned Attr = AbbrevData[i].getAttribute();
2214 unsigned Form = AbbrevData[i].getForm();
2215 assert(Form && "Too many attributes for DIE (check abbreviation)");
2218 case DW_AT_sibling: {
2219 Asm->EmitInt32(Die->SiblingOffset());
2223 // Emit an attribute using the defined form.
2224 Values[i]->EmitValue(*this, Form);
2229 Asm->EOL(AttributeString(Attr));
2232 // Emit the DIE children if any.
2233 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2234 const std::vector<DIE *> &Children = Die->getChildren();
2236 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2237 EmitDIE(Children[j]);
2240 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2244 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2246 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2247 // Get the children.
2248 const std::vector<DIE *> &Children = Die->getChildren();
2250 // If not last sibling and has children then add sibling offset attribute.
2251 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2253 // Record the abbreviation.
2254 AssignAbbrevNumber(Die->getAbbrev());
2256 // Get the abbreviation for this DIE.
2257 unsigned AbbrevNumber = Die->getAbbrevNumber();
2258 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2261 Die->setOffset(Offset);
2263 // Start the size with the size of abbreviation code.
2264 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2266 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2267 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2269 // Size the DIE attribute values.
2270 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2271 // Size attribute value.
2272 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2275 // Size the DIE children if any.
2276 if (!Children.empty()) {
2277 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2278 "Children flag not set");
2280 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2281 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2284 // End of children marker.
2285 Offset += sizeof(int8_t);
2288 Die->setSize(Offset - Die->getOffset());
2292 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2294 void SizeAndOffsets() {
2295 // Process base compile unit.
2297 // Compute size of compile unit header
2298 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2299 sizeof(int16_t) + // DWARF version number
2300 sizeof(int32_t) + // Offset Into Abbrev. Section
2301 sizeof(int8_t); // Pointer Size (in bytes)
2302 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2305 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2306 CE = DW_CUs.end(); CI != CE; ++CI) {
2307 CompileUnit *Unit = CI->second;
2308 // Compute size of compile unit header
2309 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2310 sizeof(int16_t) + // DWARF version number
2311 sizeof(int32_t) + // Offset Into Abbrev. Section
2312 sizeof(int8_t); // Pointer Size (in bytes)
2313 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2317 /// EmitDebugInfo - Emit the debug info section.
2319 void EmitDebugInfo() {
2320 // Start debug info section.
2321 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2323 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2324 CE = DW_CUs.end(); CI != CE; ++CI) {
2325 CompileUnit *Unit = CI->second;
2328 DIE *Die = Unit->getDie();
2329 // Emit the compile units header.
2330 EmitLabel("info_begin", Unit->getID());
2331 // Emit size of content not including length itself
2332 unsigned ContentSize = Die->getSize() +
2333 sizeof(int16_t) + // DWARF version number
2334 sizeof(int32_t) + // Offset Into Abbrev. Section
2335 sizeof(int8_t) + // Pointer Size (in bytes)
2336 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2338 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2339 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2340 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2341 Asm->EOL("Offset Into Abbrev. Section");
2342 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2345 // FIXME - extra padding for gdb bug.
2346 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2347 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2348 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2349 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2350 EmitLabel("info_end", Unit->getID());
2358 /// EmitAbbreviations - Emit the abbreviation section.
2360 void EmitAbbreviations() const {
2361 // Check to see if it is worth the effort.
2362 if (!Abbreviations.empty()) {
2363 // Start the debug abbrev section.
2364 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2366 EmitLabel("abbrev_begin", 0);
2368 // For each abbrevation.
2369 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2370 // Get abbreviation data
2371 const DIEAbbrev *Abbrev = Abbreviations[i];
2373 // Emit the abbrevations code (base 1 index.)
2374 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2375 Asm->EOL("Abbreviation Code");
2377 // Emit the abbreviations data.
2378 Abbrev->Emit(*this);
2383 // Mark end of abbreviations.
2384 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2386 EmitLabel("abbrev_end", 0);
2392 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2393 /// the line matrix.
2395 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2396 // Define last address of section.
2397 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2398 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2399 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2400 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2402 // Mark end of matrix.
2403 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2404 Asm->EmitULEB128Bytes(1); Asm->EOL();
2405 Asm->EmitInt8(1); Asm->EOL();
2408 /// EmitDebugLines - Emit source line information.
2410 void EmitDebugLines() {
2411 // If the target is using .loc/.file, the assembler will be emitting the
2412 // .debug_line table automatically.
2413 if (TAI->hasDotLocAndDotFile())
2416 // Minimum line delta, thus ranging from -10..(255-10).
2417 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2418 // Maximum line delta, thus ranging from -10..(255-10).
2419 const int MaxLineDelta = 255 + MinLineDelta;
2421 // Start the dwarf line section.
2422 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2424 // Construct the section header.
2426 EmitDifference("line_end", 0, "line_begin", 0, true);
2427 Asm->EOL("Length of Source Line Info");
2428 EmitLabel("line_begin", 0);
2430 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2432 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2433 Asm->EOL("Prolog Length");
2434 EmitLabel("line_prolog_begin", 0);
2436 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2438 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2440 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2442 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2444 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2446 // Line number standard opcode encodings argument count
2447 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2448 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2449 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2450 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2451 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2452 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2453 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2454 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2455 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2457 // Emit directories.
2458 for (unsigned DirectoryID = 1, NDID = Directories.size();
2459 DirectoryID <= NDID; ++DirectoryID) {
2460 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2462 Asm->EmitInt8(0); Asm->EOL("End of directories");
2465 for (unsigned SourceID = 1, NSID = SrcFiles.size();
2466 SourceID <= NSID; ++SourceID) {
2467 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2468 Asm->EmitString(SourceFile.getName());
2470 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2471 Asm->EOL("Directory #");
2472 Asm->EmitULEB128Bytes(0);
2473 Asm->EOL("Mod date");
2474 Asm->EmitULEB128Bytes(0);
2475 Asm->EOL("File size");
2477 Asm->EmitInt8(0); Asm->EOL("End of files");
2479 EmitLabel("line_prolog_end", 0);
2481 // A sequence for each text section.
2482 unsigned SecSrcLinesSize = SectionSourceLines.size();
2484 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2485 // Isolate current sections line info.
2486 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2489 const Section* S = SectionMap[j + 1];
2490 Asm->EOL(std::string("Section ") + S->getName());
2494 // Dwarf assumes we start with first line of first source file.
2495 unsigned Source = 1;
2498 // Construct rows of the address, source, line, column matrix.
2499 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2500 const SrcLineInfo &LineInfo = LineInfos[i];
2501 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2502 if (!LabelID) continue;
2504 unsigned SourceID = LineInfo.getSourceID();
2505 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2506 unsigned DirectoryID = SourceFile.getDirectoryID();
2508 Asm->EOL(Directories[DirectoryID]
2509 + SourceFile.getName()
2511 + utostr_32(LineInfo.getLine()));
2515 // Define the line address.
2516 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2517 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2518 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2519 EmitReference("label", LabelID); Asm->EOL("Location label");
2521 // If change of source, then switch to the new source.
2522 if (Source != LineInfo.getSourceID()) {
2523 Source = LineInfo.getSourceID();
2524 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2525 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2528 // If change of line.
2529 if (Line != LineInfo.getLine()) {
2530 // Determine offset.
2531 int Offset = LineInfo.getLine() - Line;
2532 int Delta = Offset - MinLineDelta;
2535 Line = LineInfo.getLine();
2537 // If delta is small enough and in range...
2538 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2539 // ... then use fast opcode.
2540 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2542 // ... otherwise use long hand.
2543 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2544 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2545 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2548 // Copy the previous row (different address or source)
2549 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2553 EmitEndOfLineMatrix(j + 1);
2556 if (SecSrcLinesSize == 0)
2557 // Because we're emitting a debug_line section, we still need a line
2558 // table. The linker and friends expect it to exist. If there's nothing to
2559 // put into it, emit an empty table.
2560 EmitEndOfLineMatrix(1);
2562 EmitLabel("line_end", 0);
2567 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2569 void EmitCommonDebugFrame() {
2570 if (!TAI->doesDwarfRequireFrameSection())
2574 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2575 TargetFrameInfo::StackGrowsUp ?
2576 TD->getPointerSize() : -TD->getPointerSize();
2578 // Start the dwarf frame section.
2579 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2581 EmitLabel("debug_frame_common", 0);
2582 EmitDifference("debug_frame_common_end", 0,
2583 "debug_frame_common_begin", 0, true);
2584 Asm->EOL("Length of Common Information Entry");
2586 EmitLabel("debug_frame_common_begin", 0);
2587 Asm->EmitInt32((int)DW_CIE_ID);
2588 Asm->EOL("CIE Identifier Tag");
2589 Asm->EmitInt8(DW_CIE_VERSION);
2590 Asm->EOL("CIE Version");
2591 Asm->EmitString("");
2592 Asm->EOL("CIE Augmentation");
2593 Asm->EmitULEB128Bytes(1);
2594 Asm->EOL("CIE Code Alignment Factor");
2595 Asm->EmitSLEB128Bytes(stackGrowth);
2596 Asm->EOL("CIE Data Alignment Factor");
2597 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2598 Asm->EOL("CIE RA Column");
2600 std::vector<MachineMove> Moves;
2601 RI->getInitialFrameState(Moves);
2603 EmitFrameMoves(NULL, 0, Moves, false);
2605 Asm->EmitAlignment(2, 0, 0, false);
2606 EmitLabel("debug_frame_common_end", 0);
2611 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2613 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2614 if (!TAI->doesDwarfRequireFrameSection())
2617 // Start the dwarf frame section.
2618 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2620 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2621 "debug_frame_begin", DebugFrameInfo.Number, true);
2622 Asm->EOL("Length of Frame Information Entry");
2624 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2626 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2628 Asm->EOL("FDE CIE offset");
2630 EmitReference("func_begin", DebugFrameInfo.Number);
2631 Asm->EOL("FDE initial location");
2632 EmitDifference("func_end", DebugFrameInfo.Number,
2633 "func_begin", DebugFrameInfo.Number);
2634 Asm->EOL("FDE address range");
2636 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2639 Asm->EmitAlignment(2, 0, 0, false);
2640 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2645 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2647 void EmitDebugPubNames() {
2648 // Start the dwarf pubnames section.
2649 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2651 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2652 CE = DW_CUs.end(); CI != CE; ++CI) {
2653 CompileUnit *Unit = CI->second;
2657 EmitDifference("pubnames_end", Unit->getID(),
2658 "pubnames_begin", Unit->getID(), true);
2659 Asm->EOL("Length of Public Names Info");
2661 EmitLabel("pubnames_begin", Unit->getID());
2663 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2665 EmitSectionOffset("info_begin", "section_info",
2666 Unit->getID(), 0, true, false);
2667 Asm->EOL("Offset of Compilation Unit Info");
2669 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2671 Asm->EOL("Compilation Unit Length");
2673 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2675 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2678 const std::string &Name = GI->first;
2679 DIE * Entity = GI->second;
2681 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2682 Asm->EmitString(Name); Asm->EOL("External Name");
2685 Asm->EmitInt32(0); Asm->EOL("End Mark");
2686 EmitLabel("pubnames_end", Unit->getID());
2694 /// EmitDebugStr - Emit visible names into a debug str section.
2696 void EmitDebugStr() {
2697 // Check to see if it is worth the effort.
2698 if (!StringPool.empty()) {
2699 // Start the dwarf str section.
2700 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2702 // For each of strings in the string pool.
2703 for (unsigned StringID = 1, N = StringPool.size();
2704 StringID <= N; ++StringID) {
2705 // Emit a label for reference from debug information entries.
2706 EmitLabel("string", StringID);
2707 // Emit the string itself.
2708 const std::string &String = StringPool[StringID];
2709 Asm->EmitString(String); Asm->EOL();
2716 /// EmitDebugLoc - Emit visible names into a debug loc section.
2718 void EmitDebugLoc() {
2719 // Start the dwarf loc section.
2720 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2725 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2727 void EmitDebugARanges() {
2728 // Start the dwarf aranges section.
2729 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2733 CompileUnit *Unit = GetBaseCompileUnit();
2735 // Don't include size of length
2736 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2738 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2740 EmitReference("info_begin", Unit->getID());
2741 Asm->EOL("Offset of Compilation Unit Info");
2743 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2745 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2747 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2748 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2751 EmitReference("text_begin", 0); Asm->EOL("Address");
2752 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2754 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2755 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2761 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2763 void EmitDebugRanges() {
2764 // Start the dwarf ranges section.
2765 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2770 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2772 void EmitDebugMacInfo() {
2773 if (TAI->doesSupportMacInfoSection()) {
2774 // Start the dwarf macinfo section.
2775 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2781 /// ConstructCompileUnits - Create a compile unit DIEs.
2782 void ConstructCompileUnits() {
2783 std::string CUName = "llvm.dbg.compile_units";
2784 std::vector<GlobalVariable*> Result;
2785 getGlobalVariablesUsing(*M, CUName, Result);
2786 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2787 RE = Result.end(); RI != RE; ++RI) {
2788 DICompileUnit DIUnit(*RI);
2789 unsigned ID = RecordSource(DIUnit.getDirectory(),
2790 DIUnit.getFilename());
2792 DIE *Die = new DIE(DW_TAG_compile_unit);
2793 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2794 DWLabel("section_line", 0), DWLabel("section_line", 0),
2796 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer());
2797 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2798 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit.getFilename());
2799 if (!DIUnit.getDirectory().empty())
2800 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit.getDirectory());
2801 if (DIUnit.isOptimized())
2802 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2803 const std::string &Flags = DIUnit.getFlags();
2805 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2806 unsigned RVer = DIUnit.getRunTimeVersion();
2808 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2810 CompileUnit *Unit = new CompileUnit(ID, Die);
2811 if (DIUnit.isMain()) {
2812 assert(!MainCU && "Multiple main compile units are found!");
2815 DW_CUs[DIUnit.getGV()] = Unit;
2819 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2820 /// visible global variables.
2821 void ConstructGlobalVariableDIEs() {
2822 std::string GVName = "llvm.dbg.global_variables";
2823 std::vector<GlobalVariable*> Result;
2824 getGlobalVariablesUsing(*M, GVName, Result);
2825 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
2826 GVE = Result.end(); GVI != GVE; ++GVI) {
2827 DIGlobalVariable DI_GV(*GVI);
2828 CompileUnit *DW_Unit = MainCU;
2830 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2832 // Check for pre-existence.
2833 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2836 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2839 DIEBlock *Block = new DIEBlock();
2840 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2841 AddObjectLabel(Block, 0, DW_FORM_udata,
2842 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2843 AddBlock(VariableDie, DW_AT_location, 0, Block);
2848 //Add to context owner.
2849 DW_Unit->getDie()->AddChild(VariableDie);
2851 //Expose as global. FIXME - need to check external flag.
2852 DW_Unit->AddGlobal(DI_GV.getName(), VariableDie);
2856 /// ConstructSubprograms - Create DIEs for each of the externally visible
2858 void ConstructSubprograms() {
2860 std::string SPName = "llvm.dbg.subprograms";
2861 std::vector<GlobalVariable*> Result;
2862 getGlobalVariablesUsing(*M, SPName, Result);
2863 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2864 RE = Result.end(); RI != RE; ++RI) {
2866 DISubprogram SP(*RI);
2867 CompileUnit *Unit = MainCU;
2869 Unit = FindCompileUnit(SP.getCompileUnit());
2871 // Check for pre-existence.
2872 DIE *&Slot = Unit->getDieMapSlotFor(SP.getGV());
2875 if (!SP.isDefinition())
2876 // This is a method declaration which will be handled while
2877 // constructing class type.
2880 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2883 Slot = SubprogramDie;
2884 //Add to context owner.
2885 Unit->getDie()->AddChild(SubprogramDie);
2887 Unit->AddGlobal(SP.getName(), SubprogramDie);
2892 //===--------------------------------------------------------------------===//
2893 // Main entry points.
2895 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2896 : Dwarf(OS, A, T, "dbg")
2898 , AbbreviationsSet(InitAbbreviationsSetSize)
2900 , ValuesSet(InitValuesSetSize)
2904 , SectionSourceLines()
2907 , RootDbgScope(NULL)
2910 virtual ~DwarfDebug() {
2911 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2915 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2916 /// This is inovked by the target AsmPrinter.
2917 void SetDebugInfo(MachineModuleInfo *mmi) {
2918 // Create all the compile unit DIEs.
2919 ConstructCompileUnits();
2926 MMI->setDebugInfoAvailability(true);
2928 // Create DIEs for each of the externally visible global variables.
2929 ConstructGlobalVariableDIEs();
2931 // Create DIEs for each of the externally visible subprograms.
2932 ConstructSubprograms();
2934 // Prime section data.
2935 SectionMap.insert(TAI->getTextSection());
2937 // Print out .file directives to specify files for .loc directives. These
2938 // are printed out early so that they precede any .loc directives.
2939 if (TAI->hasDotLocAndDotFile()) {
2940 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
2941 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
2942 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
2943 assert(AppendOk && "Could not append filename to directory!");
2945 Asm->EmitFile(i, FullPath.toString());
2950 // Emit initial sections
2954 /// BeginModule - Emit all Dwarf sections that should come prior to the
2956 void BeginModule(Module *M) {
2960 /// EndModule - Emit all Dwarf sections that should come after the content.
2963 if (!ShouldEmitDwarf()) return;
2965 // Standard sections final addresses.
2966 Asm->SwitchToSection(TAI->getTextSection());
2967 EmitLabel("text_end", 0);
2968 Asm->SwitchToSection(TAI->getDataSection());
2969 EmitLabel("data_end", 0);
2971 // End text sections.
2972 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2973 Asm->SwitchToSection(SectionMap[i]);
2974 EmitLabel("section_end", i);
2977 // Emit common frame information.
2978 EmitCommonDebugFrame();
2980 // Emit function debug frame information
2981 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2982 E = DebugFrames.end(); I != E; ++I)
2983 EmitFunctionDebugFrame(*I);
2985 // Compute DIE offsets and sizes.
2988 // Emit all the DIEs into a debug info section
2991 // Corresponding abbreviations into a abbrev section.
2992 EmitAbbreviations();
2994 // Emit source line correspondence into a debug line section.
2997 // Emit info into a debug pubnames section.
2998 EmitDebugPubNames();
3000 // Emit info into a debug str section.
3003 // Emit info into a debug loc section.
3006 // Emit info into a debug aranges section.
3009 // Emit info into a debug ranges section.
3012 // Emit info into a debug macinfo section.
3016 /// BeginFunction - Gather pre-function debug information. Assumes being
3017 /// emitted immediately after the function entry point.
3018 void BeginFunction(MachineFunction *MF) {
3021 if (!ShouldEmitDwarf()) return;
3023 // Begin accumulating function debug information.
3024 MMI->BeginFunction(MF);
3026 // Assumes in correct section after the entry point.
3027 EmitLabel("func_begin", ++SubprogramCount);
3029 // Emit label for the implicitly defined dbg.stoppoint at the start of
3031 if (!Lines.empty()) {
3032 const SrcLineInfo &LineInfo = Lines[0];
3033 Asm->printLabel(LineInfo.getLabelID());
3037 /// EndFunction - Gather and emit post-function debug information.
3039 void EndFunction(MachineFunction *MF) {
3040 if (!ShouldEmitDwarf()) return;
3042 // Define end label for subprogram.
3043 EmitLabel("func_end", SubprogramCount);
3045 // Get function line info.
3046 if (!Lines.empty()) {
3047 // Get section line info.
3048 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3049 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3050 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3051 // Append the function info to section info.
3052 SectionLineInfos.insert(SectionLineInfos.end(),
3053 Lines.begin(), Lines.end());
3056 // Construct scopes for subprogram.
3058 ConstructRootDbgScope(RootDbgScope);
3060 // FIXME: This is wrong. We are essentially getting past a problem with
3061 // debug information not being able to handle unreachable blocks that have
3062 // debug information in them. In particular, those unreachable blocks that
3063 // have "region end" info in them. That situation results in the "root
3064 // scope" not being created. If that's the case, then emit a "default"
3065 // scope, i.e., one that encompasses the whole function. This isn't
3066 // desirable. And a better way of handling this (and all of the debugging
3067 // information) needs to be explored.
3068 ConstructDefaultDbgScope(MF);
3070 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3071 MMI->getFrameMoves()));
3075 delete RootDbgScope;
3076 DbgScopeMap.clear();
3077 RootDbgScope = NULL;
3084 /// ValidDebugInfo - Return true if V represents valid debug info value.
3085 bool ValidDebugInfo(Value *V) {
3093 GlobalVariable *GV = getGlobalVariable(V);
3097 if (GV->getLinkage() != GlobalValue::InternalLinkage
3098 && GV->getLinkage() != GlobalValue::LinkOnceLinkage)
3101 DIDescriptor DI(GV);
3102 // Check current version. Allow Version6 for now.
3103 unsigned Version = DI.getVersion();
3104 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
3107 unsigned Tag = DI.getTag();
3109 case DW_TAG_variable:
3110 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3112 case DW_TAG_compile_unit:
3113 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3115 case DW_TAG_subprogram:
3116 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3125 /// RecordSourceLine - Records location information and associates it with a
3126 /// label. Returns a unique label ID used to generate a label and provide
3127 /// correspondence to the source line list.
3128 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3129 CompileUnit *Unit = DW_CUs[V];
3130 assert(Unit && "Unable to find CompileUnit");
3131 unsigned ID = MMI->NextLabelID();
3132 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3136 /// RecordSourceLine - Records location information and associates it with a
3137 /// label. Returns a unique label ID used to generate a label and provide
3138 /// correspondence to the source line list.
3139 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3140 unsigned ID = MMI->NextLabelID();
3141 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3145 unsigned getRecordSourceLineCount() {
3146 return Lines.size();
3149 /// RecordSource - Register a source file with debug info. Returns an source
3151 unsigned RecordSource(const std::string &Directory,
3152 const std::string &File) {
3153 unsigned DID = Directories.insert(Directory);
3154 return SrcFiles.insert(SrcFileInfo(DID,File));
3157 /// RecordRegionStart - Indicate the start of a region.
3159 unsigned RecordRegionStart(GlobalVariable *V) {
3160 DbgScope *Scope = getOrCreateScope(V);
3161 unsigned ID = MMI->NextLabelID();
3162 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3166 /// RecordRegionEnd - Indicate the end of a region.
3168 unsigned RecordRegionEnd(GlobalVariable *V) {
3169 DbgScope *Scope = getOrCreateScope(V);
3170 unsigned ID = MMI->NextLabelID();
3171 Scope->setEndLabelID(ID);
3175 /// RecordVariable - Indicate the declaration of a local variable.
3177 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3178 DIDescriptor Desc(GV);
3179 DbgScope *Scope = NULL;
3180 if (Desc.getTag() == DW_TAG_variable) {
3181 // GV is a global variable.
3182 DIGlobalVariable DG(GV);
3183 Scope = getOrCreateScope(DG.getContext().getGV());
3185 // or GV is a local variable.
3187 Scope = getOrCreateScope(DV.getContext().getGV());
3189 assert(Scope && "Unable to find variable' scope");
3190 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3191 Scope->AddVariable(DV);
3195 //===----------------------------------------------------------------------===//
3196 /// DwarfException - Emits Dwarf exception handling directives.
3198 class DwarfException : public Dwarf {
3199 struct FunctionEHFrameInfo {
3202 unsigned PersonalityIndex;
3204 bool hasLandingPads;
3205 std::vector<MachineMove> Moves;
3206 const Function * function;
3208 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3210 const std::vector<MachineMove> &M,
3212 FnName(FN), Number(Num), PersonalityIndex(P),
3213 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3216 std::vector<FunctionEHFrameInfo> EHFrames;
3218 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3220 bool shouldEmitTable;
3222 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3223 /// should be emitted.
3224 bool shouldEmitMoves;
3226 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3227 /// should be emitted.
3228 bool shouldEmitTableModule;
3230 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3231 /// should be emitted.
3232 bool shouldEmitMovesModule;
3234 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3236 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3237 // Size and sign of stack growth.
3239 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3240 TargetFrameInfo::StackGrowsUp ?
3241 TD->getPointerSize() : -TD->getPointerSize();
3243 // Begin eh frame section.
3244 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3246 if (!TAI->doesRequireNonLocalEHFrameLabel())
3247 O << TAI->getEHGlobalPrefix();
3248 O << "EH_frame" << Index << ":\n";
3249 EmitLabel("section_eh_frame", Index);
3251 // Define base labels.
3252 EmitLabel("eh_frame_common", Index);
3254 // Define the eh frame length.
3255 EmitDifference("eh_frame_common_end", Index,
3256 "eh_frame_common_begin", Index, true);
3257 Asm->EOL("Length of Common Information Entry");
3260 EmitLabel("eh_frame_common_begin", Index);
3261 Asm->EmitInt32((int)0);
3262 Asm->EOL("CIE Identifier Tag");
3263 Asm->EmitInt8(DW_CIE_VERSION);
3264 Asm->EOL("CIE Version");
3266 // The personality presence indicates that language specific information
3267 // will show up in the eh frame.
3268 Asm->EmitString(Personality ? "zPLR" : "zR");
3269 Asm->EOL("CIE Augmentation");
3271 // Round out reader.
3272 Asm->EmitULEB128Bytes(1);
3273 Asm->EOL("CIE Code Alignment Factor");
3274 Asm->EmitSLEB128Bytes(stackGrowth);
3275 Asm->EOL("CIE Data Alignment Factor");
3276 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3277 Asm->EOL("CIE Return Address Column");
3279 // If there is a personality, we need to indicate the functions location.
3281 Asm->EmitULEB128Bytes(7);
3282 Asm->EOL("Augmentation Size");
3284 if (TAI->getNeedsIndirectEncoding()) {
3285 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3286 Asm->EOL("Personality (pcrel sdata4 indirect)");
3288 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3289 Asm->EOL("Personality (pcrel sdata4)");
3292 PrintRelDirective(true);
3293 O << TAI->getPersonalityPrefix();
3294 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3295 O << TAI->getPersonalitySuffix();
3296 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3297 O << "-" << TAI->getPCSymbol();
3298 Asm->EOL("Personality");
3300 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3301 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3303 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3304 Asm->EOL("FDE Encoding (pcrel sdata4)");
3306 Asm->EmitULEB128Bytes(1);
3307 Asm->EOL("Augmentation Size");
3309 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3310 Asm->EOL("FDE Encoding (pcrel sdata4)");
3313 // Indicate locations of general callee saved registers in frame.
3314 std::vector<MachineMove> Moves;
3315 RI->getInitialFrameState(Moves);
3316 EmitFrameMoves(NULL, 0, Moves, true);
3318 // On Darwin the linker honors the alignment of eh_frame, which means it
3319 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3320 // you get holes which confuse readers of eh_frame.
3321 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3323 EmitLabel("eh_frame_common_end", Index);
3328 /// EmitEHFrame - Emit function exception frame information.
3330 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3331 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3333 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3335 // Externally visible entry into the functions eh frame info.
3336 // If the corresponding function is static, this should not be
3337 // externally visible.
3338 if (linkage != Function::InternalLinkage &&
3339 linkage != Function::PrivateLinkage) {
3340 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3341 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3344 // If corresponding function is weak definition, this should be too.
3345 if ((linkage == Function::WeakLinkage ||
3346 linkage == Function::LinkOnceLinkage) &&
3347 TAI->getWeakDefDirective())
3348 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3350 // If there are no calls then you can't unwind. This may mean we can
3351 // omit the EH Frame, but some environments do not handle weak absolute
3353 // If UnwindTablesMandatory is set we cannot do this optimization; the
3354 // unwind info is to be available for non-EH uses.
3355 if (!EHFrameInfo.hasCalls &&
3356 !UnwindTablesMandatory &&
3357 ((linkage != Function::WeakLinkage &&
3358 linkage != Function::LinkOnceLinkage) ||
3359 !TAI->getWeakDefDirective() ||
3360 TAI->getSupportsWeakOmittedEHFrame()))
3362 O << EHFrameInfo.FnName << " = 0\n";
3363 // This name has no connection to the function, so it might get
3364 // dead-stripped when the function is not, erroneously. Prohibit
3365 // dead-stripping unconditionally.
3366 if (const char *UsedDirective = TAI->getUsedDirective())
3367 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3369 O << EHFrameInfo.FnName << ":\n";
3372 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3373 "eh_frame_begin", EHFrameInfo.Number, true);
3374 Asm->EOL("Length of Frame Information Entry");
3376 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3378 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3379 PrintRelDirective(true, true);
3380 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3382 if (!TAI->isAbsoluteEHSectionOffsets())
3383 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3385 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3386 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3390 Asm->EOL("FDE CIE offset");
3392 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3393 Asm->EOL("FDE initial location");
3394 EmitDifference("eh_func_end", EHFrameInfo.Number,
3395 "eh_func_begin", EHFrameInfo.Number, true);
3396 Asm->EOL("FDE address range");
3398 // If there is a personality and landing pads then point to the language
3399 // specific data area in the exception table.
3400 if (EHFrameInfo.PersonalityIndex) {
3401 Asm->EmitULEB128Bytes(4);
3402 Asm->EOL("Augmentation size");
3404 if (EHFrameInfo.hasLandingPads)
3405 EmitReference("exception", EHFrameInfo.Number, true, true);
3407 Asm->EmitInt32((int)0);
3408 Asm->EOL("Language Specific Data Area");
3410 Asm->EmitULEB128Bytes(0);
3411 Asm->EOL("Augmentation size");
3414 // Indicate locations of function specific callee saved registers in
3416 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3419 // On Darwin the linker honors the alignment of eh_frame, which means it
3420 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3421 // you get holes which confuse readers of eh_frame.
3422 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3424 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3426 // If the function is marked used, this table should be also. We cannot
3427 // make the mark unconditional in this case, since retaining the table
3428 // also retains the function in this case, and there is code around
3429 // that depends on unused functions (calling undefined externals) being
3430 // dead-stripped to link correctly. Yes, there really is.
3431 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3432 if (const char *UsedDirective = TAI->getUsedDirective())
3433 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3437 /// EmitExceptionTable - Emit landing pads and actions.
3439 /// The general organization of the table is complex, but the basic concepts
3440 /// are easy. First there is a header which describes the location and
3441 /// organization of the three components that follow.
3442 /// 1. The landing pad site information describes the range of code covered
3443 /// by the try. In our case it's an accumulation of the ranges covered
3444 /// by the invokes in the try. There is also a reference to the landing
3445 /// pad that handles the exception once processed. Finally an index into
3446 /// the actions table.
3447 /// 2. The action table, in our case, is composed of pairs of type ids
3448 /// and next action offset. Starting with the action index from the
3449 /// landing pad site, each type Id is checked for a match to the current
3450 /// exception. If it matches then the exception and type id are passed
3451 /// on to the landing pad. Otherwise the next action is looked up. This
3452 /// chain is terminated with a next action of zero. If no type id is
3453 /// found the the frame is unwound and handling continues.
3454 /// 3. Type id table contains references to all the C++ typeinfo for all
3455 /// catches in the function. This tables is reversed indexed base 1.
3457 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3458 static unsigned SharedTypeIds(const LandingPadInfo *L,
3459 const LandingPadInfo *R) {
3460 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3461 unsigned LSize = LIds.size(), RSize = RIds.size();
3462 unsigned MinSize = LSize < RSize ? LSize : RSize;
3465 for (; Count != MinSize; ++Count)
3466 if (LIds[Count] != RIds[Count])
3472 /// PadLT - Order landing pads lexicographically by type id.
3473 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3474 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3475 unsigned LSize = LIds.size(), RSize = RIds.size();
3476 unsigned MinSize = LSize < RSize ? LSize : RSize;
3478 for (unsigned i = 0; i != MinSize; ++i)
3479 if (LIds[i] != RIds[i])
3480 return LIds[i] < RIds[i];
3482 return LSize < RSize;
3486 static inline unsigned getEmptyKey() { return -1U; }
3487 static inline unsigned getTombstoneKey() { return -2U; }
3488 static unsigned getHashValue(const unsigned &Key) { return Key; }
3489 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3490 static bool isPod() { return true; }
3493 /// ActionEntry - Structure describing an entry in the actions table.
3494 struct ActionEntry {
3495 int ValueForTypeID; // The value to write - may not be equal to the type id.
3497 struct ActionEntry *Previous;
3500 /// PadRange - Structure holding a try-range and the associated landing pad.
3502 // The index of the landing pad.
3504 // The index of the begin and end labels in the landing pad's label lists.
3505 unsigned RangeIndex;
3508 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3510 /// CallSiteEntry - Structure describing an entry in the call-site table.
3511 struct CallSiteEntry {
3512 // The 'try-range' is BeginLabel .. EndLabel.
3513 unsigned BeginLabel; // zero indicates the start of the function.
3514 unsigned EndLabel; // zero indicates the end of the function.
3515 // The landing pad starts at PadLabel.
3516 unsigned PadLabel; // zero indicates that there is no landing pad.
3520 void EmitExceptionTable() {
3521 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3522 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3523 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3524 if (PadInfos.empty()) return;
3526 // Sort the landing pads in order of their type ids. This is used to fold
3527 // duplicate actions.
3528 SmallVector<const LandingPadInfo *, 64> LandingPads;
3529 LandingPads.reserve(PadInfos.size());
3530 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3531 LandingPads.push_back(&PadInfos[i]);
3532 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3534 // Negative type ids index into FilterIds, positive type ids index into
3535 // TypeInfos. The value written for a positive type id is just the type
3536 // id itself. For a negative type id, however, the value written is the
3537 // (negative) byte offset of the corresponding FilterIds entry. The byte
3538 // offset is usually equal to the type id, because the FilterIds entries
3539 // are written using a variable width encoding which outputs one byte per
3540 // entry as long as the value written is not too large, but can differ.
3541 // This kind of complication does not occur for positive type ids because
3542 // type infos are output using a fixed width encoding.
3543 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3544 SmallVector<int, 16> FilterOffsets;
3545 FilterOffsets.reserve(FilterIds.size());
3547 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3548 E = FilterIds.end(); I != E; ++I) {
3549 FilterOffsets.push_back(Offset);
3550 Offset -= TargetAsmInfo::getULEB128Size(*I);
3553 // Compute the actions table and gather the first action index for each
3554 // landing pad site.
3555 SmallVector<ActionEntry, 32> Actions;
3556 SmallVector<unsigned, 64> FirstActions;
3557 FirstActions.reserve(LandingPads.size());
3559 int FirstAction = 0;
3560 unsigned SizeActions = 0;
3561 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3562 const LandingPadInfo *LP = LandingPads[i];
3563 const std::vector<int> &TypeIds = LP->TypeIds;
3564 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3565 unsigned SizeSiteActions = 0;
3567 if (NumShared < TypeIds.size()) {
3568 unsigned SizeAction = 0;
3569 ActionEntry *PrevAction = 0;
3572 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3573 assert(Actions.size());
3574 PrevAction = &Actions.back();
3575 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3576 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3577 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3579 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3580 SizeAction += -PrevAction->NextAction;
3581 PrevAction = PrevAction->Previous;
3585 // Compute the actions.
3586 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3587 int TypeID = TypeIds[I];
3588 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3589 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3590 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3592 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3593 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3594 SizeSiteActions += SizeAction;
3596 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3597 Actions.push_back(Action);
3599 PrevAction = &Actions.back();
3602 // Record the first action of the landing pad site.
3603 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3604 } // else identical - re-use previous FirstAction
3606 FirstActions.push_back(FirstAction);
3608 // Compute this sites contribution to size.
3609 SizeActions += SizeSiteActions;
3612 // Compute the call-site table. The entry for an invoke has a try-range
3613 // containing the call, a non-zero landing pad and an appropriate action.
3614 // The entry for an ordinary call has a try-range containing the call and
3615 // zero for the landing pad and the action. Calls marked 'nounwind' have
3616 // no entry and must not be contained in the try-range of any entry - they
3617 // form gaps in the table. Entries must be ordered by try-range address.
3618 SmallVector<CallSiteEntry, 64> CallSites;
3620 RangeMapType PadMap;
3621 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3622 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3623 // try-ranges for them need be deduced.
3624 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3625 const LandingPadInfo *LandingPad = LandingPads[i];
3626 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3627 unsigned BeginLabel = LandingPad->BeginLabels[j];
3628 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3629 PadRange P = { i, j };
3630 PadMap[BeginLabel] = P;
3634 // The end label of the previous invoke or nounwind try-range.
3635 unsigned LastLabel = 0;
3637 // Whether there is a potentially throwing instruction (currently this means
3638 // an ordinary call) between the end of the previous try-range and now.
3639 bool SawPotentiallyThrowing = false;
3641 // Whether the last callsite entry was for an invoke.
3642 bool PreviousIsInvoke = false;
3644 // Visit all instructions in order of address.
3645 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3647 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3649 if (!MI->isLabel()) {
3650 SawPotentiallyThrowing |= MI->getDesc().isCall();
3654 unsigned BeginLabel = MI->getOperand(0).getImm();
3655 assert(BeginLabel && "Invalid label!");
3657 // End of the previous try-range?
3658 if (BeginLabel == LastLabel)
3659 SawPotentiallyThrowing = false;
3661 // Beginning of a new try-range?
3662 RangeMapType::iterator L = PadMap.find(BeginLabel);
3663 if (L == PadMap.end())
3664 // Nope, it was just some random label.
3667 PadRange P = L->second;
3668 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3670 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3671 "Inconsistent landing pad map!");
3673 // If some instruction between the previous try-range and this one may
3674 // throw, create a call-site entry with no landing pad for the region
3675 // between the try-ranges.
3676 if (SawPotentiallyThrowing) {
3677 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3678 CallSites.push_back(Site);
3679 PreviousIsInvoke = false;
3682 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3683 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3685 if (LandingPad->LandingPadLabel) {
3686 // This try-range is for an invoke.
3687 CallSiteEntry Site = {BeginLabel, LastLabel,
3688 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3690 // Try to merge with the previous call-site.
3691 if (PreviousIsInvoke) {
3692 CallSiteEntry &Prev = CallSites.back();
3693 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3694 // Extend the range of the previous entry.
3695 Prev.EndLabel = Site.EndLabel;
3700 // Otherwise, create a new call-site.
3701 CallSites.push_back(Site);
3702 PreviousIsInvoke = true;
3705 PreviousIsInvoke = false;
3709 // If some instruction between the previous try-range and the end of the
3710 // function may throw, create a call-site entry with no landing pad for the
3711 // region following the try-range.
3712 if (SawPotentiallyThrowing) {
3713 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3714 CallSites.push_back(Site);
3720 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3721 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3722 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3723 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3726 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3727 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3730 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3731 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3733 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3734 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3735 SizeSites + SizeActions + SizeTypes;
3737 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3738 sizeof(int8_t) + // TType format
3739 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3742 unsigned SizeAlign = (4 - TotalSize) & 3;
3744 // Begin the exception table.
3745 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3746 Asm->EmitAlignment(2, 0, 0, false);
3747 O << "GCC_except_table" << SubprogramCount << ":\n";
3748 for (unsigned i = 0; i != SizeAlign; ++i) {
3750 Asm->EOL("Padding");
3752 EmitLabel("exception", SubprogramCount);
3755 Asm->EmitInt8(DW_EH_PE_omit);
3756 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3757 Asm->EmitInt8(DW_EH_PE_absptr);
3758 Asm->EOL("TType format (DW_EH_PE_absptr)");
3759 Asm->EmitULEB128Bytes(TypeOffset);
3760 Asm->EOL("TType base offset");
3761 Asm->EmitInt8(DW_EH_PE_udata4);
3762 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3763 Asm->EmitULEB128Bytes(SizeSites);
3764 Asm->EOL("Call-site table length");
3766 // Emit the landing pad site information.
3767 for (unsigned i = 0; i < CallSites.size(); ++i) {
3768 CallSiteEntry &S = CallSites[i];
3769 const char *BeginTag;
3770 unsigned BeginNumber;
3772 if (!S.BeginLabel) {
3773 BeginTag = "eh_func_begin";
3774 BeginNumber = SubprogramCount;
3777 BeginNumber = S.BeginLabel;
3780 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3782 Asm->EOL("Region start");
3785 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3788 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3790 Asm->EOL("Region length");
3795 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3797 Asm->EOL("Landing pad");
3799 Asm->EmitULEB128Bytes(S.Action);
3803 // Emit the actions.
3804 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3805 ActionEntry &Action = Actions[I];
3807 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3808 Asm->EOL("TypeInfo index");
3809 Asm->EmitSLEB128Bytes(Action.NextAction);
3810 Asm->EOL("Next action");
3813 // Emit the type ids.
3814 for (unsigned M = TypeInfos.size(); M; --M) {
3815 GlobalVariable *GV = TypeInfos[M - 1];
3817 PrintRelDirective();
3820 O << Asm->getGlobalLinkName(GV);
3824 Asm->EOL("TypeInfo");
3827 // Emit the filter typeids.
3828 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3829 unsigned TypeID = FilterIds[j];
3830 Asm->EmitULEB128Bytes(TypeID);
3831 Asm->EOL("Filter TypeInfo index");
3834 Asm->EmitAlignment(2, 0, 0, false);
3838 //===--------------------------------------------------------------------===//
3839 // Main entry points.
3841 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3842 : Dwarf(OS, A, T, "eh")
3843 , shouldEmitTable(false)
3844 , shouldEmitMoves(false)
3845 , shouldEmitTableModule(false)
3846 , shouldEmitMovesModule(false)
3849 virtual ~DwarfException() {}
3851 /// SetModuleInfo - Set machine module information when it's known that pass
3852 /// manager has created it. Set by the target AsmPrinter.
3853 void SetModuleInfo(MachineModuleInfo *mmi) {
3857 /// BeginModule - Emit all exception information that should come prior to the
3859 void BeginModule(Module *M) {
3863 /// EndModule - Emit all exception information that should come after the
3866 if (shouldEmitMovesModule || shouldEmitTableModule) {
3867 const std::vector<Function *> Personalities = MMI->getPersonalities();
3868 for (unsigned i =0; i < Personalities.size(); ++i)
3869 EmitCommonEHFrame(Personalities[i], i);
3871 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3872 E = EHFrames.end(); I != E; ++I)
3877 /// BeginFunction - Gather pre-function exception information. Assumes being
3878 /// emitted immediately after the function entry point.
3879 void BeginFunction(MachineFunction *MF) {
3881 shouldEmitTable = shouldEmitMoves = false;
3882 if (MMI && TAI->doesSupportExceptionHandling()) {
3884 // Map all labels and get rid of any dead landing pads.
3885 MMI->TidyLandingPads();
3886 // If any landing pads survive, we need an EH table.
3887 if (MMI->getLandingPads().size())
3888 shouldEmitTable = true;
3890 // See if we need frame move info.
3891 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3892 shouldEmitMoves = true;
3894 if (shouldEmitMoves || shouldEmitTable)
3895 // Assumes in correct section after the entry point.
3896 EmitLabel("eh_func_begin", ++SubprogramCount);
3898 shouldEmitTableModule |= shouldEmitTable;
3899 shouldEmitMovesModule |= shouldEmitMoves;
3902 /// EndFunction - Gather and emit post-function exception information.
3904 void EndFunction() {
3905 if (shouldEmitMoves || shouldEmitTable) {
3906 EmitLabel("eh_func_end", SubprogramCount);
3907 EmitExceptionTable();
3909 // Save EH frame information
3911 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3913 MMI->getPersonalityIndex(),
3914 MF->getFrameInfo()->hasCalls(),
3915 !MMI->getLandingPads().empty(),
3916 MMI->getFrameMoves(),
3917 MF->getFunction()));
3922 } // End of namespace llvm
3924 //===----------------------------------------------------------------------===//
3926 /// Emit - Print the abbreviation using the specified Dwarf writer.
3928 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3929 // Emit its Dwarf tag type.
3930 DD.getAsm()->EmitULEB128Bytes(Tag);
3931 DD.getAsm()->EOL(TagString(Tag));
3933 // Emit whether it has children DIEs.
3934 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3935 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3937 // For each attribute description.
3938 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3939 const DIEAbbrevData &AttrData = Data[i];
3941 // Emit attribute type.
3942 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3943 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3946 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3947 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3950 // Mark end of abbreviation.
3951 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3952 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3956 void DIEAbbrev::print(std::ostream &O) {
3957 O << "Abbreviation @"
3958 << std::hex << (intptr_t)this << std::dec
3962 << ChildrenString(ChildrenFlag)
3965 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3967 << AttributeString(Data[i].getAttribute())
3969 << FormEncodingString(Data[i].getForm())
3973 void DIEAbbrev::dump() { print(cerr); }
3976 //===----------------------------------------------------------------------===//
3979 void DIEValue::dump() {
3984 //===----------------------------------------------------------------------===//
3986 /// EmitValue - Emit integer of appropriate size.
3988 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3990 case DW_FORM_flag: // Fall thru
3991 case DW_FORM_ref1: // Fall thru
3992 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3993 case DW_FORM_ref2: // Fall thru
3994 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3995 case DW_FORM_ref4: // Fall thru
3996 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3997 case DW_FORM_ref8: // Fall thru
3998 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3999 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4000 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4001 default: assert(0 && "DIE Value form not supported yet"); break;
4005 /// SizeOf - Determine size of integer value in bytes.
4007 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4009 case DW_FORM_flag: // Fall thru
4010 case DW_FORM_ref1: // Fall thru
4011 case DW_FORM_data1: return sizeof(int8_t);
4012 case DW_FORM_ref2: // Fall thru
4013 case DW_FORM_data2: return sizeof(int16_t);
4014 case DW_FORM_ref4: // Fall thru
4015 case DW_FORM_data4: return sizeof(int32_t);
4016 case DW_FORM_ref8: // Fall thru
4017 case DW_FORM_data8: return sizeof(int64_t);
4018 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4019 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4020 default: assert(0 && "DIE Value form not supported yet"); break;
4025 //===----------------------------------------------------------------------===//
4027 /// EmitValue - Emit string value.
4029 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4030 DD.getAsm()->EmitString(String);
4033 //===----------------------------------------------------------------------===//
4035 /// EmitValue - Emit label value.
4037 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4038 bool IsSmall = Form == DW_FORM_data4;
4039 DD.EmitReference(Label, false, IsSmall);
4042 /// SizeOf - Determine size of label value in bytes.
4044 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4045 if (Form == DW_FORM_data4) return 4;
4046 return DD.getTargetData()->getPointerSize();
4049 //===----------------------------------------------------------------------===//
4051 /// EmitValue - Emit label value.
4053 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4054 bool IsSmall = Form == DW_FORM_data4;
4055 DD.EmitReference(Label, false, IsSmall);
4058 /// SizeOf - Determine size of label value in bytes.
4060 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4061 if (Form == DW_FORM_data4) return 4;
4062 return DD.getTargetData()->getPointerSize();
4065 //===----------------------------------------------------------------------===//
4067 /// EmitValue - Emit delta value.
4069 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4070 bool IsSmall = Form == DW_FORM_data4;
4071 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4072 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4075 /// SizeOf - Determine size of delta value in bytes.
4077 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4078 if (Form == DW_FORM_data4) return 4;
4079 return DD.getTargetData()->getPointerSize();
4082 //===----------------------------------------------------------------------===//
4084 /// EmitValue - Emit delta value.
4086 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4087 bool IsSmall = Form == DW_FORM_data4;
4088 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4091 /// SizeOf - Determine size of delta value in bytes.
4093 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4094 if (Form == DW_FORM_data4) return 4;
4095 return DD.getTargetData()->getPointerSize();
4098 //===----------------------------------------------------------------------===//
4100 /// EmitValue - Emit debug information entry offset.
4102 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4103 DD.getAsm()->EmitInt32(Entry->getOffset());
4106 //===----------------------------------------------------------------------===//
4108 /// ComputeSize - calculate the size of the block.
4110 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4112 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4114 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4115 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4121 /// EmitValue - Emit block data.
4123 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4125 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4126 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4127 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4128 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4129 default: assert(0 && "Improper form for block"); break;
4132 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4134 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4136 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4140 /// SizeOf - Determine size of block data in bytes.
4142 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4144 case DW_FORM_block1: return Size + sizeof(int8_t);
4145 case DW_FORM_block2: return Size + sizeof(int16_t);
4146 case DW_FORM_block4: return Size + sizeof(int32_t);
4147 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4148 default: assert(0 && "Improper form for block"); break;
4153 //===----------------------------------------------------------------------===//
4154 /// DIE Implementation
4157 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4161 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4163 void DIE::AddSiblingOffset() {
4164 DIEInteger *DI = new DIEInteger(0);
4165 Values.insert(Values.begin(), DI);
4166 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4169 /// Profile - Used to gather unique data for the value folding set.
4171 void DIE::Profile(FoldingSetNodeID &ID) {
4174 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4175 ID.AddPointer(Children[i]);
4177 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4178 ID.AddPointer(Values[j]);
4182 void DIE::print(std::ostream &O, unsigned IncIndent) {
4183 static unsigned IndentCount = 0;
4184 IndentCount += IncIndent;
4185 const std::string Indent(IndentCount, ' ');
4186 bool isBlock = Abbrev.getTag() == 0;
4191 << "0x" << std::hex << (intptr_t)this << std::dec
4192 << ", Offset: " << Offset
4193 << ", Size: " << Size
4197 << TagString(Abbrev.getTag())
4199 << ChildrenString(Abbrev.getChildrenFlag());
4201 O << "Size: " << Size;
4205 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4208 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4212 O << AttributeString(Data[i].getAttribute());
4214 O << "Blk[" << i << "]";
4217 << FormEncodingString(Data[i].getForm())
4219 Values[i]->print(O);
4224 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4225 Children[j]->print(O, 4);
4228 if (!isBlock) O << "\n";
4229 IndentCount -= IncIndent;
4237 //===----------------------------------------------------------------------===//
4238 /// DwarfWriter Implementation
4241 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4244 DwarfWriter::~DwarfWriter() {
4249 /// BeginModule - Emit all Dwarf sections that should come prior to the
4251 void DwarfWriter::BeginModule(Module *M,
4252 MachineModuleInfo *MMI,
4253 raw_ostream &OS, AsmPrinter *A,
4254 const TargetAsmInfo *T) {
4255 DE = new DwarfException(OS, A, T);
4256 DD = new DwarfDebug(OS, A, T);
4259 DD->SetDebugInfo(MMI);
4260 DE->SetModuleInfo(MMI);
4263 /// EndModule - Emit all Dwarf sections that should come after the content.
4265 void DwarfWriter::EndModule() {
4270 /// BeginFunction - Gather pre-function debug information. Assumes being
4271 /// emitted immediately after the function entry point.
4272 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4273 DE->BeginFunction(MF);
4274 DD->BeginFunction(MF);
4277 /// EndFunction - Gather and emit post-function debug information.
4279 void DwarfWriter::EndFunction(MachineFunction *MF) {
4280 DD->EndFunction(MF);
4283 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4284 // Clear function debug information.
4288 /// ValidDebugInfo - Return true if V represents valid debug info value.
4289 bool DwarfWriter::ValidDebugInfo(Value *V) {
4290 return DD && DD->ValidDebugInfo(V);
4293 /// RecordSourceLine - Records location information and associates it with a
4294 /// label. Returns a unique label ID used to generate a label and provide
4295 /// correspondence to the source line list.
4296 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4298 return DD->RecordSourceLine(Line, Col, Src);
4301 /// RecordSource - Register a source file with debug info. Returns an source
4303 unsigned DwarfWriter::RecordSource(const std::string &Dir,
4304 const std::string &File) {
4305 return DD->RecordSource(Dir, File);
4308 /// RecordRegionStart - Indicate the start of a region.
4309 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4310 return DD->RecordRegionStart(V);
4313 /// RecordRegionEnd - Indicate the end of a region.
4314 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4315 return DD->RecordRegionEnd(V);
4318 /// getRecordSourceLineCount - Count source lines.
4319 unsigned DwarfWriter::getRecordSourceLineCount() {
4320 return DD->getRecordSourceLineCount();
4323 /// RecordVariable - Indicate the declaration of a local variable.
4325 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4326 DD->RecordVariable(GV, FrameIndex);