blob: 10f7c9918401e939de2a7d921c1907f4208f06ec [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by James M. Laskey and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/DwarfWriter.h"
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/FoldingSet.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/UniqueVector.h"
20#include "llvm/Module.h"
21#include "llvm/Type.h"
22#include "llvm/CodeGen/AsmPrinter.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineLocation.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/Dwarf.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/DataTypes.h"
30#include "llvm/Support/Mangler.h"
31#include "llvm/Target/TargetAsmInfo.h"
32#include "llvm/Target/MRegisterInfo.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 <ostream>
39#include <string>
40using namespace llvm;
41using namespace llvm::dwarf;
42
43namespace llvm {
44
45//===----------------------------------------------------------------------===//
46
47/// Configuration values for initial hash set sizes (log2).
48///
49static const unsigned InitDiesSetSize = 9; // 512
50static const unsigned InitAbbreviationsSetSize = 9; // 512
51static const unsigned InitValuesSetSize = 9; // 512
52
53//===----------------------------------------------------------------------===//
54/// Forward declarations.
55///
56class DIE;
57class DIEValue;
58
59//===----------------------------------------------------------------------===//
60/// DWLabel - Labels are used to track locations in the assembler file.
Reid Spencer37c7cea2007-08-05 20:06:04 +000061/// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
62/// where the tag is a category of label (Ex. location) and number is a value
63/// unique in that category.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064class DWLabel {
65public:
66 /// Tag - Label category tag. Should always be a staticly declared C string.
67 ///
68 const char *Tag;
69
70 /// Number - Value to make label unique.
71 ///
72 unsigned Number;
73
74 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
75
76 void Profile(FoldingSetNodeID &ID) const {
77 ID.AddString(std::string(Tag));
78 ID.AddInteger(Number);
79 }
80
81#ifndef NDEBUG
82 void print(std::ostream *O) const {
83 if (O) print(*O);
84 }
85 void print(std::ostream &O) const {
86 O << "." << Tag;
87 if (Number) O << Number;
88 }
89#endif
90};
91
92//===----------------------------------------------------------------------===//
93/// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
94/// Dwarf abbreviation.
95class DIEAbbrevData {
96private:
97 /// Attribute - Dwarf attribute code.
98 ///
99 unsigned Attribute;
100
101 /// Form - Dwarf form code.
102 ///
103 unsigned Form;
104
105public:
106 DIEAbbrevData(unsigned A, unsigned F)
107 : Attribute(A)
108 , Form(F)
109 {}
110
111 // Accessors.
112 unsigned getAttribute() const { return Attribute; }
113 unsigned getForm() const { return Form; }
114
115 /// Profile - Used to gather unique data for the abbreviation folding set.
116 ///
117 void Profile(FoldingSetNodeID &ID)const {
118 ID.AddInteger(Attribute);
119 ID.AddInteger(Form);
120 }
121};
122
123//===----------------------------------------------------------------------===//
124/// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
125/// information object.
126class DIEAbbrev : public FoldingSetNode {
127private:
128 /// Tag - Dwarf tag code.
129 ///
130 unsigned Tag;
131
132 /// Unique number for node.
133 ///
134 unsigned Number;
135
136 /// ChildrenFlag - Dwarf children flag.
137 ///
138 unsigned ChildrenFlag;
139
140 /// Data - Raw data bytes for abbreviation.
141 ///
142 std::vector<DIEAbbrevData> Data;
143
144public:
145
146 DIEAbbrev(unsigned T, unsigned C)
147 : Tag(T)
148 , ChildrenFlag(C)
149 , Data()
150 {}
151 ~DIEAbbrev() {}
152
153 // Accessors.
154 unsigned getTag() const { return Tag; }
155 unsigned getNumber() const { return Number; }
156 unsigned getChildrenFlag() const { return ChildrenFlag; }
157 const std::vector<DIEAbbrevData> &getData() const { return Data; }
158 void setTag(unsigned T) { Tag = T; }
159 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
160 void setNumber(unsigned N) { Number = N; }
161
162 /// AddAttribute - Adds another set of attribute information to the
163 /// abbreviation.
164 void AddAttribute(unsigned Attribute, unsigned Form) {
165 Data.push_back(DIEAbbrevData(Attribute, Form));
166 }
167
168 /// AddFirstAttribute - Adds a set of attribute information to the front
169 /// of the abbreviation.
170 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
171 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
172 }
173
174 /// Profile - Used to gather unique data for the abbreviation folding set.
175 ///
176 void Profile(FoldingSetNodeID &ID) {
177 ID.AddInteger(Tag);
178 ID.AddInteger(ChildrenFlag);
179
180 // For each attribute description.
181 for (unsigned i = 0, N = Data.size(); i < N; ++i)
182 Data[i].Profile(ID);
183 }
184
185 /// Emit - Print the abbreviation using the specified Dwarf writer.
186 ///
187 void Emit(const DwarfDebug &DD) const;
188
189#ifndef NDEBUG
190 void print(std::ostream *O) {
191 if (O) print(*O);
192 }
193 void print(std::ostream &O);
194 void dump();
195#endif
196};
197
198//===----------------------------------------------------------------------===//
199/// DIE - A structured debug information entry. Has an abbreviation which
200/// describes it's organization.
201class DIE : public FoldingSetNode {
202protected:
203 /// Abbrev - Buffer for constructing abbreviation.
204 ///
205 DIEAbbrev Abbrev;
206
207 /// Offset - Offset in debug info section.
208 ///
209 unsigned Offset;
210
211 /// Size - Size of instance + children.
212 ///
213 unsigned Size;
214
215 /// Children DIEs.
216 ///
217 std::vector<DIE *> Children;
218
219 /// Attributes values.
220 ///
221 std::vector<DIEValue *> Values;
222
223public:
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000224 explicit DIE(unsigned Tag)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 : Abbrev(Tag, DW_CHILDREN_no)
226 , Offset(0)
227 , Size(0)
228 , Children()
229 , Values()
230 {}
231 virtual ~DIE();
232
233 // Accessors.
234 DIEAbbrev &getAbbrev() { return Abbrev; }
235 unsigned getAbbrevNumber() const {
236 return Abbrev.getNumber();
237 }
238 unsigned getTag() const { return Abbrev.getTag(); }
239 unsigned getOffset() const { return Offset; }
240 unsigned getSize() const { return Size; }
241 const std::vector<DIE *> &getChildren() const { return Children; }
242 std::vector<DIEValue *> &getValues() { return Values; }
243 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
244 void setOffset(unsigned O) { Offset = O; }
245 void setSize(unsigned S) { Size = S; }
246
247 /// AddValue - Add a value and attributes to a DIE.
248 ///
249 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
250 Abbrev.AddAttribute(Attribute, Form);
251 Values.push_back(Value);
252 }
253
254 /// SiblingOffset - Return the offset of the debug information entry's
255 /// sibling.
256 unsigned SiblingOffset() const { return Offset + Size; }
257
258 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
259 ///
260 void AddSiblingOffset();
261
262 /// AddChild - Add a child to the DIE.
263 ///
264 void AddChild(DIE *Child) {
265 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
266 Children.push_back(Child);
267 }
268
269 /// Detach - Detaches objects connected to it after copying.
270 ///
271 void Detach() {
272 Children.clear();
273 }
274
275 /// Profile - Used to gather unique data for the value folding set.
276 ///
277 void Profile(FoldingSetNodeID &ID) ;
278
279#ifndef NDEBUG
280 void print(std::ostream *O, unsigned IncIndent = 0) {
281 if (O) print(*O, IncIndent);
282 }
283 void print(std::ostream &O, unsigned IncIndent = 0);
284 void dump();
285#endif
286};
287
288//===----------------------------------------------------------------------===//
289/// DIEValue - A debug information entry value.
290///
291class DIEValue : public FoldingSetNode {
292public:
293 enum {
294 isInteger,
295 isString,
296 isLabel,
297 isAsIsLabel,
298 isDelta,
299 isEntry,
300 isBlock
301 };
302
303 /// Type - Type of data stored in the value.
304 ///
305 unsigned Type;
306
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000307 explicit DIEValue(unsigned T)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 : Type(T)
309 {}
310 virtual ~DIEValue() {}
311
312 // Accessors
313 unsigned getType() const { return Type; }
314
315 // Implement isa/cast/dyncast.
316 static bool classof(const DIEValue *) { return true; }
317
318 /// EmitValue - Emit value via the Dwarf writer.
319 ///
320 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
321
322 /// SizeOf - Return the size of a value in bytes.
323 ///
324 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
325
326 /// Profile - Used to gather unique data for the value folding set.
327 ///
328 virtual void Profile(FoldingSetNodeID &ID) = 0;
329
330#ifndef NDEBUG
331 void print(std::ostream *O) {
332 if (O) print(*O);
333 }
334 virtual void print(std::ostream &O) = 0;
335 void dump();
336#endif
337};
338
339//===----------------------------------------------------------------------===//
340/// DWInteger - An integer value DIE.
341///
342class DIEInteger : public DIEValue {
343private:
344 uint64_t Integer;
345
346public:
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000347 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348
349 // Implement isa/cast/dyncast.
350 static bool classof(const DIEInteger *) { return true; }
351 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
352
353 /// BestForm - Choose the best form for integer.
354 ///
355 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
356 if (IsSigned) {
357 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
358 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
359 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
360 } else {
361 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
362 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
363 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
364 }
365 return DW_FORM_data8;
366 }
367
368 /// EmitValue - Emit integer of appropriate size.
369 ///
370 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
371
372 /// SizeOf - Determine size of integer value in bytes.
373 ///
374 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
375
376 /// Profile - Used to gather unique data for the value folding set.
377 ///
378 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
379 ID.AddInteger(isInteger);
380 ID.AddInteger(Integer);
381 }
382 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
383
384#ifndef NDEBUG
385 virtual void print(std::ostream &O) {
386 O << "Int: " << (int64_t)Integer
387 << " 0x" << std::hex << Integer << std::dec;
388 }
389#endif
390};
391
392//===----------------------------------------------------------------------===//
393/// DIEString - A string value DIE.
394///
395class DIEString : public DIEValue {
396public:
397 const std::string String;
398
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000399 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400
401 // Implement isa/cast/dyncast.
402 static bool classof(const DIEString *) { return true; }
403 static bool classof(const DIEValue *S) { return S->Type == isString; }
404
405 /// EmitValue - Emit string value.
406 ///
407 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
408
409 /// SizeOf - Determine size of string value in bytes.
410 ///
411 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
412 return String.size() + sizeof(char); // sizeof('\0');
413 }
414
415 /// Profile - Used to gather unique data for the value folding set.
416 ///
417 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
418 ID.AddInteger(isString);
419 ID.AddString(String);
420 }
421 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
422
423#ifndef NDEBUG
424 virtual void print(std::ostream &O) {
425 O << "Str: \"" << String << "\"";
426 }
427#endif
428};
429
430//===----------------------------------------------------------------------===//
431/// DIEDwarfLabel - A Dwarf internal label expression DIE.
432//
433class DIEDwarfLabel : public DIEValue {
434public:
435
436 const DWLabel Label;
437
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000438 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439
440 // Implement isa/cast/dyncast.
441 static bool classof(const DIEDwarfLabel *) { return true; }
442 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
443
444 /// EmitValue - Emit label value.
445 ///
446 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
447
448 /// SizeOf - Determine size of label value in bytes.
449 ///
450 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
451
452 /// Profile - Used to gather unique data for the value folding set.
453 ///
454 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
455 ID.AddInteger(isLabel);
456 Label.Profile(ID);
457 }
458 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
459
460#ifndef NDEBUG
461 virtual void print(std::ostream &O) {
462 O << "Lbl: ";
463 Label.print(O);
464 }
465#endif
466};
467
468
469//===----------------------------------------------------------------------===//
470/// DIEObjectLabel - A label to an object in code or data.
471//
472class DIEObjectLabel : public DIEValue {
473public:
474 const std::string Label;
475
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000476 explicit DIEObjectLabel(const std::string &L)
477 : DIEValue(isAsIsLabel), Label(L) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478
479 // Implement isa/cast/dyncast.
480 static bool classof(const DIEObjectLabel *) { return true; }
481 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
482
483 /// EmitValue - Emit label value.
484 ///
485 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
486
487 /// SizeOf - Determine size of label value in bytes.
488 ///
489 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
490
491 /// Profile - Used to gather unique data for the value folding set.
492 ///
493 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
494 ID.AddInteger(isAsIsLabel);
495 ID.AddString(Label);
496 }
497 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
498
499#ifndef NDEBUG
500 virtual void print(std::ostream &O) {
501 O << "Obj: " << Label;
502 }
503#endif
504};
505
506//===----------------------------------------------------------------------===//
507/// DIEDelta - A simple label difference DIE.
508///
509class DIEDelta : public DIEValue {
510public:
511 const DWLabel LabelHi;
512 const DWLabel LabelLo;
513
514 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
515 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
516
517 // Implement isa/cast/dyncast.
518 static bool classof(const DIEDelta *) { return true; }
519 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
520
521 /// EmitValue - Emit delta value.
522 ///
523 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
524
525 /// SizeOf - Determine size of delta value in bytes.
526 ///
527 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
528
529 /// Profile - Used to gather unique data for the value folding set.
530 ///
531 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
532 const DWLabel &LabelLo) {
533 ID.AddInteger(isDelta);
534 LabelHi.Profile(ID);
535 LabelLo.Profile(ID);
536 }
537 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
538
539#ifndef NDEBUG
540 virtual void print(std::ostream &O) {
541 O << "Del: ";
542 LabelHi.print(O);
543 O << "-";
544 LabelLo.print(O);
545 }
546#endif
547};
548
549//===----------------------------------------------------------------------===//
550/// DIEntry - A pointer to another debug information entry. An instance of this
551/// class can also be used as a proxy for a debug information entry not yet
552/// defined (ie. types.)
553class DIEntry : public DIEValue {
554public:
555 DIE *Entry;
556
Dan Gohman9ba5d4d2007-08-27 14:50:10 +0000557 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558
559 // Implement isa/cast/dyncast.
560 static bool classof(const DIEntry *) { return true; }
561 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
562
563 /// EmitValue - Emit debug information entry offset.
564 ///
565 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
566
567 /// SizeOf - Determine size of debug information entry in bytes.
568 ///
569 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
570 return sizeof(int32_t);
571 }
572
573 /// Profile - Used to gather unique data for the value folding set.
574 ///
575 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
576 ID.AddInteger(isEntry);
577 ID.AddPointer(Entry);
578 }
579 virtual void Profile(FoldingSetNodeID &ID) {
580 ID.AddInteger(isEntry);
581
582 if (Entry) {
583 ID.AddPointer(Entry);
584 } else {
585 ID.AddPointer(this);
586 }
587 }
588
589#ifndef NDEBUG
590 virtual void print(std::ostream &O) {
591 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
592 }
593#endif
594};
595
596//===----------------------------------------------------------------------===//
597/// DIEBlock - A block of values. Primarily used for location expressions.
598//
599class DIEBlock : public DIEValue, public DIE {
600public:
601 unsigned Size; // Size in bytes excluding size header.
602
603 DIEBlock()
604 : DIEValue(isBlock)
605 , DIE(0)
606 , Size(0)
607 {}
608 ~DIEBlock() {
609 }
610
611 // Implement isa/cast/dyncast.
612 static bool classof(const DIEBlock *) { return true; }
613 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
614
615 /// ComputeSize - calculate the size of the block.
616 ///
617 unsigned ComputeSize(DwarfDebug &DD);
618
619 /// BestForm - Choose the best form for data.
620 ///
621 unsigned BestForm() const {
622 if ((unsigned char)Size == Size) return DW_FORM_block1;
623 if ((unsigned short)Size == Size) return DW_FORM_block2;
624 if ((unsigned int)Size == Size) return DW_FORM_block4;
625 return DW_FORM_block;
626 }
627
628 /// EmitValue - Emit block data.
629 ///
630 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
631
632 /// SizeOf - Determine size of block data in bytes.
633 ///
634 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
635
636
637 /// Profile - Used to gather unique data for the value folding set.
638 ///
639 virtual void Profile(FoldingSetNodeID &ID) {
640 ID.AddInteger(isBlock);
641 DIE::Profile(ID);
642 }
643
644#ifndef NDEBUG
645 virtual void print(std::ostream &O) {
646 O << "Blk: ";
647 DIE::print(O, 5);
648 }
649#endif
650};
651
652//===----------------------------------------------------------------------===//
653/// CompileUnit - This dwarf writer support class manages information associate
654/// with a source file.
655class CompileUnit {
656private:
657 /// Desc - Compile unit debug descriptor.
658 ///
659 CompileUnitDesc *Desc;
660
661 /// ID - File identifier for source.
662 ///
663 unsigned ID;
664
665 /// Die - Compile unit debug information entry.
666 ///
667 DIE *Die;
668
669 /// DescToDieMap - Tracks the mapping of unit level debug informaton
670 /// descriptors to debug information entries.
671 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
672
673 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
674 /// descriptors to debug information entries using a DIEntry proxy.
675 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
676
677 /// Globals - A map of globally visible named entities for this unit.
678 ///
679 std::map<std::string, DIE *> Globals;
680
681 /// DiesSet - Used to uniquely define dies within the compile unit.
682 ///
683 FoldingSet<DIE> DiesSet;
684
685 /// Dies - List of all dies in the compile unit.
686 ///
687 std::vector<DIE *> Dies;
688
689public:
690 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
691 : Desc(CUD)
692 , ID(I)
693 , Die(D)
694 , DescToDieMap()
695 , DescToDIEntryMap()
696 , Globals()
697 , DiesSet(InitDiesSetSize)
698 , Dies()
699 {}
700
701 ~CompileUnit() {
702 delete Die;
703
704 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
705 delete Dies[i];
706 }
707
708 // Accessors.
709 CompileUnitDesc *getDesc() const { return Desc; }
710 unsigned getID() const { return ID; }
711 DIE* getDie() const { return Die; }
712 std::map<std::string, DIE *> &getGlobals() { return Globals; }
713
714 /// hasContent - Return true if this compile unit has something to write out.
715 ///
716 bool hasContent() const {
717 return !Die->getChildren().empty();
718 }
719
720 /// AddGlobal - Add a new global entity to the compile unit.
721 ///
722 void AddGlobal(const std::string &Name, DIE *Die) {
723 Globals[Name] = Die;
724 }
725
726 /// getDieMapSlotFor - Returns the debug information entry map slot for the
727 /// specified debug descriptor.
728 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
729 return DescToDieMap[DID];
730 }
731
732 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
733 /// specified debug descriptor.
734 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
735 return DescToDIEntryMap[DID];
736 }
737
738 /// AddDie - Adds or interns the DIE to the compile unit.
739 ///
740 DIE *AddDie(DIE &Buffer) {
741 FoldingSetNodeID ID;
742 Buffer.Profile(ID);
743 void *Where;
744 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
745
746 if (!Die) {
747 Die = new DIE(Buffer);
748 DiesSet.InsertNode(Die, Where);
749 this->Die->AddChild(Die);
750 Buffer.Detach();
751 }
752
753 return Die;
754 }
755};
756
757//===----------------------------------------------------------------------===//
758/// Dwarf - Emits general Dwarf directives.
759///
760class Dwarf {
761
762protected:
763
764 //===--------------------------------------------------------------------===//
765 // Core attributes used by the Dwarf writer.
766 //
767
768 //
769 /// O - Stream to .s file.
770 ///
771 std::ostream &O;
772
773 /// Asm - Target of Dwarf emission.
774 ///
775 AsmPrinter *Asm;
776
777 /// TAI - Target Asm Printer.
778 const TargetAsmInfo *TAI;
779
780 /// TD - Target data.
781 const TargetData *TD;
782
783 /// RI - Register Information.
784 const MRegisterInfo *RI;
785
786 /// M - Current module.
787 ///
788 Module *M;
789
790 /// MF - Current machine function.
791 ///
792 MachineFunction *MF;
793
794 /// MMI - Collected machine module information.
795 ///
796 MachineModuleInfo *MMI;
797
798 /// SubprogramCount - The running count of functions being compiled.
799 ///
800 unsigned SubprogramCount;
801
802 unsigned SetCounter;
803 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
804 : O(OS)
805 , Asm(A)
806 , TAI(T)
807 , TD(Asm->TM.getTargetData())
808 , RI(Asm->TM.getRegisterInfo())
809 , M(NULL)
810 , MF(NULL)
811 , MMI(NULL)
812 , SubprogramCount(0)
813 , SetCounter(1)
814 {
815 }
816
817public:
818
819 //===--------------------------------------------------------------------===//
820 // Accessors.
821 //
822 AsmPrinter *getAsm() const { return Asm; }
823 MachineModuleInfo *getMMI() const { return MMI; }
824 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
825
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000826 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
827 const {
828 if (isInSection && TAI->getDwarfSectionOffsetDirective())
829 O << TAI->getDwarfSectionOffsetDirective();
830 else if (Force32Bit || TAI->getAddressSize() == sizeof(int32_t))
831 O << TAI->getData32bitsDirective();
832 else
833 O << TAI->getData64bitsDirective();
834 }
835
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 /// PrintLabelName - Print label name in form used by Dwarf writer.
837 ///
838 void PrintLabelName(DWLabel Label) const {
839 PrintLabelName(Label.Tag, Label.Number);
840 }
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000841 void PrintLabelName(const char *Tag, unsigned Number) const {
842
843 O << TAI->getPrivateGlobalPrefix() << Tag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 if (Number) O << Number;
845 }
846
847 /// EmitLabel - Emit location label for internal use by Dwarf.
848 ///
849 void EmitLabel(DWLabel Label) const {
850 EmitLabel(Label.Tag, Label.Number);
851 }
852 void EmitLabel(const char *Tag, unsigned Number) const {
853 PrintLabelName(Tag, Number);
854 O << ":\n";
855 }
856
857 /// EmitReference - Emit a reference to a label.
858 ///
859 void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
860 EmitReference(Label.Tag, Label.Number, IsPCRelative);
861 }
862 void EmitReference(const char *Tag, unsigned Number,
863 bool IsPCRelative = false) const {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000864 PrintRelDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 PrintLabelName(Tag, Number);
866
867 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
868 }
869 void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000870 PrintRelDirective();
871
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 O << Name;
873
874 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
875 }
876
877 /// EmitDifference - Emit the difference between two labels. Some
878 /// assemblers do not behave with absolute expressions with data directives,
879 /// so there is an option (needsSet) to use an intermediary set expression.
880 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
881 bool IsSmall = false) {
882 EmitDifference(LabelHi.Tag, LabelHi.Number,
883 LabelLo.Tag, LabelLo.Number,
884 IsSmall);
885 }
886 void EmitDifference(const char *TagHi, unsigned NumberHi,
887 const char *TagLo, unsigned NumberLo,
888 bool IsSmall = false) {
889 if (TAI->needsSet()) {
890 O << "\t.set\t";
891 PrintLabelName("set", SetCounter);
892 O << ",";
893 PrintLabelName(TagHi, NumberHi);
894 O << "-";
895 PrintLabelName(TagLo, NumberLo);
896 O << "\n";
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000897
898 PrintRelDirective(IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899
900 PrintLabelName("set", SetCounter);
901
902 ++SetCounter;
903 } else {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000904 PrintRelDirective(IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905
906 PrintLabelName(TagHi, NumberHi);
907 O << "-";
908 PrintLabelName(TagLo, NumberLo);
909 }
910 }
911
912 void EmitSectionOffset(const char* Label, const char* Section,
913 unsigned LabelNumber, unsigned SectionNumber,
914 bool IsSmall = false, bool isEH = false) {
915 bool printAbsolute = false;
916 if (TAI->needsSet()) {
917 O << "\t.set\t";
918 PrintLabelName("set", SetCounter);
919 O << ",";
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000920 PrintLabelName(Label, LabelNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921
922 if (isEH)
923 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
924 else
925 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
926
927 if (!printAbsolute) {
928 O << "-";
929 PrintLabelName(Section, SectionNumber);
930 }
931 O << "\n";
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000932
933 PrintRelDirective(IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 PrintLabelName("set", SetCounter);
936 ++SetCounter;
937 } else {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000938 PrintRelDirective(IsSmall, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000940 PrintLabelName(Label, LabelNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941
942 if (isEH)
943 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
944 else
945 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
946
947 if (!printAbsolute) {
948 O << "-";
949 PrintLabelName(Section, SectionNumber);
950 }
951 }
952 }
953
954 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
955 /// frame.
956 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
957 const std::vector<MachineMove> &Moves) {
958 int stackGrowth =
959 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
960 TargetFrameInfo::StackGrowsUp ?
961 TAI->getAddressSize() : -TAI->getAddressSize();
962 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
963
964 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
965 const MachineMove &Move = Moves[i];
966 unsigned LabelID = Move.getLabelID();
967
968 if (LabelID) {
969 LabelID = MMI->MappedLabel(LabelID);
970
971 // Throw out move if the label is invalid.
972 if (!LabelID) continue;
973 }
974
975 const MachineLocation &Dst = Move.getDestination();
976 const MachineLocation &Src = Move.getSource();
977
978 // Advance row if new location.
979 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
980 Asm->EmitInt8(DW_CFA_advance_loc4);
981 Asm->EOL("DW_CFA_advance_loc4");
982 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
983 Asm->EOL();
984
985 BaseLabelID = LabelID;
986 BaseLabel = "label";
987 IsLocal = true;
988 }
989
990 // If advancing cfa.
991 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
992 if (!Src.isRegister()) {
993 if (Src.getRegister() == MachineLocation::VirtualFP) {
994 Asm->EmitInt8(DW_CFA_def_cfa_offset);
995 Asm->EOL("DW_CFA_def_cfa_offset");
996 } else {
997 Asm->EmitInt8(DW_CFA_def_cfa);
998 Asm->EOL("DW_CFA_def_cfa");
999 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
1000 Asm->EOL("Register");
1001 }
1002
1003 int Offset = -Src.getOffset();
1004
1005 Asm->EmitULEB128Bytes(Offset);
1006 Asm->EOL("Offset");
1007 } else {
1008 assert(0 && "Machine move no supported yet.");
1009 }
1010 } else if (Src.isRegister() &&
1011 Src.getRegister() == MachineLocation::VirtualFP) {
1012 if (Dst.isRegister()) {
1013 Asm->EmitInt8(DW_CFA_def_cfa_register);
1014 Asm->EOL("DW_CFA_def_cfa_register");
1015 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1016 Asm->EOL("Register");
1017 } else {
1018 assert(0 && "Machine move no supported yet.");
1019 }
1020 } else {
1021 unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1022 int Offset = Dst.getOffset() / stackGrowth;
1023
1024 if (Offset < 0) {
1025 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1026 Asm->EOL("DW_CFA_offset_extended_sf");
1027 Asm->EmitULEB128Bytes(Reg);
1028 Asm->EOL("Reg");
1029 Asm->EmitSLEB128Bytes(Offset);
1030 Asm->EOL("Offset");
1031 } else if (Reg < 64) {
1032 Asm->EmitInt8(DW_CFA_offset + Reg);
Anton Korobeynikovc6449f12007-07-25 00:06:28 +00001033 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 Asm->EmitULEB128Bytes(Offset);
1035 Asm->EOL("Offset");
1036 } else {
1037 Asm->EmitInt8(DW_CFA_offset_extended);
1038 Asm->EOL("DW_CFA_offset_extended");
1039 Asm->EmitULEB128Bytes(Reg);
1040 Asm->EOL("Reg");
1041 Asm->EmitULEB128Bytes(Offset);
1042 Asm->EOL("Offset");
1043 }
1044 }
1045 }
1046 }
1047
1048};
1049
1050//===----------------------------------------------------------------------===//
1051/// DwarfDebug - Emits Dwarf debug directives.
1052///
1053class DwarfDebug : public Dwarf {
1054
1055private:
1056 //===--------------------------------------------------------------------===//
1057 // Attributes used to construct specific Dwarf sections.
1058 //
1059
1060 /// CompileUnits - All the compile units involved in this build. The index
1061 /// of each entry in this vector corresponds to the sources in MMI.
1062 std::vector<CompileUnit *> CompileUnits;
1063
1064 /// AbbreviationsSet - Used to uniquely define abbreviations.
1065 ///
1066 FoldingSet<DIEAbbrev> AbbreviationsSet;
1067
1068 /// Abbreviations - A list of all the unique abbreviations in use.
1069 ///
1070 std::vector<DIEAbbrev *> Abbreviations;
1071
1072 /// ValuesSet - Used to uniquely define values.
1073 ///
1074 FoldingSet<DIEValue> ValuesSet;
1075
1076 /// Values - A list of all the unique values in use.
1077 ///
1078 std::vector<DIEValue *> Values;
1079
1080 /// StringPool - A UniqueVector of strings used by indirect references.
1081 ///
1082 UniqueVector<std::string> StringPool;
1083
1084 /// UnitMap - Map debug information descriptor to compile unit.
1085 ///
1086 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1087
1088 /// SectionMap - Provides a unique id per text section.
1089 ///
1090 UniqueVector<std::string> SectionMap;
1091
1092 /// SectionSourceLines - Tracks line numbers per text section.
1093 ///
1094 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1095
1096 /// didInitial - Flag to indicate if initial emission has been done.
1097 ///
1098 bool didInitial;
1099
1100 /// shouldEmit - Flag to indicate if debug information should be emitted.
1101 ///
1102 bool shouldEmit;
1103
1104 struct FunctionDebugFrameInfo {
1105 unsigned Number;
1106 std::vector<MachineMove> Moves;
1107
1108 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
Dan Gohman9ba5d4d2007-08-27 14:50:10 +00001109 Number(Num), Moves(M) { }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 };
1111
1112 std::vector<FunctionDebugFrameInfo> DebugFrames;
1113
1114public:
1115
1116 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1117 ///
1118 bool ShouldEmitDwarf() const { return shouldEmit; }
1119
1120 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1121 ///
1122 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1123 // Profile the node so that we can make it unique.
1124 FoldingSetNodeID ID;
1125 Abbrev.Profile(ID);
1126
1127 // Check the set for priors.
1128 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1129
1130 // If it's newly added.
1131 if (InSet == &Abbrev) {
1132 // Add to abbreviation list.
1133 Abbreviations.push_back(&Abbrev);
1134 // Assign the vector position + 1 as its number.
1135 Abbrev.setNumber(Abbreviations.size());
1136 } else {
1137 // Assign existing abbreviation number.
1138 Abbrev.setNumber(InSet->getNumber());
1139 }
1140 }
1141
1142 /// NewString - Add a string to the constant pool and returns a label.
1143 ///
1144 DWLabel NewString(const std::string &String) {
1145 unsigned StringID = StringPool.insert(String);
1146 return DWLabel("string", StringID);
1147 }
1148
1149 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1150 /// entry.
1151 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1152 DIEntry *Value;
1153
1154 if (Entry) {
1155 FoldingSetNodeID ID;
1156 DIEntry::Profile(ID, Entry);
1157 void *Where;
1158 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1159
1160 if (Value) return Value;
1161
1162 Value = new DIEntry(Entry);
1163 ValuesSet.InsertNode(Value, Where);
1164 } else {
1165 Value = new DIEntry(Entry);
1166 }
1167
1168 Values.push_back(Value);
1169 return Value;
1170 }
1171
1172 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1173 ///
1174 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1175 Value->Entry = Entry;
1176 // Add to values set if not already there. If it is, we merely have a
1177 // duplicate in the values list (no harm.)
1178 ValuesSet.GetOrInsertNode(Value);
1179 }
1180
1181 /// AddUInt - Add an unsigned integer attribute data and value.
1182 ///
1183 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1184 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1185
1186 FoldingSetNodeID ID;
1187 DIEInteger::Profile(ID, Integer);
1188 void *Where;
1189 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1190 if (!Value) {
1191 Value = new DIEInteger(Integer);
1192 ValuesSet.InsertNode(Value, Where);
1193 Values.push_back(Value);
1194 }
1195
1196 Die->AddValue(Attribute, Form, Value);
1197 }
1198
1199 /// AddSInt - Add an signed integer attribute data and value.
1200 ///
1201 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1202 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1203
1204 FoldingSetNodeID ID;
1205 DIEInteger::Profile(ID, (uint64_t)Integer);
1206 void *Where;
1207 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1208 if (!Value) {
1209 Value = new DIEInteger(Integer);
1210 ValuesSet.InsertNode(Value, Where);
1211 Values.push_back(Value);
1212 }
1213
1214 Die->AddValue(Attribute, Form, Value);
1215 }
1216
1217 /// AddString - Add a std::string attribute data and value.
1218 ///
1219 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1220 const std::string &String) {
1221 FoldingSetNodeID ID;
1222 DIEString::Profile(ID, String);
1223 void *Where;
1224 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1225 if (!Value) {
1226 Value = new DIEString(String);
1227 ValuesSet.InsertNode(Value, Where);
1228 Values.push_back(Value);
1229 }
1230
1231 Die->AddValue(Attribute, Form, Value);
1232 }
1233
1234 /// AddLabel - Add a Dwarf label attribute data and value.
1235 ///
1236 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1237 const DWLabel &Label) {
1238 FoldingSetNodeID ID;
1239 DIEDwarfLabel::Profile(ID, Label);
1240 void *Where;
1241 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1242 if (!Value) {
1243 Value = new DIEDwarfLabel(Label);
1244 ValuesSet.InsertNode(Value, Where);
1245 Values.push_back(Value);
1246 }
1247
1248 Die->AddValue(Attribute, Form, Value);
1249 }
1250
1251 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1252 ///
1253 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1254 const std::string &Label) {
1255 FoldingSetNodeID ID;
1256 DIEObjectLabel::Profile(ID, Label);
1257 void *Where;
1258 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1259 if (!Value) {
1260 Value = new DIEObjectLabel(Label);
1261 ValuesSet.InsertNode(Value, Where);
1262 Values.push_back(Value);
1263 }
1264
1265 Die->AddValue(Attribute, Form, Value);
1266 }
1267
1268 /// AddDelta - Add a label delta attribute data and value.
1269 ///
1270 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1271 const DWLabel &Hi, const DWLabel &Lo) {
1272 FoldingSetNodeID ID;
1273 DIEDelta::Profile(ID, Hi, Lo);
1274 void *Where;
1275 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1276 if (!Value) {
1277 Value = new DIEDelta(Hi, Lo);
1278 ValuesSet.InsertNode(Value, Where);
1279 Values.push_back(Value);
1280 }
1281
1282 Die->AddValue(Attribute, Form, Value);
1283 }
1284
1285 /// AddDIEntry - Add a DIE attribute data and value.
1286 ///
1287 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1288 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1289 }
1290
1291 /// AddBlock - Add block data.
1292 ///
1293 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1294 Block->ComputeSize(*this);
1295 FoldingSetNodeID ID;
1296 Block->Profile(ID);
1297 void *Where;
1298 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1299 if (!Value) {
1300 Value = Block;
1301 ValuesSet.InsertNode(Value, Where);
1302 Values.push_back(Value);
1303 } else {
1304 delete Block;
1305 }
1306
1307 Die->AddValue(Attribute, Block->BestForm(), Value);
1308 }
1309
1310private:
1311
1312 /// AddSourceLine - Add location information to specified debug information
1313 /// entry.
1314 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1315 if (File && Line) {
1316 CompileUnit *FileUnit = FindCompileUnit(File);
1317 unsigned FileID = FileUnit->getID();
1318 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1319 AddUInt(Die, DW_AT_decl_line, 0, Line);
1320 }
1321 }
1322
1323 /// AddAddress - Add an address attribute to a die based on the location
1324 /// provided.
1325 void AddAddress(DIE *Die, unsigned Attribute,
1326 const MachineLocation &Location) {
1327 unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1328 DIEBlock *Block = new DIEBlock();
1329
1330 if (Location.isRegister()) {
1331 if (Reg < 32) {
1332 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1333 } else {
1334 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1335 AddUInt(Block, 0, DW_FORM_udata, Reg);
1336 }
1337 } else {
1338 if (Reg < 32) {
1339 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1340 } else {
1341 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1342 AddUInt(Block, 0, DW_FORM_udata, Reg);
1343 }
1344 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1345 }
1346
1347 AddBlock(Die, Attribute, 0, Block);
1348 }
1349
1350 /// AddBasicType - Add a new basic type attribute to the specified entity.
1351 ///
1352 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1353 const std::string &Name,
1354 unsigned Encoding, unsigned Size) {
1355 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1356 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1357 }
1358
1359 /// ConstructBasicType - Construct a new basic type.
1360 ///
1361 DIE *ConstructBasicType(CompileUnit *Unit,
1362 const std::string &Name,
1363 unsigned Encoding, unsigned Size) {
1364 DIE Buffer(DW_TAG_base_type);
1365 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1366 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1367 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1368 return Unit->AddDie(Buffer);
1369 }
1370
1371 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1372 ///
1373 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1374 DIE *Die = ConstructPointerType(Unit, Name);
1375 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1376 }
1377
1378 /// ConstructPointerType - Construct a new pointer type.
1379 ///
1380 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1381 DIE Buffer(DW_TAG_pointer_type);
1382 AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1383 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1384 return Unit->AddDie(Buffer);
1385 }
1386
1387 /// AddType - Add a new type attribute to the specified entity.
1388 ///
1389 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1390 if (!TyDesc) {
1391 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1392 } else {
1393 // Check for pre-existence.
1394 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1395
1396 // If it exists then use the existing value.
1397 if (Slot) {
1398 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1399 return;
1400 }
1401
1402 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1403 // FIXME - Not sure why programs and variables are coming through here.
1404 // Short cut for handling subprogram types (not really a TyDesc.)
1405 AddPointerType(Entity, Unit, SubprogramTy->getName());
1406 } else if (GlobalVariableDesc *GlobalTy =
1407 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1408 // FIXME - Not sure why programs and variables are coming through here.
1409 // Short cut for handling global variable types (not really a TyDesc.)
1410 AddPointerType(Entity, Unit, GlobalTy->getName());
1411 } else {
1412 // Set up proxy.
1413 Slot = NewDIEntry();
1414
1415 // Construct type.
1416 DIE Buffer(DW_TAG_base_type);
1417 ConstructType(Buffer, TyDesc, Unit);
1418
1419 // Add debug information entry to entity and unit.
1420 DIE *Die = Unit->AddDie(Buffer);
1421 SetDIEntry(Slot, Die);
1422 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1423 }
1424 }
1425 }
1426
1427 /// ConstructType - Adds all the required attributes to the type.
1428 ///
1429 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1430 // Get core information.
1431 const std::string &Name = TyDesc->getName();
1432 uint64_t Size = TyDesc->getSize() >> 3;
1433
1434 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1435 // Fundamental types like int, float, bool
1436 Buffer.setTag(DW_TAG_base_type);
1437 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1438 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1439 // Fetch tag.
1440 unsigned Tag = DerivedTy->getTag();
1441 // FIXME - Workaround for templates.
1442 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1443 // Pointers, typedefs et al.
1444 Buffer.setTag(Tag);
1445 // Map to main type, void will not have a type.
1446 if (TypeDesc *FromTy = DerivedTy->getFromType())
1447 AddType(&Buffer, FromTy, Unit);
1448 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1449 // Fetch tag.
1450 unsigned Tag = CompTy->getTag();
1451
1452 // Set tag accordingly.
1453 if (Tag == DW_TAG_vector_type)
1454 Buffer.setTag(DW_TAG_array_type);
1455 else
1456 Buffer.setTag(Tag);
1457
1458 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1459
1460 switch (Tag) {
1461 case DW_TAG_vector_type:
1462 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1463 // Fall thru
1464 case DW_TAG_array_type: {
1465 // Add element type.
1466 if (TypeDesc *FromTy = CompTy->getFromType())
1467 AddType(&Buffer, FromTy, Unit);
1468
1469 // Don't emit size attribute.
1470 Size = 0;
1471
1472 // Construct an anonymous type for index type.
1473 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1474 sizeof(int32_t));
1475
1476 // Add subranges to array type.
1477 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1478 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1479 int64_t Lo = SRD->getLo();
1480 int64_t Hi = SRD->getHi();
1481 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1482
1483 // If a range is available.
1484 if (Lo != Hi) {
1485 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1486 // Only add low if non-zero.
1487 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1488 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1489 }
1490
1491 Buffer.AddChild(Subrange);
1492 }
1493 break;
1494 }
1495 case DW_TAG_structure_type:
1496 case DW_TAG_union_type: {
1497 // Add elements to structure type.
1498 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1499 DebugInfoDesc *Element = Elements[i];
1500
1501 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1502 // Add field or base class.
1503
1504 unsigned Tag = MemberDesc->getTag();
1505
1506 // Extract the basic information.
1507 const std::string &Name = MemberDesc->getName();
1508 uint64_t Size = MemberDesc->getSize();
1509 uint64_t Align = MemberDesc->getAlign();
1510 uint64_t Offset = MemberDesc->getOffset();
1511
1512 // Construct member debug information entry.
1513 DIE *Member = new DIE(Tag);
1514
1515 // Add name if not "".
1516 if (!Name.empty())
1517 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1518 // Add location if available.
1519 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1520
1521 // Most of the time the field info is the same as the members.
1522 uint64_t FieldSize = Size;
1523 uint64_t FieldAlign = Align;
1524 uint64_t FieldOffset = Offset;
1525
1526 // Set the member type.
1527 TypeDesc *FromTy = MemberDesc->getFromType();
1528 AddType(Member, FromTy, Unit);
1529
1530 // Walk up typedefs until a real size is found.
1531 while (FromTy) {
1532 if (FromTy->getTag() != DW_TAG_typedef) {
1533 FieldSize = FromTy->getSize();
1534 FieldAlign = FromTy->getSize();
1535 break;
1536 }
1537
Dan Gohman53491e92007-07-23 20:24:29 +00001538 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001539 }
1540
1541 // Unless we have a bit field.
1542 if (Tag == DW_TAG_member && FieldSize != Size) {
1543 // Construct the alignment mask.
1544 uint64_t AlignMask = ~(FieldAlign - 1);
1545 // Determine the high bit + 1 of the declared size.
1546 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1547 // Work backwards to determine the base offset of the field.
1548 FieldOffset = HiMark - FieldSize;
1549 // Now normalize offset to the field.
1550 Offset -= FieldOffset;
1551
1552 // Maybe we need to work from the other end.
1553 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1554
1555 // Add size and offset.
1556 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1557 AddUInt(Member, DW_AT_bit_size, 0, Size);
1558 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1559 }
1560
1561 // Add computation for offset.
1562 DIEBlock *Block = new DIEBlock();
1563 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1564 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1565 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1566
1567 // Add accessibility (public default unless is base class.
1568 if (MemberDesc->isProtected()) {
1569 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1570 } else if (MemberDesc->isPrivate()) {
1571 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1572 } else if (Tag == DW_TAG_inheritance) {
1573 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1574 }
1575
1576 Buffer.AddChild(Member);
1577 } else if (GlobalVariableDesc *StaticDesc =
1578 dyn_cast<GlobalVariableDesc>(Element)) {
1579 // Add static member.
1580
1581 // Construct member debug information entry.
1582 DIE *Static = new DIE(DW_TAG_variable);
1583
1584 // Add name and mangled name.
1585 const std::string &Name = StaticDesc->getName();
1586 const std::string &LinkageName = StaticDesc->getLinkageName();
1587 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1588 if (!LinkageName.empty()) {
1589 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1590 LinkageName);
1591 }
1592
1593 // Add location.
1594 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1595
1596 // Add type.
1597 if (TypeDesc *StaticTy = StaticDesc->getType())
1598 AddType(Static, StaticTy, Unit);
1599
1600 // Add flags.
1601 if (!StaticDesc->isStatic())
1602 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1603 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1604
1605 Buffer.AddChild(Static);
1606 } else if (SubprogramDesc *MethodDesc =
1607 dyn_cast<SubprogramDesc>(Element)) {
1608 // Add member function.
1609
1610 // Construct member debug information entry.
1611 DIE *Method = new DIE(DW_TAG_subprogram);
1612
1613 // Add name and mangled name.
1614 const std::string &Name = MethodDesc->getName();
1615 const std::string &LinkageName = MethodDesc->getLinkageName();
1616
1617 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1618 bool IsCTor = TyDesc->getName() == Name;
1619
1620 if (!LinkageName.empty()) {
1621 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1622 LinkageName);
1623 }
1624
1625 // Add location.
1626 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1627
1628 // Add type.
1629 if (CompositeTypeDesc *MethodTy =
1630 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1631 // Get argument information.
1632 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1633
1634 // If not a ctor.
1635 if (!IsCTor) {
1636 // Add return type.
1637 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1638 }
1639
1640 // Add arguments.
1641 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1642 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1643 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1644 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1645 Method->AddChild(Arg);
1646 }
1647 }
1648
1649 // Add flags.
1650 if (!MethodDesc->isStatic())
1651 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1652 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1653
1654 Buffer.AddChild(Method);
1655 }
1656 }
1657 break;
1658 }
1659 case DW_TAG_enumeration_type: {
1660 // Add enumerators to enumeration type.
1661 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1662 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1663 const std::string &Name = ED->getName();
1664 int64_t Value = ED->getValue();
1665 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1666 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1667 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1668 Buffer.AddChild(Enumerator);
1669 }
1670
1671 break;
1672 }
1673 case DW_TAG_subroutine_type: {
1674 // Add prototype flag.
1675 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1676 // Add return type.
1677 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1678
1679 // Add arguments.
1680 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1681 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1682 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1683 Buffer.AddChild(Arg);
1684 }
1685
1686 break;
1687 }
1688 default: break;
1689 }
1690 }
1691
1692 // Add size if non-zero (derived types don't have a size.)
1693 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1694 // Add name if not anonymous or intermediate type.
1695 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1696 // Add source line info if available.
1697 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1698 }
1699
1700 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1701 ///
1702 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1703 // Construct debug information entry.
1704 DIE *Die = new DIE(DW_TAG_compile_unit);
1705 if (TAI->isAbsoluteDebugSectionOffsets())
1706 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1707 else
1708 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1709 DWLabel("section_line", 0));
1710 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1711 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1712 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1713 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1714
1715 // Construct compile unit.
1716 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1717
1718 // Add Unit to compile unit map.
1719 DescToUnitMap[UnitDesc] = Unit;
1720
1721 return Unit;
1722 }
1723
1724 /// GetBaseCompileUnit - Get the main compile unit.
1725 ///
1726 CompileUnit *GetBaseCompileUnit() const {
1727 CompileUnit *Unit = CompileUnits[0];
1728 assert(Unit && "Missing compile unit.");
1729 return Unit;
1730 }
1731
1732 /// FindCompileUnit - Get the compile unit for the given descriptor.
1733 ///
1734 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1735 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1736 assert(Unit && "Missing compile unit.");
1737 return Unit;
1738 }
1739
1740 /// NewGlobalVariable - Add a new global variable DIE.
1741 ///
1742 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1743 // Get the compile unit context.
1744 CompileUnitDesc *UnitDesc =
1745 static_cast<CompileUnitDesc *>(GVD->getContext());
1746 CompileUnit *Unit = GetBaseCompileUnit();
1747
1748 // Check for pre-existence.
1749 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1750 if (Slot) return Slot;
1751
1752 // Get the global variable itself.
1753 GlobalVariable *GV = GVD->getGlobalVariable();
1754
1755 const std::string &Name = GVD->getName();
1756 const std::string &FullName = GVD->getFullName();
1757 const std::string &LinkageName = GVD->getLinkageName();
1758 // Create the global's variable DIE.
1759 DIE *VariableDie = new DIE(DW_TAG_variable);
1760 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1761 if (!LinkageName.empty()) {
1762 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1763 LinkageName);
1764 }
1765 AddType(VariableDie, GVD->getType(), Unit);
1766 if (!GVD->isStatic())
1767 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1768
1769 // Add source line info if available.
1770 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1771
1772 // Add address.
1773 DIEBlock *Block = new DIEBlock();
1774 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1775 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1776 AddBlock(VariableDie, DW_AT_location, 0, Block);
1777
1778 // Add to map.
1779 Slot = VariableDie;
1780
1781 // Add to context owner.
1782 Unit->getDie()->AddChild(VariableDie);
1783
1784 // Expose as global.
1785 // FIXME - need to check external flag.
1786 Unit->AddGlobal(FullName, VariableDie);
1787
1788 return VariableDie;
1789 }
1790
1791 /// NewSubprogram - Add a new subprogram DIE.
1792 ///
1793 DIE *NewSubprogram(SubprogramDesc *SPD) {
1794 // Get the compile unit context.
1795 CompileUnitDesc *UnitDesc =
1796 static_cast<CompileUnitDesc *>(SPD->getContext());
1797 CompileUnit *Unit = GetBaseCompileUnit();
1798
1799 // Check for pre-existence.
1800 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1801 if (Slot) return Slot;
1802
1803 // Gather the details (simplify add attribute code.)
1804 const std::string &Name = SPD->getName();
1805 const std::string &FullName = SPD->getFullName();
1806 const std::string &LinkageName = SPD->getLinkageName();
1807
1808 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1809 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1810 if (!LinkageName.empty()) {
1811 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1812 LinkageName);
1813 }
1814 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1815 if (!SPD->isStatic())
1816 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1817 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1818
1819 // Add source line info if available.
1820 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1821
1822 // Add to map.
1823 Slot = SubprogramDie;
1824
1825 // Add to context owner.
1826 Unit->getDie()->AddChild(SubprogramDie);
1827
1828 // Expose as global.
1829 Unit->AddGlobal(FullName, SubprogramDie);
1830
1831 return SubprogramDie;
1832 }
1833
1834 /// NewScopeVariable - Create a new scope variable.
1835 ///
1836 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1837 // Get the descriptor.
1838 VariableDesc *VD = DV->getDesc();
1839
1840 // Translate tag to proper Dwarf tag. The result variable is dropped for
1841 // now.
1842 unsigned Tag;
1843 switch (VD->getTag()) {
1844 case DW_TAG_return_variable: return NULL;
1845 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1846 case DW_TAG_auto_variable: // fall thru
1847 default: Tag = DW_TAG_variable; break;
1848 }
1849
1850 // Define variable debug information entry.
1851 DIE *VariableDie = new DIE(Tag);
1852 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1853
1854 // Add source line info if available.
1855 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1856
1857 // Add variable type.
1858 AddType(VariableDie, VD->getType(), Unit);
1859
1860 // Add variable address.
1861 MachineLocation Location;
1862 RI->getLocation(*MF, DV->getFrameIndex(), Location);
1863 AddAddress(VariableDie, DW_AT_location, Location);
1864
1865 return VariableDie;
1866 }
1867
1868 /// ConstructScope - Construct the components of a scope.
1869 ///
1870 void ConstructScope(DebugScope *ParentScope,
1871 unsigned ParentStartID, unsigned ParentEndID,
1872 DIE *ParentDie, CompileUnit *Unit) {
1873 // Add variables to scope.
1874 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1875 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1876 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1877 if (VariableDie) ParentDie->AddChild(VariableDie);
1878 }
1879
1880 // Add nested scopes.
1881 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1882 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1883 // Define the Scope debug information entry.
1884 DebugScope *Scope = Scopes[j];
1885 // FIXME - Ignore inlined functions for the time being.
1886 if (!Scope->getParent()) continue;
1887
1888 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1889 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1890
1891 // Ignore empty scopes.
1892 if (StartID == EndID && StartID != 0) continue;
1893 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1894
1895 if (StartID == ParentStartID && EndID == ParentEndID) {
1896 // Just add stuff to the parent scope.
1897 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1898 } else {
1899 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1900
1901 // Add the scope bounds.
1902 if (StartID) {
1903 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1904 DWLabel("label", StartID));
1905 } else {
1906 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1907 DWLabel("func_begin", SubprogramCount));
1908 }
1909 if (EndID) {
1910 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1911 DWLabel("label", EndID));
1912 } else {
1913 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1914 DWLabel("func_end", SubprogramCount));
1915 }
1916
1917 // Add the scope contents.
1918 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1919 ParentDie->AddChild(ScopeDie);
1920 }
1921 }
1922 }
1923
1924 /// ConstructRootScope - Construct the scope for the subprogram.
1925 ///
1926 void ConstructRootScope(DebugScope *RootScope) {
1927 // Exit if there is no root scope.
1928 if (!RootScope) return;
1929
1930 // Get the subprogram debug information entry.
1931 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1932
1933 // Get the compile unit context.
1934 CompileUnit *Unit = GetBaseCompileUnit();
1935
1936 // Get the subprogram die.
1937 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1938 assert(SPDie && "Missing subprogram descriptor");
1939
1940 // Add the function bounds.
1941 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1942 DWLabel("func_begin", SubprogramCount));
1943 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1944 DWLabel("func_end", SubprogramCount));
1945 MachineLocation Location(RI->getFrameRegister(*MF));
1946 AddAddress(SPDie, DW_AT_frame_base, Location);
1947
1948 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1949 }
1950
1951 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1952 /// tools to recognize the object file contains Dwarf information.
1953 void EmitInitial() {
1954 // Check to see if we already emitted intial headers.
1955 if (didInitial) return;
1956 didInitial = true;
1957
1958 // Dwarf sections base addresses.
1959 if (TAI->doesDwarfRequireFrameSection()) {
1960 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1961 EmitLabel("section_debug_frame", 0);
1962 }
1963 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1964 EmitLabel("section_info", 0);
1965 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1966 EmitLabel("section_abbrev", 0);
1967 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1968 EmitLabel("section_aranges", 0);
1969 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1970 EmitLabel("section_macinfo", 0);
1971 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1972 EmitLabel("section_line", 0);
1973 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1974 EmitLabel("section_loc", 0);
1975 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1976 EmitLabel("section_pubnames", 0);
1977 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1978 EmitLabel("section_str", 0);
1979 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1980 EmitLabel("section_ranges", 0);
1981
1982 Asm->SwitchToTextSection(TAI->getTextSection());
1983 EmitLabel("text_begin", 0);
1984 Asm->SwitchToDataSection(TAI->getDataSection());
1985 EmitLabel("data_begin", 0);
1986 }
1987
1988 /// EmitDIE - Recusively Emits a debug information entry.
1989 ///
1990 void EmitDIE(DIE *Die) {
1991 // Get the abbreviation for this DIE.
1992 unsigned AbbrevNumber = Die->getAbbrevNumber();
1993 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1994
1995 Asm->EOL();
1996
1997 // Emit the code (index) for the abbreviation.
1998 Asm->EmitULEB128Bytes(AbbrevNumber);
1999 Asm->EOL(std::string("Abbrev [" +
2000 utostr(AbbrevNumber) +
2001 "] 0x" + utohexstr(Die->getOffset()) +
2002 ":0x" + utohexstr(Die->getSize()) + " " +
2003 TagString(Abbrev->getTag())));
2004
2005 std::vector<DIEValue *> &Values = Die->getValues();
2006 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2007
2008 // Emit the DIE attribute values.
2009 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2010 unsigned Attr = AbbrevData[i].getAttribute();
2011 unsigned Form = AbbrevData[i].getForm();
2012 assert(Form && "Too many attributes for DIE (check abbreviation)");
2013
2014 switch (Attr) {
2015 case DW_AT_sibling: {
2016 Asm->EmitInt32(Die->SiblingOffset());
2017 break;
2018 }
2019 default: {
2020 // Emit an attribute using the defined form.
2021 Values[i]->EmitValue(*this, Form);
2022 break;
2023 }
2024 }
2025
2026 Asm->EOL(AttributeString(Attr));
2027 }
2028
2029 // Emit the DIE children if any.
2030 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2031 const std::vector<DIE *> &Children = Die->getChildren();
2032
2033 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2034 EmitDIE(Children[j]);
2035 }
2036
2037 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2038 }
2039 }
2040
2041 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2042 ///
2043 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2044 // Get the children.
2045 const std::vector<DIE *> &Children = Die->getChildren();
2046
2047 // If not last sibling and has children then add sibling offset attribute.
2048 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2049
2050 // Record the abbreviation.
2051 AssignAbbrevNumber(Die->getAbbrev());
2052
2053 // Get the abbreviation for this DIE.
2054 unsigned AbbrevNumber = Die->getAbbrevNumber();
2055 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2056
2057 // Set DIE offset
2058 Die->setOffset(Offset);
2059
2060 // Start the size with the size of abbreviation code.
2061 Offset += Asm->SizeULEB128(AbbrevNumber);
2062
2063 const std::vector<DIEValue *> &Values = Die->getValues();
2064 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2065
2066 // Size the DIE attribute values.
2067 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2068 // Size attribute value.
2069 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2070 }
2071
2072 // Size the DIE children if any.
2073 if (!Children.empty()) {
2074 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2075 "Children flag not set");
2076
2077 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2078 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2079 }
2080
2081 // End of children marker.
2082 Offset += sizeof(int8_t);
2083 }
2084
2085 Die->setSize(Offset - Die->getOffset());
2086 return Offset;
2087 }
2088
2089 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2090 ///
2091 void SizeAndOffsets() {
2092 // Process base compile unit.
2093 CompileUnit *Unit = GetBaseCompileUnit();
2094 // Compute size of compile unit header
2095 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2096 sizeof(int16_t) + // DWARF version number
2097 sizeof(int32_t) + // Offset Into Abbrev. Section
2098 sizeof(int8_t); // Pointer Size (in bytes)
2099 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2100 }
2101
2102 /// EmitDebugInfo - Emit the debug info section.
2103 ///
2104 void EmitDebugInfo() {
2105 // Start debug info section.
2106 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2107
2108 CompileUnit *Unit = GetBaseCompileUnit();
2109 DIE *Die = Unit->getDie();
2110 // Emit the compile units header.
2111 EmitLabel("info_begin", Unit->getID());
2112 // Emit size of content not including length itself
2113 unsigned ContentSize = Die->getSize() +
2114 sizeof(int16_t) + // DWARF version number
2115 sizeof(int32_t) + // Offset Into Abbrev. Section
2116 sizeof(int8_t) + // Pointer Size (in bytes)
2117 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2118
2119 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2120 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2121 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2122 Asm->EOL("Offset Into Abbrev. Section");
2123 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2124
2125 EmitDIE(Die);
2126 // FIXME - extra padding for gdb bug.
2127 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2128 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2129 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2130 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2131 EmitLabel("info_end", Unit->getID());
2132
2133 Asm->EOL();
2134 }
2135
2136 /// EmitAbbreviations - Emit the abbreviation section.
2137 ///
2138 void EmitAbbreviations() const {
2139 // Check to see if it is worth the effort.
2140 if (!Abbreviations.empty()) {
2141 // Start the debug abbrev section.
2142 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2143
2144 EmitLabel("abbrev_begin", 0);
2145
2146 // For each abbrevation.
2147 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2148 // Get abbreviation data
2149 const DIEAbbrev *Abbrev = Abbreviations[i];
2150
2151 // Emit the abbrevations code (base 1 index.)
2152 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2153 Asm->EOL("Abbreviation Code");
2154
2155 // Emit the abbreviations data.
2156 Abbrev->Emit(*this);
2157
2158 Asm->EOL();
2159 }
2160
2161 // Mark end of abbreviations.
2162 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2163
2164 EmitLabel("abbrev_end", 0);
2165
2166 Asm->EOL();
2167 }
2168 }
2169
2170 /// EmitDebugLines - Emit source line information.
2171 ///
2172 void EmitDebugLines() {
2173 // Minimum line delta, thus ranging from -10..(255-10).
2174 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2175 // Maximum line delta, thus ranging from -10..(255-10).
2176 const int MaxLineDelta = 255 + MinLineDelta;
2177
2178 // Start the dwarf line section.
2179 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2180
2181 // Construct the section header.
2182
2183 EmitDifference("line_end", 0, "line_begin", 0, true);
2184 Asm->EOL("Length of Source Line Info");
2185 EmitLabel("line_begin", 0);
2186
2187 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2188
2189 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2190 Asm->EOL("Prolog Length");
2191 EmitLabel("line_prolog_begin", 0);
2192
2193 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2194
2195 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2196
2197 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2198
2199 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2200
2201 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2202
2203 // Line number standard opcode encodings argument count
2204 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2205 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2206 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2207 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2208 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2209 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2210 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2211 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2212 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2213
2214 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2215 const UniqueVector<SourceFileInfo>
2216 &SourceFiles = MMI->getSourceFiles();
2217
2218 // Emit directories.
2219 for (unsigned DirectoryID = 1, NDID = Directories.size();
2220 DirectoryID <= NDID; ++DirectoryID) {
2221 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2222 }
2223 Asm->EmitInt8(0); Asm->EOL("End of directories");
2224
2225 // Emit files.
2226 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2227 SourceID <= NSID; ++SourceID) {
2228 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2229 Asm->EmitString(SourceFile.getName());
2230 Asm->EOL("Source");
2231 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2232 Asm->EOL("Directory #");
2233 Asm->EmitULEB128Bytes(0);
2234 Asm->EOL("Mod date");
2235 Asm->EmitULEB128Bytes(0);
2236 Asm->EOL("File size");
2237 }
2238 Asm->EmitInt8(0); Asm->EOL("End of files");
2239
2240 EmitLabel("line_prolog_end", 0);
2241
2242 // A sequence for each text section.
2243 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2244 // Isolate current sections line info.
2245 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2246
2247 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2248
2249 // Dwarf assumes we start with first line of first source file.
2250 unsigned Source = 1;
2251 unsigned Line = 1;
2252
2253 // Construct rows of the address, source, line, column matrix.
2254 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2255 const SourceLineInfo &LineInfo = LineInfos[i];
2256 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2257 if (!LabelID) continue;
2258
2259 unsigned SourceID = LineInfo.getSourceID();
2260 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2261 unsigned DirectoryID = SourceFile.getDirectoryID();
2262 Asm->EOL(Directories[DirectoryID]
2263 + SourceFile.getName()
2264 + ":"
2265 + utostr_32(LineInfo.getLine()));
2266
2267 // Define the line address.
2268 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2269 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2270 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2271 EmitReference("label", LabelID); Asm->EOL("Location label");
2272
2273 // If change of source, then switch to the new source.
2274 if (Source != LineInfo.getSourceID()) {
2275 Source = LineInfo.getSourceID();
2276 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2277 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2278 }
2279
2280 // If change of line.
2281 if (Line != LineInfo.getLine()) {
2282 // Determine offset.
2283 int Offset = LineInfo.getLine() - Line;
2284 int Delta = Offset - MinLineDelta;
2285
2286 // Update line.
2287 Line = LineInfo.getLine();
2288
2289 // If delta is small enough and in range...
2290 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2291 // ... then use fast opcode.
2292 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2293 } else {
2294 // ... otherwise use long hand.
2295 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2296 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2297 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2298 }
2299 } else {
2300 // Copy the previous row (different address or source)
2301 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2302 }
2303 }
2304
2305 // Define last address of section.
2306 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2307 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2308 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2309 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2310
2311 // Mark end of matrix.
2312 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2313 Asm->EmitULEB128Bytes(1); Asm->EOL();
2314 Asm->EmitInt8(1); Asm->EOL();
2315 }
2316
2317 EmitLabel("line_end", 0);
2318
2319 Asm->EOL();
2320 }
2321
2322 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2323 ///
2324 void EmitCommonDebugFrame() {
2325 if (!TAI->doesDwarfRequireFrameSection())
2326 return;
2327
2328 int stackGrowth =
2329 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2330 TargetFrameInfo::StackGrowsUp ?
2331 TAI->getAddressSize() : -TAI->getAddressSize();
2332
2333 // Start the dwarf frame section.
2334 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2335
2336 EmitLabel("debug_frame_common", 0);
2337 EmitDifference("debug_frame_common_end", 0,
2338 "debug_frame_common_begin", 0, true);
2339 Asm->EOL("Length of Common Information Entry");
2340
2341 EmitLabel("debug_frame_common_begin", 0);
2342 Asm->EmitInt32((int)DW_CIE_ID);
2343 Asm->EOL("CIE Identifier Tag");
2344 Asm->EmitInt8(DW_CIE_VERSION);
2345 Asm->EOL("CIE Version");
2346 Asm->EmitString("");
2347 Asm->EOL("CIE Augmentation");
2348 Asm->EmitULEB128Bytes(1);
2349 Asm->EOL("CIE Code Alignment Factor");
2350 Asm->EmitSLEB128Bytes(stackGrowth);
2351 Asm->EOL("CIE Data Alignment Factor");
2352 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2353 Asm->EOL("CIE RA Column");
2354
2355 std::vector<MachineMove> Moves;
2356 RI->getInitialFrameState(Moves);
2357
2358 EmitFrameMoves(NULL, 0, Moves);
2359
2360 Asm->EmitAlignment(2);
2361 EmitLabel("debug_frame_common_end", 0);
2362
2363 Asm->EOL();
2364 }
2365
2366 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2367 /// section.
2368 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2369 if (!TAI->doesDwarfRequireFrameSection())
2370 return;
2371
2372 // Start the dwarf frame section.
2373 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2374
2375 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2376 "debug_frame_begin", DebugFrameInfo.Number, true);
2377 Asm->EOL("Length of Frame Information Entry");
2378
2379 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2380
2381 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2382 0, 0, true, false);
2383 Asm->EOL("FDE CIE offset");
2384
2385 EmitReference("func_begin", DebugFrameInfo.Number);
2386 Asm->EOL("FDE initial location");
2387 EmitDifference("func_end", DebugFrameInfo.Number,
2388 "func_begin", DebugFrameInfo.Number);
2389 Asm->EOL("FDE address range");
2390
2391 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves);
2392
2393 Asm->EmitAlignment(2);
2394 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2395
2396 Asm->EOL();
2397 }
2398
2399 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2400 ///
2401 void EmitDebugPubNames() {
2402 // Start the dwarf pubnames section.
2403 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2404
2405 CompileUnit *Unit = GetBaseCompileUnit();
2406
2407 EmitDifference("pubnames_end", Unit->getID(),
2408 "pubnames_begin", Unit->getID(), true);
2409 Asm->EOL("Length of Public Names Info");
2410
2411 EmitLabel("pubnames_begin", Unit->getID());
2412
2413 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2414
2415 EmitSectionOffset("info_begin", "section_info",
2416 Unit->getID(), 0, true, false);
2417 Asm->EOL("Offset of Compilation Unit Info");
2418
2419 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2420 Asm->EOL("Compilation Unit Length");
2421
2422 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2423
2424 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2425 GE = Globals.end();
2426 GI != GE; ++GI) {
2427 const std::string &Name = GI->first;
2428 DIE * Entity = GI->second;
2429
2430 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2431 Asm->EmitString(Name); Asm->EOL("External Name");
2432 }
2433
2434 Asm->EmitInt32(0); Asm->EOL("End Mark");
2435 EmitLabel("pubnames_end", Unit->getID());
2436
2437 Asm->EOL();
2438 }
2439
2440 /// EmitDebugStr - Emit visible names into a debug str section.
2441 ///
2442 void EmitDebugStr() {
2443 // Check to see if it is worth the effort.
2444 if (!StringPool.empty()) {
2445 // Start the dwarf str section.
2446 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2447
2448 // For each of strings in the string pool.
2449 for (unsigned StringID = 1, N = StringPool.size();
2450 StringID <= N; ++StringID) {
2451 // Emit a label for reference from debug information entries.
2452 EmitLabel("string", StringID);
2453 // Emit the string itself.
2454 const std::string &String = StringPool[StringID];
2455 Asm->EmitString(String); Asm->EOL();
2456 }
2457
2458 Asm->EOL();
2459 }
2460 }
2461
2462 /// EmitDebugLoc - Emit visible names into a debug loc section.
2463 ///
2464 void EmitDebugLoc() {
2465 // Start the dwarf loc section.
2466 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2467
2468 Asm->EOL();
2469 }
2470
2471 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2472 ///
2473 void EmitDebugARanges() {
2474 // Start the dwarf aranges section.
2475 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2476
2477 // FIXME - Mock up
2478 #if 0
2479 CompileUnit *Unit = GetBaseCompileUnit();
2480
2481 // Don't include size of length
2482 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2483
2484 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2485
2486 EmitReference("info_begin", Unit->getID());
2487 Asm->EOL("Offset of Compilation Unit Info");
2488
2489 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2490
2491 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2492
2493 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2494 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2495
2496 // Range 1
2497 EmitReference("text_begin", 0); Asm->EOL("Address");
2498 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2499
2500 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2501 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2502
2503 Asm->EOL();
2504 #endif
2505 }
2506
2507 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2508 ///
2509 void EmitDebugRanges() {
2510 // Start the dwarf ranges section.
2511 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2512
2513 Asm->EOL();
2514 }
2515
2516 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2517 ///
2518 void EmitDebugMacInfo() {
2519 // Start the dwarf macinfo section.
2520 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2521
2522 Asm->EOL();
2523 }
2524
2525 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2526 /// header file.
2527 void ConstructCompileUnitDIEs() {
2528 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2529
2530 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2531 unsigned ID = MMI->RecordSource(CUW[i]);
2532 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2533 CompileUnits.push_back(Unit);
2534 }
2535 }
2536
2537 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2538 /// global variables.
2539 void ConstructGlobalDIEs() {
2540 std::vector<GlobalVariableDesc *> GlobalVariables =
2541 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2542
2543 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2544 GlobalVariableDesc *GVD = GlobalVariables[i];
2545 NewGlobalVariable(GVD);
2546 }
2547 }
2548
2549 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2550 /// subprograms.
2551 void ConstructSubprogramDIEs() {
2552 std::vector<SubprogramDesc *> Subprograms =
2553 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2554
2555 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2556 SubprogramDesc *SPD = Subprograms[i];
2557 NewSubprogram(SPD);
2558 }
2559 }
2560
2561public:
2562 //===--------------------------------------------------------------------===//
2563 // Main entry points.
2564 //
2565 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2566 : Dwarf(OS, A, T)
2567 , CompileUnits()
2568 , AbbreviationsSet(InitAbbreviationsSetSize)
2569 , Abbreviations()
2570 , ValuesSet(InitValuesSetSize)
2571 , Values()
2572 , StringPool()
2573 , DescToUnitMap()
2574 , SectionMap()
2575 , SectionSourceLines()
2576 , didInitial(false)
2577 , shouldEmit(false)
2578 {
2579 }
2580 virtual ~DwarfDebug() {
2581 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2582 delete CompileUnits[i];
2583 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2584 delete Values[j];
2585 }
2586
2587 /// SetModuleInfo - Set machine module information when it's known that pass
2588 /// manager has created it. Set by the target AsmPrinter.
2589 void SetModuleInfo(MachineModuleInfo *mmi) {
2590 // Make sure initial declarations are made.
2591 if (!MMI && mmi->hasDebugInfo()) {
2592 MMI = mmi;
2593 shouldEmit = true;
2594
2595 // Emit initial sections
2596 EmitInitial();
2597
2598 // Create all the compile unit DIEs.
2599 ConstructCompileUnitDIEs();
2600
2601 // Create DIEs for each of the externally visible global variables.
2602 ConstructGlobalDIEs();
2603
2604 // Create DIEs for each of the externally visible subprograms.
2605 ConstructSubprogramDIEs();
2606
2607 // Prime section data.
2608 SectionMap.insert(TAI->getTextSection());
2609 }
2610 }
2611
2612 /// BeginModule - Emit all Dwarf sections that should come prior to the
2613 /// content.
2614 void BeginModule(Module *M) {
2615 this->M = M;
2616
2617 if (!ShouldEmitDwarf()) return;
2618 }
2619
2620 /// EndModule - Emit all Dwarf sections that should come after the content.
2621 ///
2622 void EndModule() {
2623 if (!ShouldEmitDwarf()) return;
2624
2625 // Standard sections final addresses.
2626 Asm->SwitchToTextSection(TAI->getTextSection());
2627 EmitLabel("text_end", 0);
2628 Asm->SwitchToDataSection(TAI->getDataSection());
2629 EmitLabel("data_end", 0);
2630
2631 // End text sections.
2632 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2633 Asm->SwitchToTextSection(SectionMap[i].c_str());
2634 EmitLabel("section_end", i);
2635 }
2636
2637 // Emit common frame information.
2638 EmitCommonDebugFrame();
2639
2640 // Emit function debug frame information
2641 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2642 E = DebugFrames.end(); I != E; ++I)
2643 EmitFunctionDebugFrame(*I);
2644
2645 // Compute DIE offsets and sizes.
2646 SizeAndOffsets();
2647
2648 // Emit all the DIEs into a debug info section
2649 EmitDebugInfo();
2650
2651 // Corresponding abbreviations into a abbrev section.
2652 EmitAbbreviations();
2653
2654 // Emit source line correspondence into a debug line section.
2655 EmitDebugLines();
2656
2657 // Emit info into a debug pubnames section.
2658 EmitDebugPubNames();
2659
2660 // Emit info into a debug str section.
2661 EmitDebugStr();
2662
2663 // Emit info into a debug loc section.
2664 EmitDebugLoc();
2665
2666 // Emit info into a debug aranges section.
2667 EmitDebugARanges();
2668
2669 // Emit info into a debug ranges section.
2670 EmitDebugRanges();
2671
2672 // Emit info into a debug macinfo section.
2673 EmitDebugMacInfo();
2674 }
2675
2676 /// BeginFunction - Gather pre-function debug information. Assumes being
2677 /// emitted immediately after the function entry point.
2678 void BeginFunction(MachineFunction *MF) {
2679 this->MF = MF;
2680
2681 if (!ShouldEmitDwarf()) return;
2682
2683 // Begin accumulating function debug information.
2684 MMI->BeginFunction(MF);
2685
2686 // Assumes in correct section after the entry point.
2687 EmitLabel("func_begin", ++SubprogramCount);
2688 }
2689
2690 /// EndFunction - Gather and emit post-function debug information.
2691 ///
2692 void EndFunction() {
2693 if (!ShouldEmitDwarf()) return;
2694
2695 // Define end label for subprogram.
2696 EmitLabel("func_end", SubprogramCount);
2697
2698 // Get function line info.
2699 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2700
2701 if (!LineInfos.empty()) {
2702 // Get section line info.
2703 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2704 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2705 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2706 // Append the function info to section info.
2707 SectionLineInfos.insert(SectionLineInfos.end(),
2708 LineInfos.begin(), LineInfos.end());
2709 }
2710
2711 // Construct scopes for subprogram.
2712 ConstructRootScope(MMI->getRootScope());
2713
2714 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2715 MMI->getFrameMoves()));
2716 }
2717};
2718
2719//===----------------------------------------------------------------------===//
2720/// DwarfException - Emits Dwarf exception handling directives.
2721///
2722class DwarfException : public Dwarf {
2723
2724private:
2725 struct FunctionEHFrameInfo {
2726 std::string FnName;
2727 unsigned Number;
2728 unsigned PersonalityIndex;
2729 bool hasCalls;
2730 bool hasLandingPads;
2731 std::vector<MachineMove> Moves;
2732
2733 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2734 bool hC, bool hL,
2735 const std::vector<MachineMove> &M):
2736 FnName(FN), Number(Num), PersonalityIndex(P),
Dan Gohman9ba5d4d2007-08-27 14:50:10 +00002737 hasCalls(hC), hasLandingPads(hL), Moves(M) { }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738 };
2739
2740 std::vector<FunctionEHFrameInfo> EHFrames;
2741
2742 /// shouldEmit - Flag to indicate if debug information should be emitted.
2743 ///
2744 bool shouldEmit;
2745
2746 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2747 ///
2748 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2749 // Size and sign of stack growth.
2750 int stackGrowth =
2751 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2752 TargetFrameInfo::StackGrowsUp ?
2753 TAI->getAddressSize() : -TAI->getAddressSize();
2754
2755 // Begin eh frame section.
2756 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2757 O << "EH_frame" << Index << ":\n";
2758 EmitLabel("section_eh_frame", Index);
2759
2760 // Define base labels.
2761 EmitLabel("eh_frame_common", Index);
2762
2763 // Define the eh frame length.
2764 EmitDifference("eh_frame_common_end", Index,
2765 "eh_frame_common_begin", Index, true);
2766 Asm->EOL("Length of Common Information Entry");
2767
2768 // EH frame header.
2769 EmitLabel("eh_frame_common_begin", Index);
2770 Asm->EmitInt32((int)0);
2771 Asm->EOL("CIE Identifier Tag");
2772 Asm->EmitInt8(DW_CIE_VERSION);
2773 Asm->EOL("CIE Version");
2774
2775 // The personality presence indicates that language specific information
2776 // will show up in the eh frame.
2777 Asm->EmitString(Personality ? "zPLR" : "zR");
2778 Asm->EOL("CIE Augmentation");
2779
2780 // Round out reader.
2781 Asm->EmitULEB128Bytes(1);
2782 Asm->EOL("CIE Code Alignment Factor");
2783 Asm->EmitSLEB128Bytes(stackGrowth);
2784 Asm->EOL("CIE Data Alignment Factor");
2785 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2786 Asm->EOL("CIE RA Column");
2787
2788 // If there is a personality, we need to indicate the functions location.
2789 if (Personality) {
2790 Asm->EmitULEB128Bytes(7);
2791 Asm->EOL("Augmentation Size");
Bill Wendling2d369922007-09-11 17:20:55 +00002792
2793 if (TAI->getNeedsIndirectEncoding())
2794 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2795 else
2796 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2797
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00002798 Asm->EOL("Personality (pcrel sdata4 indirect)");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00002800 PrintRelDirective();
2801 O << TAI->getPersonalityPrefix();
2802 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2803 O << TAI->getPersonalitySuffix();
2804 O << "-" << TAI->getPCSymbol();
2805 Asm->EOL("Personality");
Bill Wendling38cb7c92007-08-25 00:51:55 +00002806
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2808 Asm->EOL("LSDA Encoding (pcrel)");
2809 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2810 Asm->EOL("FDE Encoding (pcrel)");
2811 } else {
2812 Asm->EmitULEB128Bytes(1);
2813 Asm->EOL("Augmentation Size");
2814 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2815 Asm->EOL("FDE Encoding (pcrel)");
2816 }
2817
2818 // Indicate locations of general callee saved registers in frame.
2819 std::vector<MachineMove> Moves;
2820 RI->getInitialFrameState(Moves);
2821 EmitFrameMoves(NULL, 0, Moves);
2822
2823 Asm->EmitAlignment(2);
2824 EmitLabel("eh_frame_common_end", Index);
2825
2826 Asm->EOL();
2827 }
2828
2829 /// EmitEHFrame - Emit function exception frame information.
2830 ///
2831 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2832 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2833
2834 // Externally visible entry into the functions eh frame info.
2835 if (const char *GlobalDirective = TAI->getGlobalDirective())
2836 O << GlobalDirective << EHFrameInfo.FnName << ".eh\n";
2837
2838 // If there are no calls then you can't unwind.
2839 if (!EHFrameInfo.hasCalls) {
2840 O << EHFrameInfo.FnName << ".eh = 0\n";
2841 } else {
2842 O << EHFrameInfo.FnName << ".eh:\n";
2843
2844 // EH frame header.
2845 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2846 "eh_frame_begin", EHFrameInfo.Number, true);
2847 Asm->EOL("Length of Frame Information Entry");
2848
2849 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2850
2851 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2852 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2853 true, true);
2854 Asm->EOL("FDE CIE offset");
2855
2856 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2857 Asm->EOL("FDE initial location");
2858 EmitDifference("eh_func_end", EHFrameInfo.Number,
2859 "eh_func_begin", EHFrameInfo.Number);
2860 Asm->EOL("FDE address range");
2861
2862 // If there is a personality and landing pads then point to the language
2863 // specific data area in the exception table.
2864 if (EHFrameInfo.PersonalityIndex) {
2865 Asm->EmitULEB128Bytes(4);
2866 Asm->EOL("Augmentation size");
2867
2868 if (EHFrameInfo.hasLandingPads) {
2869 EmitReference("exception", EHFrameInfo.Number, true);
2870 } else if(TAI->getAddressSize() == 8) {
2871 Asm->EmitInt64((int)0);
2872 } else {
2873 Asm->EmitInt32((int)0);
2874 }
2875 Asm->EOL("Language Specific Data Area");
2876 } else {
2877 Asm->EmitULEB128Bytes(0);
2878 Asm->EOL("Augmentation size");
2879 }
2880
2881 // Indicate locations of function specific callee saved registers in
2882 // frame.
2883 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves);
2884
2885 Asm->EmitAlignment(2);
2886 EmitLabel("eh_frame_end", EHFrameInfo.Number);
2887 }
2888
2889 if (const char *UsedDirective = TAI->getUsedDirective())
2890 O << UsedDirective << EHFrameInfo.FnName << ".eh\n\n";
2891 }
2892
Duncan Sands241a0c92007-09-05 11:27:52 +00002893 /// EmitExceptionTable - Emit landing pads and actions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002894 ///
2895 /// The general organization of the table is complex, but the basic concepts
2896 /// are easy. First there is a header which describes the location and
2897 /// organization of the three components that follow.
2898 /// 1. The landing pad site information describes the range of code covered
2899 /// by the try. In our case it's an accumulation of the ranges covered
2900 /// by the invokes in the try. There is also a reference to the landing
2901 /// pad that handles the exception once processed. Finally an index into
2902 /// the actions table.
2903 /// 2. The action table, in our case, is composed of pairs of type ids
2904 /// and next action offset. Starting with the action index from the
2905 /// landing pad site, each type Id is checked for a match to the current
2906 /// exception. If it matches then the exception and type id are passed
2907 /// on to the landing pad. Otherwise the next action is looked up. This
2908 /// chain is terminated with a next action of zero. If no type id is
2909 /// found the the frame is unwound and handling continues.
2910 /// 3. Type id table contains references to all the C++ typeinfo for all
2911 /// catches in the function. This tables is reversed indexed base 1.
2912
2913 /// SharedTypeIds - How many leading type ids two landing pads have in common.
2914 static unsigned SharedTypeIds(const LandingPadInfo *L,
2915 const LandingPadInfo *R) {
2916 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2917 unsigned LSize = LIds.size(), RSize = RIds.size();
2918 unsigned MinSize = LSize < RSize ? LSize : RSize;
2919 unsigned Count = 0;
2920
2921 for (; Count != MinSize; ++Count)
2922 if (LIds[Count] != RIds[Count])
2923 return Count;
2924
2925 return Count;
2926 }
2927
2928 /// PadLT - Order landing pads lexicographically by type id.
2929 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
2930 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2931 unsigned LSize = LIds.size(), RSize = RIds.size();
2932 unsigned MinSize = LSize < RSize ? LSize : RSize;
2933
2934 for (unsigned i = 0; i != MinSize; ++i)
2935 if (LIds[i] != RIds[i])
2936 return LIds[i] < RIds[i];
2937
2938 return LSize < RSize;
2939 }
2940
2941 struct KeyInfo {
2942 static inline unsigned getEmptyKey() { return -1U; }
2943 static inline unsigned getTombstoneKey() { return -2U; }
2944 static unsigned getHashValue(const unsigned &Key) { return Key; }
Chris Lattner92eea072007-09-17 18:34:04 +00002945 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002946 static bool isPod() { return true; }
2947 };
2948
Duncan Sands241a0c92007-09-05 11:27:52 +00002949 /// ActionEntry - Structure describing an entry in the actions table.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950 struct ActionEntry {
2951 int ValueForTypeID; // The value to write - may not be equal to the type id.
2952 int NextAction;
2953 struct ActionEntry *Previous;
2954 };
2955
Duncan Sands241a0c92007-09-05 11:27:52 +00002956 /// PadRange - Structure holding a try-range and the associated landing pad.
2957 struct PadRange {
2958 // The index of the landing pad.
2959 unsigned PadIndex;
2960 // The index of the begin and end labels in the landing pad's label lists.
2961 unsigned RangeIndex;
2962 };
2963
2964 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
2965
2966 /// CallSiteEntry - Structure describing an entry in the call-site table.
2967 struct CallSiteEntry {
2968 unsigned BeginLabel; // zero indicates the start of the function.
2969 unsigned EndLabel; // zero indicates the end of the function.
2970 unsigned PadLabel; // zero indicates that there is no landing pad.
2971 unsigned Action;
2972 };
2973
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974 void EmitExceptionTable() {
2975 // Map all labels and get rid of any dead landing pads.
2976 MMI->TidyLandingPads();
2977
2978 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
2979 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
2980 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
2981 if (PadInfos.empty()) return;
2982
2983 // Sort the landing pads in order of their type ids. This is used to fold
2984 // duplicate actions.
2985 SmallVector<const LandingPadInfo *, 64> LandingPads;
2986 LandingPads.reserve(PadInfos.size());
2987 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
2988 LandingPads.push_back(&PadInfos[i]);
2989 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
2990
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002991 // Negative type ids index into FilterIds, positive type ids index into
2992 // TypeInfos. The value written for a positive type id is just the type
2993 // id itself. For a negative type id, however, the value written is the
2994 // (negative) byte offset of the corresponding FilterIds entry. The byte
2995 // offset is usually equal to the type id, because the FilterIds entries
2996 // are written using a variable width encoding which outputs one byte per
2997 // entry as long as the value written is not too large, but can differ.
2998 // This kind of complication does not occur for positive type ids because
2999 // type infos are output using a fixed width encoding.
3000 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3001 SmallVector<int, 16> FilterOffsets;
3002 FilterOffsets.reserve(FilterIds.size());
3003 int Offset = -1;
3004 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3005 E = FilterIds.end(); I != E; ++I) {
3006 FilterOffsets.push_back(Offset);
3007 Offset -= Asm->SizeULEB128(*I);
3008 }
3009
Duncan Sands241a0c92007-09-05 11:27:52 +00003010 // Compute the actions table and gather the first action index for each
3011 // landing pad site.
3012 SmallVector<ActionEntry, 32> Actions;
3013 SmallVector<unsigned, 64> FirstActions;
3014 FirstActions.reserve(LandingPads.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016 int FirstAction = 0;
Duncan Sands241a0c92007-09-05 11:27:52 +00003017 unsigned SizeActions = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003018 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3019 const LandingPadInfo *LP = LandingPads[i];
3020 const std::vector<int> &TypeIds = LP->TypeIds;
3021 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3022 unsigned SizeSiteActions = 0;
3023
3024 if (NumShared < TypeIds.size()) {
3025 unsigned SizeAction = 0;
3026 ActionEntry *PrevAction = 0;
3027
3028 if (NumShared) {
3029 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3030 assert(Actions.size());
3031 PrevAction = &Actions.back();
3032 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3033 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3034 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3035 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3036 SizeAction += -PrevAction->NextAction;
3037 PrevAction = PrevAction->Previous;
3038 }
3039 }
3040
3041 // Compute the actions.
3042 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3043 int TypeID = TypeIds[I];
3044 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3045 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3046 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3047
3048 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3049 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3050 SizeSiteActions += SizeAction;
3051
3052 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3053 Actions.push_back(Action);
3054
3055 PrevAction = &Actions.back();
3056 }
3057
3058 // Record the first action of the landing pad site.
3059 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3060 } // else identical - re-use previous FirstAction
3061
3062 FirstActions.push_back(FirstAction);
3063
3064 // Compute this sites contribution to size.
3065 SizeActions += SizeSiteActions;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003066 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003067
3068 // Compute the call-site table. Entries must be ordered by address.
3069 SmallVector<CallSiteEntry, 64> CallSites;
3070
3071 RangeMapType PadMap;
3072 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3073 const LandingPadInfo *LandingPad = LandingPads[i];
3074 for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3075 unsigned BeginLabel = LandingPad->BeginLabels[j];
3076 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3077 PadRange P = { i, j };
3078 PadMap[BeginLabel] = P;
3079 }
3080 }
3081
3082 bool MayThrow = false;
3083 unsigned LastLabel = 0;
3084 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
3085 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3086 I != E; ++I) {
3087 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3088 MI != E; ++MI) {
3089 if (MI->getOpcode() != TargetInstrInfo::LABEL) {
3090 MayThrow |= TII->isCall(MI->getOpcode());
3091 continue;
3092 }
3093
3094 unsigned BeginLabel = MI->getOperand(0).getImmedValue();
3095 assert(BeginLabel && "Invalid label!");
Duncan Sands89372f62007-09-05 14:12:46 +00003096
3097 if (BeginLabel == LastLabel)
Duncan Sands241a0c92007-09-05 11:27:52 +00003098 MayThrow = false;
Duncan Sands241a0c92007-09-05 11:27:52 +00003099
3100 RangeMapType::iterator L = PadMap.find(BeginLabel);
3101
3102 if (L == PadMap.end())
3103 continue;
3104
3105 PadRange P = L->second;
3106 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3107
3108 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3109 "Inconsistent landing pad map!");
3110
3111 // If some instruction between the previous try-range and this one may
3112 // throw, create a call-site entry with no landing pad for the region
3113 // between the try-ranges.
3114 if (MayThrow) {
3115 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3116 CallSites.push_back(Site);
3117 }
3118
3119 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3120 CallSiteEntry Site = {BeginLabel, LastLabel,
3121 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3122
3123 assert(Site.BeginLabel && Site.EndLabel && Site.PadLabel &&
3124 "Invalid landing pad!");
3125
3126 // Try to merge with the previous call-site.
3127 if (CallSites.size()) {
3128 CallSiteEntry &Prev = CallSites[CallSites.size()-1];
3129 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3130 // Extend the range of the previous entry.
3131 Prev.EndLabel = Site.EndLabel;
3132 continue;
3133 }
3134 }
3135
3136 // Otherwise, create a new call-site.
3137 CallSites.push_back(Site);
3138 }
3139 }
3140 // If some instruction between the previous try-range and the end of the
3141 // function may throw, create a call-site entry with no landing pad for the
3142 // region following the try-range.
3143 if (MayThrow) {
3144 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3145 CallSites.push_back(Site);
3146 }
3147
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148 // Final tallies.
Duncan Sands241a0c92007-09-05 11:27:52 +00003149 unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
3150 sizeof(int32_t) + // Site length.
3151 sizeof(int32_t)); // Landing pad.
3152 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3153 SizeSites += Asm->SizeULEB128(CallSites[i].Action);
3154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 unsigned SizeTypes = TypeInfos.size() * TAI->getAddressSize();
3156
3157 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3158 Asm->SizeULEB128(SizeSites) + // Call-site table length
3159 SizeSites + SizeActions + SizeTypes;
3160
3161 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3162 sizeof(int8_t) + // TType format
3163 Asm->SizeULEB128(TypeOffset) + // TType base offset
3164 TypeOffset;
3165
3166 unsigned SizeAlign = (4 - TotalSize) & 3;
3167
3168 // Begin the exception table.
3169 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3170 O << "GCC_except_table" << SubprogramCount << ":\n";
3171 Asm->EmitAlignment(2);
3172 for (unsigned i = 0; i != SizeAlign; ++i) {
3173 Asm->EmitInt8(0);
3174 Asm->EOL("Padding");
3175 }
3176 EmitLabel("exception", SubprogramCount);
3177
3178 // Emit the header.
3179 Asm->EmitInt8(DW_EH_PE_omit);
3180 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3181 Asm->EmitInt8(DW_EH_PE_absptr);
3182 Asm->EOL("TType format (DW_EH_PE_absptr)");
3183 Asm->EmitULEB128Bytes(TypeOffset);
3184 Asm->EOL("TType base offset");
3185 Asm->EmitInt8(DW_EH_PE_udata4);
3186 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3187 Asm->EmitULEB128Bytes(SizeSites);
3188 Asm->EOL("Call-site table length");
3189
Duncan Sands241a0c92007-09-05 11:27:52 +00003190 // Emit the landing pad site information.
3191 for (unsigned i = 0; i < CallSites.size(); ++i) {
3192 CallSiteEntry &S = CallSites[i];
3193 const char *BeginTag;
3194 unsigned BeginNumber;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195
Duncan Sands241a0c92007-09-05 11:27:52 +00003196 if (!S.BeginLabel) {
3197 BeginTag = "eh_func_begin";
3198 BeginNumber = SubprogramCount;
3199 } else {
3200 BeginTag = "label";
3201 BeginNumber = S.BeginLabel;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003202 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203
Duncan Sands241a0c92007-09-05 11:27:52 +00003204 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3205 false, true);
3206 Asm->EOL("Region start");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207
Duncan Sands241a0c92007-09-05 11:27:52 +00003208 if (!S.EndLabel) {
3209 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber);
3210 } else {
3211 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber);
3212 }
3213 Asm->EOL("Region length");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214
Duncan Sands241a0c92007-09-05 11:27:52 +00003215 if (!S.PadLabel) {
3216 if (TAI->getAddressSize() == sizeof(int32_t))
3217 Asm->EmitInt32(0);
3218 else
3219 Asm->EmitInt64(0);
3220 } else {
3221 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003222 false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003223 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003224 Asm->EOL("Landing pad");
3225
3226 Asm->EmitULEB128Bytes(S.Action);
3227 Asm->EOL("Action");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228 }
3229
3230 // Emit the actions.
3231 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3232 ActionEntry &Action = Actions[I];
3233
3234 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3235 Asm->EOL("TypeInfo index");
3236 Asm->EmitSLEB128Bytes(Action.NextAction);
3237 Asm->EOL("Next action");
3238 }
3239
3240 // Emit the type ids.
3241 for (unsigned M = TypeInfos.size(); M; --M) {
3242 GlobalVariable *GV = TypeInfos[M - 1];
Anton Korobeynikov5ef86702007-09-02 22:07:21 +00003243
3244 PrintRelDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003245
3246 if (GV)
3247 O << Asm->getGlobalLinkName(GV);
3248 else
3249 O << "0";
Duncan Sands241a0c92007-09-05 11:27:52 +00003250
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003251 Asm->EOL("TypeInfo");
3252 }
3253
3254 // Emit the filter typeids.
3255 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3256 unsigned TypeID = FilterIds[j];
3257 Asm->EmitULEB128Bytes(TypeID);
3258 Asm->EOL("Filter TypeInfo index");
3259 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003260
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261 Asm->EmitAlignment(2);
3262 }
3263
3264public:
3265 //===--------------------------------------------------------------------===//
3266 // Main entry points.
3267 //
3268 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3269 : Dwarf(OS, A, T)
3270 , shouldEmit(false)
3271 {}
3272
3273 virtual ~DwarfException() {}
3274
3275 /// SetModuleInfo - Set machine module information when it's known that pass
3276 /// manager has created it. Set by the target AsmPrinter.
3277 void SetModuleInfo(MachineModuleInfo *mmi) {
3278 MMI = mmi;
3279 }
3280
3281 /// BeginModule - Emit all exception information that should come prior to the
3282 /// content.
3283 void BeginModule(Module *M) {
3284 this->M = M;
3285 }
3286
3287 /// EndModule - Emit all exception information that should come after the
3288 /// content.
3289 void EndModule() {
3290 if (!shouldEmit) return;
3291
3292 const std::vector<Function *> Personalities = MMI->getPersonalities();
3293 for (unsigned i =0; i < Personalities.size(); ++i)
3294 EmitCommonEHFrame(Personalities[i], i);
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00003295
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3297 E = EHFrames.end(); I != E; ++I)
3298 EmitEHFrame(*I);
3299 }
3300
3301 /// BeginFunction - Gather pre-function exception information. Assumes being
3302 /// emitted immediately after the function entry point.
3303 void BeginFunction(MachineFunction *MF) {
3304 this->MF = MF;
3305
3306 if (MMI &&
3307 ExceptionHandling &&
3308 TAI->doesSupportExceptionHandling()) {
3309 shouldEmit = true;
3310 // Assumes in correct section after the entry point.
3311 EmitLabel("eh_func_begin", ++SubprogramCount);
3312 }
3313 }
3314
3315 /// EndFunction - Gather and emit post-function exception information.
3316 ///
3317 void EndFunction() {
3318 if (!shouldEmit) return;
3319
3320 EmitLabel("eh_func_end", SubprogramCount);
3321 EmitExceptionTable();
3322
3323 // Save EH frame information
3324 EHFrames.push_back(FunctionEHFrameInfo(getAsm()->CurrentFnName,
3325 SubprogramCount,
3326 MMI->getPersonalityIndex(),
3327 MF->getFrameInfo()->hasCalls(),
3328 !MMI->getLandingPads().empty(),
3329 MMI->getFrameMoves()));
3330 }
3331};
3332
3333} // End of namespace llvm
3334
3335//===----------------------------------------------------------------------===//
3336
3337/// Emit - Print the abbreviation using the specified Dwarf writer.
3338///
3339void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3340 // Emit its Dwarf tag type.
3341 DD.getAsm()->EmitULEB128Bytes(Tag);
3342 DD.getAsm()->EOL(TagString(Tag));
3343
3344 // Emit whether it has children DIEs.
3345 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3346 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3347
3348 // For each attribute description.
3349 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3350 const DIEAbbrevData &AttrData = Data[i];
3351
3352 // Emit attribute type.
3353 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3354 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3355
3356 // Emit form type.
3357 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3358 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3359 }
3360
3361 // Mark end of abbreviation.
3362 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3363 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3364}
3365
3366#ifndef NDEBUG
3367void DIEAbbrev::print(std::ostream &O) {
3368 O << "Abbreviation @"
3369 << std::hex << (intptr_t)this << std::dec
3370 << " "
3371 << TagString(Tag)
3372 << " "
3373 << ChildrenString(ChildrenFlag)
3374 << "\n";
3375
3376 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3377 O << " "
3378 << AttributeString(Data[i].getAttribute())
3379 << " "
3380 << FormEncodingString(Data[i].getForm())
3381 << "\n";
3382 }
3383}
3384void DIEAbbrev::dump() { print(cerr); }
3385#endif
3386
3387//===----------------------------------------------------------------------===//
3388
3389#ifndef NDEBUG
3390void DIEValue::dump() {
3391 print(cerr);
3392}
3393#endif
3394
3395//===----------------------------------------------------------------------===//
3396
3397/// EmitValue - Emit integer of appropriate size.
3398///
3399void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3400 switch (Form) {
3401 case DW_FORM_flag: // Fall thru
3402 case DW_FORM_ref1: // Fall thru
3403 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3404 case DW_FORM_ref2: // Fall thru
3405 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3406 case DW_FORM_ref4: // Fall thru
3407 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3408 case DW_FORM_ref8: // Fall thru
3409 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3410 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3411 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3412 default: assert(0 && "DIE Value form not supported yet"); break;
3413 }
3414}
3415
3416/// SizeOf - Determine size of integer value in bytes.
3417///
3418unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3419 switch (Form) {
3420 case DW_FORM_flag: // Fall thru
3421 case DW_FORM_ref1: // Fall thru
3422 case DW_FORM_data1: return sizeof(int8_t);
3423 case DW_FORM_ref2: // Fall thru
3424 case DW_FORM_data2: return sizeof(int16_t);
3425 case DW_FORM_ref4: // Fall thru
3426 case DW_FORM_data4: return sizeof(int32_t);
3427 case DW_FORM_ref8: // Fall thru
3428 case DW_FORM_data8: return sizeof(int64_t);
3429 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3430 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3431 default: assert(0 && "DIE Value form not supported yet"); break;
3432 }
3433 return 0;
3434}
3435
3436//===----------------------------------------------------------------------===//
3437
3438/// EmitValue - Emit string value.
3439///
3440void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3441 DD.getAsm()->EmitString(String);
3442}
3443
3444//===----------------------------------------------------------------------===//
3445
3446/// EmitValue - Emit label value.
3447///
3448void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3449 DD.EmitReference(Label);
3450}
3451
3452/// SizeOf - Determine size of label value in bytes.
3453///
3454unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3455 return DD.getTargetAsmInfo()->getAddressSize();
3456}
3457
3458//===----------------------------------------------------------------------===//
3459
3460/// EmitValue - Emit label value.
3461///
3462void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3463 DD.EmitReference(Label);
3464}
3465
3466/// SizeOf - Determine size of label value in bytes.
3467///
3468unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3469 return DD.getTargetAsmInfo()->getAddressSize();
3470}
3471
3472//===----------------------------------------------------------------------===//
3473
3474/// EmitValue - Emit delta value.
3475///
3476void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3477 bool IsSmall = Form == DW_FORM_data4;
3478 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3479}
3480
3481/// SizeOf - Determine size of delta value in bytes.
3482///
3483unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3484 if (Form == DW_FORM_data4) return 4;
3485 return DD.getTargetAsmInfo()->getAddressSize();
3486}
3487
3488//===----------------------------------------------------------------------===//
3489
3490/// EmitValue - Emit debug information entry offset.
3491///
3492void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3493 DD.getAsm()->EmitInt32(Entry->getOffset());
3494}
3495
3496//===----------------------------------------------------------------------===//
3497
3498/// ComputeSize - calculate the size of the block.
3499///
3500unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3501 if (!Size) {
3502 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3503
3504 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3505 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3506 }
3507 }
3508 return Size;
3509}
3510
3511/// EmitValue - Emit block data.
3512///
3513void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3514 switch (Form) {
3515 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3516 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3517 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3518 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3519 default: assert(0 && "Improper form for block"); break;
3520 }
3521
3522 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3523
3524 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3525 DD.getAsm()->EOL();
3526 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3527 }
3528}
3529
3530/// SizeOf - Determine size of block data in bytes.
3531///
3532unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3533 switch (Form) {
3534 case DW_FORM_block1: return Size + sizeof(int8_t);
3535 case DW_FORM_block2: return Size + sizeof(int16_t);
3536 case DW_FORM_block4: return Size + sizeof(int32_t);
3537 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3538 default: assert(0 && "Improper form for block"); break;
3539 }
3540 return 0;
3541}
3542
3543//===----------------------------------------------------------------------===//
3544/// DIE Implementation
3545
3546DIE::~DIE() {
3547 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3548 delete Children[i];
3549}
3550
3551/// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3552///
3553void DIE::AddSiblingOffset() {
3554 DIEInteger *DI = new DIEInteger(0);
3555 Values.insert(Values.begin(), DI);
3556 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3557}
3558
3559/// Profile - Used to gather unique data for the value folding set.
3560///
3561void DIE::Profile(FoldingSetNodeID &ID) {
3562 Abbrev.Profile(ID);
3563
3564 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3565 ID.AddPointer(Children[i]);
3566
3567 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3568 ID.AddPointer(Values[j]);
3569}
3570
3571#ifndef NDEBUG
3572void DIE::print(std::ostream &O, unsigned IncIndent) {
3573 static unsigned IndentCount = 0;
3574 IndentCount += IncIndent;
3575 const std::string Indent(IndentCount, ' ');
3576 bool isBlock = Abbrev.getTag() == 0;
3577
3578 if (!isBlock) {
3579 O << Indent
3580 << "Die: "
3581 << "0x" << std::hex << (intptr_t)this << std::dec
3582 << ", Offset: " << Offset
3583 << ", Size: " << Size
3584 << "\n";
3585
3586 O << Indent
3587 << TagString(Abbrev.getTag())
3588 << " "
3589 << ChildrenString(Abbrev.getChildrenFlag());
3590 } else {
3591 O << "Size: " << Size;
3592 }
3593 O << "\n";
3594
3595 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3596
3597 IndentCount += 2;
3598 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3599 O << Indent;
3600 if (!isBlock) {
3601 O << AttributeString(Data[i].getAttribute());
3602 } else {
3603 O << "Blk[" << i << "]";
3604 }
3605 O << " "
3606 << FormEncodingString(Data[i].getForm())
3607 << " ";
3608 Values[i]->print(O);
3609 O << "\n";
3610 }
3611 IndentCount -= 2;
3612
3613 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3614 Children[j]->print(O, 4);
3615 }
3616
3617 if (!isBlock) O << "\n";
3618 IndentCount -= IncIndent;
3619}
3620
3621void DIE::dump() {
3622 print(cerr);
3623}
3624#endif
3625
3626//===----------------------------------------------------------------------===//
3627/// DwarfWriter Implementation
3628///
3629
3630DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3631 const TargetAsmInfo *T) {
3632 DE = new DwarfException(OS, A, T);
3633 DD = new DwarfDebug(OS, A, T);
3634}
3635
3636DwarfWriter::~DwarfWriter() {
3637 delete DE;
3638 delete DD;
3639}
3640
3641/// SetModuleInfo - Set machine module info when it's known that pass manager
3642/// has created it. Set by the target AsmPrinter.
3643void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3644 DD->SetModuleInfo(MMI);
3645 DE->SetModuleInfo(MMI);
3646}
3647
3648/// BeginModule - Emit all Dwarf sections that should come prior to the
3649/// content.
3650void DwarfWriter::BeginModule(Module *M) {
3651 DE->BeginModule(M);
3652 DD->BeginModule(M);
3653}
3654
3655/// EndModule - Emit all Dwarf sections that should come after the content.
3656///
3657void DwarfWriter::EndModule() {
3658 DE->EndModule();
3659 DD->EndModule();
3660}
3661
3662/// BeginFunction - Gather pre-function debug information. Assumes being
3663/// emitted immediately after the function entry point.
3664void DwarfWriter::BeginFunction(MachineFunction *MF) {
3665 DE->BeginFunction(MF);
3666 DD->BeginFunction(MF);
3667}
3668
3669/// EndFunction - Gather and emit post-function debug information.
3670///
3671void DwarfWriter::EndFunction() {
3672 DD->EndFunction();
3673 DE->EndFunction();
3674
3675 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3676 // Clear function debug information.
3677 MMI->EndFunction();
3678 }
3679}