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