1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/Analysis/DebugInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/FoldingSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringMap.h"
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
51 static TimerGroup &getDwarfTimerGroup() {
52 static TimerGroup DwarfTimerGroup("Dwarf Exception and Debugging");
53 return DwarfTimerGroup;
58 //===----------------------------------------------------------------------===//
60 /// Configuration values for initial hash set sizes (log2).
62 static const unsigned InitDiesSetSize = 9; // log2(512)
63 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
64 static const unsigned InitValuesSetSize = 9; // log2(512)
66 //===----------------------------------------------------------------------===//
67 /// Forward declarations.
72 //===----------------------------------------------------------------------===//
75 /// getGlobalVariable - Return either a direct or cast Global value.
77 static GlobalVariable *getGlobalVariable(Value *V) {
78 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
80 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
81 if (CE->getOpcode() == Instruction::BitCast) {
82 return dyn_cast<GlobalVariable>(CE->getOperand(0));
83 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
84 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
85 if (!CE->getOperand(i)->isNullValue())
88 return dyn_cast<GlobalVariable>(CE->getOperand(0));
94 //===----------------------------------------------------------------------===//
95 /// DWLabel - Labels are used to track locations in the assembler file.
96 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
97 /// where the tag is a category of label (Ex. location) and number is a value
98 /// unique in that category.
101 /// Tag - Label category tag. Should always be a staticly declared C string.
105 /// Number - Value to make label unique.
109 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
111 void Profile(FoldingSetNodeID &ID) const {
113 ID.AddInteger(Number);
117 void print(std::ostream *O) const {
120 void print(std::ostream &O) const {
122 if (Number) O << Number;
127 //===----------------------------------------------------------------------===//
128 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
129 /// Dwarf abbreviation.
130 class DIEAbbrevData {
132 /// Attribute - Dwarf attribute code.
136 /// Form - Dwarf form code.
141 DIEAbbrevData(unsigned A, unsigned F)
147 unsigned getAttribute() const { return Attribute; }
148 unsigned getForm() const { return Form; }
150 /// Profile - Used to gather unique data for the abbreviation folding set.
152 void Profile(FoldingSetNodeID &ID)const {
153 ID.AddInteger(Attribute);
158 //===----------------------------------------------------------------------===//
159 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
160 /// information object.
161 class DIEAbbrev : public FoldingSetNode {
163 /// Tag - Dwarf tag code.
167 /// Unique number for node.
171 /// ChildrenFlag - Dwarf children flag.
173 unsigned ChildrenFlag;
175 /// Data - Raw data bytes for abbreviation.
177 SmallVector<DIEAbbrevData, 8> Data;
181 DIEAbbrev(unsigned T, unsigned C)
189 unsigned getTag() const { return Tag; }
190 unsigned getNumber() const { return Number; }
191 unsigned getChildrenFlag() const { return ChildrenFlag; }
192 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
193 void setTag(unsigned T) { Tag = T; }
194 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
195 void setNumber(unsigned N) { Number = N; }
197 /// AddAttribute - Adds another set of attribute information to the
199 void AddAttribute(unsigned Attribute, unsigned Form) {
200 Data.push_back(DIEAbbrevData(Attribute, Form));
203 /// AddFirstAttribute - Adds a set of attribute information to the front
204 /// of the abbreviation.
205 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
206 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
209 /// Profile - Used to gather unique data for the abbreviation folding set.
211 void Profile(FoldingSetNodeID &ID) {
213 ID.AddInteger(ChildrenFlag);
215 // For each attribute description.
216 for (unsigned i = 0, N = Data.size(); i < N; ++i)
220 /// Emit - Print the abbreviation using the specified Dwarf writer.
222 void Emit(const DwarfDebug &DD) const;
225 void print(std::ostream *O) {
228 void print(std::ostream &O);
233 //===----------------------------------------------------------------------===//
234 /// DIE - A structured debug information entry. Has an abbreviation which
235 /// describes it's organization.
236 class DIE : public FoldingSetNode {
238 /// Abbrev - Buffer for constructing abbreviation.
242 /// Offset - Offset in debug info section.
246 /// Size - Size of instance + children.
252 std::vector<DIE *> Children;
254 /// Attributes values.
256 SmallVector<DIEValue*, 32> Values;
259 explicit DIE(unsigned Tag)
260 : Abbrev(Tag, DW_CHILDREN_no)
269 DIEAbbrev &getAbbrev() { return Abbrev; }
270 unsigned getAbbrevNumber() const {
271 return Abbrev.getNumber();
273 unsigned getTag() const { return Abbrev.getTag(); }
274 unsigned getOffset() const { return Offset; }
275 unsigned getSize() const { return Size; }
276 const std::vector<DIE *> &getChildren() const { return Children; }
277 SmallVector<DIEValue*, 32> &getValues() { return Values; }
278 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
279 void setOffset(unsigned O) { Offset = O; }
280 void setSize(unsigned S) { Size = S; }
282 /// AddValue - Add a value and attributes to a DIE.
284 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
285 Abbrev.AddAttribute(Attribute, Form);
286 Values.push_back(Value);
289 /// SiblingOffset - Return the offset of the debug information entry's
291 unsigned SiblingOffset() const { return Offset + Size; }
293 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
295 void AddSiblingOffset();
297 /// AddChild - Add a child to the DIE.
299 void AddChild(DIE *Child) {
300 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
301 Children.push_back(Child);
304 /// Detach - Detaches objects connected to it after copying.
310 /// Profile - Used to gather unique data for the value folding set.
312 void Profile(FoldingSetNodeID &ID) ;
315 void print(std::ostream *O, unsigned IncIndent = 0) {
316 if (O) print(*O, IncIndent);
318 void print(std::ostream &O, unsigned IncIndent = 0);
323 //===----------------------------------------------------------------------===//
324 /// DIEValue - A debug information entry value.
326 class DIEValue : public FoldingSetNode {
339 /// Type - Type of data stored in the value.
343 explicit DIEValue(unsigned T)
346 virtual ~DIEValue() {}
349 unsigned getType() const { return Type; }
351 // Implement isa/cast/dyncast.
352 static bool classof(const DIEValue *) { return true; }
354 /// EmitValue - Emit value via the Dwarf writer.
356 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
358 /// SizeOf - Return the size of a value in bytes.
360 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
362 /// Profile - Used to gather unique data for the value folding set.
364 virtual void Profile(FoldingSetNodeID &ID) = 0;
367 void print(std::ostream *O) {
370 virtual void print(std::ostream &O) = 0;
375 //===----------------------------------------------------------------------===//
376 /// DWInteger - An integer value DIE.
378 class DIEInteger : public DIEValue {
383 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
385 // Implement isa/cast/dyncast.
386 static bool classof(const DIEInteger *) { return true; }
387 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
389 /// BestForm - Choose the best form for integer.
391 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
393 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
394 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
395 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
397 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
398 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
399 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
401 return DW_FORM_data8;
404 /// EmitValue - Emit integer of appropriate size.
406 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
408 /// SizeOf - Determine size of integer value in bytes.
410 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
412 /// Profile - Used to gather unique data for the value folding set.
414 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
415 ID.AddInteger(isInteger);
416 ID.AddInteger(Integer);
418 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
421 virtual void print(std::ostream &O) {
422 O << "Int: " << (int64_t)Integer
423 << " 0x" << std::hex << Integer << std::dec;
428 //===----------------------------------------------------------------------===//
429 /// DIEString - A string value DIE.
431 class DIEString : public DIEValue {
433 const std::string String;
435 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
437 // Implement isa/cast/dyncast.
438 static bool classof(const DIEString *) { return true; }
439 static bool classof(const DIEValue *S) { return S->Type == isString; }
441 /// EmitValue - Emit string value.
443 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
445 /// SizeOf - Determine size of string value in bytes.
447 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
448 return String.size() + sizeof(char); // sizeof('\0');
451 /// Profile - Used to gather unique data for the value folding set.
453 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
454 ID.AddInteger(isString);
455 ID.AddString(String);
457 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
460 virtual void print(std::ostream &O) {
461 O << "Str: \"" << String << "\"";
466 //===----------------------------------------------------------------------===//
467 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
469 class DIEDwarfLabel : public DIEValue {
474 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
476 // Implement isa/cast/dyncast.
477 static bool classof(const DIEDwarfLabel *) { return true; }
478 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
480 /// EmitValue - Emit label value.
482 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
484 /// SizeOf - Determine size of label value in bytes.
486 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
488 /// Profile - Used to gather unique data for the value folding set.
490 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
491 ID.AddInteger(isLabel);
494 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
497 virtual void print(std::ostream &O) {
505 //===----------------------------------------------------------------------===//
506 /// DIEObjectLabel - A label to an object in code or data.
508 class DIEObjectLabel : public DIEValue {
510 const std::string Label;
512 explicit DIEObjectLabel(const std::string &L)
513 : DIEValue(isAsIsLabel), Label(L) {}
515 // Implement isa/cast/dyncast.
516 static bool classof(const DIEObjectLabel *) { return true; }
517 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
519 /// EmitValue - Emit label value.
521 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
523 /// SizeOf - Determine size of label value in bytes.
525 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
527 /// Profile - Used to gather unique data for the value folding set.
529 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
530 ID.AddInteger(isAsIsLabel);
533 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
536 virtual void print(std::ostream &O) {
537 O << "Obj: " << Label;
542 //===----------------------------------------------------------------------===//
543 /// DIESectionOffset - A section offset DIE.
545 class DIESectionOffset : public DIEValue {
548 const DWLabel Section;
552 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
553 bool isEH = false, bool useSet = true)
554 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
555 IsEH(isEH), UseSet(useSet) {}
557 // Implement isa/cast/dyncast.
558 static bool classof(const DIESectionOffset *) { return true; }
559 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
561 /// EmitValue - Emit section offset.
563 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
565 /// SizeOf - Determine size of section offset value in bytes.
567 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
569 /// Profile - Used to gather unique data for the value folding set.
571 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
572 const DWLabel &Section) {
573 ID.AddInteger(isSectionOffset);
576 // IsEH and UseSet are specific to the Label/Section that we will emit
577 // the offset for; so Label/Section are enough for uniqueness.
579 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
582 virtual void print(std::ostream &O) {
587 O << "-" << IsEH << "-" << UseSet;
592 //===----------------------------------------------------------------------===//
593 /// DIEDelta - A simple label difference DIE.
595 class DIEDelta : public DIEValue {
597 const DWLabel LabelHi;
598 const DWLabel LabelLo;
600 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
601 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
603 // Implement isa/cast/dyncast.
604 static bool classof(const DIEDelta *) { return true; }
605 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
607 /// EmitValue - Emit delta value.
609 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
611 /// SizeOf - Determine size of delta value in bytes.
613 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
615 /// Profile - Used to gather unique data for the value folding set.
617 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
618 const DWLabel &LabelLo) {
619 ID.AddInteger(isDelta);
623 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
626 virtual void print(std::ostream &O) {
635 //===----------------------------------------------------------------------===//
636 /// DIEntry - A pointer to another debug information entry. An instance of this
637 /// class can also be used as a proxy for a debug information entry not yet
638 /// defined (ie. types.)
639 class DIEntry : public DIEValue {
643 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
645 // Implement isa/cast/dyncast.
646 static bool classof(const DIEntry *) { return true; }
647 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
649 /// EmitValue - Emit debug information entry offset.
651 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
653 /// SizeOf - Determine size of debug information entry in bytes.
655 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
656 return sizeof(int32_t);
659 /// Profile - Used to gather unique data for the value folding set.
661 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
662 ID.AddInteger(isEntry);
663 ID.AddPointer(Entry);
665 virtual void Profile(FoldingSetNodeID &ID) {
666 ID.AddInteger(isEntry);
669 ID.AddPointer(Entry);
676 virtual void print(std::ostream &O) {
677 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
682 //===----------------------------------------------------------------------===//
683 /// DIEBlock - A block of values. Primarily used for location expressions.
685 class DIEBlock : public DIEValue, public DIE {
687 unsigned Size; // Size in bytes excluding size header.
697 // Implement isa/cast/dyncast.
698 static bool classof(const DIEBlock *) { return true; }
699 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
701 /// ComputeSize - calculate the size of the block.
703 unsigned ComputeSize(DwarfDebug &DD);
705 /// BestForm - Choose the best form for data.
707 unsigned BestForm() const {
708 if ((unsigned char)Size == Size) return DW_FORM_block1;
709 if ((unsigned short)Size == Size) return DW_FORM_block2;
710 if ((unsigned int)Size == Size) return DW_FORM_block4;
711 return DW_FORM_block;
714 /// EmitValue - Emit block data.
716 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
718 /// SizeOf - Determine size of block data in bytes.
720 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
723 /// Profile - Used to gather unique data for the value folding set.
725 virtual void Profile(FoldingSetNodeID &ID) {
726 ID.AddInteger(isBlock);
731 virtual void print(std::ostream &O) {
738 //===----------------------------------------------------------------------===//
739 /// CompileUnit - This dwarf writer support class manages information associate
740 /// with a source file.
743 /// ID - File identifier for source.
747 /// Die - Compile unit debug information entry.
751 /// GVToDieMap - Tracks the mapping of unit level debug informaton
752 /// variables to debug information entries.
753 std::map<GlobalVariable *, DIE *> GVToDieMap;
755 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
756 /// descriptors to debug information entries using a DIEntry proxy.
757 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
759 /// Globals - A map of globally visible named entities for this unit.
761 std::map<std::string, DIE *> Globals;
763 /// DiesSet - Used to uniquely define dies within the compile unit.
765 FoldingSet<DIE> DiesSet;
768 CompileUnit(unsigned I, DIE *D)
769 : ID(I), Die(D), GVToDieMap(),
770 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
778 unsigned getID() const { return ID; }
779 DIE* getDie() const { return Die; }
780 std::map<std::string, DIE *> &getGlobals() { return Globals; }
782 /// hasContent - Return true if this compile unit has something to write out.
784 bool hasContent() const {
785 return !Die->getChildren().empty();
788 /// AddGlobal - Add a new global entity to the compile unit.
790 void AddGlobal(const std::string &Name, DIE *Die) {
794 /// getDieMapSlotFor - Returns the debug information entry map slot for the
795 /// specified debug variable.
796 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
797 return GVToDieMap[GV];
800 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
801 /// specified debug variable.
802 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
803 return GVToDIEntryMap[GV];
806 /// AddDie - Adds or interns the DIE to the compile unit.
808 DIE *AddDie(DIE &Buffer) {
812 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
815 Die = new DIE(Buffer);
816 DiesSet.InsertNode(Die, Where);
817 this->Die->AddChild(Die);
825 //===----------------------------------------------------------------------===//
826 /// Dwarf - Emits general Dwarf directives.
830 //===--------------------------------------------------------------------===//
831 // Core attributes used by the Dwarf writer.
835 /// O - Stream to .s file.
839 /// Asm - Target of Dwarf emission.
843 /// TAI - Target asm information.
844 const TargetAsmInfo *TAI;
846 /// TD - Target data.
847 const TargetData *TD;
849 /// RI - Register Information.
850 const TargetRegisterInfo *RI;
852 /// M - Current module.
856 /// MF - Current machine function.
860 /// MMI - Collected machine module information.
862 MachineModuleInfo *MMI;
864 /// SubprogramCount - The running count of functions being compiled.
866 unsigned SubprogramCount;
868 /// Flavor - A unique string indicating what dwarf producer this is, used to
870 const char * const Flavor;
873 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
878 , TD(Asm->TM.getTargetData())
879 , RI(Asm->TM.getRegisterInfo())
890 //===--------------------------------------------------------------------===//
893 AsmPrinter *getAsm() const { return Asm; }
894 MachineModuleInfo *getMMI() const { return MMI; }
895 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
896 const TargetData *getTargetData() const { return TD; }
898 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
900 if (isInSection && TAI->getDwarfSectionOffsetDirective())
901 O << TAI->getDwarfSectionOffsetDirective();
902 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
903 O << TAI->getData32bitsDirective();
905 O << TAI->getData64bitsDirective();
908 /// PrintLabelName - Print label name in form used by Dwarf writer.
910 void PrintLabelName(DWLabel Label) const {
911 PrintLabelName(Label.Tag, Label.Number);
913 void PrintLabelName(const char *Tag, unsigned Number) const {
914 O << TAI->getPrivateGlobalPrefix() << Tag;
915 if (Number) O << Number;
918 void PrintLabelName(const char *Tag, unsigned Number,
919 const char *Suffix) const {
920 O << TAI->getPrivateGlobalPrefix() << Tag;
921 if (Number) O << Number;
925 /// EmitLabel - Emit location label for internal use by Dwarf.
927 void EmitLabel(DWLabel Label) const {
928 EmitLabel(Label.Tag, Label.Number);
930 void EmitLabel(const char *Tag, unsigned Number) const {
931 PrintLabelName(Tag, Number);
935 /// EmitReference - Emit a reference to a label.
937 void EmitReference(DWLabel Label, bool IsPCRelative = false,
938 bool Force32Bit = false) const {
939 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
941 void EmitReference(const char *Tag, unsigned Number,
942 bool IsPCRelative = false, bool Force32Bit = false) const {
943 PrintRelDirective(Force32Bit);
944 PrintLabelName(Tag, Number);
946 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
948 void EmitReference(const std::string &Name, bool IsPCRelative = false,
949 bool Force32Bit = false) const {
950 PrintRelDirective(Force32Bit);
954 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
957 /// EmitDifference - Emit the difference between two labels. Some
958 /// assemblers do not behave with absolute expressions with data directives,
959 /// so there is an option (needsSet) to use an intermediary set expression.
960 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
961 bool IsSmall = false) {
962 EmitDifference(LabelHi.Tag, LabelHi.Number,
963 LabelLo.Tag, LabelLo.Number,
966 void EmitDifference(const char *TagHi, unsigned NumberHi,
967 const char *TagLo, unsigned NumberLo,
968 bool IsSmall = false) {
969 if (TAI->needsSet()) {
971 PrintLabelName("set", SetCounter, Flavor);
973 PrintLabelName(TagHi, NumberHi);
975 PrintLabelName(TagLo, NumberLo);
978 PrintRelDirective(IsSmall);
979 PrintLabelName("set", SetCounter, Flavor);
982 PrintRelDirective(IsSmall);
984 PrintLabelName(TagHi, NumberHi);
986 PrintLabelName(TagLo, NumberLo);
990 void EmitSectionOffset(const char* Label, const char* Section,
991 unsigned LabelNumber, unsigned SectionNumber,
992 bool IsSmall = false, bool isEH = false,
993 bool useSet = true) {
994 bool printAbsolute = false;
996 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
998 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1000 if (TAI->needsSet() && useSet) {
1002 PrintLabelName("set", SetCounter, Flavor);
1004 PrintLabelName(Label, LabelNumber);
1006 if (!printAbsolute) {
1008 PrintLabelName(Section, SectionNumber);
1012 PrintRelDirective(IsSmall);
1014 PrintLabelName("set", SetCounter, Flavor);
1017 PrintRelDirective(IsSmall, true);
1019 PrintLabelName(Label, LabelNumber);
1021 if (!printAbsolute) {
1023 PrintLabelName(Section, SectionNumber);
1028 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1030 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1031 const std::vector<MachineMove> &Moves, bool isEH) {
1033 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1034 TargetFrameInfo::StackGrowsUp ?
1035 TD->getPointerSize() : -TD->getPointerSize();
1036 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1038 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1039 const MachineMove &Move = Moves[i];
1040 unsigned LabelID = Move.getLabelID();
1043 LabelID = MMI->MappedLabel(LabelID);
1045 // Throw out move if the label is invalid.
1046 if (!LabelID) continue;
1049 const MachineLocation &Dst = Move.getDestination();
1050 const MachineLocation &Src = Move.getSource();
1052 // Advance row if new location.
1053 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1054 Asm->EmitInt8(DW_CFA_advance_loc4);
1055 Asm->EOL("DW_CFA_advance_loc4");
1056 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1059 BaseLabelID = LabelID;
1060 BaseLabel = "label";
1064 // If advancing cfa.
1065 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1067 if (Src.getReg() == MachineLocation::VirtualFP) {
1068 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1069 Asm->EOL("DW_CFA_def_cfa_offset");
1071 Asm->EmitInt8(DW_CFA_def_cfa);
1072 Asm->EOL("DW_CFA_def_cfa");
1073 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1074 Asm->EOL("Register");
1077 int Offset = -Src.getOffset();
1079 Asm->EmitULEB128Bytes(Offset);
1082 assert(0 && "Machine move no supported yet.");
1084 } else if (Src.isReg() &&
1085 Src.getReg() == MachineLocation::VirtualFP) {
1087 Asm->EmitInt8(DW_CFA_def_cfa_register);
1088 Asm->EOL("DW_CFA_def_cfa_register");
1089 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1090 Asm->EOL("Register");
1092 assert(0 && "Machine move no supported yet.");
1095 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1096 int Offset = Dst.getOffset() / stackGrowth;
1099 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1100 Asm->EOL("DW_CFA_offset_extended_sf");
1101 Asm->EmitULEB128Bytes(Reg);
1103 Asm->EmitSLEB128Bytes(Offset);
1105 } else if (Reg < 64) {
1106 Asm->EmitInt8(DW_CFA_offset + Reg);
1108 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1111 Asm->EmitULEB128Bytes(Offset);
1114 Asm->EmitInt8(DW_CFA_offset_extended);
1115 Asm->EOL("DW_CFA_offset_extended");
1116 Asm->EmitULEB128Bytes(Reg);
1118 Asm->EmitULEB128Bytes(Offset);
1127 //===----------------------------------------------------------------------===//
1128 /// SrcLineInfo - This class is used to record source line correspondence.
1131 unsigned Line; // Source line number.
1132 unsigned Column; // Source column.
1133 unsigned SourceID; // Source ID number.
1134 unsigned LabelID; // Label in code ID number.
1136 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1137 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1140 unsigned getLine() const { return Line; }
1141 unsigned getColumn() const { return Column; }
1142 unsigned getSourceID() const { return SourceID; }
1143 unsigned getLabelID() const { return LabelID; }
1146 //===----------------------------------------------------------------------===//
1147 /// DbgVariable - This class is used to track local variable information.
1150 DIVariable Var; // Variable Descriptor.
1151 unsigned FrameIndex; // Variable frame index.
1153 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1156 DIVariable getVariable() const { return Var; }
1157 unsigned getFrameIndex() const { return FrameIndex; }
1160 //===----------------------------------------------------------------------===//
1161 /// DbgScope - This class is used to track scope information.
1164 DbgScope *Parent; // Parent to this scope.
1165 DIDescriptor Desc; // Debug info descriptor for scope.
1166 // Either subprogram or block.
1167 unsigned StartLabelID; // Label ID of the beginning of scope.
1168 unsigned EndLabelID; // Label ID of the end of scope.
1169 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1170 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1172 DbgScope(DbgScope *P, DIDescriptor D)
1173 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1176 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1177 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1181 DbgScope *getParent() const { return Parent; }
1182 DIDescriptor getDesc() const { return Desc; }
1183 unsigned getStartLabelID() const { return StartLabelID; }
1184 unsigned getEndLabelID() const { return EndLabelID; }
1185 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1186 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1187 void setStartLabelID(unsigned S) { StartLabelID = S; }
1188 void setEndLabelID(unsigned E) { EndLabelID = E; }
1190 /// AddScope - Add a scope to the scope.
1192 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1194 /// AddVariable - Add a variable to the scope.
1196 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1199 //===----------------------------------------------------------------------===//
1200 /// DwarfDebug - Emits Dwarf debug directives.
1202 class DwarfDebug : public Dwarf {
1203 //===--------------------------------------------------------------------===//
1204 // Attributes used to construct specific Dwarf sections.
1207 /// CompileUnitMap - A map of global variables representing compile units to
1209 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1211 /// CompileUnits - All the compile units in this module.
1213 SmallVector<CompileUnit *, 8> CompileUnits;
1215 /// MainCU - Some platform prefers one compile unit per .o file. In such
1216 /// cases, all dies are inserted in MainCU.
1217 CompileUnit *MainCU;
1219 /// AbbreviationsSet - Used to uniquely define abbreviations.
1221 FoldingSet<DIEAbbrev> AbbreviationsSet;
1223 /// Abbreviations - A list of all the unique abbreviations in use.
1225 std::vector<DIEAbbrev *> Abbreviations;
1227 /// DirectoryIdMap - Directory name to directory id map.
1229 StringMap<unsigned> DirectoryIdMap;
1231 /// DirectoryNames - A list of directory names.
1232 SmallVector<std::string, 8> DirectoryNames;
1234 /// SourceFileIdMap - Source file name to source file id map.
1236 StringMap<unsigned> SourceFileIdMap;
1238 /// SourceFileNames - A list of source file names.
1239 SmallVector<std::string, 8> SourceFileNames;
1241 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1242 /// id mapped to a unique id.
1243 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1245 /// SourceIds - Reverse map from source id to directory id + file id pair.
1247 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1249 /// Lines - List of of source line correspondence.
1250 std::vector<SrcLineInfo> Lines;
1252 /// ValuesSet - Used to uniquely define values.
1254 FoldingSet<DIEValue> ValuesSet;
1256 /// Values - A list of all the unique values in use.
1258 std::vector<DIEValue *> Values;
1260 /// StringPool - A UniqueVector of strings used by indirect references.
1262 UniqueVector<std::string> StringPool;
1264 /// SectionMap - Provides a unique id per text section.
1266 UniqueVector<const Section*> SectionMap;
1268 /// SectionSourceLines - Tracks line numbers per text section.
1270 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1272 /// didInitial - Flag to indicate if initial emission has been done.
1276 /// shouldEmit - Flag to indicate if debug information should be emitted.
1280 // RootDbgScope - Top level scope for the current function.
1282 DbgScope *RootDbgScope;
1284 /// DbgScopeMap - Tracks the scopes in the current function.
1285 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1287 /// DebugTimer - Timer for the Dwarf debug writer.
1290 struct FunctionDebugFrameInfo {
1292 std::vector<MachineMove> Moves;
1294 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1295 Number(Num), Moves(M) { }
1298 std::vector<FunctionDebugFrameInfo> DebugFrames;
1301 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1302 /// maps to the source id. Source id starts at 1.
1303 std::pair<unsigned, unsigned>
1304 getSourceDirectoryAndFileIds(unsigned SId) const {
1305 return SourceIds[SId-1];
1308 /// getNumSourceDirectories - Return the number of source directories in the
1310 unsigned getNumSourceDirectories() const {
1311 return DirectoryNames.size();
1314 /// getSourceDirectoryName - Return the name of the directory corresponding
1316 const std::string &getSourceDirectoryName(unsigned Id) const {
1317 return DirectoryNames[Id - 1];
1320 /// getSourceFileName - Return the name of the source file corresponding
1322 const std::string &getSourceFileName(unsigned Id) const {
1323 return SourceFileNames[Id - 1];
1326 /// getNumSourceIds - Return the number of unique source ids.
1327 unsigned getNumSourceIds() const {
1328 return SourceIds.size();
1331 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1333 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1334 // Profile the node so that we can make it unique.
1335 FoldingSetNodeID ID;
1338 // Check the set for priors.
1339 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1341 // If it's newly added.
1342 if (InSet == &Abbrev) {
1343 // Add to abbreviation list.
1344 Abbreviations.push_back(&Abbrev);
1345 // Assign the vector position + 1 as its number.
1346 Abbrev.setNumber(Abbreviations.size());
1348 // Assign existing abbreviation number.
1349 Abbrev.setNumber(InSet->getNumber());
1353 /// NewString - Add a string to the constant pool and returns a label.
1355 DWLabel NewString(const std::string &String) {
1356 unsigned StringID = StringPool.insert(String);
1357 return DWLabel("string", StringID);
1360 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1362 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1366 FoldingSetNodeID ID;
1367 DIEntry::Profile(ID, Entry);
1369 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1371 if (Value) return Value;
1373 Value = new DIEntry(Entry);
1374 ValuesSet.InsertNode(Value, Where);
1376 Value = new DIEntry(Entry);
1379 Values.push_back(Value);
1383 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1385 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1386 Value->Entry = Entry;
1387 // Add to values set if not already there. If it is, we merely have a
1388 // duplicate in the values list (no harm.)
1389 ValuesSet.GetOrInsertNode(Value);
1392 /// AddUInt - Add an unsigned integer attribute data and value.
1394 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1395 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1397 FoldingSetNodeID ID;
1398 DIEInteger::Profile(ID, Integer);
1400 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1402 Value = new DIEInteger(Integer);
1403 ValuesSet.InsertNode(Value, Where);
1404 Values.push_back(Value);
1407 Die->AddValue(Attribute, Form, Value);
1410 /// AddSInt - Add an signed integer attribute data and value.
1412 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1413 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1415 FoldingSetNodeID ID;
1416 DIEInteger::Profile(ID, (uint64_t)Integer);
1418 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1420 Value = new DIEInteger(Integer);
1421 ValuesSet.InsertNode(Value, Where);
1422 Values.push_back(Value);
1425 Die->AddValue(Attribute, Form, Value);
1428 /// AddString - Add a string attribute data and value.
1430 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1431 const std::string &String) {
1432 FoldingSetNodeID ID;
1433 DIEString::Profile(ID, String);
1435 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1437 Value = new DIEString(String);
1438 ValuesSet.InsertNode(Value, Where);
1439 Values.push_back(Value);
1442 Die->AddValue(Attribute, Form, Value);
1445 /// AddLabel - Add a Dwarf label attribute data and value.
1447 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1448 const DWLabel &Label) {
1449 FoldingSetNodeID ID;
1450 DIEDwarfLabel::Profile(ID, Label);
1452 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1454 Value = new DIEDwarfLabel(Label);
1455 ValuesSet.InsertNode(Value, Where);
1456 Values.push_back(Value);
1459 Die->AddValue(Attribute, Form, Value);
1462 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1464 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1465 const std::string &Label) {
1466 FoldingSetNodeID ID;
1467 DIEObjectLabel::Profile(ID, Label);
1469 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1471 Value = new DIEObjectLabel(Label);
1472 ValuesSet.InsertNode(Value, Where);
1473 Values.push_back(Value);
1476 Die->AddValue(Attribute, Form, Value);
1479 /// AddSectionOffset - Add a section offset label attribute data and value.
1481 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1482 const DWLabel &Label, const DWLabel &Section,
1483 bool isEH = false, bool useSet = true) {
1484 FoldingSetNodeID ID;
1485 DIESectionOffset::Profile(ID, Label, Section);
1487 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1489 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1490 ValuesSet.InsertNode(Value, Where);
1491 Values.push_back(Value);
1494 Die->AddValue(Attribute, Form, Value);
1497 /// AddDelta - Add a label delta attribute data and value.
1499 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1500 const DWLabel &Hi, const DWLabel &Lo) {
1501 FoldingSetNodeID ID;
1502 DIEDelta::Profile(ID, Hi, Lo);
1504 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1506 Value = new DIEDelta(Hi, Lo);
1507 ValuesSet.InsertNode(Value, Where);
1508 Values.push_back(Value);
1511 Die->AddValue(Attribute, Form, Value);
1514 /// AddDIEntry - Add a DIE attribute data and value.
1516 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1517 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1520 /// AddBlock - Add block data.
1522 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1523 Block->ComputeSize(*this);
1524 FoldingSetNodeID ID;
1527 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1530 ValuesSet.InsertNode(Value, Where);
1531 Values.push_back(Value);
1533 // Already exists, reuse the previous one.
1535 Block = cast<DIEBlock>(Value);
1538 Die->AddValue(Attribute, Block->BestForm(), Value);
1541 /// AddSourceLine - Add location information to specified debug information
1543 void AddSourceLine(DIE *Die, const DIVariable *V) {
1544 unsigned FileID = 0;
1545 unsigned Line = V->getLineNumber();
1546 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1547 FileID = Unit->getID();
1548 assert (FileID && "Invalid file id");
1549 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1550 AddUInt(Die, DW_AT_decl_line, 0, Line);
1553 /// AddSourceLine - Add location information to specified debug information
1555 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1556 unsigned FileID = 0;
1557 unsigned Line = G->getLineNumber();
1558 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1559 FileID = Unit->getID();
1560 assert (FileID && "Invalid file id");
1561 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1562 AddUInt(Die, DW_AT_decl_line, 0, Line);
1565 void AddSourceLine(DIE *Die, const DIType *Ty) {
1566 unsigned FileID = 0;
1567 unsigned Line = Ty->getLineNumber();
1568 DICompileUnit CU = Ty->getCompileUnit();
1571 CompileUnit *Unit = FindCompileUnit(CU);
1572 FileID = Unit->getID();
1573 assert (FileID && "Invalid file id");
1574 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1575 AddUInt(Die, DW_AT_decl_line, 0, Line);
1578 /// AddAddress - Add an address attribute to a die based on the location
1580 void AddAddress(DIE *Die, unsigned Attribute,
1581 const MachineLocation &Location) {
1582 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1583 DIEBlock *Block = new DIEBlock();
1585 if (Location.isReg()) {
1587 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1589 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1590 AddUInt(Block, 0, DW_FORM_udata, Reg);
1594 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1596 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1597 AddUInt(Block, 0, DW_FORM_udata, Reg);
1599 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1602 AddBlock(Die, Attribute, 0, Block);
1605 /// AddType - Add a new type attribute to the specified entity.
1606 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1610 // Check for pre-existence.
1611 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1612 // If it exists then use the existing value.
1614 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1619 Slot = NewDIEntry();
1622 DIE Buffer(DW_TAG_base_type);
1623 if (Ty.isBasicType(Ty.getTag()))
1624 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1625 else if (Ty.isDerivedType(Ty.getTag()))
1626 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1628 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1629 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1632 // Add debug information entry to entity and appropriate context.
1634 DIDescriptor Context = Ty.getContext();
1635 if (!Context.isNull())
1636 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1639 DIE *Child = new DIE(Buffer);
1640 Die->AddChild(Child);
1642 SetDIEntry(Slot, Child);
1644 Die = DW_Unit->AddDie(Buffer);
1645 SetDIEntry(Slot, Die);
1648 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1651 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1652 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1655 // Get core information.
1658 Buffer.setTag(DW_TAG_base_type);
1659 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1660 // Add name if not anonymous or intermediate type.
1662 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1663 uint64_t Size = BTy.getSizeInBits() >> 3;
1664 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1667 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1668 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1669 DIDerivedType DTy) {
1671 // Get core information.
1674 uint64_t Size = DTy.getSizeInBits() >> 3;
1675 unsigned Tag = DTy.getTag();
1677 // FIXME - Workaround for templates.
1678 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1682 // Map to main type, void will not have a type.
1683 DIType FromTy = DTy.getTypeDerivedFrom();
1684 AddType(DW_Unit, &Buffer, FromTy);
1686 // Add name if not anonymous or intermediate type.
1688 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1690 // Add size if non-zero (derived types might be zero-sized.)
1692 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1694 // Add source line info if available and TyDesc is not a forward
1696 if (!DTy.isForwardDecl())
1697 AddSourceLine(&Buffer, &DTy);
1700 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1701 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1702 DICompositeType CTy) {
1703 // Get core information.
1707 uint64_t Size = CTy.getSizeInBits() >> 3;
1708 unsigned Tag = CTy.getTag();
1712 case DW_TAG_vector_type:
1713 case DW_TAG_array_type:
1714 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1716 case DW_TAG_enumeration_type:
1718 DIArray Elements = CTy.getTypeArray();
1719 // Add enumerators to enumeration type.
1720 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1721 DIE *ElemDie = NULL;
1722 DIEnumerator Enum(Elements.getElement(i).getGV());
1723 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1724 Buffer.AddChild(ElemDie);
1728 case DW_TAG_subroutine_type:
1730 // Add prototype flag.
1731 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1732 DIArray Elements = CTy.getTypeArray();
1734 DIDescriptor RTy = Elements.getElement(0);
1735 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1738 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1739 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1740 DIDescriptor Ty = Elements.getElement(i);
1741 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1742 Buffer.AddChild(Arg);
1746 case DW_TAG_structure_type:
1747 case DW_TAG_union_type:
1749 // Add elements to structure type.
1750 DIArray Elements = CTy.getTypeArray();
1752 // A forward struct declared type may not have elements available.
1753 if (Elements.isNull())
1756 // Add elements to structure type.
1757 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1758 DIDescriptor Element = Elements.getElement(i);
1759 DIE *ElemDie = NULL;
1760 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1761 ElemDie = CreateSubprogramDIE(DW_Unit,
1762 DISubprogram(Element.getGV()));
1763 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1764 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1765 DIGlobalVariable(Element.getGV()));
1767 ElemDie = CreateMemberDIE(DW_Unit,
1768 DIDerivedType(Element.getGV()));
1769 Buffer.AddChild(ElemDie);
1771 unsigned RLang = CTy.getRunTimeLang();
1773 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1780 // Add name if not anonymous or intermediate type.
1782 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1784 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1785 || Tag == DW_TAG_union_type) {
1786 // Add size if non-zero (derived types might be zero-sized.)
1788 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1790 // Add zero size if it is not a forward declaration.
1791 if (CTy.isForwardDecl())
1792 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1794 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1797 // Add source line info if available.
1798 if (!CTy.isForwardDecl())
1799 AddSourceLine(&Buffer, &CTy);
1803 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1804 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1805 int64_t L = SR.getLo();
1806 int64_t H = SR.getHi();
1807 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1809 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1811 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1812 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1814 Buffer.AddChild(DW_Subrange);
1817 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1818 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1819 DICompositeType *CTy) {
1820 Buffer.setTag(DW_TAG_array_type);
1821 if (CTy->getTag() == DW_TAG_vector_type)
1822 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1824 // Emit derived type.
1825 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1826 DIArray Elements = CTy->getTypeArray();
1828 // Construct an anonymous type for index type.
1829 DIE IdxBuffer(DW_TAG_base_type);
1830 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1831 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1832 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1834 // Add subranges to array type.
1835 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1836 DIDescriptor Element = Elements.getElement(i);
1837 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1838 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1842 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1843 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1845 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1848 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1849 int64_t Value = ETy->getEnumValue();
1850 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1854 /// CreateGlobalVariableDIE - Create new DIE using GV.
1855 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1857 DIE *GVDie = new DIE(DW_TAG_variable);
1859 GV.getDisplayName(Name);
1860 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1861 std::string LinkageName;
1862 GV.getLinkageName(LinkageName);
1863 if (!LinkageName.empty())
1864 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1865 AddType(DW_Unit, GVDie, GV.getType());
1866 if (!GV.isLocalToUnit())
1867 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1868 AddSourceLine(GVDie, &GV);
1872 /// CreateMemberDIE - Create new member DIE.
1873 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1874 DIE *MemberDie = new DIE(DT.getTag());
1878 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1880 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1882 AddSourceLine(MemberDie, &DT);
1884 uint64_t Size = DT.getSizeInBits();
1885 uint64_t FieldSize = DT.getOriginalTypeSize();
1887 if (Size != FieldSize) {
1889 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1890 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1892 uint64_t Offset = DT.getOffsetInBits();
1893 uint64_t FieldOffset = Offset;
1894 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1895 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1896 FieldOffset = (HiMark - FieldSize);
1897 Offset -= FieldOffset;
1898 // Maybe we need to work from the other end.
1899 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1900 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1902 DIEBlock *Block = new DIEBlock();
1903 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1904 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1905 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1907 if (DT.isProtected())
1908 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1909 else if (DT.isPrivate())
1910 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1915 /// CreateSubprogramDIE - Create new DIE using SP.
1916 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1917 const DISubprogram &SP,
1918 bool IsConstructor = false) {
1919 DIE *SPDie = new DIE(DW_TAG_subprogram);
1922 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1923 std::string LinkageName;
1924 SP.getLinkageName(LinkageName);
1925 if (!LinkageName.empty())
1926 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1928 AddSourceLine(SPDie, &SP);
1930 DICompositeType SPTy = SP.getType();
1931 DIArray Args = SPTy.getTypeArray();
1934 if (!IsConstructor) {
1936 AddType(DW_Unit, SPDie, SPTy);
1938 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1941 if (!SP.isDefinition()) {
1942 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1944 // Do not add arguments for subprogram definition. They will be
1945 // handled through RecordVariable.
1947 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1948 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1949 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1950 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1951 SPDie->AddChild(Arg);
1955 unsigned Lang = SP.getCompileUnit().getLanguage();
1956 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1957 || Lang == DW_LANG_ObjC)
1958 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1960 if (!SP.isLocalToUnit())
1961 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1965 /// FindCompileUnit - Get the compile unit for the given descriptor.
1967 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1968 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1969 assert(DW_Unit && "Missing compile unit.");
1973 /// NewDbgScopeVariable - Create a new scope variable.
1975 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1976 // Get the descriptor.
1977 const DIVariable &VD = DV->getVariable();
1979 // Translate tag to proper Dwarf tag. The result variable is dropped for
1982 switch (VD.getTag()) {
1983 case DW_TAG_return_variable: return NULL;
1984 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1985 case DW_TAG_auto_variable: // fall thru
1986 default: Tag = DW_TAG_variable; break;
1989 // Define variable debug information entry.
1990 DIE *VariableDie = new DIE(Tag);
1993 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1995 // Add source line info if available.
1996 AddSourceLine(VariableDie, &VD);
1998 // Add variable type.
1999 AddType(Unit, VariableDie, VD.getType());
2001 // Add variable address.
2002 MachineLocation Location;
2003 Location.set(RI->getFrameRegister(*MF),
2004 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2005 AddAddress(VariableDie, DW_AT_location, Location);
2010 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2012 DbgScope *getOrCreateScope(GlobalVariable *V) {
2013 DbgScope *&Slot = DbgScopeMap[V];
2014 if (Slot) return Slot;
2016 // FIXME - breaks down when the context is an inlined function.
2017 DIDescriptor ParentDesc;
2018 DIDescriptor Desc(V);
2020 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
2022 ParentDesc = Block.getContext();
2025 DbgScope *Parent = ParentDesc.isNull() ?
2026 NULL : getOrCreateScope(ParentDesc.getGV());
2027 Slot = new DbgScope(Parent, Desc);
2030 Parent->AddScope(Slot);
2031 } else if (RootDbgScope) {
2032 // FIXME - Add inlined function scopes to the root so we can delete them
2033 // later. Long term, handle inlined functions properly.
2034 RootDbgScope->AddScope(Slot);
2036 // First function is top level function.
2037 RootDbgScope = Slot;
2043 /// ConstructDbgScope - Construct the components of a scope.
2045 void ConstructDbgScope(DbgScope *ParentScope,
2046 unsigned ParentStartID, unsigned ParentEndID,
2047 DIE *ParentDie, CompileUnit *Unit) {
2048 // Add variables to scope.
2049 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2050 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2051 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2052 if (VariableDie) ParentDie->AddChild(VariableDie);
2055 // Add nested scopes.
2056 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2057 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2058 // Define the Scope debug information entry.
2059 DbgScope *Scope = Scopes[j];
2060 // FIXME - Ignore inlined functions for the time being.
2061 if (!Scope->getParent()) continue;
2063 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2064 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2066 // Ignore empty scopes.
2067 if (StartID == EndID && StartID != 0) continue;
2068 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2070 if (StartID == ParentStartID && EndID == ParentEndID) {
2071 // Just add stuff to the parent scope.
2072 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2074 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2076 // Add the scope bounds.
2078 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2079 DWLabel("label", StartID));
2081 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2082 DWLabel("func_begin", SubprogramCount));
2085 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2086 DWLabel("label", EndID));
2088 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2089 DWLabel("func_end", SubprogramCount));
2092 // Add the scope contents.
2093 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2094 ParentDie->AddChild(ScopeDie);
2099 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2101 void ConstructRootDbgScope(DbgScope *RootScope) {
2102 // Exit if there is no root scope.
2103 if (!RootScope) return;
2104 DIDescriptor Desc = RootScope->getDesc();
2108 // Get the subprogram debug information entry.
2109 DISubprogram SPD(Desc.getGV());
2111 // Get the compile unit context.
2112 CompileUnit *Unit = MainCU;
2114 Unit = FindCompileUnit(SPD.getCompileUnit());
2116 // Get the subprogram die.
2117 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2118 assert(SPDie && "Missing subprogram descriptor");
2120 // Add the function bounds.
2121 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2122 DWLabel("func_begin", SubprogramCount));
2123 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2124 DWLabel("func_end", SubprogramCount));
2125 MachineLocation Location(RI->getFrameRegister(*MF));
2126 AddAddress(SPDie, DW_AT_frame_base, Location);
2128 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2131 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2133 void ConstructDefaultDbgScope(MachineFunction *MF) {
2134 const char *FnName = MF->getFunction()->getNameStart();
2136 std::map<std::string, DIE*> &Globals = MainCU->getGlobals();
2137 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2138 if (GI != Globals.end()) {
2139 DIE *SPDie = GI->second;
2141 // Add the function bounds.
2142 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2143 DWLabel("func_begin", SubprogramCount));
2144 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2145 DWLabel("func_end", SubprogramCount));
2147 MachineLocation Location(RI->getFrameRegister(*MF));
2148 AddAddress(SPDie, DW_AT_frame_base, Location);
2152 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2153 CompileUnit *Unit = CompileUnits[i];
2154 std::map<std::string, DIE*> &Globals = Unit->getGlobals();
2155 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2156 if (GI != Globals.end()) {
2157 DIE *SPDie = GI->second;
2159 // Add the function bounds.
2160 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2161 DWLabel("func_begin", SubprogramCount));
2162 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2163 DWLabel("func_end", SubprogramCount));
2165 MachineLocation Location(RI->getFrameRegister(*MF));
2166 AddAddress(SPDie, DW_AT_frame_base, Location);
2173 // FIXME: This is causing an abort because C++ mangled names are compared
2174 // with their unmangled counterparts. See PR2885. Don't do this assert.
2175 assert(0 && "Couldn't find DIE for machine function!");
2180 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2181 /// tools to recognize the object file contains Dwarf information.
2182 void EmitInitial() {
2183 // Check to see if we already emitted intial headers.
2184 if (didInitial) return;
2187 // Dwarf sections base addresses.
2188 if (TAI->doesDwarfRequireFrameSection()) {
2189 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2190 EmitLabel("section_debug_frame", 0);
2192 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2193 EmitLabel("section_info", 0);
2194 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2195 EmitLabel("section_abbrev", 0);
2196 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2197 EmitLabel("section_aranges", 0);
2198 if (TAI->doesSupportMacInfoSection()) {
2199 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2200 EmitLabel("section_macinfo", 0);
2202 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2203 EmitLabel("section_line", 0);
2204 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2205 EmitLabel("section_loc", 0);
2206 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2207 EmitLabel("section_pubnames", 0);
2208 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2209 EmitLabel("section_str", 0);
2210 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2211 EmitLabel("section_ranges", 0);
2213 Asm->SwitchToSection(TAI->getTextSection());
2214 EmitLabel("text_begin", 0);
2215 Asm->SwitchToSection(TAI->getDataSection());
2216 EmitLabel("data_begin", 0);
2219 /// EmitDIE - Recusively Emits a debug information entry.
2221 void EmitDIE(DIE *Die) {
2222 // Get the abbreviation for this DIE.
2223 unsigned AbbrevNumber = Die->getAbbrevNumber();
2224 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2228 // Emit the code (index) for the abbreviation.
2229 Asm->EmitULEB128Bytes(AbbrevNumber);
2232 Asm->EOL(std::string("Abbrev [" +
2233 utostr(AbbrevNumber) +
2234 "] 0x" + utohexstr(Die->getOffset()) +
2235 ":0x" + utohexstr(Die->getSize()) + " " +
2236 TagString(Abbrev->getTag())));
2240 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2241 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2243 // Emit the DIE attribute values.
2244 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2245 unsigned Attr = AbbrevData[i].getAttribute();
2246 unsigned Form = AbbrevData[i].getForm();
2247 assert(Form && "Too many attributes for DIE (check abbreviation)");
2250 case DW_AT_sibling: {
2251 Asm->EmitInt32(Die->SiblingOffset());
2255 // Emit an attribute using the defined form.
2256 Values[i]->EmitValue(*this, Form);
2261 Asm->EOL(AttributeString(Attr));
2264 // Emit the DIE children if any.
2265 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2266 const std::vector<DIE *> &Children = Die->getChildren();
2268 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2269 EmitDIE(Children[j]);
2272 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2276 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2278 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2279 // Get the children.
2280 const std::vector<DIE *> &Children = Die->getChildren();
2282 // If not last sibling and has children then add sibling offset attribute.
2283 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2285 // Record the abbreviation.
2286 AssignAbbrevNumber(Die->getAbbrev());
2288 // Get the abbreviation for this DIE.
2289 unsigned AbbrevNumber = Die->getAbbrevNumber();
2290 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2293 Die->setOffset(Offset);
2295 // Start the size with the size of abbreviation code.
2296 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2298 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2299 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2301 // Size the DIE attribute values.
2302 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2303 // Size attribute value.
2304 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2307 // Size the DIE children if any.
2308 if (!Children.empty()) {
2309 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2310 "Children flag not set");
2312 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2313 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2316 // End of children marker.
2317 Offset += sizeof(int8_t);
2320 Die->setSize(Offset - Die->getOffset());
2324 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2326 void SizeAndOffsets() {
2327 // Process base compile unit.
2329 // Compute size of compile unit header
2330 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2331 sizeof(int16_t) + // DWARF version number
2332 sizeof(int32_t) + // Offset Into Abbrev. Section
2333 sizeof(int8_t); // Pointer Size (in bytes)
2334 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2337 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2338 CompileUnit *Unit = CompileUnits[i];
2339 // Compute size of compile unit header
2340 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2341 sizeof(int16_t) + // DWARF version number
2342 sizeof(int32_t) + // Offset Into Abbrev. Section
2343 sizeof(int8_t); // Pointer Size (in bytes)
2344 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2348 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2350 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2351 DIE *Die = Unit->getDie();
2352 // Emit the compile units header.
2353 EmitLabel("info_begin", Unit->getID());
2354 // Emit size of content not including length itself
2355 unsigned ContentSize = Die->getSize() +
2356 sizeof(int16_t) + // DWARF version number
2357 sizeof(int32_t) + // Offset Into Abbrev. Section
2358 sizeof(int8_t) + // Pointer Size (in bytes)
2359 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2361 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2362 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2363 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2364 Asm->EOL("Offset Into Abbrev. Section");
2365 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2368 // FIXME - extra padding for gdb bug.
2369 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2370 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2371 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2372 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2373 EmitLabel("info_end", Unit->getID());
2378 void EmitDebugInfo() {
2379 // Start debug info section.
2380 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2383 EmitDebugInfoPerCU(MainCU);
2387 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2388 EmitDebugInfoPerCU(CompileUnits[i]);
2391 /// EmitAbbreviations - Emit the abbreviation section.
2393 void EmitAbbreviations() const {
2394 // Check to see if it is worth the effort.
2395 if (!Abbreviations.empty()) {
2396 // Start the debug abbrev section.
2397 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2399 EmitLabel("abbrev_begin", 0);
2401 // For each abbrevation.
2402 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2403 // Get abbreviation data
2404 const DIEAbbrev *Abbrev = Abbreviations[i];
2406 // Emit the abbrevations code (base 1 index.)
2407 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2408 Asm->EOL("Abbreviation Code");
2410 // Emit the abbreviations data.
2411 Abbrev->Emit(*this);
2416 // Mark end of abbreviations.
2417 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2419 EmitLabel("abbrev_end", 0);
2425 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2426 /// the line matrix.
2428 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2429 // Define last address of section.
2430 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2431 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2432 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2433 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2435 // Mark end of matrix.
2436 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2437 Asm->EmitULEB128Bytes(1); Asm->EOL();
2438 Asm->EmitInt8(1); Asm->EOL();
2441 /// EmitDebugLines - Emit source line information.
2443 void EmitDebugLines() {
2444 // If the target is using .loc/.file, the assembler will be emitting the
2445 // .debug_line table automatically.
2446 if (TAI->hasDotLocAndDotFile())
2449 // Minimum line delta, thus ranging from -10..(255-10).
2450 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2451 // Maximum line delta, thus ranging from -10..(255-10).
2452 const int MaxLineDelta = 255 + MinLineDelta;
2454 // Start the dwarf line section.
2455 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2457 // Construct the section header.
2459 EmitDifference("line_end", 0, "line_begin", 0, true);
2460 Asm->EOL("Length of Source Line Info");
2461 EmitLabel("line_begin", 0);
2463 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2465 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2466 Asm->EOL("Prolog Length");
2467 EmitLabel("line_prolog_begin", 0);
2469 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2471 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2473 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2475 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2477 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2479 // Line number standard opcode encodings argument count
2480 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2481 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2482 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2483 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2484 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2485 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2486 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2487 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2488 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2490 // Emit directories.
2491 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2492 Asm->EmitString(getSourceDirectoryName(DI));
2493 Asm->EOL("Directory");
2495 Asm->EmitInt8(0); Asm->EOL("End of directories");
2498 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2499 // Remember source id starts at 1.
2500 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2501 Asm->EmitString(getSourceFileName(Id.second));
2503 Asm->EmitULEB128Bytes(Id.first);
2504 Asm->EOL("Directory #");
2505 Asm->EmitULEB128Bytes(0);
2506 Asm->EOL("Mod date");
2507 Asm->EmitULEB128Bytes(0);
2508 Asm->EOL("File size");
2510 Asm->EmitInt8(0); Asm->EOL("End of files");
2512 EmitLabel("line_prolog_end", 0);
2514 // A sequence for each text section.
2515 unsigned SecSrcLinesSize = SectionSourceLines.size();
2517 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2518 // Isolate current sections line info.
2519 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2522 const Section* S = SectionMap[j + 1];
2523 O << '\t' << TAI->getCommentString() << " Section"
2524 << S->getName() << '\n';
2528 // Dwarf assumes we start with first line of first source file.
2529 unsigned Source = 1;
2532 // Construct rows of the address, source, line, column matrix.
2533 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2534 const SrcLineInfo &LineInfo = LineInfos[i];
2535 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2536 if (!LabelID) continue;
2541 std::pair<unsigned, unsigned> SourceID =
2542 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2543 O << '\t' << TAI->getCommentString() << ' '
2544 << getSourceDirectoryName(SourceID.first) << ' '
2545 << getSourceFileName(SourceID.second)
2546 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2549 // Define the line address.
2550 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2551 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2552 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2553 EmitReference("label", LabelID); Asm->EOL("Location label");
2555 // If change of source, then switch to the new source.
2556 if (Source != LineInfo.getSourceID()) {
2557 Source = LineInfo.getSourceID();
2558 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2559 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2562 // If change of line.
2563 if (Line != LineInfo.getLine()) {
2564 // Determine offset.
2565 int Offset = LineInfo.getLine() - Line;
2566 int Delta = Offset - MinLineDelta;
2569 Line = LineInfo.getLine();
2571 // If delta is small enough and in range...
2572 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2573 // ... then use fast opcode.
2574 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2576 // ... otherwise use long hand.
2577 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2578 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2579 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2582 // Copy the previous row (different address or source)
2583 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2587 EmitEndOfLineMatrix(j + 1);
2590 if (SecSrcLinesSize == 0)
2591 // Because we're emitting a debug_line section, we still need a line
2592 // table. The linker and friends expect it to exist. If there's nothing to
2593 // put into it, emit an empty table.
2594 EmitEndOfLineMatrix(1);
2596 EmitLabel("line_end", 0);
2601 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2603 void EmitCommonDebugFrame() {
2604 if (!TAI->doesDwarfRequireFrameSection())
2608 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2609 TargetFrameInfo::StackGrowsUp ?
2610 TD->getPointerSize() : -TD->getPointerSize();
2612 // Start the dwarf frame section.
2613 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2615 EmitLabel("debug_frame_common", 0);
2616 EmitDifference("debug_frame_common_end", 0,
2617 "debug_frame_common_begin", 0, true);
2618 Asm->EOL("Length of Common Information Entry");
2620 EmitLabel("debug_frame_common_begin", 0);
2621 Asm->EmitInt32((int)DW_CIE_ID);
2622 Asm->EOL("CIE Identifier Tag");
2623 Asm->EmitInt8(DW_CIE_VERSION);
2624 Asm->EOL("CIE Version");
2625 Asm->EmitString("");
2626 Asm->EOL("CIE Augmentation");
2627 Asm->EmitULEB128Bytes(1);
2628 Asm->EOL("CIE Code Alignment Factor");
2629 Asm->EmitSLEB128Bytes(stackGrowth);
2630 Asm->EOL("CIE Data Alignment Factor");
2631 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2632 Asm->EOL("CIE RA Column");
2634 std::vector<MachineMove> Moves;
2635 RI->getInitialFrameState(Moves);
2637 EmitFrameMoves(NULL, 0, Moves, false);
2639 Asm->EmitAlignment(2, 0, 0, false);
2640 EmitLabel("debug_frame_common_end", 0);
2645 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2647 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2648 if (!TAI->doesDwarfRequireFrameSection())
2651 // Start the dwarf frame section.
2652 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2654 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2655 "debug_frame_begin", DebugFrameInfo.Number, true);
2656 Asm->EOL("Length of Frame Information Entry");
2658 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2660 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2662 Asm->EOL("FDE CIE offset");
2664 EmitReference("func_begin", DebugFrameInfo.Number);
2665 Asm->EOL("FDE initial location");
2666 EmitDifference("func_end", DebugFrameInfo.Number,
2667 "func_begin", DebugFrameInfo.Number);
2668 Asm->EOL("FDE address range");
2670 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2673 Asm->EmitAlignment(2, 0, 0, false);
2674 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2679 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2680 EmitDifference("pubnames_end", Unit->getID(),
2681 "pubnames_begin", Unit->getID(), true);
2682 Asm->EOL("Length of Public Names Info");
2684 EmitLabel("pubnames_begin", Unit->getID());
2686 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2688 EmitSectionOffset("info_begin", "section_info",
2689 Unit->getID(), 0, true, false);
2690 Asm->EOL("Offset of Compilation Unit Info");
2692 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2694 Asm->EOL("Compilation Unit Length");
2696 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2697 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2698 GE = Globals.end(); GI != GE; ++GI) {
2699 const std::string &Name = GI->first;
2700 DIE * Entity = GI->second;
2702 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2703 Asm->EmitString(Name); Asm->EOL("External Name");
2706 Asm->EmitInt32(0); Asm->EOL("End Mark");
2707 EmitLabel("pubnames_end", Unit->getID());
2712 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2714 void EmitDebugPubNames() {
2715 // Start the dwarf pubnames section.
2716 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2719 EmitDebugPubNamesPerCU(MainCU);
2723 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2724 EmitDebugPubNamesPerCU(CompileUnits[i]);
2727 /// EmitDebugStr - Emit visible names into a debug str section.
2729 void EmitDebugStr() {
2730 // Check to see if it is worth the effort.
2731 if (!StringPool.empty()) {
2732 // Start the dwarf str section.
2733 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2735 // For each of strings in the string pool.
2736 for (unsigned StringID = 1, N = StringPool.size();
2737 StringID <= N; ++StringID) {
2738 // Emit a label for reference from debug information entries.
2739 EmitLabel("string", StringID);
2740 // Emit the string itself.
2741 const std::string &String = StringPool[StringID];
2742 Asm->EmitString(String); Asm->EOL();
2749 /// EmitDebugLoc - Emit visible names into a debug loc section.
2751 void EmitDebugLoc() {
2752 // Start the dwarf loc section.
2753 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2758 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2760 void EmitDebugARanges() {
2761 // Start the dwarf aranges section.
2762 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2766 CompileUnit *Unit = GetBaseCompileUnit();
2768 // Don't include size of length
2769 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2771 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2773 EmitReference("info_begin", Unit->getID());
2774 Asm->EOL("Offset of Compilation Unit Info");
2776 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2778 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2780 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2781 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2784 EmitReference("text_begin", 0); Asm->EOL("Address");
2785 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2787 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2788 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2794 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2796 void EmitDebugRanges() {
2797 // Start the dwarf ranges section.
2798 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2803 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2805 void EmitDebugMacInfo() {
2806 if (TAI->doesSupportMacInfoSection()) {
2807 // Start the dwarf macinfo section.
2808 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2814 /// GetOrCreateSourceID - Look up the source id with the given directory and
2815 /// source file names. If none currently exists, create a new id and insert it
2816 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2818 unsigned GetOrCreateSourceID(const std::string &DirName,
2819 const std::string &FileName) {
2821 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2822 if (DI != DirectoryIdMap.end()) {
2823 DId = DI->getValue();
2825 DId = DirectoryNames.size() + 1;
2826 DirectoryIdMap[DirName] = DId;
2827 DirectoryNames.push_back(DirName);
2831 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2832 if (FI != SourceFileIdMap.end()) {
2833 FId = FI->getValue();
2835 FId = SourceFileNames.size() + 1;
2836 SourceFileIdMap[FileName] = FId;
2837 SourceFileNames.push_back(FileName);
2840 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2841 SourceIdMap.find(std::make_pair(DId, FId));
2842 if (SI != SourceIdMap.end())
2845 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2846 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2847 SourceIds.push_back(std::make_pair(DId, FId));
2852 void ConstructCompileUnit(GlobalVariable *GV) {
2853 DICompileUnit DIUnit(GV);
2854 std::string Dir, FN, Prod;
2855 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2856 DIUnit.getFilename(FN));
2858 DIE *Die = new DIE(DW_TAG_compile_unit);
2859 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2860 DWLabel("section_line", 0), DWLabel("section_line", 0),
2862 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2863 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2864 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2866 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2867 if (DIUnit.isOptimized())
2868 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2870 DIUnit.getFlags(Flags);
2872 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2873 unsigned RVer = DIUnit.getRunTimeVersion();
2875 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2877 CompileUnit *Unit = new CompileUnit(ID, Die);
2878 if (DIUnit.isMain()) {
2879 assert(!MainCU && "Multiple main compile units are found!");
2882 CompileUnitMap[DIUnit.getGV()] = Unit;
2883 CompileUnits.push_back(Unit);
2886 /// ConstructCompileUnits - Create a compile unit DIEs.
2887 void ConstructCompileUnits() {
2888 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2891 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2892 "Malformed compile unit descriptor anchor type");
2893 Constant *RootC = cast<Constant>(*Root->use_begin());
2894 assert(RootC->hasNUsesOrMore(1) &&
2895 "Malformed compile unit descriptor anchor type");
2896 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2898 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2899 UUI != UUE; ++UUI) {
2900 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2901 ConstructCompileUnit(GV);
2905 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2906 DIGlobalVariable DI_GV(GV);
2907 CompileUnit *DW_Unit = MainCU;
2909 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2911 // Check for pre-existence.
2912 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2916 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2919 DIEBlock *Block = new DIEBlock();
2920 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2921 AddObjectLabel(Block, 0, DW_FORM_udata,
2922 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2923 AddBlock(VariableDie, DW_AT_location, 0, Block);
2927 // Add to context owner.
2928 DW_Unit->getDie()->AddChild(VariableDie);
2929 // Expose as global. FIXME - need to check external flag.
2931 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2935 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2936 /// visible global variables. Return true if at least one global DIE is
2938 bool ConstructGlobalVariableDIEs() {
2939 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2943 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2944 "Malformed global variable descriptor anchor type");
2945 Constant *RootC = cast<Constant>(*Root->use_begin());
2946 assert(RootC->hasNUsesOrMore(1) &&
2947 "Malformed global variable descriptor anchor type");
2949 bool Result = false;
2950 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2952 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2953 UUI != UUE; ++UUI) {
2954 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2955 Result |= ConstructGlobalVariableDIE(GV);
2960 bool ConstructSubprogram(GlobalVariable *GV) {
2961 DISubprogram SP(GV);
2962 CompileUnit *Unit = MainCU;
2964 Unit = FindCompileUnit(SP.getCompileUnit());
2966 // Check for pre-existence.
2967 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2971 if (!SP.isDefinition())
2972 // This is a method declaration which will be handled while
2973 // constructing class type.
2976 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2979 Slot = SubprogramDie;
2980 // Add to context owner.
2981 Unit->getDie()->AddChild(SubprogramDie);
2982 // Expose as global.
2984 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2988 /// ConstructSubprograms - Create DIEs for each of the externally visible
2989 /// subprograms. Return true if at least one subprogram DIE is created.
2990 bool ConstructSubprograms() {
2991 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2995 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2996 "Malformed subprogram descriptor anchor type");
2997 Constant *RootC = cast<Constant>(*Root->use_begin());
2998 assert(RootC->hasNUsesOrMore(1) &&
2999 "Malformed subprogram descriptor anchor type");
3001 bool Result = false;
3002 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3004 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3005 UUI != UUE; ++UUI) {
3006 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3007 Result |= ConstructSubprogram(GV);
3013 //===--------------------------------------------------------------------===//
3014 // Main entry points.
3016 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3017 : Dwarf(OS, A, T, "dbg"), MainCU(0),
3018 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
3019 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
3020 SectionSourceLines(), didInitial(false), shouldEmit(false),
3021 RootDbgScope(0), DebugTimer(0) {
3022 if (TimePassesIsEnabled)
3023 DebugTimer = new Timer("Dwarf Debug Writer",
3024 getDwarfTimerGroup());
3026 virtual ~DwarfDebug() {
3027 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3033 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3035 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
3037 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3038 /// This is inovked by the target AsmPrinter.
3039 void SetDebugInfo(MachineModuleInfo *mmi) {
3040 if (TimePassesIsEnabled)
3041 DebugTimer->startTimer();
3043 // Create all the compile unit DIEs.
3044 ConstructCompileUnits();
3046 if (CompileUnits.empty()) {
3047 if (TimePassesIsEnabled)
3048 DebugTimer->stopTimer();
3053 // Create DIEs for each of the externally visible global variables.
3054 bool globalDIEs = ConstructGlobalVariableDIEs();
3056 // Create DIEs for each of the externally visible subprograms.
3057 bool subprogramDIEs = ConstructSubprograms();
3059 // If there is not any debug info available for any global variables
3060 // and any subprograms then there is not any debug info to emit.
3061 if (!globalDIEs && !subprogramDIEs) {
3062 if (TimePassesIsEnabled)
3063 DebugTimer->stopTimer();
3070 MMI->setDebugInfoAvailability(true);
3072 // Prime section data.
3073 SectionMap.insert(TAI->getTextSection());
3075 // Print out .file directives to specify files for .loc directives. These
3076 // are printed out early so that they precede any .loc directives.
3077 if (TAI->hasDotLocAndDotFile()) {
3078 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3079 // Remember source id starts at 1.
3080 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3081 sys::Path FullPath(getSourceDirectoryName(Id.first));
3083 FullPath.appendComponent(getSourceFileName(Id.second));
3084 assert(AppendOk && "Could not append filename to directory!");
3086 Asm->EmitFile(i, FullPath.toString());
3091 // Emit initial sections
3094 if (TimePassesIsEnabled)
3095 DebugTimer->stopTimer();
3098 /// BeginModule - Emit all Dwarf sections that should come prior to the
3100 void BeginModule(Module *M) {
3104 /// EndModule - Emit all Dwarf sections that should come after the content.
3107 if (!ShouldEmitDwarfDebug())
3110 if (TimePassesIsEnabled)
3111 DebugTimer->startTimer();
3113 // Standard sections final addresses.
3114 Asm->SwitchToSection(TAI->getTextSection());
3115 EmitLabel("text_end", 0);
3116 Asm->SwitchToSection(TAI->getDataSection());
3117 EmitLabel("data_end", 0);
3119 // End text sections.
3120 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3121 Asm->SwitchToSection(SectionMap[i]);
3122 EmitLabel("section_end", i);
3125 // Emit common frame information.
3126 EmitCommonDebugFrame();
3128 // Emit function debug frame information
3129 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3130 E = DebugFrames.end(); I != E; ++I)
3131 EmitFunctionDebugFrame(*I);
3133 // Compute DIE offsets and sizes.
3136 // Emit all the DIEs into a debug info section
3139 // Corresponding abbreviations into a abbrev section.
3140 EmitAbbreviations();
3142 // Emit source line correspondence into a debug line section.
3145 // Emit info into a debug pubnames section.
3146 EmitDebugPubNames();
3148 // Emit info into a debug str section.
3151 // Emit info into a debug loc section.
3154 // Emit info into a debug aranges section.
3157 // Emit info into a debug ranges section.
3160 // Emit info into a debug macinfo section.
3163 if (TimePassesIsEnabled)
3164 DebugTimer->stopTimer();
3167 /// BeginFunction - Gather pre-function debug information. Assumes being
3168 /// emitted immediately after the function entry point.
3169 void BeginFunction(MachineFunction *MF) {
3170 if (!ShouldEmitDwarfDebug()) return;
3172 if (TimePassesIsEnabled)
3173 DebugTimer->startTimer();
3177 // Begin accumulating function debug information.
3178 MMI->BeginFunction(MF);
3180 // Assumes in correct section after the entry point.
3181 EmitLabel("func_begin", ++SubprogramCount);
3183 // Emit label for the implicitly defined dbg.stoppoint at the start of
3185 if (!Lines.empty()) {
3186 const SrcLineInfo &LineInfo = Lines[0];
3187 Asm->printLabel(LineInfo.getLabelID());
3190 if (TimePassesIsEnabled)
3191 DebugTimer->stopTimer();
3194 /// EndFunction - Gather and emit post-function debug information.
3196 void EndFunction(MachineFunction *MF) {
3197 if (!ShouldEmitDwarfDebug()) return;
3199 if (TimePassesIsEnabled)
3200 DebugTimer->startTimer();
3202 // Define end label for subprogram.
3203 EmitLabel("func_end", SubprogramCount);
3205 // Get function line info.
3206 if (!Lines.empty()) {
3207 // Get section line info.
3208 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3209 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3210 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3211 // Append the function info to section info.
3212 SectionLineInfos.insert(SectionLineInfos.end(),
3213 Lines.begin(), Lines.end());
3216 // Construct scopes for subprogram.
3218 ConstructRootDbgScope(RootDbgScope);
3220 // FIXME: This is wrong. We are essentially getting past a problem with
3221 // debug information not being able to handle unreachable blocks that have
3222 // debug information in them. In particular, those unreachable blocks that
3223 // have "region end" info in them. That situation results in the "root
3224 // scope" not being created. If that's the case, then emit a "default"
3225 // scope, i.e., one that encompasses the whole function. This isn't
3226 // desirable. And a better way of handling this (and all of the debugging
3227 // information) needs to be explored.
3228 ConstructDefaultDbgScope(MF);
3230 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3231 MMI->getFrameMoves()));
3235 delete RootDbgScope;
3236 DbgScopeMap.clear();
3237 RootDbgScope = NULL;
3242 if (TimePassesIsEnabled)
3243 DebugTimer->stopTimer();
3246 /// ValidDebugInfo - Return true if V represents valid debug info value.
3247 bool ValidDebugInfo(Value *V) {
3254 GlobalVariable *GV = getGlobalVariable(V);
3258 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3261 if (TimePassesIsEnabled)
3262 DebugTimer->startTimer();
3264 DIDescriptor DI(GV);
3266 // Check current version. Allow Version6 for now.
3267 unsigned Version = DI.getVersion();
3268 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) {
3269 if (TimePassesIsEnabled)
3270 DebugTimer->stopTimer();
3275 unsigned Tag = DI.getTag();
3277 case DW_TAG_variable:
3278 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3280 case DW_TAG_compile_unit:
3281 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3283 case DW_TAG_subprogram:
3284 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3290 if (TimePassesIsEnabled)
3291 DebugTimer->stopTimer();
3296 /// RecordSourceLine - Records location information and associates it with a
3297 /// label. Returns a unique label ID used to generate a label and provide
3298 /// correspondence to the source line list.
3299 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3300 if (TimePassesIsEnabled)
3301 DebugTimer->startTimer();
3303 CompileUnit *Unit = CompileUnitMap[V];
3304 assert(Unit && "Unable to find CompileUnit");
3305 unsigned ID = MMI->NextLabelID();
3306 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3308 if (TimePassesIsEnabled)
3309 DebugTimer->stopTimer();
3314 /// RecordSourceLine - Records location information and associates it with a
3315 /// label. Returns a unique label ID used to generate a label and provide
3316 /// correspondence to the source line list.
3317 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3318 if (TimePassesIsEnabled)
3319 DebugTimer->startTimer();
3321 unsigned ID = MMI->NextLabelID();
3322 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3324 if (TimePassesIsEnabled)
3325 DebugTimer->stopTimer();
3330 /// getRecordSourceLineCount - Return the number of source lines in the debug
3332 unsigned getRecordSourceLineCount() const {
3333 return Lines.size();
3336 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3337 /// timed. Look up the source id with the given directory and source file
3338 /// names. If none currently exists, create a new id and insert it in the
3339 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3341 unsigned getOrCreateSourceID(const std::string &DirName,
3342 const std::string &FileName) {
3343 if (TimePassesIsEnabled)
3344 DebugTimer->startTimer();
3346 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3348 if (TimePassesIsEnabled)
3349 DebugTimer->stopTimer();
3354 /// RecordRegionStart - Indicate the start of a region.
3355 unsigned RecordRegionStart(GlobalVariable *V) {
3356 if (TimePassesIsEnabled)
3357 DebugTimer->startTimer();
3359 DbgScope *Scope = getOrCreateScope(V);
3360 unsigned ID = MMI->NextLabelID();
3361 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3363 if (TimePassesIsEnabled)
3364 DebugTimer->stopTimer();
3369 /// RecordRegionEnd - Indicate the end of a region.
3370 unsigned RecordRegionEnd(GlobalVariable *V) {
3371 if (TimePassesIsEnabled)
3372 DebugTimer->startTimer();
3374 DbgScope *Scope = getOrCreateScope(V);
3375 unsigned ID = MMI->NextLabelID();
3376 Scope->setEndLabelID(ID);
3378 if (TimePassesIsEnabled)
3379 DebugTimer->stopTimer();
3384 /// RecordVariable - Indicate the declaration of a local variable.
3385 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3386 if (TimePassesIsEnabled)
3387 DebugTimer->startTimer();
3389 DIDescriptor Desc(GV);
3390 DbgScope *Scope = NULL;
3392 if (Desc.getTag() == DW_TAG_variable) {
3393 // GV is a global variable.
3394 DIGlobalVariable DG(GV);
3395 Scope = getOrCreateScope(DG.getContext().getGV());
3397 // or GV is a local variable.
3399 Scope = getOrCreateScope(DV.getContext().getGV());
3402 assert(Scope && "Unable to find variable' scope");
3403 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3404 Scope->AddVariable(DV);
3406 if (TimePassesIsEnabled)
3407 DebugTimer->stopTimer();
3411 //===----------------------------------------------------------------------===//
3412 /// DwarfException - Emits Dwarf exception handling directives.
3414 class DwarfException : public Dwarf {
3415 struct FunctionEHFrameInfo {
3418 unsigned PersonalityIndex;
3420 bool hasLandingPads;
3421 std::vector<MachineMove> Moves;
3422 const Function * function;
3424 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3426 const std::vector<MachineMove> &M,
3428 FnName(FN), Number(Num), PersonalityIndex(P),
3429 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3432 std::vector<FunctionEHFrameInfo> EHFrames;
3434 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3436 bool shouldEmitTable;
3438 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3439 /// should be emitted.
3440 bool shouldEmitMoves;
3442 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3443 /// should be emitted.
3444 bool shouldEmitTableModule;
3446 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3447 /// should be emitted.
3448 bool shouldEmitMovesModule;
3450 /// ExceptionTimer - Timer for the Dwarf exception writer.
3451 Timer *ExceptionTimer;
3453 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3455 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3456 // Size and sign of stack growth.
3458 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3459 TargetFrameInfo::StackGrowsUp ?
3460 TD->getPointerSize() : -TD->getPointerSize();
3462 // Begin eh frame section.
3463 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3465 if (!TAI->doesRequireNonLocalEHFrameLabel())
3466 O << TAI->getEHGlobalPrefix();
3467 O << "EH_frame" << Index << ":\n";
3468 EmitLabel("section_eh_frame", Index);
3470 // Define base labels.
3471 EmitLabel("eh_frame_common", Index);
3473 // Define the eh frame length.
3474 EmitDifference("eh_frame_common_end", Index,
3475 "eh_frame_common_begin", Index, true);
3476 Asm->EOL("Length of Common Information Entry");
3479 EmitLabel("eh_frame_common_begin", Index);
3480 Asm->EmitInt32((int)0);
3481 Asm->EOL("CIE Identifier Tag");
3482 Asm->EmitInt8(DW_CIE_VERSION);
3483 Asm->EOL("CIE Version");
3485 // The personality presence indicates that language specific information
3486 // will show up in the eh frame.
3487 Asm->EmitString(Personality ? "zPLR" : "zR");
3488 Asm->EOL("CIE Augmentation");
3490 // Round out reader.
3491 Asm->EmitULEB128Bytes(1);
3492 Asm->EOL("CIE Code Alignment Factor");
3493 Asm->EmitSLEB128Bytes(stackGrowth);
3494 Asm->EOL("CIE Data Alignment Factor");
3495 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3496 Asm->EOL("CIE Return Address Column");
3498 // If there is a personality, we need to indicate the functions location.
3500 Asm->EmitULEB128Bytes(7);
3501 Asm->EOL("Augmentation Size");
3503 if (TAI->getNeedsIndirectEncoding()) {
3504 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3505 Asm->EOL("Personality (pcrel sdata4 indirect)");
3507 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3508 Asm->EOL("Personality (pcrel sdata4)");
3511 PrintRelDirective(true);
3512 O << TAI->getPersonalityPrefix();
3513 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3514 O << TAI->getPersonalitySuffix();
3515 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3516 O << "-" << TAI->getPCSymbol();
3517 Asm->EOL("Personality");
3519 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3520 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3522 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3523 Asm->EOL("FDE Encoding (pcrel sdata4)");
3525 Asm->EmitULEB128Bytes(1);
3526 Asm->EOL("Augmentation Size");
3528 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3529 Asm->EOL("FDE Encoding (pcrel sdata4)");
3532 // Indicate locations of general callee saved registers in frame.
3533 std::vector<MachineMove> Moves;
3534 RI->getInitialFrameState(Moves);
3535 EmitFrameMoves(NULL, 0, Moves, true);
3537 // On Darwin the linker honors the alignment of eh_frame, which means it
3538 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3539 // you get holes which confuse readers of eh_frame.
3540 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3542 EmitLabel("eh_frame_common_end", Index);
3547 /// EmitEHFrame - Emit function exception frame information.
3549 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3550 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3552 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3554 // Externally visible entry into the functions eh frame info.
3555 // If the corresponding function is static, this should not be
3556 // externally visible.
3557 if (linkage != Function::InternalLinkage &&
3558 linkage != Function::PrivateLinkage) {
3559 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3560 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3563 // If corresponding function is weak definition, this should be too.
3564 if ((linkage == Function::WeakAnyLinkage ||
3565 linkage == Function::WeakODRLinkage ||
3566 linkage == Function::LinkOnceAnyLinkage ||
3567 linkage == Function::LinkOnceODRLinkage) &&
3568 TAI->getWeakDefDirective())
3569 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3571 // If there are no calls then you can't unwind. This may mean we can
3572 // omit the EH Frame, but some environments do not handle weak absolute
3574 // If UnwindTablesMandatory is set we cannot do this optimization; the
3575 // unwind info is to be available for non-EH uses.
3576 if (!EHFrameInfo.hasCalls &&
3577 !UnwindTablesMandatory &&
3578 ((linkage != Function::WeakAnyLinkage &&
3579 linkage != Function::WeakODRLinkage &&
3580 linkage != Function::LinkOnceAnyLinkage &&
3581 linkage != Function::LinkOnceODRLinkage) ||
3582 !TAI->getWeakDefDirective() ||
3583 TAI->getSupportsWeakOmittedEHFrame()))
3585 O << EHFrameInfo.FnName << " = 0\n";
3586 // This name has no connection to the function, so it might get
3587 // dead-stripped when the function is not, erroneously. Prohibit
3588 // dead-stripping unconditionally.
3589 if (const char *UsedDirective = TAI->getUsedDirective())
3590 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3592 O << EHFrameInfo.FnName << ":\n";
3595 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3596 "eh_frame_begin", EHFrameInfo.Number, true);
3597 Asm->EOL("Length of Frame Information Entry");
3599 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3601 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3602 PrintRelDirective(true, true);
3603 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3605 if (!TAI->isAbsoluteEHSectionOffsets())
3606 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3608 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3609 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3613 Asm->EOL("FDE CIE offset");
3615 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3616 Asm->EOL("FDE initial location");
3617 EmitDifference("eh_func_end", EHFrameInfo.Number,
3618 "eh_func_begin", EHFrameInfo.Number, true);
3619 Asm->EOL("FDE address range");
3621 // If there is a personality and landing pads then point to the language
3622 // specific data area in the exception table.
3623 if (EHFrameInfo.PersonalityIndex) {
3624 Asm->EmitULEB128Bytes(4);
3625 Asm->EOL("Augmentation size");
3627 if (EHFrameInfo.hasLandingPads)
3628 EmitReference("exception", EHFrameInfo.Number, true, true);
3630 Asm->EmitInt32((int)0);
3631 Asm->EOL("Language Specific Data Area");
3633 Asm->EmitULEB128Bytes(0);
3634 Asm->EOL("Augmentation size");
3637 // Indicate locations of function specific callee saved registers in
3639 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3642 // On Darwin the linker honors the alignment of eh_frame, which means it
3643 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3644 // you get holes which confuse readers of eh_frame.
3645 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3647 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3649 // If the function is marked used, this table should be also. We cannot
3650 // make the mark unconditional in this case, since retaining the table
3651 // also retains the function in this case, and there is code around
3652 // that depends on unused functions (calling undefined externals) being
3653 // dead-stripped to link correctly. Yes, there really is.
3654 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3655 if (const char *UsedDirective = TAI->getUsedDirective())
3656 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3660 /// EmitExceptionTable - Emit landing pads and actions.
3662 /// The general organization of the table is complex, but the basic concepts
3663 /// are easy. First there is a header which describes the location and
3664 /// organization of the three components that follow.
3665 /// 1. The landing pad site information describes the range of code covered
3666 /// by the try. In our case it's an accumulation of the ranges covered
3667 /// by the invokes in the try. There is also a reference to the landing
3668 /// pad that handles the exception once processed. Finally an index into
3669 /// the actions table.
3670 /// 2. The action table, in our case, is composed of pairs of type ids
3671 /// and next action offset. Starting with the action index from the
3672 /// landing pad site, each type Id is checked for a match to the current
3673 /// exception. If it matches then the exception and type id are passed
3674 /// on to the landing pad. Otherwise the next action is looked up. This
3675 /// chain is terminated with a next action of zero. If no type id is
3676 /// found the the frame is unwound and handling continues.
3677 /// 3. Type id table contains references to all the C++ typeinfo for all
3678 /// catches in the function. This tables is reversed indexed base 1.
3680 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3681 static unsigned SharedTypeIds(const LandingPadInfo *L,
3682 const LandingPadInfo *R) {
3683 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3684 unsigned LSize = LIds.size(), RSize = RIds.size();
3685 unsigned MinSize = LSize < RSize ? LSize : RSize;
3688 for (; Count != MinSize; ++Count)
3689 if (LIds[Count] != RIds[Count])
3695 /// PadLT - Order landing pads lexicographically by type id.
3696 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3697 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3698 unsigned LSize = LIds.size(), RSize = RIds.size();
3699 unsigned MinSize = LSize < RSize ? LSize : RSize;
3701 for (unsigned i = 0; i != MinSize; ++i)
3702 if (LIds[i] != RIds[i])
3703 return LIds[i] < RIds[i];
3705 return LSize < RSize;
3709 static inline unsigned getEmptyKey() { return -1U; }
3710 static inline unsigned getTombstoneKey() { return -2U; }
3711 static unsigned getHashValue(const unsigned &Key) { return Key; }
3712 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3713 static bool isPod() { return true; }
3716 /// ActionEntry - Structure describing an entry in the actions table.
3717 struct ActionEntry {
3718 int ValueForTypeID; // The value to write - may not be equal to the type id.
3720 struct ActionEntry *Previous;
3723 /// PadRange - Structure holding a try-range and the associated landing pad.
3725 // The index of the landing pad.
3727 // The index of the begin and end labels in the landing pad's label lists.
3728 unsigned RangeIndex;
3731 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3733 /// CallSiteEntry - Structure describing an entry in the call-site table.
3734 struct CallSiteEntry {
3735 // The 'try-range' is BeginLabel .. EndLabel.
3736 unsigned BeginLabel; // zero indicates the start of the function.
3737 unsigned EndLabel; // zero indicates the end of the function.
3738 // The landing pad starts at PadLabel.
3739 unsigned PadLabel; // zero indicates that there is no landing pad.
3743 void EmitExceptionTable() {
3744 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3745 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3746 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3747 if (PadInfos.empty()) return;
3749 // Sort the landing pads in order of their type ids. This is used to fold
3750 // duplicate actions.
3751 SmallVector<const LandingPadInfo *, 64> LandingPads;
3752 LandingPads.reserve(PadInfos.size());
3753 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3754 LandingPads.push_back(&PadInfos[i]);
3755 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3757 // Negative type ids index into FilterIds, positive type ids index into
3758 // TypeInfos. The value written for a positive type id is just the type
3759 // id itself. For a negative type id, however, the value written is the
3760 // (negative) byte offset of the corresponding FilterIds entry. The byte
3761 // offset is usually equal to the type id, because the FilterIds entries
3762 // are written using a variable width encoding which outputs one byte per
3763 // entry as long as the value written is not too large, but can differ.
3764 // This kind of complication does not occur for positive type ids because
3765 // type infos are output using a fixed width encoding.
3766 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3767 SmallVector<int, 16> FilterOffsets;
3768 FilterOffsets.reserve(FilterIds.size());
3770 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3771 E = FilterIds.end(); I != E; ++I) {
3772 FilterOffsets.push_back(Offset);
3773 Offset -= TargetAsmInfo::getULEB128Size(*I);
3776 // Compute the actions table and gather the first action index for each
3777 // landing pad site.
3778 SmallVector<ActionEntry, 32> Actions;
3779 SmallVector<unsigned, 64> FirstActions;
3780 FirstActions.reserve(LandingPads.size());
3782 int FirstAction = 0;
3783 unsigned SizeActions = 0;
3784 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3785 const LandingPadInfo *LP = LandingPads[i];
3786 const std::vector<int> &TypeIds = LP->TypeIds;
3787 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3788 unsigned SizeSiteActions = 0;
3790 if (NumShared < TypeIds.size()) {
3791 unsigned SizeAction = 0;
3792 ActionEntry *PrevAction = 0;
3795 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3796 assert(Actions.size());
3797 PrevAction = &Actions.back();
3798 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3799 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3800 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3802 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3803 SizeAction += -PrevAction->NextAction;
3804 PrevAction = PrevAction->Previous;
3808 // Compute the actions.
3809 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3810 int TypeID = TypeIds[I];
3811 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3812 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3813 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3815 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3816 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3817 SizeSiteActions += SizeAction;
3819 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3820 Actions.push_back(Action);
3822 PrevAction = &Actions.back();
3825 // Record the first action of the landing pad site.
3826 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3827 } // else identical - re-use previous FirstAction
3829 FirstActions.push_back(FirstAction);
3831 // Compute this sites contribution to size.
3832 SizeActions += SizeSiteActions;
3835 // Compute the call-site table. The entry for an invoke has a try-range
3836 // containing the call, a non-zero landing pad and an appropriate action.
3837 // The entry for an ordinary call has a try-range containing the call and
3838 // zero for the landing pad and the action. Calls marked 'nounwind' have
3839 // no entry and must not be contained in the try-range of any entry - they
3840 // form gaps in the table. Entries must be ordered by try-range address.
3841 SmallVector<CallSiteEntry, 64> CallSites;
3843 RangeMapType PadMap;
3844 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3845 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3846 // try-ranges for them need be deduced.
3847 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3848 const LandingPadInfo *LandingPad = LandingPads[i];
3849 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3850 unsigned BeginLabel = LandingPad->BeginLabels[j];
3851 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3852 PadRange P = { i, j };
3853 PadMap[BeginLabel] = P;
3857 // The end label of the previous invoke or nounwind try-range.
3858 unsigned LastLabel = 0;
3860 // Whether there is a potentially throwing instruction (currently this means
3861 // an ordinary call) between the end of the previous try-range and now.
3862 bool SawPotentiallyThrowing = false;
3864 // Whether the last callsite entry was for an invoke.
3865 bool PreviousIsInvoke = false;
3867 // Visit all instructions in order of address.
3868 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3870 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3872 if (!MI->isLabel()) {
3873 SawPotentiallyThrowing |= MI->getDesc().isCall();
3877 unsigned BeginLabel = MI->getOperand(0).getImm();
3878 assert(BeginLabel && "Invalid label!");
3880 // End of the previous try-range?
3881 if (BeginLabel == LastLabel)
3882 SawPotentiallyThrowing = false;
3884 // Beginning of a new try-range?
3885 RangeMapType::iterator L = PadMap.find(BeginLabel);
3886 if (L == PadMap.end())
3887 // Nope, it was just some random label.
3890 PadRange P = L->second;
3891 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3893 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3894 "Inconsistent landing pad map!");
3896 // If some instruction between the previous try-range and this one may
3897 // throw, create a call-site entry with no landing pad for the region
3898 // between the try-ranges.
3899 if (SawPotentiallyThrowing) {
3900 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3901 CallSites.push_back(Site);
3902 PreviousIsInvoke = false;
3905 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3906 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3908 if (LandingPad->LandingPadLabel) {
3909 // This try-range is for an invoke.
3910 CallSiteEntry Site = {BeginLabel, LastLabel,
3911 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3913 // Try to merge with the previous call-site.
3914 if (PreviousIsInvoke) {
3915 CallSiteEntry &Prev = CallSites.back();
3916 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3917 // Extend the range of the previous entry.
3918 Prev.EndLabel = Site.EndLabel;
3923 // Otherwise, create a new call-site.
3924 CallSites.push_back(Site);
3925 PreviousIsInvoke = true;
3928 PreviousIsInvoke = false;
3932 // If some instruction between the previous try-range and the end of the
3933 // function may throw, create a call-site entry with no landing pad for the
3934 // region following the try-range.
3935 if (SawPotentiallyThrowing) {
3936 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3937 CallSites.push_back(Site);
3943 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3944 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3945 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3946 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3949 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3950 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3953 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3954 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3956 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3957 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3958 SizeSites + SizeActions + SizeTypes;
3960 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3961 sizeof(int8_t) + // TType format
3962 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3965 unsigned SizeAlign = (4 - TotalSize) & 3;
3967 // Begin the exception table.
3968 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3969 Asm->EmitAlignment(2, 0, 0, false);
3970 O << "GCC_except_table" << SubprogramCount << ":\n";
3971 for (unsigned i = 0; i != SizeAlign; ++i) {
3973 Asm->EOL("Padding");
3975 EmitLabel("exception", SubprogramCount);
3978 Asm->EmitInt8(DW_EH_PE_omit);
3979 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3980 Asm->EmitInt8(DW_EH_PE_absptr);
3981 Asm->EOL("TType format (DW_EH_PE_absptr)");
3982 Asm->EmitULEB128Bytes(TypeOffset);
3983 Asm->EOL("TType base offset");
3984 Asm->EmitInt8(DW_EH_PE_udata4);
3985 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3986 Asm->EmitULEB128Bytes(SizeSites);
3987 Asm->EOL("Call-site table length");
3989 // Emit the landing pad site information.
3990 for (unsigned i = 0; i < CallSites.size(); ++i) {
3991 CallSiteEntry &S = CallSites[i];
3992 const char *BeginTag;
3993 unsigned BeginNumber;
3995 if (!S.BeginLabel) {
3996 BeginTag = "eh_func_begin";
3997 BeginNumber = SubprogramCount;
4000 BeginNumber = S.BeginLabel;
4003 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4005 Asm->EOL("Region start");
4008 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4011 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4013 Asm->EOL("Region length");
4018 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4020 Asm->EOL("Landing pad");
4022 Asm->EmitULEB128Bytes(S.Action);
4026 // Emit the actions.
4027 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4028 ActionEntry &Action = Actions[I];
4030 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4031 Asm->EOL("TypeInfo index");
4032 Asm->EmitSLEB128Bytes(Action.NextAction);
4033 Asm->EOL("Next action");
4036 // Emit the type ids.
4037 for (unsigned M = TypeInfos.size(); M; --M) {
4038 GlobalVariable *GV = TypeInfos[M - 1];
4040 PrintRelDirective();
4043 O << Asm->getGlobalLinkName(GV);
4047 Asm->EOL("TypeInfo");
4050 // Emit the filter typeids.
4051 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4052 unsigned TypeID = FilterIds[j];
4053 Asm->EmitULEB128Bytes(TypeID);
4054 Asm->EOL("Filter TypeInfo index");
4057 Asm->EmitAlignment(2, 0, 0, false);
4061 //===--------------------------------------------------------------------===//
4062 // Main entry points.
4064 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4065 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4066 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4068 if (TimePassesIsEnabled)
4069 ExceptionTimer = new Timer("Dwarf Exception Writer",
4070 getDwarfTimerGroup());
4073 virtual ~DwarfException() {
4074 delete ExceptionTimer;
4077 /// SetModuleInfo - Set machine module information when it's known that pass
4078 /// manager has created it. Set by the target AsmPrinter.
4079 void SetModuleInfo(MachineModuleInfo *mmi) {
4083 /// BeginModule - Emit all exception information that should come prior to the
4085 void BeginModule(Module *M) {
4089 /// EndModule - Emit all exception information that should come after the
4092 if (TimePassesIsEnabled)
4093 ExceptionTimer->startTimer();
4095 if (shouldEmitMovesModule || shouldEmitTableModule) {
4096 const std::vector<Function *> Personalities = MMI->getPersonalities();
4097 for (unsigned i = 0; i < Personalities.size(); ++i)
4098 EmitCommonEHFrame(Personalities[i], i);
4100 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4101 E = EHFrames.end(); I != E; ++I)
4105 if (TimePassesIsEnabled)
4106 ExceptionTimer->stopTimer();
4109 /// BeginFunction - Gather pre-function exception information. Assumes being
4110 /// emitted immediately after the function entry point.
4111 void BeginFunction(MachineFunction *MF) {
4112 if (TimePassesIsEnabled)
4113 ExceptionTimer->startTimer();
4116 shouldEmitTable = shouldEmitMoves = false;
4118 if (MMI && TAI->doesSupportExceptionHandling()) {
4119 // Map all labels and get rid of any dead landing pads.
4120 MMI->TidyLandingPads();
4122 // If any landing pads survive, we need an EH table.
4123 if (MMI->getLandingPads().size())
4124 shouldEmitTable = true;
4126 // See if we need frame move info.
4127 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4128 shouldEmitMoves = true;
4130 if (shouldEmitMoves || shouldEmitTable)
4131 // Assumes in correct section after the entry point.
4132 EmitLabel("eh_func_begin", ++SubprogramCount);
4135 shouldEmitTableModule |= shouldEmitTable;
4136 shouldEmitMovesModule |= shouldEmitMoves;
4138 if (TimePassesIsEnabled)
4139 ExceptionTimer->stopTimer();
4142 /// EndFunction - Gather and emit post-function exception information.
4144 void EndFunction() {
4145 if (TimePassesIsEnabled)
4146 ExceptionTimer->startTimer();
4148 if (shouldEmitMoves || shouldEmitTable) {
4149 EmitLabel("eh_func_end", SubprogramCount);
4150 EmitExceptionTable();
4152 // Save EH frame information
4154 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4156 MMI->getPersonalityIndex(),
4157 MF->getFrameInfo()->hasCalls(),
4158 !MMI->getLandingPads().empty(),
4159 MMI->getFrameMoves(),
4160 MF->getFunction()));
4163 if (TimePassesIsEnabled)
4164 ExceptionTimer->stopTimer();
4168 } // End of namespace llvm
4170 //===----------------------------------------------------------------------===//
4172 /// Emit - Print the abbreviation using the specified Dwarf writer.
4174 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4175 // Emit its Dwarf tag type.
4176 DD.getAsm()->EmitULEB128Bytes(Tag);
4177 DD.getAsm()->EOL(TagString(Tag));
4179 // Emit whether it has children DIEs.
4180 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4181 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4183 // For each attribute description.
4184 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4185 const DIEAbbrevData &AttrData = Data[i];
4187 // Emit attribute type.
4188 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4189 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4192 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4193 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4196 // Mark end of abbreviation.
4197 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4198 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4202 void DIEAbbrev::print(std::ostream &O) {
4203 O << "Abbreviation @"
4204 << std::hex << (intptr_t)this << std::dec
4208 << ChildrenString(ChildrenFlag)
4211 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4213 << AttributeString(Data[i].getAttribute())
4215 << FormEncodingString(Data[i].getForm())
4219 void DIEAbbrev::dump() { print(cerr); }
4222 //===----------------------------------------------------------------------===//
4225 void DIEValue::dump() {
4230 //===----------------------------------------------------------------------===//
4232 /// EmitValue - Emit integer of appropriate size.
4234 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4236 case DW_FORM_flag: // Fall thru
4237 case DW_FORM_ref1: // Fall thru
4238 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4239 case DW_FORM_ref2: // Fall thru
4240 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4241 case DW_FORM_ref4: // Fall thru
4242 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4243 case DW_FORM_ref8: // Fall thru
4244 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4245 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4246 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4247 default: assert(0 && "DIE Value form not supported yet"); break;
4251 /// SizeOf - Determine size of integer value in bytes.
4253 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4255 case DW_FORM_flag: // Fall thru
4256 case DW_FORM_ref1: // Fall thru
4257 case DW_FORM_data1: return sizeof(int8_t);
4258 case DW_FORM_ref2: // Fall thru
4259 case DW_FORM_data2: return sizeof(int16_t);
4260 case DW_FORM_ref4: // Fall thru
4261 case DW_FORM_data4: return sizeof(int32_t);
4262 case DW_FORM_ref8: // Fall thru
4263 case DW_FORM_data8: return sizeof(int64_t);
4264 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4265 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4266 default: assert(0 && "DIE Value form not supported yet"); break;
4271 //===----------------------------------------------------------------------===//
4273 /// EmitValue - Emit string value.
4275 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4276 DD.getAsm()->EmitString(String);
4279 //===----------------------------------------------------------------------===//
4281 /// EmitValue - Emit label value.
4283 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4284 bool IsSmall = Form == DW_FORM_data4;
4285 DD.EmitReference(Label, false, IsSmall);
4288 /// SizeOf - Determine size of label value in bytes.
4290 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4291 if (Form == DW_FORM_data4) return 4;
4292 return DD.getTargetData()->getPointerSize();
4295 //===----------------------------------------------------------------------===//
4297 /// EmitValue - Emit label value.
4299 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4300 bool IsSmall = Form == DW_FORM_data4;
4301 DD.EmitReference(Label, false, IsSmall);
4304 /// SizeOf - Determine size of label value in bytes.
4306 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4307 if (Form == DW_FORM_data4) return 4;
4308 return DD.getTargetData()->getPointerSize();
4311 //===----------------------------------------------------------------------===//
4313 /// EmitValue - Emit delta value.
4315 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4316 bool IsSmall = Form == DW_FORM_data4;
4317 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4318 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4321 /// SizeOf - Determine size of delta value in bytes.
4323 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4324 if (Form == DW_FORM_data4) return 4;
4325 return DD.getTargetData()->getPointerSize();
4328 //===----------------------------------------------------------------------===//
4330 /// EmitValue - Emit delta value.
4332 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4333 bool IsSmall = Form == DW_FORM_data4;
4334 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4337 /// SizeOf - Determine size of delta value in bytes.
4339 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4340 if (Form == DW_FORM_data4) return 4;
4341 return DD.getTargetData()->getPointerSize();
4344 //===----------------------------------------------------------------------===//
4346 /// EmitValue - Emit debug information entry offset.
4348 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4349 DD.getAsm()->EmitInt32(Entry->getOffset());
4352 //===----------------------------------------------------------------------===//
4354 /// ComputeSize - calculate the size of the block.
4356 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4358 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4360 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4361 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4367 /// EmitValue - Emit block data.
4369 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4371 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4372 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4373 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4374 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4375 default: assert(0 && "Improper form for block"); break;
4378 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4380 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4382 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4386 /// SizeOf - Determine size of block data in bytes.
4388 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4390 case DW_FORM_block1: return Size + sizeof(int8_t);
4391 case DW_FORM_block2: return Size + sizeof(int16_t);
4392 case DW_FORM_block4: return Size + sizeof(int32_t);
4393 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4394 default: assert(0 && "Improper form for block"); break;
4399 //===----------------------------------------------------------------------===//
4400 /// DIE Implementation
4403 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4407 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4409 void DIE::AddSiblingOffset() {
4410 DIEInteger *DI = new DIEInteger(0);
4411 Values.insert(Values.begin(), DI);
4412 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4415 /// Profile - Used to gather unique data for the value folding set.
4417 void DIE::Profile(FoldingSetNodeID &ID) {
4420 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4421 ID.AddPointer(Children[i]);
4423 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4424 ID.AddPointer(Values[j]);
4428 void DIE::print(std::ostream &O, unsigned IncIndent) {
4429 static unsigned IndentCount = 0;
4430 IndentCount += IncIndent;
4431 const std::string Indent(IndentCount, ' ');
4432 bool isBlock = Abbrev.getTag() == 0;
4437 << "0x" << std::hex << (intptr_t)this << std::dec
4438 << ", Offset: " << Offset
4439 << ", Size: " << Size
4443 << TagString(Abbrev.getTag())
4445 << ChildrenString(Abbrev.getChildrenFlag());
4447 O << "Size: " << Size;
4451 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4454 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4458 O << AttributeString(Data[i].getAttribute());
4460 O << "Blk[" << i << "]";
4463 << FormEncodingString(Data[i].getForm())
4465 Values[i]->print(O);
4470 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4471 Children[j]->print(O, 4);
4474 if (!isBlock) O << "\n";
4475 IndentCount -= IncIndent;
4483 //===----------------------------------------------------------------------===//
4484 /// DwarfWriter Implementation
4487 DwarfWriter::DwarfWriter()
4488 : ImmutablePass(&ID), DD(0), DE(0) {}
4490 DwarfWriter::~DwarfWriter() {
4495 /// BeginModule - Emit all Dwarf sections that should come prior to the
4497 void DwarfWriter::BeginModule(Module *M,
4498 MachineModuleInfo *MMI,
4499 raw_ostream &OS, AsmPrinter *A,
4500 const TargetAsmInfo *T) {
4501 DE = new DwarfException(OS, A, T);
4502 DD = new DwarfDebug(OS, A, T);
4505 DD->SetDebugInfo(MMI);
4506 DE->SetModuleInfo(MMI);
4509 /// EndModule - Emit all Dwarf sections that should come after the content.
4511 void DwarfWriter::EndModule() {
4516 /// BeginFunction - Gather pre-function debug information. Assumes being
4517 /// emitted immediately after the function entry point.
4518 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4519 DE->BeginFunction(MF);
4520 DD->BeginFunction(MF);
4523 /// EndFunction - Gather and emit post-function debug information.
4525 void DwarfWriter::EndFunction(MachineFunction *MF) {
4526 DD->EndFunction(MF);
4529 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4530 // Clear function debug information.
4534 /// ValidDebugInfo - Return true if V represents valid debug info value.
4535 bool DwarfWriter::ValidDebugInfo(Value *V) {
4536 return DD && DD->ValidDebugInfo(V);
4539 /// RecordSourceLine - Records location information and associates it with a
4540 /// label. Returns a unique label ID used to generate a label and provide
4541 /// correspondence to the source line list.
4542 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4544 return DD->RecordSourceLine(Line, Col, Src);
4547 /// getOrCreateSourceID - Look up the source id with the given directory and
4548 /// source file names. If none currently exists, create a new id and insert it
4549 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
4551 unsigned DwarfWriter::getOrCreateSourceID(const std::string &DirName,
4552 const std::string &FileName) {
4553 return DD->getOrCreateSourceID(DirName, FileName);
4556 /// RecordRegionStart - Indicate the start of a region.
4557 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4558 return DD->RecordRegionStart(V);
4561 /// RecordRegionEnd - Indicate the end of a region.
4562 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4563 return DD->RecordRegionEnd(V);
4566 /// getRecordSourceLineCount - Count source lines.
4567 unsigned DwarfWriter::getRecordSourceLineCount() {
4568 return DD->getRecordSourceLineCount();
4571 /// RecordVariable - Indicate the declaration of a local variable.
4573 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4574 DD->RecordVariable(GV, FrameIndex);
4577 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4579 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4580 return DD->ShouldEmitDwarfDebug();