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/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
44 using namespace llvm::dwarf;
46 static RegisterPass<DwarfWriter>
47 X("dwarfwriter", "DWARF Information Writer");
48 char DwarfWriter::ID = 0;
52 //===----------------------------------------------------------------------===//
54 /// Configuration values for initial hash set sizes (log2).
56 static const unsigned InitDiesSetSize = 9; // 512
57 static const unsigned InitAbbreviationsSetSize = 9; // 512
58 static const unsigned InitValuesSetSize = 9; // 512
60 //===----------------------------------------------------------------------===//
61 /// Forward declarations.
66 //===----------------------------------------------------------------------===//
69 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
70 /// specified value in their initializer somewhere.
72 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
73 // Scan though value users.
74 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
75 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
76 // If the user is a GlobalVariable then add to result.
78 } else if (Constant *C = dyn_cast<Constant>(*I)) {
79 // If the user is a constant variable then scan its users
80 getGlobalVariablesUsing(C, Result);
85 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
86 /// named GlobalVariable.
88 getGlobalVariablesUsing(Module &M, const std::string &RootName,
89 std::vector<GlobalVariable*> &Result) {
90 std::vector<const Type*> FieldTypes;
91 FieldTypes.push_back(Type::Int32Ty);
92 FieldTypes.push_back(Type::Int32Ty);
94 // Get the GlobalVariable root.
95 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
96 StructType::get(FieldTypes));
98 // If present and linkonce then scan for users.
99 if (UseRoot && UseRoot->hasLinkOnceLinkage())
100 getGlobalVariablesUsing(UseRoot, Result);
103 //===----------------------------------------------------------------------===//
104 /// DWLabel - Labels are used to track locations in the assembler file.
105 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
106 /// where the tag is a category of label (Ex. location) and number is a value
107 /// unique in that category.
110 /// Tag - Label category tag. Should always be a staticly declared C string.
114 /// Number - Value to make label unique.
118 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
120 void Profile(FoldingSetNodeID &ID) const {
121 ID.AddString(std::string(Tag));
122 ID.AddInteger(Number);
126 void print(std::ostream *O) const {
129 void print(std::ostream &O) const {
131 if (Number) O << Number;
136 //===----------------------------------------------------------------------===//
137 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
138 /// Dwarf abbreviation.
139 class DIEAbbrevData {
141 /// Attribute - Dwarf attribute code.
145 /// Form - Dwarf form code.
150 DIEAbbrevData(unsigned A, unsigned F)
156 unsigned getAttribute() const { return Attribute; }
157 unsigned getForm() const { return Form; }
159 /// Profile - Used to gather unique data for the abbreviation folding set.
161 void Profile(FoldingSetNodeID &ID)const {
162 ID.AddInteger(Attribute);
167 //===----------------------------------------------------------------------===//
168 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
169 /// information object.
170 class DIEAbbrev : public FoldingSetNode {
172 /// Tag - Dwarf tag code.
176 /// Unique number for node.
180 /// ChildrenFlag - Dwarf children flag.
182 unsigned ChildrenFlag;
184 /// Data - Raw data bytes for abbreviation.
186 SmallVector<DIEAbbrevData, 8> Data;
190 DIEAbbrev(unsigned T, unsigned C)
198 unsigned getTag() const { return Tag; }
199 unsigned getNumber() const { return Number; }
200 unsigned getChildrenFlag() const { return ChildrenFlag; }
201 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
202 void setTag(unsigned T) { Tag = T; }
203 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
204 void setNumber(unsigned N) { Number = N; }
206 /// AddAttribute - Adds another set of attribute information to the
208 void AddAttribute(unsigned Attribute, unsigned Form) {
209 Data.push_back(DIEAbbrevData(Attribute, Form));
212 /// AddFirstAttribute - Adds a set of attribute information to the front
213 /// of the abbreviation.
214 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
215 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
218 /// Profile - Used to gather unique data for the abbreviation folding set.
220 void Profile(FoldingSetNodeID &ID) {
222 ID.AddInteger(ChildrenFlag);
224 // For each attribute description.
225 for (unsigned i = 0, N = Data.size(); i < N; ++i)
229 /// Emit - Print the abbreviation using the specified Dwarf writer.
231 void Emit(const DwarfDebug &DD) const;
234 void print(std::ostream *O) {
237 void print(std::ostream &O);
242 //===----------------------------------------------------------------------===//
243 /// DIE - A structured debug information entry. Has an abbreviation which
244 /// describes it's organization.
245 class DIE : public FoldingSetNode {
247 /// Abbrev - Buffer for constructing abbreviation.
251 /// Offset - Offset in debug info section.
255 /// Size - Size of instance + children.
261 std::vector<DIE *> Children;
263 /// Attributes values.
265 SmallVector<DIEValue*, 32> Values;
268 explicit DIE(unsigned Tag)
269 : Abbrev(Tag, DW_CHILDREN_no)
278 DIEAbbrev &getAbbrev() { return Abbrev; }
279 unsigned getAbbrevNumber() const {
280 return Abbrev.getNumber();
282 unsigned getTag() const { return Abbrev.getTag(); }
283 unsigned getOffset() const { return Offset; }
284 unsigned getSize() const { return Size; }
285 const std::vector<DIE *> &getChildren() const { return Children; }
286 SmallVector<DIEValue*, 32> &getValues() { return Values; }
287 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
288 void setOffset(unsigned O) { Offset = O; }
289 void setSize(unsigned S) { Size = S; }
291 /// AddValue - Add a value and attributes to a DIE.
293 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
294 Abbrev.AddAttribute(Attribute, Form);
295 Values.push_back(Value);
298 /// SiblingOffset - Return the offset of the debug information entry's
300 unsigned SiblingOffset() const { return Offset + Size; }
302 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
304 void AddSiblingOffset();
306 /// AddChild - Add a child to the DIE.
308 void AddChild(DIE *Child) {
309 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
310 Children.push_back(Child);
313 /// Detach - Detaches objects connected to it after copying.
319 /// Profile - Used to gather unique data for the value folding set.
321 void Profile(FoldingSetNodeID &ID) ;
324 void print(std::ostream *O, unsigned IncIndent = 0) {
325 if (O) print(*O, IncIndent);
327 void print(std::ostream &O, unsigned IncIndent = 0);
332 //===----------------------------------------------------------------------===//
333 /// DIEValue - A debug information entry value.
335 class DIEValue : public FoldingSetNode {
348 /// Type - Type of data stored in the value.
352 explicit DIEValue(unsigned T)
355 virtual ~DIEValue() {}
358 unsigned getType() const { return Type; }
360 // Implement isa/cast/dyncast.
361 static bool classof(const DIEValue *) { return true; }
363 /// EmitValue - Emit value via the Dwarf writer.
365 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
367 /// SizeOf - Return the size of a value in bytes.
369 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
371 /// Profile - Used to gather unique data for the value folding set.
373 virtual void Profile(FoldingSetNodeID &ID) = 0;
376 void print(std::ostream *O) {
379 virtual void print(std::ostream &O) = 0;
384 //===----------------------------------------------------------------------===//
385 /// DWInteger - An integer value DIE.
387 class DIEInteger : public DIEValue {
392 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
394 // Implement isa/cast/dyncast.
395 static bool classof(const DIEInteger *) { return true; }
396 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
398 /// BestForm - Choose the best form for integer.
400 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
402 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
403 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
404 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
406 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
407 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
408 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
410 return DW_FORM_data8;
413 /// EmitValue - Emit integer of appropriate size.
415 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
417 /// SizeOf - Determine size of integer value in bytes.
419 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
421 /// Profile - Used to gather unique data for the value folding set.
423 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
424 ID.AddInteger(isInteger);
425 ID.AddInteger(Integer);
427 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
430 virtual void print(std::ostream &O) {
431 O << "Int: " << (int64_t)Integer
432 << " 0x" << std::hex << Integer << std::dec;
437 //===----------------------------------------------------------------------===//
438 /// DIEString - A string value DIE.
440 class DIEString : public DIEValue {
442 const std::string String;
444 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
446 // Implement isa/cast/dyncast.
447 static bool classof(const DIEString *) { return true; }
448 static bool classof(const DIEValue *S) { return S->Type == isString; }
450 /// EmitValue - Emit string value.
452 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
454 /// SizeOf - Determine size of string value in bytes.
456 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
457 return String.size() + sizeof(char); // sizeof('\0');
460 /// Profile - Used to gather unique data for the value folding set.
462 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
463 ID.AddInteger(isString);
464 ID.AddString(String);
466 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
469 virtual void print(std::ostream &O) {
470 O << "Str: \"" << String << "\"";
475 //===----------------------------------------------------------------------===//
476 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
478 class DIEDwarfLabel : public DIEValue {
483 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
485 // Implement isa/cast/dyncast.
486 static bool classof(const DIEDwarfLabel *) { return true; }
487 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
489 /// EmitValue - Emit label value.
491 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
493 /// SizeOf - Determine size of label value in bytes.
495 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
497 /// Profile - Used to gather unique data for the value folding set.
499 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
500 ID.AddInteger(isLabel);
503 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
506 virtual void print(std::ostream &O) {
514 //===----------------------------------------------------------------------===//
515 /// DIEObjectLabel - A label to an object in code or data.
517 class DIEObjectLabel : public DIEValue {
519 const std::string Label;
521 explicit DIEObjectLabel(const std::string &L)
522 : DIEValue(isAsIsLabel), Label(L) {}
524 // Implement isa/cast/dyncast.
525 static bool classof(const DIEObjectLabel *) { return true; }
526 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
528 /// EmitValue - Emit label value.
530 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
532 /// SizeOf - Determine size of label value in bytes.
534 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
536 /// Profile - Used to gather unique data for the value folding set.
538 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
539 ID.AddInteger(isAsIsLabel);
542 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
545 virtual void print(std::ostream &O) {
546 O << "Obj: " << Label;
551 //===----------------------------------------------------------------------===//
552 /// DIESectionOffset - A section offset DIE.
554 class DIESectionOffset : public DIEValue {
557 const DWLabel Section;
561 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
562 bool isEH = false, bool useSet = true)
563 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
564 IsEH(isEH), UseSet(useSet) {}
566 // Implement isa/cast/dyncast.
567 static bool classof(const DIESectionOffset *) { return true; }
568 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
570 /// EmitValue - Emit section offset.
572 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
574 /// SizeOf - Determine size of section offset value in bytes.
576 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
578 /// Profile - Used to gather unique data for the value folding set.
580 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
581 const DWLabel &Section) {
582 ID.AddInteger(isSectionOffset);
585 // IsEH and UseSet are specific to the Label/Section that we will emit
586 // the offset for; so Label/Section are enough for uniqueness.
588 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
591 virtual void print(std::ostream &O) {
596 O << "-" << IsEH << "-" << UseSet;
601 //===----------------------------------------------------------------------===//
602 /// DIEDelta - A simple label difference DIE.
604 class DIEDelta : public DIEValue {
606 const DWLabel LabelHi;
607 const DWLabel LabelLo;
609 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
610 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
612 // Implement isa/cast/dyncast.
613 static bool classof(const DIEDelta *) { return true; }
614 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
616 /// EmitValue - Emit delta value.
618 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
620 /// SizeOf - Determine size of delta value in bytes.
622 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
624 /// Profile - Used to gather unique data for the value folding set.
626 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
627 const DWLabel &LabelLo) {
628 ID.AddInteger(isDelta);
632 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
635 virtual void print(std::ostream &O) {
644 //===----------------------------------------------------------------------===//
645 /// DIEntry - A pointer to another debug information entry. An instance of this
646 /// class can also be used as a proxy for a debug information entry not yet
647 /// defined (ie. types.)
648 class DIEntry : public DIEValue {
652 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
654 // Implement isa/cast/dyncast.
655 static bool classof(const DIEntry *) { return true; }
656 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
658 /// EmitValue - Emit debug information entry offset.
660 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
662 /// SizeOf - Determine size of debug information entry in bytes.
664 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
665 return sizeof(int32_t);
668 /// Profile - Used to gather unique data for the value folding set.
670 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
671 ID.AddInteger(isEntry);
672 ID.AddPointer(Entry);
674 virtual void Profile(FoldingSetNodeID &ID) {
675 ID.AddInteger(isEntry);
678 ID.AddPointer(Entry);
685 virtual void print(std::ostream &O) {
686 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
691 //===----------------------------------------------------------------------===//
692 /// DIEBlock - A block of values. Primarily used for location expressions.
694 class DIEBlock : public DIEValue, public DIE {
696 unsigned Size; // Size in bytes excluding size header.
706 // Implement isa/cast/dyncast.
707 static bool classof(const DIEBlock *) { return true; }
708 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
710 /// ComputeSize - calculate the size of the block.
712 unsigned ComputeSize(DwarfDebug &DD);
714 /// BestForm - Choose the best form for data.
716 unsigned BestForm() const {
717 if ((unsigned char)Size == Size) return DW_FORM_block1;
718 if ((unsigned short)Size == Size) return DW_FORM_block2;
719 if ((unsigned int)Size == Size) return DW_FORM_block4;
720 return DW_FORM_block;
723 /// EmitValue - Emit block data.
725 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
727 /// SizeOf - Determine size of block data in bytes.
729 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
732 /// Profile - Used to gather unique data for the value folding set.
734 virtual void Profile(FoldingSetNodeID &ID) {
735 ID.AddInteger(isBlock);
740 virtual void print(std::ostream &O) {
747 //===----------------------------------------------------------------------===//
748 /// CompileUnit - This dwarf writer support class manages information associate
749 /// with a source file.
752 /// ID - File identifier for source.
756 /// Die - Compile unit debug information entry.
760 /// GVToDieMap - Tracks the mapping of unit level debug informaton
761 /// variables to debug information entries.
762 DenseMap<GlobalVariable *, DIE *> GVToDieMap;
764 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
765 /// descriptors to debug information entries using a DIEntry proxy.
766 DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
768 /// Globals - A map of globally visible named entities for this unit.
770 std::map<std::string, DIE *> Globals;
772 /// DiesSet - Used to uniquely define dies within the compile unit.
774 FoldingSet<DIE> DiesSet;
776 /// Dies - List of all dies in the compile unit.
778 std::vector<DIE *> Dies;
781 CompileUnit(unsigned I, DIE *D)
782 : ID(I), Die(D), GVToDieMap(),
783 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
789 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
794 unsigned getID() const { return ID; }
795 DIE* getDie() const { return Die; }
796 std::map<std::string, DIE *> &getGlobals() { return Globals; }
798 /// hasContent - Return true if this compile unit has something to write out.
800 bool hasContent() const {
801 return !Die->getChildren().empty();
804 /// AddGlobal - Add a new global entity to the compile unit.
806 void AddGlobal(const std::string &Name, DIE *Die) {
810 /// getDieMapSlotFor - Returns the debug information entry map slot for the
811 /// specified debug variable.
812 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
813 return GVToDieMap[GV];
816 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
817 /// specified debug variable.
818 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
819 return GVToDIEntryMap[GV];
822 /// AddDie - Adds or interns the DIE to the compile unit.
824 DIE *AddDie(DIE &Buffer) {
828 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
831 Die = new DIE(Buffer);
832 DiesSet.InsertNode(Die, Where);
833 this->Die->AddChild(Die);
841 //===----------------------------------------------------------------------===//
842 /// Dwarf - Emits general Dwarf directives.
848 //===--------------------------------------------------------------------===//
849 // Core attributes used by the Dwarf writer.
853 /// O - Stream to .s file.
857 /// Asm - Target of Dwarf emission.
861 /// TAI - Target asm information.
862 const TargetAsmInfo *TAI;
864 /// TD - Target data.
865 const TargetData *TD;
867 /// RI - Register Information.
868 const TargetRegisterInfo *RI;
870 /// M - Current module.
874 /// MF - Current machine function.
878 /// MMI - Collected machine module information.
880 MachineModuleInfo *MMI;
882 /// SubprogramCount - The running count of functions being compiled.
884 unsigned SubprogramCount;
886 /// Flavor - A unique string indicating what dwarf producer this is, used to
888 const char * const Flavor;
891 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
896 , TD(Asm->TM.getTargetData())
897 , RI(Asm->TM.getRegisterInfo())
909 //===--------------------------------------------------------------------===//
912 AsmPrinter *getAsm() const { return Asm; }
913 MachineModuleInfo *getMMI() const { return MMI; }
914 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
915 const TargetData *getTargetData() const { return TD; }
917 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
919 if (isInSection && TAI->getDwarfSectionOffsetDirective())
920 O << TAI->getDwarfSectionOffsetDirective();
921 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
922 O << TAI->getData32bitsDirective();
924 O << TAI->getData64bitsDirective();
927 /// PrintLabelName - Print label name in form used by Dwarf writer.
929 void PrintLabelName(DWLabel Label) const {
930 PrintLabelName(Label.Tag, Label.Number);
932 void PrintLabelName(const char *Tag, unsigned Number) const {
933 O << TAI->getPrivateGlobalPrefix() << Tag;
934 if (Number) O << Number;
937 void PrintLabelName(const char *Tag, unsigned Number,
938 const char *Suffix) const {
939 O << TAI->getPrivateGlobalPrefix() << Tag;
940 if (Number) O << Number;
944 /// EmitLabel - Emit location label for internal use by Dwarf.
946 void EmitLabel(DWLabel Label) const {
947 EmitLabel(Label.Tag, Label.Number);
949 void EmitLabel(const char *Tag, unsigned Number) const {
950 PrintLabelName(Tag, Number);
954 /// EmitReference - Emit a reference to a label.
956 void EmitReference(DWLabel Label, bool IsPCRelative = false,
957 bool Force32Bit = false) const {
958 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
960 void EmitReference(const char *Tag, unsigned Number,
961 bool IsPCRelative = false, bool Force32Bit = false) const {
962 PrintRelDirective(Force32Bit);
963 PrintLabelName(Tag, Number);
965 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
967 void EmitReference(const std::string &Name, bool IsPCRelative = false,
968 bool Force32Bit = false) const {
969 PrintRelDirective(Force32Bit);
973 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
976 /// EmitDifference - Emit the difference between two labels. Some
977 /// assemblers do not behave with absolute expressions with data directives,
978 /// so there is an option (needsSet) to use an intermediary set expression.
979 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
980 bool IsSmall = false) {
981 EmitDifference(LabelHi.Tag, LabelHi.Number,
982 LabelLo.Tag, LabelLo.Number,
985 void EmitDifference(const char *TagHi, unsigned NumberHi,
986 const char *TagLo, unsigned NumberLo,
987 bool IsSmall = false) {
988 if (TAI->needsSet()) {
990 PrintLabelName("set", SetCounter, Flavor);
992 PrintLabelName(TagHi, NumberHi);
994 PrintLabelName(TagLo, NumberLo);
997 PrintRelDirective(IsSmall);
998 PrintLabelName("set", SetCounter, Flavor);
1001 PrintRelDirective(IsSmall);
1003 PrintLabelName(TagHi, NumberHi);
1005 PrintLabelName(TagLo, NumberLo);
1009 void EmitSectionOffset(const char* Label, const char* Section,
1010 unsigned LabelNumber, unsigned SectionNumber,
1011 bool IsSmall = false, bool isEH = false,
1012 bool useSet = true) {
1013 bool printAbsolute = false;
1015 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1017 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1019 if (TAI->needsSet() && useSet) {
1021 PrintLabelName("set", SetCounter, Flavor);
1023 PrintLabelName(Label, LabelNumber);
1025 if (!printAbsolute) {
1027 PrintLabelName(Section, SectionNumber);
1031 PrintRelDirective(IsSmall);
1033 PrintLabelName("set", SetCounter, Flavor);
1036 PrintRelDirective(IsSmall, true);
1038 PrintLabelName(Label, LabelNumber);
1040 if (!printAbsolute) {
1042 PrintLabelName(Section, SectionNumber);
1047 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1049 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1050 const std::vector<MachineMove> &Moves, bool isEH) {
1052 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1053 TargetFrameInfo::StackGrowsUp ?
1054 TD->getPointerSize() : -TD->getPointerSize();
1055 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1057 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1058 const MachineMove &Move = Moves[i];
1059 unsigned LabelID = Move.getLabelID();
1062 LabelID = MMI->MappedLabel(LabelID);
1064 // Throw out move if the label is invalid.
1065 if (!LabelID) continue;
1068 const MachineLocation &Dst = Move.getDestination();
1069 const MachineLocation &Src = Move.getSource();
1071 // Advance row if new location.
1072 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1073 Asm->EmitInt8(DW_CFA_advance_loc4);
1074 Asm->EOL("DW_CFA_advance_loc4");
1075 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1078 BaseLabelID = LabelID;
1079 BaseLabel = "label";
1083 // If advancing cfa.
1084 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1086 if (Src.getReg() == MachineLocation::VirtualFP) {
1087 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1088 Asm->EOL("DW_CFA_def_cfa_offset");
1090 Asm->EmitInt8(DW_CFA_def_cfa);
1091 Asm->EOL("DW_CFA_def_cfa");
1092 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1093 Asm->EOL("Register");
1096 int Offset = -Src.getOffset();
1098 Asm->EmitULEB128Bytes(Offset);
1101 assert(0 && "Machine move no supported yet.");
1103 } else if (Src.isReg() &&
1104 Src.getReg() == MachineLocation::VirtualFP) {
1106 Asm->EmitInt8(DW_CFA_def_cfa_register);
1107 Asm->EOL("DW_CFA_def_cfa_register");
1108 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1109 Asm->EOL("Register");
1111 assert(0 && "Machine move no supported yet.");
1114 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1115 int Offset = Dst.getOffset() / stackGrowth;
1118 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1119 Asm->EOL("DW_CFA_offset_extended_sf");
1120 Asm->EmitULEB128Bytes(Reg);
1122 Asm->EmitSLEB128Bytes(Offset);
1124 } else if (Reg < 64) {
1125 Asm->EmitInt8(DW_CFA_offset + Reg);
1127 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1130 Asm->EmitULEB128Bytes(Offset);
1133 Asm->EmitInt8(DW_CFA_offset_extended);
1134 Asm->EOL("DW_CFA_offset_extended");
1135 Asm->EmitULEB128Bytes(Reg);
1137 Asm->EmitULEB128Bytes(Offset);
1146 //===----------------------------------------------------------------------===//
1147 /// SrcLineInfo - This class is used to record source line correspondence.
1150 unsigned Line; // Source line number.
1151 unsigned Column; // Source column.
1152 unsigned SourceID; // Source ID number.
1153 unsigned LabelID; // Label in code ID number.
1155 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1156 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1159 unsigned getLine() const { return Line; }
1160 unsigned getColumn() const { return Column; }
1161 unsigned getSourceID() const { return SourceID; }
1162 unsigned getLabelID() const { return LabelID; }
1166 //===----------------------------------------------------------------------===//
1167 /// SrcFileInfo - This class is used to track source information.
1170 unsigned DirectoryID; // Directory ID number.
1171 std::string Name; // File name (not including directory.)
1173 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1176 unsigned getDirectoryID() const { return DirectoryID; }
1177 const std::string &getName() const { return Name; }
1179 /// operator== - Used by UniqueVector to locate entry.
1181 bool operator==(const SrcFileInfo &SI) const {
1182 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1185 /// operator< - Used by UniqueVector to locate entry.
1187 bool operator<(const SrcFileInfo &SI) const {
1188 return getDirectoryID() < SI.getDirectoryID() ||
1189 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1193 //===----------------------------------------------------------------------===//
1194 /// DbgVariable - This class is used to track local variable information.
1198 DIVariable *Var; // Variable Descriptor.
1199 unsigned FrameIndex; // Variable frame index.
1202 DbgVariable(DIVariable *V, unsigned I) : Var(V), FrameIndex(I) {}
1205 DIVariable *getVariable() const { return Var; }
1206 unsigned getFrameIndex() const { return FrameIndex; }
1209 //===----------------------------------------------------------------------===//
1210 /// DbgScope - This class is used to track scope information.
1214 DbgScope *Parent; // Parent to this scope.
1215 DIDescriptor *Desc; // Debug info descriptor for scope.
1216 // Either subprogram or block.
1217 unsigned StartLabelID; // Label ID of the beginning of scope.
1218 unsigned EndLabelID; // Label ID of the end of scope.
1219 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1220 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1223 DbgScope(DbgScope *P, DIDescriptor *D)
1224 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1227 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1228 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1232 DbgScope *getParent() const { return Parent; }
1233 DIDescriptor *getDesc() const { return Desc; }
1234 unsigned getStartLabelID() const { return StartLabelID; }
1235 unsigned getEndLabelID() const { return EndLabelID; }
1236 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1237 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1238 void setStartLabelID(unsigned S) { StartLabelID = S; }
1239 void setEndLabelID(unsigned E) { EndLabelID = E; }
1241 /// AddScope - Add a scope to the scope.
1243 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1245 /// AddVariable - Add a variable to the scope.
1247 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1250 //===----------------------------------------------------------------------===//
1251 /// DwarfDebug - Emits Dwarf debug directives.
1253 class DwarfDebug : public Dwarf {
1256 //===--------------------------------------------------------------------===//
1257 // Attributes used to construct specific Dwarf sections.
1260 /// CompileUnits - All the compile units involved in this build. The index
1261 /// of each entry in this vector corresponds to the sources in MMI.
1262 std::vector<CompileUnit *> CompileUnits;
1263 DenseMap<Value *, CompileUnit *> DW_CUs;
1265 /// AbbreviationsSet - Used to uniquely define abbreviations.
1267 FoldingSet<DIEAbbrev> AbbreviationsSet;
1269 /// Abbreviations - A list of all the unique abbreviations in use.
1271 std::vector<DIEAbbrev *> Abbreviations;
1273 /// ValuesSet - Used to uniquely define values.
1275 // Directories - Uniquing vector for directories.
1276 UniqueVector<std::string> Directories;
1278 // SourceFiles - Uniquing vector for source files.
1279 UniqueVector<SrcFileInfo> SrcFiles;
1281 // Lines - List of of source line correspondence.
1282 std::vector<SrcLineInfo> Lines;
1284 FoldingSet<DIEValue> ValuesSet;
1286 /// Values - A list of all the unique values in use.
1288 std::vector<DIEValue *> Values;
1290 /// StringPool - A UniqueVector of strings used by indirect references.
1292 UniqueVector<std::string> StringPool;
1294 /// SectionMap - Provides a unique id per text section.
1296 UniqueVector<const Section*> SectionMap;
1298 /// SectionSourceLines - Tracks line numbers per text section.
1300 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1302 /// didInitial - Flag to indicate if initial emission has been done.
1306 /// shouldEmit - Flag to indicate if debug information should be emitted.
1310 // RootScope - Top level scope for the current function.
1312 DbgScope *RootDbgScope;
1314 // DbgScopeMap - Tracks the scopes in the current function.
1315 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1317 struct FunctionDebugFrameInfo {
1319 std::vector<MachineMove> Moves;
1321 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1322 Number(Num), Moves(M) { }
1325 std::vector<FunctionDebugFrameInfo> DebugFrames;
1329 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1331 bool ShouldEmitDwarf() const { return shouldEmit; }
1333 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1335 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1336 // Profile the node so that we can make it unique.
1337 FoldingSetNodeID ID;
1340 // Check the set for priors.
1341 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1343 // If it's newly added.
1344 if (InSet == &Abbrev) {
1345 // Add to abbreviation list.
1346 Abbreviations.push_back(&Abbrev);
1347 // Assign the vector position + 1 as its number.
1348 Abbrev.setNumber(Abbreviations.size());
1350 // Assign existing abbreviation number.
1351 Abbrev.setNumber(InSet->getNumber());
1355 /// NewString - Add a string to the constant pool and returns a label.
1357 DWLabel NewString(const std::string &String) {
1358 unsigned StringID = StringPool.insert(String);
1359 return DWLabel("string", StringID);
1362 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1364 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1368 FoldingSetNodeID ID;
1369 DIEntry::Profile(ID, Entry);
1371 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1373 if (Value) return Value;
1375 Value = new DIEntry(Entry);
1376 ValuesSet.InsertNode(Value, Where);
1378 Value = new DIEntry(Entry);
1381 Values.push_back(Value);
1385 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1387 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1388 Value->Entry = Entry;
1389 // Add to values set if not already there. If it is, we merely have a
1390 // duplicate in the values list (no harm.)
1391 ValuesSet.GetOrInsertNode(Value);
1394 /// AddUInt - Add an unsigned integer attribute data and value.
1396 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1397 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1399 FoldingSetNodeID ID;
1400 DIEInteger::Profile(ID, Integer);
1402 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1404 Value = new DIEInteger(Integer);
1405 ValuesSet.InsertNode(Value, Where);
1406 Values.push_back(Value);
1409 Die->AddValue(Attribute, Form, Value);
1412 /// AddSInt - Add an signed integer attribute data and value.
1414 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1415 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1417 FoldingSetNodeID ID;
1418 DIEInteger::Profile(ID, (uint64_t)Integer);
1420 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1422 Value = new DIEInteger(Integer);
1423 ValuesSet.InsertNode(Value, Where);
1424 Values.push_back(Value);
1427 Die->AddValue(Attribute, Form, Value);
1430 /// AddString - Add a std::string attribute data and value.
1432 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1433 const std::string &String) {
1434 FoldingSetNodeID ID;
1435 DIEString::Profile(ID, String);
1437 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1439 Value = new DIEString(String);
1440 ValuesSet.InsertNode(Value, Where);
1441 Values.push_back(Value);
1444 Die->AddValue(Attribute, Form, Value);
1447 /// AddLabel - Add a Dwarf label attribute data and value.
1449 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1450 const DWLabel &Label) {
1451 FoldingSetNodeID ID;
1452 DIEDwarfLabel::Profile(ID, Label);
1454 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1456 Value = new DIEDwarfLabel(Label);
1457 ValuesSet.InsertNode(Value, Where);
1458 Values.push_back(Value);
1461 Die->AddValue(Attribute, Form, Value);
1464 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1466 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1467 const std::string &Label) {
1468 FoldingSetNodeID ID;
1469 DIEObjectLabel::Profile(ID, Label);
1471 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1473 Value = new DIEObjectLabel(Label);
1474 ValuesSet.InsertNode(Value, Where);
1475 Values.push_back(Value);
1478 Die->AddValue(Attribute, Form, Value);
1481 /// AddSectionOffset - Add a section offset label attribute data and value.
1483 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1484 const DWLabel &Label, const DWLabel &Section,
1485 bool isEH = false, bool useSet = true) {
1486 FoldingSetNodeID ID;
1487 DIESectionOffset::Profile(ID, Label, Section);
1489 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1491 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1492 ValuesSet.InsertNode(Value, Where);
1493 Values.push_back(Value);
1496 Die->AddValue(Attribute, Form, Value);
1499 /// AddDelta - Add a label delta attribute data and value.
1501 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1502 const DWLabel &Hi, const DWLabel &Lo) {
1503 FoldingSetNodeID ID;
1504 DIEDelta::Profile(ID, Hi, Lo);
1506 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1508 Value = new DIEDelta(Hi, Lo);
1509 ValuesSet.InsertNode(Value, Where);
1510 Values.push_back(Value);
1513 Die->AddValue(Attribute, Form, Value);
1516 /// AddDIEntry - Add a DIE attribute data and value.
1518 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1519 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1522 /// AddBlock - Add block data.
1524 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1525 Block->ComputeSize(*this);
1526 FoldingSetNodeID ID;
1529 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1532 ValuesSet.InsertNode(Value, Where);
1533 Values.push_back(Value);
1535 // Already exists, reuse the previous one.
1537 Block = cast<DIEBlock>(Value);
1540 Die->AddValue(Attribute, Block->BestForm(), Value);
1545 /// AddSourceLine - Add location information to specified debug information
1547 void AddSourceLine(DIE *Die, DIVariable *V) {
1548 unsigned FileID = 0;
1549 unsigned Line = V->getLineNumber();
1550 if (V->getVersion() < DIDescriptor::Version7) {
1551 // Version6 or earlier. Use compile unit info to get file id.
1552 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1553 FileID = Unit->getID();
1555 // Version7 or newer, use filename and directory info from DIVariable
1557 unsigned DID = Directories.idFor(V->getDirectory());
1558 FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1560 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1561 AddUInt(Die, DW_AT_decl_line, 0, Line);
1564 /// AddSourceLine - Add location information to specified debug information
1566 void AddSourceLine(DIE *Die, DIGlobal *G) {
1567 unsigned FileID = 0;
1568 unsigned Line = G->getLineNumber();
1569 if (G->getVersion() < DIDescriptor::Version7) {
1570 // Version6 or earlier. Use compile unit info to get file id.
1571 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1572 FileID = Unit->getID();
1574 // Version7 or newer, use filename and directory info from DIGlobal
1576 unsigned DID = Directories.idFor(G->getDirectory());
1577 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1579 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1580 AddUInt(Die, DW_AT_decl_line, 0, Line);
1583 void AddSourceLine(DIE *Die, DIType *G) {
1584 unsigned FileID = 0;
1585 unsigned Line = G->getLineNumber();
1586 if (G->getVersion() < DIDescriptor::Version7) {
1587 // Version6 or earlier. Use compile unit info to get file id.
1588 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1589 FileID = Unit->getID();
1591 // Version7 or newer, use filename and directory info from DIGlobal
1593 unsigned DID = Directories.idFor(G->getDirectory());
1594 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1596 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1597 AddUInt(Die, DW_AT_decl_line, 0, Line);
1600 /// AddAddress - Add an address attribute to a die based on the location
1602 void AddAddress(DIE *Die, unsigned Attribute,
1603 const MachineLocation &Location) {
1604 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1605 DIEBlock *Block = new DIEBlock();
1607 if (Location.isReg()) {
1609 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1611 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1612 AddUInt(Block, 0, DW_FORM_udata, Reg);
1616 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1618 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1619 AddUInt(Block, 0, DW_FORM_udata, Reg);
1621 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1624 AddBlock(Die, Attribute, 0, Block);
1627 /// AddBasicType - Add a new basic type attribute to the specified entity.
1629 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1630 const std::string &Name,
1631 unsigned Encoding, unsigned Size) {
1633 DIE Buffer(DW_TAG_base_type);
1634 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1635 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1636 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1637 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1638 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1641 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1643 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1644 DIE Buffer(DW_TAG_pointer_type);
1645 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1646 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1647 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1648 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1651 /// AddType - Add a new type attribute to the specified entity.
1652 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1654 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1658 // Check for pre-existence.
1659 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1660 // If it exists then use the existing value.
1662 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1667 Slot = NewDIEntry();
1670 DIE Buffer(DW_TAG_base_type);
1671 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1672 ConstructTypeDIE(DW_Unit, Buffer, BT);
1673 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1674 ConstructTypeDIE(DW_Unit, Buffer, DT);
1675 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1676 ConstructTypeDIE(DW_Unit, Buffer, CT);
1678 // Add debug information entry to entity and unit.
1679 DIE *Die = DW_Unit->AddDie(Buffer);
1680 SetDIEntry(Slot, Die);
1681 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1684 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1685 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1688 // Get core information.
1689 const std::string &Name = BTy->getName();
1690 Buffer.setTag(DW_TAG_base_type);
1691 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1692 // Add name if not anonymous or intermediate type.
1694 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1695 uint64_t Size = BTy->getSizeInBits() >> 3;
1696 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1699 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1700 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1701 DIDerivedType *DTy) {
1703 // Get core information.
1704 const std::string &Name = DTy->getName();
1705 uint64_t Size = DTy->getSizeInBits() >> 3;
1706 unsigned Tag = DTy->getTag();
1707 // FIXME - Workaround for templates.
1708 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1711 // Map to main type, void will not have a type.
1712 DIType FromTy = DTy->getTypeDerivedFrom();
1713 AddType(DW_Unit, &Buffer, FromTy);
1715 // Add name if not anonymous or intermediate type.
1716 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1718 // Add size if non-zero (derived types might be zero-sized.)
1720 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1722 // Add source line info if available and TyDesc is not a forward
1724 // FIXME - Enable this. if (!DTy->isForwardDecl())
1725 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1728 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1729 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1730 DICompositeType *CTy) {
1732 // Get core information.
1733 const std::string &Name = CTy->getName();
1734 uint64_t Size = CTy->getSizeInBits() >> 3;
1735 unsigned Tag = CTy->getTag();
1737 case DW_TAG_vector_type:
1738 case DW_TAG_array_type:
1739 ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1741 //FIXME - Enable this.
1742 // case DW_TAG_enumeration_type:
1743 // DIArray Elements = CTy->getTypeArray();
1744 // // Add enumerators to enumeration type.
1745 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1746 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1748 case DW_TAG_subroutine_type:
1750 // Add prototype flag.
1751 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1752 DIArray Elements = CTy->getTypeArray();
1754 DIDescriptor RTy = Elements.getElement(0);
1755 if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1756 AddType(DW_Unit, &Buffer, *BT);
1757 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1758 AddType(DW_Unit, &Buffer, *DT);
1759 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1760 AddType(DW_Unit, &Buffer, *CT);
1762 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1764 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1765 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1766 DIDescriptor Ty = Elements.getElement(i);
1767 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1768 AddType(DW_Unit, &Buffer, *BT);
1769 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1770 AddType(DW_Unit, &Buffer, *DT);
1771 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1772 AddType(DW_Unit, &Buffer, *CT);
1773 Buffer.AddChild(Arg);
1777 case DW_TAG_structure_type:
1778 case DW_TAG_union_type:
1780 // Add elements to structure type.
1781 DIArray Elements = CTy->getTypeArray();
1782 // Add elements to structure type.
1783 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1784 DIDescriptor Element = Elements.getElement(i);
1785 if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1786 ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1787 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1788 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1789 else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1790 ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1798 // Add name if not anonymous or intermediate type.
1799 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1801 // Add size if non-zero (derived types might be zero-sized.)
1803 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1805 // Add zero size even if it is not a forward declaration.
1806 // FIXME - Enable this.
1807 // if (!CTy->isDefinition())
1808 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1810 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1813 // Add source line info if available and TyDesc is not a forward
1815 // FIXME - Enable this.
1816 // if (CTy->isForwardDecl())
1817 // AddSourceLine(&Buffer, *CTy);
1820 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1821 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1822 int64_t L = SR->getLo();
1823 int64_t H = SR->getHi();
1824 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1826 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1828 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1829 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1831 Buffer.AddChild(DW_Subrange);
1834 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1835 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1836 DICompositeType *CTy) {
1837 Buffer.setTag(DW_TAG_array_type);
1838 if (CTy->getTag() == DW_TAG_vector_type)
1839 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1841 DIArray Elements = CTy->getTypeArray();
1842 // FIXME - Enable this.
1843 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1845 // Construct an anonymous type for index type.
1846 DIE IdxBuffer(DW_TAG_base_type);
1847 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1848 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1849 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1851 // Add subranges to array type.
1852 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1853 DIDescriptor Element = Elements.getElement(i);
1854 if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1855 ConstructSubrangeDIE(Buffer, SR, IndexTy);
1859 /// ConstructEnumTypeDIE - Construct enum type DIE from
1861 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1862 DIE &Buffer, DIEnumerator *ETy) {
1864 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1865 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1866 int64_t Value = ETy->getEnumValue();
1867 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1868 Buffer.AddChild(Enumerator);
1871 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1872 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1873 DIE &Buffer, DIGlobalVariable *V) {
1875 DIE *VariableDie = new DIE(DW_TAG_variable);
1876 const std::string &LinkageName = V->getLinkageName();
1877 if (!LinkageName.empty())
1878 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1880 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1881 AddType(DW_Unit, VariableDie, V->getType());
1882 if (!V->isLocalToUnit())
1883 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1884 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1885 Buffer.AddChild(VariableDie);
1888 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1889 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1890 DIE &Buffer, DISubprogram *SP,
1891 bool IsConstructor = false) {
1892 DIE *Method = new DIE(DW_TAG_subprogram);
1893 AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1894 const std::string &LinkageName = SP->getLinkageName();
1895 if (!LinkageName.empty())
1896 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1897 // FIXME - Enable this. AddSourceLine(Method, SP);
1899 DICompositeType MTy = SP->getType();
1900 DIArray Args = MTy.getTypeArray();
1903 if (!IsConstructor) {
1904 DIDescriptor Ty = Args.getElement(0);
1905 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1906 AddType(DW_Unit, Method, *BT);
1907 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1908 AddType(DW_Unit, Method, *DT);
1909 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1910 AddType(DW_Unit, Method, *CT);
1914 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1915 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1916 DIDescriptor Ty = Args.getElement(i);
1917 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1918 AddType(DW_Unit, Method, *BT);
1919 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1920 AddType(DW_Unit, Method, *DT);
1921 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1922 AddType(DW_Unit, Method, *CT);
1923 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1924 Method->AddChild(Arg);
1927 if (!SP->isLocalToUnit())
1928 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1929 Buffer.AddChild(Method);
1932 /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
1933 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1934 DIDerivedType *DTy) {
1935 unsigned Tag = DTy->getTag();
1936 DIE *MemberDie = new DIE(Tag);
1937 if (!DTy->getName().empty())
1938 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
1939 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
1941 DIType FromTy = DTy->getTypeDerivedFrom();
1942 AddType(DW_Unit, MemberDie, FromTy);
1944 uint64_t Size = DTy->getSizeInBits();
1945 uint64_t Offset = DTy->getOffsetInBits();
1947 // FIXME Handle bitfields
1950 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
1951 // Add computation for offset.
1952 DIEBlock *Block = new DIEBlock();
1953 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1954 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
1955 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1957 // FIXME Handle DW_AT_accessibility.
1959 Buffer.AddChild(MemberDie);
1962 /// FindCompileUnit - Get the compile unit for the given descriptor.
1964 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1965 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
1966 assert(DW_Unit && "Missing compile unit.");
1970 /// NewDbgScopeVariable - Create a new scope variable.
1972 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1973 // Get the descriptor.
1974 DIVariable *VD = DV->getVariable();
1976 // Translate tag to proper Dwarf tag. The result variable is dropped for
1979 switch (VD->getTag()) {
1980 case DW_TAG_return_variable: return NULL;
1981 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1982 case DW_TAG_auto_variable: // fall thru
1983 default: Tag = DW_TAG_variable; break;
1986 // Define variable debug information entry.
1987 DIE *VariableDie = new DIE(Tag);
1988 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1990 // Add source line info if available.
1991 AddSourceLine(VariableDie, VD);
1993 // Add variable type.
1994 AddType(Unit, VariableDie, VD->getType());
1996 // Add variable address.
1997 MachineLocation Location;
1998 Location.set(RI->getFrameRegister(*MF),
1999 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2000 AddAddress(VariableDie, DW_AT_location, Location);
2005 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2007 DbgScope *getOrCreateScope(GlobalVariable *V) {
2008 DbgScope *&Slot = DbgScopeMap[V];
2010 // FIXME - breaks down when the context is an inlined function.
2011 DIDescriptor ParentDesc;
2012 DIDescriptor *DB = new DIDescriptor(V);
2013 if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
2014 ParentDesc = Block->getContext();
2016 DbgScope *Parent = ParentDesc.isNull() ?
2017 NULL : getOrCreateScope(ParentDesc.getGV());
2018 Slot = new DbgScope(Parent, DB);
2020 Parent->AddScope(Slot);
2021 } else if (RootDbgScope) {
2022 // FIXME - Add inlined function scopes to the root so we can delete
2023 // them later. Long term, handle inlined functions properly.
2024 RootDbgScope->AddScope(Slot);
2026 // First function is top level function.
2027 RootDbgScope = Slot;
2033 /// ConstructDbgScope - Construct the components of a scope.
2035 void ConstructDbgScope(DbgScope *ParentScope,
2036 unsigned ParentStartID, unsigned ParentEndID,
2037 DIE *ParentDie, CompileUnit *Unit) {
2038 // Add variables to scope.
2039 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2040 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2041 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2042 if (VariableDie) ParentDie->AddChild(VariableDie);
2045 // Add nested scopes.
2046 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2047 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2048 // Define the Scope debug information entry.
2049 DbgScope *Scope = Scopes[j];
2050 // FIXME - Ignore inlined functions for the time being.
2051 if (!Scope->getParent()) continue;
2053 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2054 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2056 // Ignore empty scopes.
2057 if (StartID == EndID && StartID != 0) continue;
2058 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2060 if (StartID == ParentStartID && EndID == ParentEndID) {
2061 // Just add stuff to the parent scope.
2062 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2064 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2066 // Add the scope bounds.
2068 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2069 DWLabel("label", StartID));
2071 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2072 DWLabel("func_begin", SubprogramCount));
2075 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2076 DWLabel("label", EndID));
2078 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2079 DWLabel("func_end", SubprogramCount));
2082 // Add the scope contents.
2083 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2084 ParentDie->AddChild(ScopeDie);
2089 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2091 void ConstructRootDbgScope(DbgScope *RootScope) {
2092 // Exit if there is no root scope.
2093 if (!RootScope) return;
2094 if (RootScope->getDesc()->isNull()) return;
2096 // Get the subprogram debug information entry.
2097 DISubprogram SPD(RootScope->getDesc()->getGV());
2099 // Get the compile unit context.
2100 CompileUnit *Unit = FindCompileUnit(SPD.getCompileUnit());
2102 // Get the subprogram die.
2103 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2104 assert(SPDie && "Missing subprogram descriptor");
2106 // Add the function bounds.
2107 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2108 DWLabel("func_begin", SubprogramCount));
2109 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2110 DWLabel("func_end", SubprogramCount));
2111 MachineLocation Location(RI->getFrameRegister(*MF));
2112 AddAddress(SPDie, DW_AT_frame_base, Location);
2114 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2117 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2119 void ConstructDefaultDbgScope(MachineFunction *MF) {
2120 // Find the correct subprogram descriptor.
2121 std::string SPName = "llvm.dbg.subprograms";
2122 std::vector<GlobalVariable*> Result;
2123 getGlobalVariablesUsing(*M, SPName, Result);
2124 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2125 E = Result.end(); I != E; ++I) {
2127 DISubprogram *SPD = new DISubprogram(*I);
2129 if (SPD->getName() == MF->getFunction()->getName()) {
2130 // Get the compile unit context.
2131 CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2133 // Get the subprogram die.
2134 DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2135 assert(SPDie && "Missing subprogram descriptor");
2137 // Add the function bounds.
2138 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2139 DWLabel("func_begin", SubprogramCount));
2140 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2141 DWLabel("func_end", SubprogramCount));
2143 MachineLocation Location(RI->getFrameRegister(*MF));
2144 AddAddress(SPDie, DW_AT_frame_base, Location);
2149 // FIXME: This is causing an abort because C++ mangled names are compared
2150 // with their unmangled counterparts. See PR2885. Don't do this assert.
2151 assert(0 && "Couldn't find DIE for machine function!");
2155 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2156 /// tools to recognize the object file contains Dwarf information.
2157 void EmitInitial() {
2158 // Check to see if we already emitted intial headers.
2159 if (didInitial) return;
2162 // Dwarf sections base addresses.
2163 if (TAI->doesDwarfRequireFrameSection()) {
2164 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2165 EmitLabel("section_debug_frame", 0);
2167 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2168 EmitLabel("section_info", 0);
2169 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2170 EmitLabel("section_abbrev", 0);
2171 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2172 EmitLabel("section_aranges", 0);
2173 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2174 EmitLabel("section_macinfo", 0);
2175 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2176 EmitLabel("section_line", 0);
2177 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2178 EmitLabel("section_loc", 0);
2179 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2180 EmitLabel("section_pubnames", 0);
2181 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2182 EmitLabel("section_str", 0);
2183 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2184 EmitLabel("section_ranges", 0);
2186 Asm->SwitchToSection(TAI->getTextSection());
2187 EmitLabel("text_begin", 0);
2188 Asm->SwitchToSection(TAI->getDataSection());
2189 EmitLabel("data_begin", 0);
2192 /// EmitDIE - Recusively Emits a debug information entry.
2194 void EmitDIE(DIE *Die) {
2195 // Get the abbreviation for this DIE.
2196 unsigned AbbrevNumber = Die->getAbbrevNumber();
2197 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2201 // Emit the code (index) for the abbreviation.
2202 Asm->EmitULEB128Bytes(AbbrevNumber);
2205 Asm->EOL(std::string("Abbrev [" +
2206 utostr(AbbrevNumber) +
2207 "] 0x" + utohexstr(Die->getOffset()) +
2208 ":0x" + utohexstr(Die->getSize()) + " " +
2209 TagString(Abbrev->getTag())));
2213 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2214 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2216 // Emit the DIE attribute values.
2217 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2218 unsigned Attr = AbbrevData[i].getAttribute();
2219 unsigned Form = AbbrevData[i].getForm();
2220 assert(Form && "Too many attributes for DIE (check abbreviation)");
2223 case DW_AT_sibling: {
2224 Asm->EmitInt32(Die->SiblingOffset());
2228 // Emit an attribute using the defined form.
2229 Values[i]->EmitValue(*this, Form);
2234 Asm->EOL(AttributeString(Attr));
2237 // Emit the DIE children if any.
2238 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2239 const std::vector<DIE *> &Children = Die->getChildren();
2241 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2242 EmitDIE(Children[j]);
2245 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2249 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2251 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2252 // Get the children.
2253 const std::vector<DIE *> &Children = Die->getChildren();
2255 // If not last sibling and has children then add sibling offset attribute.
2256 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2258 // Record the abbreviation.
2259 AssignAbbrevNumber(Die->getAbbrev());
2261 // Get the abbreviation for this DIE.
2262 unsigned AbbrevNumber = Die->getAbbrevNumber();
2263 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2266 Die->setOffset(Offset);
2268 // Start the size with the size of abbreviation code.
2269 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2271 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2272 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2274 // Size the DIE attribute values.
2275 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2276 // Size attribute value.
2277 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2280 // Size the DIE children if any.
2281 if (!Children.empty()) {
2282 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2283 "Children flag not set");
2285 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2286 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2289 // End of children marker.
2290 Offset += sizeof(int8_t);
2293 Die->setSize(Offset - Die->getOffset());
2297 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2299 void SizeAndOffsets() {
2300 // Process base compile unit.
2301 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2302 CE = DW_CUs.end(); CI != CE; ++CI) {
2303 CompileUnit *Unit = CI->second;
2304 // Compute size of compile unit header
2305 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2306 sizeof(int16_t) + // DWARF version number
2307 sizeof(int32_t) + // Offset Into Abbrev. Section
2308 sizeof(int8_t); // Pointer Size (in bytes)
2309 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2313 /// EmitDebugInfo - Emit the debug info section.
2315 void EmitDebugInfo() {
2316 // Start debug info section.
2317 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2319 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2320 CE = DW_CUs.end(); CI != CE; ++CI) {
2321 CompileUnit *Unit = CI->second;
2322 DIE *Die = Unit->getDie();
2323 // Emit the compile units header.
2324 EmitLabel("info_begin", Unit->getID());
2325 // Emit size of content not including length itself
2326 unsigned ContentSize = Die->getSize() +
2327 sizeof(int16_t) + // DWARF version number
2328 sizeof(int32_t) + // Offset Into Abbrev. Section
2329 sizeof(int8_t) + // Pointer Size (in bytes)
2330 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2332 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2333 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2334 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2335 Asm->EOL("Offset Into Abbrev. Section");
2336 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2339 // FIXME - extra padding for gdb bug.
2340 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2341 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2342 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2343 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2344 EmitLabel("info_end", Unit->getID());
2350 /// EmitAbbreviations - Emit the abbreviation section.
2352 void EmitAbbreviations() const {
2353 // Check to see if it is worth the effort.
2354 if (!Abbreviations.empty()) {
2355 // Start the debug abbrev section.
2356 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2358 EmitLabel("abbrev_begin", 0);
2360 // For each abbrevation.
2361 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2362 // Get abbreviation data
2363 const DIEAbbrev *Abbrev = Abbreviations[i];
2365 // Emit the abbrevations code (base 1 index.)
2366 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2367 Asm->EOL("Abbreviation Code");
2369 // Emit the abbreviations data.
2370 Abbrev->Emit(*this);
2375 // Mark end of abbreviations.
2376 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2378 EmitLabel("abbrev_end", 0);
2384 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2385 /// the line matrix.
2387 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2388 // Define last address of section.
2389 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2390 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2391 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2392 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2394 // Mark end of matrix.
2395 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2396 Asm->EmitULEB128Bytes(1); Asm->EOL();
2397 Asm->EmitInt8(1); Asm->EOL();
2400 /// EmitDebugLines - Emit source line information.
2402 void EmitDebugLines() {
2403 // If the target is using .loc/.file, the assembler will be emitting the
2404 // .debug_line table automatically.
2405 if (TAI->hasDotLocAndDotFile())
2408 // Minimum line delta, thus ranging from -10..(255-10).
2409 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2410 // Maximum line delta, thus ranging from -10..(255-10).
2411 const int MaxLineDelta = 255 + MinLineDelta;
2413 // Start the dwarf line section.
2414 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2416 // Construct the section header.
2418 EmitDifference("line_end", 0, "line_begin", 0, true);
2419 Asm->EOL("Length of Source Line Info");
2420 EmitLabel("line_begin", 0);
2422 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2424 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2425 Asm->EOL("Prolog Length");
2426 EmitLabel("line_prolog_begin", 0);
2428 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2430 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2432 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2434 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2436 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2438 // Line number standard opcode encodings argument count
2439 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2440 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2441 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2442 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2443 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2444 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2445 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2446 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2447 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2449 // Emit directories.
2450 for (unsigned DirectoryID = 1, NDID = Directories.size();
2451 DirectoryID <= NDID; ++DirectoryID) {
2452 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2454 Asm->EmitInt8(0); Asm->EOL("End of directories");
2457 for (unsigned SourceID = 1, NSID = SrcFiles.size();
2458 SourceID <= NSID; ++SourceID) {
2459 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2460 Asm->EmitString(SourceFile.getName());
2462 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2463 Asm->EOL("Directory #");
2464 Asm->EmitULEB128Bytes(0);
2465 Asm->EOL("Mod date");
2466 Asm->EmitULEB128Bytes(0);
2467 Asm->EOL("File size");
2469 Asm->EmitInt8(0); Asm->EOL("End of files");
2471 EmitLabel("line_prolog_end", 0);
2473 // A sequence for each text section.
2474 unsigned SecSrcLinesSize = SectionSourceLines.size();
2476 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2477 // Isolate current sections line info.
2478 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2481 const Section* S = SectionMap[j + 1];
2482 Asm->EOL(std::string("Section ") + S->getName());
2486 // Dwarf assumes we start with first line of first source file.
2487 unsigned Source = 1;
2490 // Construct rows of the address, source, line, column matrix.
2491 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2492 const SrcLineInfo &LineInfo = LineInfos[i];
2493 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2494 if (!LabelID) continue;
2496 unsigned SourceID = LineInfo.getSourceID();
2497 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2498 unsigned DirectoryID = SourceFile.getDirectoryID();
2500 Asm->EOL(Directories[DirectoryID]
2501 + SourceFile.getName()
2503 + utostr_32(LineInfo.getLine()));
2507 // Define the line address.
2508 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2509 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2510 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2511 EmitReference("label", LabelID); Asm->EOL("Location label");
2513 // If change of source, then switch to the new source.
2514 if (Source != LineInfo.getSourceID()) {
2515 Source = LineInfo.getSourceID();
2516 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2517 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2520 // If change of line.
2521 if (Line != LineInfo.getLine()) {
2522 // Determine offset.
2523 int Offset = LineInfo.getLine() - Line;
2524 int Delta = Offset - MinLineDelta;
2527 Line = LineInfo.getLine();
2529 // If delta is small enough and in range...
2530 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2531 // ... then use fast opcode.
2532 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2534 // ... otherwise use long hand.
2535 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2536 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2537 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2540 // Copy the previous row (different address or source)
2541 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2545 EmitEndOfLineMatrix(j + 1);
2548 if (SecSrcLinesSize == 0)
2549 // Because we're emitting a debug_line section, we still need a line
2550 // table. The linker and friends expect it to exist. If there's nothing to
2551 // put into it, emit an empty table.
2552 EmitEndOfLineMatrix(1);
2554 EmitLabel("line_end", 0);
2559 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2561 void EmitCommonDebugFrame() {
2562 if (!TAI->doesDwarfRequireFrameSection())
2566 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2567 TargetFrameInfo::StackGrowsUp ?
2568 TD->getPointerSize() : -TD->getPointerSize();
2570 // Start the dwarf frame section.
2571 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2573 EmitLabel("debug_frame_common", 0);
2574 EmitDifference("debug_frame_common_end", 0,
2575 "debug_frame_common_begin", 0, true);
2576 Asm->EOL("Length of Common Information Entry");
2578 EmitLabel("debug_frame_common_begin", 0);
2579 Asm->EmitInt32((int)DW_CIE_ID);
2580 Asm->EOL("CIE Identifier Tag");
2581 Asm->EmitInt8(DW_CIE_VERSION);
2582 Asm->EOL("CIE Version");
2583 Asm->EmitString("");
2584 Asm->EOL("CIE Augmentation");
2585 Asm->EmitULEB128Bytes(1);
2586 Asm->EOL("CIE Code Alignment Factor");
2587 Asm->EmitSLEB128Bytes(stackGrowth);
2588 Asm->EOL("CIE Data Alignment Factor");
2589 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2590 Asm->EOL("CIE RA Column");
2592 std::vector<MachineMove> Moves;
2593 RI->getInitialFrameState(Moves);
2595 EmitFrameMoves(NULL, 0, Moves, false);
2597 Asm->EmitAlignment(2, 0, 0, false);
2598 EmitLabel("debug_frame_common_end", 0);
2603 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2605 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2606 if (!TAI->doesDwarfRequireFrameSection())
2609 // Start the dwarf frame section.
2610 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2612 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2613 "debug_frame_begin", DebugFrameInfo.Number, true);
2614 Asm->EOL("Length of Frame Information Entry");
2616 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2618 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2620 Asm->EOL("FDE CIE offset");
2622 EmitReference("func_begin", DebugFrameInfo.Number);
2623 Asm->EOL("FDE initial location");
2624 EmitDifference("func_end", DebugFrameInfo.Number,
2625 "func_begin", DebugFrameInfo.Number);
2626 Asm->EOL("FDE address range");
2628 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2630 Asm->EmitAlignment(2, 0, 0, false);
2631 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2636 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2638 void EmitDebugPubNames() {
2639 // Start the dwarf pubnames section.
2640 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2642 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2643 CE = DW_CUs.end(); CI != CE; ++CI) {
2644 CompileUnit *Unit = CI->second;
2646 EmitDifference("pubnames_end", Unit->getID(),
2647 "pubnames_begin", Unit->getID(), true);
2648 Asm->EOL("Length of Public Names Info");
2650 EmitLabel("pubnames_begin", Unit->getID());
2652 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2654 EmitSectionOffset("info_begin", "section_info",
2655 Unit->getID(), 0, true, false);
2656 Asm->EOL("Offset of Compilation Unit Info");
2658 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2659 Asm->EOL("Compilation Unit Length");
2661 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2663 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2666 const std::string &Name = GI->first;
2667 DIE * Entity = GI->second;
2669 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2670 Asm->EmitString(Name); Asm->EOL("External Name");
2673 Asm->EmitInt32(0); Asm->EOL("End Mark");
2674 EmitLabel("pubnames_end", Unit->getID());
2680 /// EmitDebugStr - Emit visible names into a debug str section.
2682 void EmitDebugStr() {
2683 // Check to see if it is worth the effort.
2684 if (!StringPool.empty()) {
2685 // Start the dwarf str section.
2686 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2688 // For each of strings in the string pool.
2689 for (unsigned StringID = 1, N = StringPool.size();
2690 StringID <= N; ++StringID) {
2691 // Emit a label for reference from debug information entries.
2692 EmitLabel("string", StringID);
2693 // Emit the string itself.
2694 const std::string &String = StringPool[StringID];
2695 Asm->EmitString(String); Asm->EOL();
2702 /// EmitDebugLoc - Emit visible names into a debug loc section.
2704 void EmitDebugLoc() {
2705 // Start the dwarf loc section.
2706 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2711 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2713 void EmitDebugARanges() {
2714 // Start the dwarf aranges section.
2715 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2719 CompileUnit *Unit = GetBaseCompileUnit();
2721 // Don't include size of length
2722 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2724 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2726 EmitReference("info_begin", Unit->getID());
2727 Asm->EOL("Offset of Compilation Unit Info");
2729 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2731 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2733 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2734 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2737 EmitReference("text_begin", 0); Asm->EOL("Address");
2738 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2740 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2741 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2747 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2749 void EmitDebugRanges() {
2750 // Start the dwarf ranges section.
2751 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2756 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2758 void EmitDebugMacInfo() {
2759 // Start the dwarf macinfo section.
2760 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2765 /// ConstructCompileUnits - Create a compile unit DIEs.
2766 void ConstructCompileUnits() {
2767 std::string CUName = "llvm.dbg.compile_units";
2768 std::vector<GlobalVariable*> Result;
2769 getGlobalVariablesUsing(*M, CUName, Result);
2770 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2771 RE = Result.end(); RI != RE; ++RI) {
2772 DICompileUnit *DIUnit = new DICompileUnit(*RI);
2773 unsigned ID = RecordSource(DIUnit->getDirectory(),
2774 DIUnit->getFilename());
2776 DIE *Die = new DIE(DW_TAG_compile_unit);
2777 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2778 DWLabel("section_line", 0), DWLabel("section_line", 0),
2780 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
2781 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
2782 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
2783 if (!DIUnit->getDirectory().empty())
2784 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
2786 CompileUnit *Unit = new CompileUnit(ID, Die);
2787 DW_CUs[DIUnit->getGV()] = Unit;
2791 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2792 /// visible global variables.
2793 void ConstructGlobalVariableDIEs() {
2794 std::string GVName = "llvm.dbg.global_variables";
2795 std::vector<GlobalVariable*> Result;
2796 getGlobalVariablesUsing(*M, GVName, Result);
2797 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
2798 GVE = Result.end(); GVI != GVE; ++GVI) {
2799 DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
2800 CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
2802 // Check for pre-existence.
2803 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
2806 DIE *VariableDie = new DIE(DW_TAG_variable);
2807 AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
2808 const std::string &LinkageName = DI_GV->getLinkageName();
2809 if (!LinkageName.empty())
2810 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2812 AddType(DW_Unit, VariableDie, DI_GV->getType());
2814 if (!DI_GV->isLocalToUnit())
2815 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2817 // Add source line info, if available.
2818 AddSourceLine(VariableDie, DI_GV);
2821 DIEBlock *Block = new DIEBlock();
2822 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2823 AddObjectLabel(Block, 0, DW_FORM_udata,
2824 Asm->getGlobalLinkName(DI_GV->getGV()));
2825 AddBlock(VariableDie, DW_AT_location, 0, Block);
2830 //Add to context owner.
2831 DW_Unit->getDie()->AddChild(VariableDie);
2833 //Expose as global. FIXME - need to check external flag.
2834 DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
2838 /// ConstructSubprograms - Create DIEs for each of the externally visible
2840 void ConstructSubprograms() {
2842 std::string SPName = "llvm.dbg.subprograms";
2843 std::vector<GlobalVariable*> Result;
2844 getGlobalVariablesUsing(*M, SPName, Result);
2845 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2846 RE = Result.end(); RI != RE; ++RI) {
2848 DISubprogram *SP = new DISubprogram(*RI);
2849 CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
2851 // Check for pre-existence.
2852 DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
2855 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2856 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
2857 const std::string &LinkageName = SP->getLinkageName();
2858 if (!LinkageName.empty())
2859 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2861 DIType SPTy = SP->getType();
2862 AddType(Unit, SubprogramDie, SPTy);
2863 if (!SP->isLocalToUnit())
2864 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2865 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2867 AddSourceLine(SubprogramDie, SP);
2869 Slot = SubprogramDie;
2870 //Add to context owner.
2871 Unit->getDie()->AddChild(SubprogramDie);
2873 Unit->AddGlobal(SP->getName(), SubprogramDie);
2878 //===--------------------------------------------------------------------===//
2879 // Main entry points.
2881 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2882 : Dwarf(OS, A, T, "dbg")
2884 , AbbreviationsSet(InitAbbreviationsSetSize)
2886 , ValuesSet(InitValuesSetSize)
2890 , SectionSourceLines()
2893 , RootDbgScope(NULL)
2896 virtual ~DwarfDebug() {
2897 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2898 delete CompileUnits[i];
2899 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2903 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2904 /// This is inovked by the target AsmPrinter.
2905 void SetDebugInfo(MachineModuleInfo *mmi) {
2907 // Create all the compile unit DIEs.
2908 ConstructCompileUnits();
2915 MMI->setDebugInfoAvailability(true);
2917 // Create DIEs for each of the externally visible global variables.
2918 ConstructGlobalVariableDIEs();
2920 // Create DIEs for each of the externally visible subprograms.
2921 ConstructSubprograms();
2923 // Prime section data.
2924 SectionMap.insert(TAI->getTextSection());
2926 // Print out .file directives to specify files for .loc directives. These
2927 // are printed out early so that they precede any .loc directives.
2928 if (TAI->hasDotLocAndDotFile()) {
2929 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
2930 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
2931 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
2932 assert(AppendOk && "Could not append filename to directory!");
2934 Asm->EmitFile(i, FullPath.toString());
2939 // Emit initial sections
2943 /// BeginModule - Emit all Dwarf sections that should come prior to the
2945 void BeginModule(Module *M) {
2949 /// EndModule - Emit all Dwarf sections that should come after the content.
2952 if (!ShouldEmitDwarf()) return;
2954 // Standard sections final addresses.
2955 Asm->SwitchToSection(TAI->getTextSection());
2956 EmitLabel("text_end", 0);
2957 Asm->SwitchToSection(TAI->getDataSection());
2958 EmitLabel("data_end", 0);
2960 // End text sections.
2961 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2962 Asm->SwitchToSection(SectionMap[i]);
2963 EmitLabel("section_end", i);
2966 // Emit common frame information.
2967 EmitCommonDebugFrame();
2969 // Emit function debug frame information
2970 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2971 E = DebugFrames.end(); I != E; ++I)
2972 EmitFunctionDebugFrame(*I);
2974 // Compute DIE offsets and sizes.
2977 // Emit all the DIEs into a debug info section
2980 // Corresponding abbreviations into a abbrev section.
2981 EmitAbbreviations();
2983 // Emit source line correspondence into a debug line section.
2986 // Emit info into a debug pubnames section.
2987 EmitDebugPubNames();
2989 // Emit info into a debug str section.
2992 // Emit info into a debug loc section.
2995 // Emit info into a debug aranges section.
2998 // Emit info into a debug ranges section.
3001 // Emit info into a debug macinfo section.
3005 /// BeginFunction - Gather pre-function debug information. Assumes being
3006 /// emitted immediately after the function entry point.
3007 void BeginFunction(MachineFunction *MF) {
3010 if (!ShouldEmitDwarf()) return;
3012 // Begin accumulating function debug information.
3013 MMI->BeginFunction(MF);
3015 // Assumes in correct section after the entry point.
3016 EmitLabel("func_begin", ++SubprogramCount);
3018 // Emit label for the implicitly defined dbg.stoppoint at the start of
3020 if (!Lines.empty()) {
3021 const SrcLineInfo &LineInfo = Lines[0];
3022 Asm->printLabel(LineInfo.getLabelID());
3026 /// EndFunction - Gather and emit post-function debug information.
3028 void EndFunction(MachineFunction *MF) {
3029 if (!ShouldEmitDwarf()) return;
3031 // Define end label for subprogram.
3032 EmitLabel("func_end", SubprogramCount);
3034 // Get function line info.
3035 if (!Lines.empty()) {
3036 // Get section line info.
3037 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3038 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3039 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3040 // Append the function info to section info.
3041 SectionLineInfos.insert(SectionLineInfos.end(),
3042 Lines.begin(), Lines.end());
3045 // Construct scopes for subprogram.
3047 ConstructRootDbgScope(RootDbgScope);
3049 // FIXME: This is wrong. We are essentially getting past a problem with
3050 // debug information not being able to handle unreachable blocks that have
3051 // debug information in them. In particular, those unreachable blocks that
3052 // have "region end" info in them. That situation results in the "root
3053 // scope" not being created. If that's the case, then emit a "default"
3054 // scope, i.e., one that encompasses the whole function. This isn't
3055 // desirable. And a better way of handling this (and all of the debugging
3056 // information) needs to be explored.
3057 ConstructDefaultDbgScope(MF);
3059 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3060 MMI->getFrameMoves()));
3064 delete RootDbgScope;
3065 DbgScopeMap.clear();
3066 RootDbgScope = NULL;
3073 /// RecordSourceLine - Records location information and associates it with a
3074 /// label. Returns a unique label ID used to generate a label and provide
3075 /// correspondence to the source line list.
3076 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3077 CompileUnit *Unit = DW_CUs[V];
3078 assert (Unit && "Unable to find CompileUnit");
3079 unsigned ID = MMI->NextLabelID();
3080 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3084 /// RecordSourceLine - Records location information and associates it with a
3085 /// label. Returns a unique label ID used to generate a label and provide
3086 /// correspondence to the source line list.
3087 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3088 unsigned ID = MMI->NextLabelID();
3089 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3093 unsigned getRecordSourceLineCount() {
3094 return Lines.size();
3097 /// RecordSource - Register a source file with debug info. Returns an source
3099 unsigned RecordSource(const std::string &Directory,
3100 const std::string &File) {
3101 unsigned DID = Directories.insert(Directory);
3102 return SrcFiles.insert(SrcFileInfo(DID,File));
3105 /// RecordRegionStart - Indicate the start of a region.
3107 unsigned RecordRegionStart(GlobalVariable *V) {
3108 DbgScope *Scope = getOrCreateScope(V);
3109 unsigned ID = MMI->NextLabelID();
3110 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3114 /// RecordRegionEnd - Indicate the end of a region.
3116 unsigned RecordRegionEnd(GlobalVariable *V) {
3117 DbgScope *Scope = getOrCreateScope(V);
3118 unsigned ID = MMI->NextLabelID();
3119 Scope->setEndLabelID(ID);
3123 /// RecordVariable - Indicate the declaration of a local variable.
3125 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3126 DbgScope *Scope = getOrCreateScope(GV);
3127 DIVariable *VD = new DIVariable(GV);
3128 DbgVariable *DV = new DbgVariable(VD, FrameIndex);
3129 Scope->AddVariable(DV);
3133 //===----------------------------------------------------------------------===//
3134 /// DwarfException - Emits Dwarf exception handling directives.
3136 class DwarfException : public Dwarf {
3139 struct FunctionEHFrameInfo {
3142 unsigned PersonalityIndex;
3144 bool hasLandingPads;
3145 std::vector<MachineMove> Moves;
3146 const Function * function;
3148 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3150 const std::vector<MachineMove> &M,
3152 FnName(FN), Number(Num), PersonalityIndex(P),
3153 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3156 std::vector<FunctionEHFrameInfo> EHFrames;
3158 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3160 bool shouldEmitTable;
3162 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3163 /// should be emitted.
3164 bool shouldEmitMoves;
3166 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3167 /// should be emitted.
3168 bool shouldEmitTableModule;
3170 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3171 /// should be emitted.
3172 bool shouldEmitMovesModule;
3174 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3176 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3177 // Size and sign of stack growth.
3179 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3180 TargetFrameInfo::StackGrowsUp ?
3181 TD->getPointerSize() : -TD->getPointerSize();
3183 // Begin eh frame section.
3184 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3186 if (!TAI->doesRequireNonLocalEHFrameLabel())
3187 O << TAI->getEHGlobalPrefix();
3188 O << "EH_frame" << Index << ":\n";
3189 EmitLabel("section_eh_frame", Index);
3191 // Define base labels.
3192 EmitLabel("eh_frame_common", Index);
3194 // Define the eh frame length.
3195 EmitDifference("eh_frame_common_end", Index,
3196 "eh_frame_common_begin", Index, true);
3197 Asm->EOL("Length of Common Information Entry");
3200 EmitLabel("eh_frame_common_begin", Index);
3201 Asm->EmitInt32((int)0);
3202 Asm->EOL("CIE Identifier Tag");
3203 Asm->EmitInt8(DW_CIE_VERSION);
3204 Asm->EOL("CIE Version");
3206 // The personality presence indicates that language specific information
3207 // will show up in the eh frame.
3208 Asm->EmitString(Personality ? "zPLR" : "zR");
3209 Asm->EOL("CIE Augmentation");
3211 // Round out reader.
3212 Asm->EmitULEB128Bytes(1);
3213 Asm->EOL("CIE Code Alignment Factor");
3214 Asm->EmitSLEB128Bytes(stackGrowth);
3215 Asm->EOL("CIE Data Alignment Factor");
3216 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3217 Asm->EOL("CIE Return Address Column");
3219 // If there is a personality, we need to indicate the functions location.
3221 Asm->EmitULEB128Bytes(7);
3222 Asm->EOL("Augmentation Size");
3224 if (TAI->getNeedsIndirectEncoding()) {
3225 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3226 Asm->EOL("Personality (pcrel sdata4 indirect)");
3228 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3229 Asm->EOL("Personality (pcrel sdata4)");
3232 PrintRelDirective(true);
3233 O << TAI->getPersonalityPrefix();
3234 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3235 O << TAI->getPersonalitySuffix();
3236 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3237 O << "-" << TAI->getPCSymbol();
3238 Asm->EOL("Personality");
3240 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3241 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3243 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3244 Asm->EOL("FDE Encoding (pcrel sdata4)");
3246 Asm->EmitULEB128Bytes(1);
3247 Asm->EOL("Augmentation Size");
3249 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3250 Asm->EOL("FDE Encoding (pcrel sdata4)");
3253 // Indicate locations of general callee saved registers in frame.
3254 std::vector<MachineMove> Moves;
3255 RI->getInitialFrameState(Moves);
3256 EmitFrameMoves(NULL, 0, Moves, true);
3258 // On Darwin the linker honors the alignment of eh_frame, which means it
3259 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3260 // you get holes which confuse readers of eh_frame.
3261 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3263 EmitLabel("eh_frame_common_end", Index);
3268 /// EmitEHFrame - Emit function exception frame information.
3270 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3271 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3273 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3275 // Externally visible entry into the functions eh frame info.
3276 // If the corresponding function is static, this should not be
3277 // externally visible.
3278 if (linkage != Function::InternalLinkage) {
3279 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3280 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3283 // If corresponding function is weak definition, this should be too.
3284 if ((linkage == Function::WeakLinkage ||
3285 linkage == Function::LinkOnceLinkage) &&
3286 TAI->getWeakDefDirective())
3287 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3289 // If there are no calls then you can't unwind. This may mean we can
3290 // omit the EH Frame, but some environments do not handle weak absolute
3292 // If UnwindTablesMandatory is set we cannot do this optimization; the
3293 // unwind info is to be available for non-EH uses.
3294 if (!EHFrameInfo.hasCalls &&
3295 !UnwindTablesMandatory &&
3296 ((linkage != Function::WeakLinkage &&
3297 linkage != Function::LinkOnceLinkage) ||
3298 !TAI->getWeakDefDirective() ||
3299 TAI->getSupportsWeakOmittedEHFrame()))
3301 O << EHFrameInfo.FnName << " = 0\n";
3302 // This name has no connection to the function, so it might get
3303 // dead-stripped when the function is not, erroneously. Prohibit
3304 // dead-stripping unconditionally.
3305 if (const char *UsedDirective = TAI->getUsedDirective())
3306 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3308 O << EHFrameInfo.FnName << ":\n";
3311 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3312 "eh_frame_begin", EHFrameInfo.Number, true);
3313 Asm->EOL("Length of Frame Information Entry");
3315 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3317 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3318 PrintRelDirective(true, true);
3319 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3321 if (!TAI->isAbsoluteEHSectionOffsets())
3322 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3324 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3325 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3329 Asm->EOL("FDE CIE offset");
3331 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3332 Asm->EOL("FDE initial location");
3333 EmitDifference("eh_func_end", EHFrameInfo.Number,
3334 "eh_func_begin", EHFrameInfo.Number, true);
3335 Asm->EOL("FDE address range");
3337 // If there is a personality and landing pads then point to the language
3338 // specific data area in the exception table.
3339 if (EHFrameInfo.PersonalityIndex) {
3340 Asm->EmitULEB128Bytes(4);
3341 Asm->EOL("Augmentation size");
3343 if (EHFrameInfo.hasLandingPads)
3344 EmitReference("exception", EHFrameInfo.Number, true, true);
3346 Asm->EmitInt32((int)0);
3347 Asm->EOL("Language Specific Data Area");
3349 Asm->EmitULEB128Bytes(0);
3350 Asm->EOL("Augmentation size");
3353 // Indicate locations of function specific callee saved registers in
3355 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3357 // On Darwin the linker honors the alignment of eh_frame, which means it
3358 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3359 // you get holes which confuse readers of eh_frame.
3360 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3362 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3364 // If the function is marked used, this table should be also. We cannot
3365 // make the mark unconditional in this case, since retaining the table
3366 // also retains the function in this case, and there is code around
3367 // that depends on unused functions (calling undefined externals) being
3368 // dead-stripped to link correctly. Yes, there really is.
3369 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3370 if (const char *UsedDirective = TAI->getUsedDirective())
3371 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3375 /// EmitExceptionTable - Emit landing pads and actions.
3377 /// The general organization of the table is complex, but the basic concepts
3378 /// are easy. First there is a header which describes the location and
3379 /// organization of the three components that follow.
3380 /// 1. The landing pad site information describes the range of code covered
3381 /// by the try. In our case it's an accumulation of the ranges covered
3382 /// by the invokes in the try. There is also a reference to the landing
3383 /// pad that handles the exception once processed. Finally an index into
3384 /// the actions table.
3385 /// 2. The action table, in our case, is composed of pairs of type ids
3386 /// and next action offset. Starting with the action index from the
3387 /// landing pad site, each type Id is checked for a match to the current
3388 /// exception. If it matches then the exception and type id are passed
3389 /// on to the landing pad. Otherwise the next action is looked up. This
3390 /// chain is terminated with a next action of zero. If no type id is
3391 /// found the the frame is unwound and handling continues.
3392 /// 3. Type id table contains references to all the C++ typeinfo for all
3393 /// catches in the function. This tables is reversed indexed base 1.
3395 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3396 static unsigned SharedTypeIds(const LandingPadInfo *L,
3397 const LandingPadInfo *R) {
3398 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3399 unsigned LSize = LIds.size(), RSize = RIds.size();
3400 unsigned MinSize = LSize < RSize ? LSize : RSize;
3403 for (; Count != MinSize; ++Count)
3404 if (LIds[Count] != RIds[Count])
3410 /// PadLT - Order landing pads lexicographically by type id.
3411 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3412 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3413 unsigned LSize = LIds.size(), RSize = RIds.size();
3414 unsigned MinSize = LSize < RSize ? LSize : RSize;
3416 for (unsigned i = 0; i != MinSize; ++i)
3417 if (LIds[i] != RIds[i])
3418 return LIds[i] < RIds[i];
3420 return LSize < RSize;
3424 static inline unsigned getEmptyKey() { return -1U; }
3425 static inline unsigned getTombstoneKey() { return -2U; }
3426 static unsigned getHashValue(const unsigned &Key) { return Key; }
3427 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3428 static bool isPod() { return true; }
3431 /// ActionEntry - Structure describing an entry in the actions table.
3432 struct ActionEntry {
3433 int ValueForTypeID; // The value to write - may not be equal to the type id.
3435 struct ActionEntry *Previous;
3438 /// PadRange - Structure holding a try-range and the associated landing pad.
3440 // The index of the landing pad.
3442 // The index of the begin and end labels in the landing pad's label lists.
3443 unsigned RangeIndex;
3446 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3448 /// CallSiteEntry - Structure describing an entry in the call-site table.
3449 struct CallSiteEntry {
3450 // The 'try-range' is BeginLabel .. EndLabel.
3451 unsigned BeginLabel; // zero indicates the start of the function.
3452 unsigned EndLabel; // zero indicates the end of the function.
3453 // The landing pad starts at PadLabel.
3454 unsigned PadLabel; // zero indicates that there is no landing pad.
3458 void EmitExceptionTable() {
3459 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3460 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3461 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3462 if (PadInfos.empty()) return;
3464 // Sort the landing pads in order of their type ids. This is used to fold
3465 // duplicate actions.
3466 SmallVector<const LandingPadInfo *, 64> LandingPads;
3467 LandingPads.reserve(PadInfos.size());
3468 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3469 LandingPads.push_back(&PadInfos[i]);
3470 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3472 // Negative type ids index into FilterIds, positive type ids index into
3473 // TypeInfos. The value written for a positive type id is just the type
3474 // id itself. For a negative type id, however, the value written is the
3475 // (negative) byte offset of the corresponding FilterIds entry. The byte
3476 // offset is usually equal to the type id, because the FilterIds entries
3477 // are written using a variable width encoding which outputs one byte per
3478 // entry as long as the value written is not too large, but can differ.
3479 // This kind of complication does not occur for positive type ids because
3480 // type infos are output using a fixed width encoding.
3481 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3482 SmallVector<int, 16> FilterOffsets;
3483 FilterOffsets.reserve(FilterIds.size());
3485 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3486 E = FilterIds.end(); I != E; ++I) {
3487 FilterOffsets.push_back(Offset);
3488 Offset -= TargetAsmInfo::getULEB128Size(*I);
3491 // Compute the actions table and gather the first action index for each
3492 // landing pad site.
3493 SmallVector<ActionEntry, 32> Actions;
3494 SmallVector<unsigned, 64> FirstActions;
3495 FirstActions.reserve(LandingPads.size());
3497 int FirstAction = 0;
3498 unsigned SizeActions = 0;
3499 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3500 const LandingPadInfo *LP = LandingPads[i];
3501 const std::vector<int> &TypeIds = LP->TypeIds;
3502 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3503 unsigned SizeSiteActions = 0;
3505 if (NumShared < TypeIds.size()) {
3506 unsigned SizeAction = 0;
3507 ActionEntry *PrevAction = 0;
3510 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3511 assert(Actions.size());
3512 PrevAction = &Actions.back();
3513 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3514 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3515 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3517 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3518 SizeAction += -PrevAction->NextAction;
3519 PrevAction = PrevAction->Previous;
3523 // Compute the actions.
3524 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3525 int TypeID = TypeIds[I];
3526 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3527 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3528 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3530 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3531 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3532 SizeSiteActions += SizeAction;
3534 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3535 Actions.push_back(Action);
3537 PrevAction = &Actions.back();
3540 // Record the first action of the landing pad site.
3541 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3542 } // else identical - re-use previous FirstAction
3544 FirstActions.push_back(FirstAction);
3546 // Compute this sites contribution to size.
3547 SizeActions += SizeSiteActions;
3550 // Compute the call-site table. The entry for an invoke has a try-range
3551 // containing the call, a non-zero landing pad and an appropriate action.
3552 // The entry for an ordinary call has a try-range containing the call and
3553 // zero for the landing pad and the action. Calls marked 'nounwind' have
3554 // no entry and must not be contained in the try-range of any entry - they
3555 // form gaps in the table. Entries must be ordered by try-range address.
3556 SmallVector<CallSiteEntry, 64> CallSites;
3558 RangeMapType PadMap;
3559 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3560 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3561 // try-ranges for them need be deduced.
3562 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3563 const LandingPadInfo *LandingPad = LandingPads[i];
3564 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3565 unsigned BeginLabel = LandingPad->BeginLabels[j];
3566 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3567 PadRange P = { i, j };
3568 PadMap[BeginLabel] = P;
3572 // The end label of the previous invoke or nounwind try-range.
3573 unsigned LastLabel = 0;
3575 // Whether there is a potentially throwing instruction (currently this means
3576 // an ordinary call) between the end of the previous try-range and now.
3577 bool SawPotentiallyThrowing = false;
3579 // Whether the last callsite entry was for an invoke.
3580 bool PreviousIsInvoke = false;
3582 // Visit all instructions in order of address.
3583 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3585 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3587 if (!MI->isLabel()) {
3588 SawPotentiallyThrowing |= MI->getDesc().isCall();
3592 unsigned BeginLabel = MI->getOperand(0).getImm();
3593 assert(BeginLabel && "Invalid label!");
3595 // End of the previous try-range?
3596 if (BeginLabel == LastLabel)
3597 SawPotentiallyThrowing = false;
3599 // Beginning of a new try-range?
3600 RangeMapType::iterator L = PadMap.find(BeginLabel);
3601 if (L == PadMap.end())
3602 // Nope, it was just some random label.
3605 PadRange P = L->second;
3606 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3608 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3609 "Inconsistent landing pad map!");
3611 // If some instruction between the previous try-range and this one may
3612 // throw, create a call-site entry with no landing pad for the region
3613 // between the try-ranges.
3614 if (SawPotentiallyThrowing) {
3615 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3616 CallSites.push_back(Site);
3617 PreviousIsInvoke = false;
3620 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3621 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3623 if (LandingPad->LandingPadLabel) {
3624 // This try-range is for an invoke.
3625 CallSiteEntry Site = {BeginLabel, LastLabel,
3626 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3628 // Try to merge with the previous call-site.
3629 if (PreviousIsInvoke) {
3630 CallSiteEntry &Prev = CallSites.back();
3631 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3632 // Extend the range of the previous entry.
3633 Prev.EndLabel = Site.EndLabel;
3638 // Otherwise, create a new call-site.
3639 CallSites.push_back(Site);
3640 PreviousIsInvoke = true;
3643 PreviousIsInvoke = false;
3647 // If some instruction between the previous try-range and the end of the
3648 // function may throw, create a call-site entry with no landing pad for the
3649 // region following the try-range.
3650 if (SawPotentiallyThrowing) {
3651 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3652 CallSites.push_back(Site);
3658 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3659 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3660 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3661 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3664 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3665 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3668 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3669 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3671 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3672 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3673 SizeSites + SizeActions + SizeTypes;
3675 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3676 sizeof(int8_t) + // TType format
3677 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3680 unsigned SizeAlign = (4 - TotalSize) & 3;
3682 // Begin the exception table.
3683 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3684 Asm->EmitAlignment(2, 0, 0, false);
3685 O << "GCC_except_table" << SubprogramCount << ":\n";
3686 for (unsigned i = 0; i != SizeAlign; ++i) {
3688 Asm->EOL("Padding");
3690 EmitLabel("exception", SubprogramCount);
3693 Asm->EmitInt8(DW_EH_PE_omit);
3694 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3695 Asm->EmitInt8(DW_EH_PE_absptr);
3696 Asm->EOL("TType format (DW_EH_PE_absptr)");
3697 Asm->EmitULEB128Bytes(TypeOffset);
3698 Asm->EOL("TType base offset");
3699 Asm->EmitInt8(DW_EH_PE_udata4);
3700 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3701 Asm->EmitULEB128Bytes(SizeSites);
3702 Asm->EOL("Call-site table length");
3704 // Emit the landing pad site information.
3705 for (unsigned i = 0; i < CallSites.size(); ++i) {
3706 CallSiteEntry &S = CallSites[i];
3707 const char *BeginTag;
3708 unsigned BeginNumber;
3710 if (!S.BeginLabel) {
3711 BeginTag = "eh_func_begin";
3712 BeginNumber = SubprogramCount;
3715 BeginNumber = S.BeginLabel;
3718 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3720 Asm->EOL("Region start");
3723 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3726 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3728 Asm->EOL("Region length");
3733 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3735 Asm->EOL("Landing pad");
3737 Asm->EmitULEB128Bytes(S.Action);
3741 // Emit the actions.
3742 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3743 ActionEntry &Action = Actions[I];
3745 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3746 Asm->EOL("TypeInfo index");
3747 Asm->EmitSLEB128Bytes(Action.NextAction);
3748 Asm->EOL("Next action");
3751 // Emit the type ids.
3752 for (unsigned M = TypeInfos.size(); M; --M) {
3753 GlobalVariable *GV = TypeInfos[M - 1];
3755 PrintRelDirective();
3758 O << Asm->getGlobalLinkName(GV);
3762 Asm->EOL("TypeInfo");
3765 // Emit the filter typeids.
3766 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3767 unsigned TypeID = FilterIds[j];
3768 Asm->EmitULEB128Bytes(TypeID);
3769 Asm->EOL("Filter TypeInfo index");
3772 Asm->EmitAlignment(2, 0, 0, false);
3776 //===--------------------------------------------------------------------===//
3777 // Main entry points.
3779 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3780 : Dwarf(OS, A, T, "eh")
3781 , shouldEmitTable(false)
3782 , shouldEmitMoves(false)
3783 , shouldEmitTableModule(false)
3784 , shouldEmitMovesModule(false)
3787 virtual ~DwarfException() {}
3789 /// SetModuleInfo - Set machine module information when it's known that pass
3790 /// manager has created it. Set by the target AsmPrinter.
3791 void SetModuleInfo(MachineModuleInfo *mmi) {
3795 /// BeginModule - Emit all exception information that should come prior to the
3797 void BeginModule(Module *M) {
3801 /// EndModule - Emit all exception information that should come after the
3804 if (shouldEmitMovesModule || shouldEmitTableModule) {
3805 const std::vector<Function *> Personalities = MMI->getPersonalities();
3806 for (unsigned i =0; i < Personalities.size(); ++i)
3807 EmitCommonEHFrame(Personalities[i], i);
3809 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3810 E = EHFrames.end(); I != E; ++I)
3815 /// BeginFunction - Gather pre-function exception information. Assumes being
3816 /// emitted immediately after the function entry point.
3817 void BeginFunction(MachineFunction *MF) {
3819 shouldEmitTable = shouldEmitMoves = false;
3820 if (MMI && TAI->doesSupportExceptionHandling()) {
3822 // Map all labels and get rid of any dead landing pads.
3823 MMI->TidyLandingPads();
3824 // If any landing pads survive, we need an EH table.
3825 if (MMI->getLandingPads().size())
3826 shouldEmitTable = true;
3828 // See if we need frame move info.
3829 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3830 shouldEmitMoves = true;
3832 if (shouldEmitMoves || shouldEmitTable)
3833 // Assumes in correct section after the entry point.
3834 EmitLabel("eh_func_begin", ++SubprogramCount);
3836 shouldEmitTableModule |= shouldEmitTable;
3837 shouldEmitMovesModule |= shouldEmitMoves;
3840 /// EndFunction - Gather and emit post-function exception information.
3842 void EndFunction() {
3843 if (shouldEmitMoves || shouldEmitTable) {
3844 EmitLabel("eh_func_end", SubprogramCount);
3845 EmitExceptionTable();
3847 // Save EH frame information
3849 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3851 MMI->getPersonalityIndex(),
3852 MF->getFrameInfo()->hasCalls(),
3853 !MMI->getLandingPads().empty(),
3854 MMI->getFrameMoves(),
3855 MF->getFunction()));
3860 } // End of namespace llvm
3862 //===----------------------------------------------------------------------===//
3864 /// Emit - Print the abbreviation using the specified Dwarf writer.
3866 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3867 // Emit its Dwarf tag type.
3868 DD.getAsm()->EmitULEB128Bytes(Tag);
3869 DD.getAsm()->EOL(TagString(Tag));
3871 // Emit whether it has children DIEs.
3872 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3873 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3875 // For each attribute description.
3876 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3877 const DIEAbbrevData &AttrData = Data[i];
3879 // Emit attribute type.
3880 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3881 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3884 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3885 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3888 // Mark end of abbreviation.
3889 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3890 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3894 void DIEAbbrev::print(std::ostream &O) {
3895 O << "Abbreviation @"
3896 << std::hex << (intptr_t)this << std::dec
3900 << ChildrenString(ChildrenFlag)
3903 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3905 << AttributeString(Data[i].getAttribute())
3907 << FormEncodingString(Data[i].getForm())
3911 void DIEAbbrev::dump() { print(cerr); }
3914 //===----------------------------------------------------------------------===//
3917 void DIEValue::dump() {
3922 //===----------------------------------------------------------------------===//
3924 /// EmitValue - Emit integer of appropriate size.
3926 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3928 case DW_FORM_flag: // Fall thru
3929 case DW_FORM_ref1: // Fall thru
3930 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3931 case DW_FORM_ref2: // Fall thru
3932 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3933 case DW_FORM_ref4: // Fall thru
3934 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3935 case DW_FORM_ref8: // Fall thru
3936 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3937 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3938 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3939 default: assert(0 && "DIE Value form not supported yet"); break;
3943 /// SizeOf - Determine size of integer value in bytes.
3945 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3947 case DW_FORM_flag: // Fall thru
3948 case DW_FORM_ref1: // Fall thru
3949 case DW_FORM_data1: return sizeof(int8_t);
3950 case DW_FORM_ref2: // Fall thru
3951 case DW_FORM_data2: return sizeof(int16_t);
3952 case DW_FORM_ref4: // Fall thru
3953 case DW_FORM_data4: return sizeof(int32_t);
3954 case DW_FORM_ref8: // Fall thru
3955 case DW_FORM_data8: return sizeof(int64_t);
3956 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
3957 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
3958 default: assert(0 && "DIE Value form not supported yet"); break;
3963 //===----------------------------------------------------------------------===//
3965 /// EmitValue - Emit string value.
3967 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3968 DD.getAsm()->EmitString(String);
3971 //===----------------------------------------------------------------------===//
3973 /// EmitValue - Emit label value.
3975 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3976 bool IsSmall = Form == DW_FORM_data4;
3977 DD.EmitReference(Label, false, IsSmall);
3980 /// SizeOf - Determine size of label value in bytes.
3982 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3983 if (Form == DW_FORM_data4) return 4;
3984 return DD.getTargetData()->getPointerSize();
3987 //===----------------------------------------------------------------------===//
3989 /// EmitValue - Emit label value.
3991 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3992 bool IsSmall = Form == DW_FORM_data4;
3993 DD.EmitReference(Label, false, IsSmall);
3996 /// SizeOf - Determine size of label value in bytes.
3998 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3999 if (Form == DW_FORM_data4) return 4;
4000 return DD.getTargetData()->getPointerSize();
4003 //===----------------------------------------------------------------------===//
4005 /// EmitValue - Emit delta value.
4007 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4008 bool IsSmall = Form == DW_FORM_data4;
4009 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4010 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4013 /// SizeOf - Determine size of delta value in bytes.
4015 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4016 if (Form == DW_FORM_data4) return 4;
4017 return DD.getTargetData()->getPointerSize();
4020 //===----------------------------------------------------------------------===//
4022 /// EmitValue - Emit delta value.
4024 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4025 bool IsSmall = Form == DW_FORM_data4;
4026 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4029 /// SizeOf - Determine size of delta value in bytes.
4031 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4032 if (Form == DW_FORM_data4) return 4;
4033 return DD.getTargetData()->getPointerSize();
4036 //===----------------------------------------------------------------------===//
4038 /// EmitValue - Emit debug information entry offset.
4040 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4041 DD.getAsm()->EmitInt32(Entry->getOffset());
4044 //===----------------------------------------------------------------------===//
4046 /// ComputeSize - calculate the size of the block.
4048 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4050 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4052 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4053 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4059 /// EmitValue - Emit block data.
4061 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4063 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4064 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4065 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4066 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4067 default: assert(0 && "Improper form for block"); break;
4070 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4072 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4074 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4078 /// SizeOf - Determine size of block data in bytes.
4080 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4082 case DW_FORM_block1: return Size + sizeof(int8_t);
4083 case DW_FORM_block2: return Size + sizeof(int16_t);
4084 case DW_FORM_block4: return Size + sizeof(int32_t);
4085 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4086 default: assert(0 && "Improper form for block"); break;
4091 //===----------------------------------------------------------------------===//
4092 /// DIE Implementation
4095 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4099 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4101 void DIE::AddSiblingOffset() {
4102 DIEInteger *DI = new DIEInteger(0);
4103 Values.insert(Values.begin(), DI);
4104 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4107 /// Profile - Used to gather unique data for the value folding set.
4109 void DIE::Profile(FoldingSetNodeID &ID) {
4112 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4113 ID.AddPointer(Children[i]);
4115 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4116 ID.AddPointer(Values[j]);
4120 void DIE::print(std::ostream &O, unsigned IncIndent) {
4121 static unsigned IndentCount = 0;
4122 IndentCount += IncIndent;
4123 const std::string Indent(IndentCount, ' ');
4124 bool isBlock = Abbrev.getTag() == 0;
4129 << "0x" << std::hex << (intptr_t)this << std::dec
4130 << ", Offset: " << Offset
4131 << ", Size: " << Size
4135 << TagString(Abbrev.getTag())
4137 << ChildrenString(Abbrev.getChildrenFlag());
4139 O << "Size: " << Size;
4143 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4146 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4150 O << AttributeString(Data[i].getAttribute());
4152 O << "Blk[" << i << "]";
4155 << FormEncodingString(Data[i].getForm())
4157 Values[i]->print(O);
4162 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4163 Children[j]->print(O, 4);
4166 if (!isBlock) O << "\n";
4167 IndentCount -= IncIndent;
4175 //===----------------------------------------------------------------------===//
4176 /// DwarfWriter Implementation
4179 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4182 DwarfWriter::~DwarfWriter() {
4187 /// BeginModule - Emit all Dwarf sections that should come prior to the
4189 void DwarfWriter::BeginModule(Module *M,
4190 MachineModuleInfo *MMI,
4191 raw_ostream &OS, AsmPrinter *A,
4192 const TargetAsmInfo *T) {
4193 DE = new DwarfException(OS, A, T);
4194 DD = new DwarfDebug(OS, A, T);
4197 DD->SetDebugInfo(MMI);
4198 DE->SetModuleInfo(MMI);
4201 /// EndModule - Emit all Dwarf sections that should come after the content.
4203 void DwarfWriter::EndModule() {
4208 /// BeginFunction - Gather pre-function debug information. Assumes being
4209 /// emitted immediately after the function entry point.
4210 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4211 DE->BeginFunction(MF);
4212 DD->BeginFunction(MF);
4215 /// EndFunction - Gather and emit post-function debug information.
4217 void DwarfWriter::EndFunction(MachineFunction *MF) {
4218 DD->EndFunction(MF);
4221 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4222 // Clear function debug information.
4226 /// RecordSourceLine - Records location information and associates it with a
4227 /// label. Returns a unique label ID used to generate a label and provide
4228 /// correspondence to the source line list.
4229 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4231 return DD->RecordSourceLine(Line, Col, Src);
4234 /// RecordSource - Register a source file with debug info. Returns an source
4236 unsigned DwarfWriter::RecordSource(const std::string &Dir,
4237 const std::string &File) {
4238 return DD->RecordSource(Dir, File);
4241 /// RecordRegionStart - Indicate the start of a region.
4242 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4243 return DD->RecordRegionStart(V);
4246 /// RecordRegionEnd - Indicate the end of a region.
4247 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4248 return DD->RecordRegionEnd(V);
4251 /// getRecordSourceLineCount - Count source lines.
4252 unsigned DwarfWriter::getRecordSourceLineCount() {
4253 return DD->getRecordSourceLineCount();
4256 /// RecordVariable - Indicate the declaration of a local variable.
4258 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4259 DD->RecordVariable(GV, FrameIndex);