blob: 8cc7f30979b8e9d5d81667b82d35a04bac883216 [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//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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"
Dan Gohman1e57df32008-02-10 18:45:23 +000033#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#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.
Dan Gohman1e57df32008-02-10 18:45:23 +0000785 const TargetRegisterInfo *RI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786
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; }
Dan Gohmancfb72b22007-09-27 23:12:31 +0000832 const TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000834 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
835 const {
836 if (isInSection && TAI->getDwarfSectionOffsetDirective())
837 O << TAI->getDwarfSectionOffsetDirective();
Dan Gohmancfb72b22007-09-27 23:12:31 +0000838 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000839 O << TAI->getData32bitsDirective();
840 else
841 O << TAI->getData64bitsDirective();
842 }
843
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 /// PrintLabelName - Print label name in form used by Dwarf writer.
845 ///
846 void PrintLabelName(DWLabel Label) const {
847 PrintLabelName(Label.Tag, Label.Number);
848 }
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000849 void PrintLabelName(const char *Tag, unsigned Number) const {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000850 O << TAI->getPrivateGlobalPrefix() << Tag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 if (Number) O << Number;
852 }
853
Chris Lattnerb3876c72007-09-24 03:35:37 +0000854 void PrintLabelName(const char *Tag, unsigned Number,
855 const char *Suffix) const {
856 O << TAI->getPrivateGlobalPrefix() << Tag;
857 if (Number) O << Number;
858 O << Suffix;
859 }
860
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 /// EmitLabel - Emit location label for internal use by Dwarf.
862 ///
863 void EmitLabel(DWLabel Label) const {
864 EmitLabel(Label.Tag, Label.Number);
865 }
866 void EmitLabel(const char *Tag, unsigned Number) const {
867 PrintLabelName(Tag, Number);
868 O << ":\n";
869 }
870
871 /// EmitReference - Emit a reference to a label.
872 ///
Dan Gohman4fd77742007-09-28 15:43:33 +0000873 void EmitReference(DWLabel Label, bool IsPCRelative = false,
874 bool Force32Bit = false) const {
875 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876 }
877 void EmitReference(const char *Tag, unsigned Number,
Dan Gohman4fd77742007-09-28 15:43:33 +0000878 bool IsPCRelative = false, bool Force32Bit = false) const {
879 PrintRelDirective(Force32Bit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 PrintLabelName(Tag, Number);
881
882 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
883 }
Dan Gohman4fd77742007-09-28 15:43:33 +0000884 void EmitReference(const std::string &Name, bool IsPCRelative = false,
885 bool Force32Bit = false) const {
886 PrintRelDirective(Force32Bit);
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000887
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 O << Name;
889
890 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
891 }
892
893 /// EmitDifference - Emit the difference between two labels. Some
894 /// assemblers do not behave with absolute expressions with data directives,
895 /// so there is an option (needsSet) to use an intermediary set expression.
896 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
897 bool IsSmall = false) {
898 EmitDifference(LabelHi.Tag, LabelHi.Number,
899 LabelLo.Tag, LabelLo.Number,
900 IsSmall);
901 }
902 void EmitDifference(const char *TagHi, unsigned NumberHi,
903 const char *TagLo, unsigned NumberLo,
904 bool IsSmall = false) {
905 if (TAI->needsSet()) {
906 O << "\t.set\t";
Chris Lattnerb3876c72007-09-24 03:35:37 +0000907 PrintLabelName("set", SetCounter, Flavor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 O << ",";
909 PrintLabelName(TagHi, NumberHi);
910 O << "-";
911 PrintLabelName(TagLo, NumberLo);
912 O << "\n";
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000913
914 PrintRelDirective(IsSmall);
Chris Lattnerb3876c72007-09-24 03:35:37 +0000915 PrintLabelName("set", SetCounter, Flavor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 ++SetCounter;
917 } else {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000918 PrintRelDirective(IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919
920 PrintLabelName(TagHi, NumberHi);
921 O << "-";
922 PrintLabelName(TagLo, NumberLo);
923 }
924 }
925
926 void EmitSectionOffset(const char* Label, const char* Section,
927 unsigned LabelNumber, unsigned SectionNumber,
928 bool IsSmall = false, bool isEH = false) {
929 bool printAbsolute = false;
930 if (TAI->needsSet()) {
931 O << "\t.set\t";
Chris Lattnerb3876c72007-09-24 03:35:37 +0000932 PrintLabelName("set", SetCounter, Flavor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933 O << ",";
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000934 PrintLabelName(Label, LabelNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935
936 if (isEH)
937 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
938 else
939 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
940
941 if (!printAbsolute) {
942 O << "-";
943 PrintLabelName(Section, SectionNumber);
944 }
945 O << "\n";
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000946
947 PrintRelDirective(IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
Chris Lattnerb3876c72007-09-24 03:35:37 +0000949 PrintLabelName("set", SetCounter, Flavor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950 ++SetCounter;
951 } else {
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000952 PrintRelDirective(IsSmall, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953
Anton Korobeynikov5ef86702007-09-02 22:07:21 +0000954 PrintLabelName(Label, LabelNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955
956 if (isEH)
957 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
958 else
959 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
960
961 if (!printAbsolute) {
962 O << "-";
963 PrintLabelName(Section, SectionNumber);
964 }
965 }
966 }
967
968 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
969 /// frame.
970 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
Dale Johannesenf5a11532007-11-13 19:13:01 +0000971 const std::vector<MachineMove> &Moves, bool isEH) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 int stackGrowth =
973 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
974 TargetFrameInfo::StackGrowsUp ?
Dan Gohmancfb72b22007-09-27 23:12:31 +0000975 TD->getPointerSize() : -TD->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
977
978 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
979 const MachineMove &Move = Moves[i];
980 unsigned LabelID = Move.getLabelID();
981
982 if (LabelID) {
983 LabelID = MMI->MappedLabel(LabelID);
984
985 // Throw out move if the label is invalid.
986 if (!LabelID) continue;
987 }
988
989 const MachineLocation &Dst = Move.getDestination();
990 const MachineLocation &Src = Move.getSource();
991
992 // Advance row if new location.
993 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
994 Asm->EmitInt8(DW_CFA_advance_loc4);
995 Asm->EOL("DW_CFA_advance_loc4");
996 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
997 Asm->EOL();
998
999 BaseLabelID = LabelID;
1000 BaseLabel = "label";
1001 IsLocal = true;
1002 }
1003
1004 // If advancing cfa.
1005 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1006 if (!Src.isRegister()) {
1007 if (Src.getRegister() == MachineLocation::VirtualFP) {
1008 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1009 Asm->EOL("DW_CFA_def_cfa_offset");
1010 } else {
1011 Asm->EmitInt8(DW_CFA_def_cfa);
1012 Asm->EOL("DW_CFA_def_cfa");
Dale Johannesenf5a11532007-11-13 19:13:01 +00001013 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister(), isEH));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 Asm->EOL("Register");
1015 }
1016
1017 int Offset = -Src.getOffset();
1018
1019 Asm->EmitULEB128Bytes(Offset);
1020 Asm->EOL("Offset");
1021 } else {
1022 assert(0 && "Machine move no supported yet.");
1023 }
1024 } else if (Src.isRegister() &&
1025 Src.getRegister() == MachineLocation::VirtualFP) {
1026 if (Dst.isRegister()) {
1027 Asm->EmitInt8(DW_CFA_def_cfa_register);
1028 Asm->EOL("DW_CFA_def_cfa_register");
Dale Johannesenf5a11532007-11-13 19:13:01 +00001029 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister(), isEH));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 Asm->EOL("Register");
1031 } else {
1032 assert(0 && "Machine move no supported yet.");
1033 }
1034 } else {
Dale Johannesenf5a11532007-11-13 19:13:01 +00001035 unsigned Reg = RI->getDwarfRegNum(Src.getRegister(), isEH);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 int Offset = Dst.getOffset() / stackGrowth;
1037
1038 if (Offset < 0) {
1039 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1040 Asm->EOL("DW_CFA_offset_extended_sf");
1041 Asm->EmitULEB128Bytes(Reg);
1042 Asm->EOL("Reg");
1043 Asm->EmitSLEB128Bytes(Offset);
1044 Asm->EOL("Offset");
1045 } else if (Reg < 64) {
1046 Asm->EmitInt8(DW_CFA_offset + Reg);
Anton Korobeynikovc6449f12007-07-25 00:06:28 +00001047 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 Asm->EmitULEB128Bytes(Offset);
1049 Asm->EOL("Offset");
1050 } else {
1051 Asm->EmitInt8(DW_CFA_offset_extended);
1052 Asm->EOL("DW_CFA_offset_extended");
1053 Asm->EmitULEB128Bytes(Reg);
1054 Asm->EOL("Reg");
1055 Asm->EmitULEB128Bytes(Offset);
1056 Asm->EOL("Offset");
1057 }
1058 }
1059 }
1060 }
1061
1062};
1063
1064//===----------------------------------------------------------------------===//
1065/// DwarfDebug - Emits Dwarf debug directives.
1066///
1067class DwarfDebug : public Dwarf {
1068
1069private:
1070 //===--------------------------------------------------------------------===//
1071 // Attributes used to construct specific Dwarf sections.
1072 //
1073
1074 /// CompileUnits - All the compile units involved in this build. The index
1075 /// of each entry in this vector corresponds to the sources in MMI.
1076 std::vector<CompileUnit *> CompileUnits;
1077
1078 /// AbbreviationsSet - Used to uniquely define abbreviations.
1079 ///
1080 FoldingSet<DIEAbbrev> AbbreviationsSet;
1081
1082 /// Abbreviations - A list of all the unique abbreviations in use.
1083 ///
1084 std::vector<DIEAbbrev *> Abbreviations;
1085
1086 /// ValuesSet - Used to uniquely define values.
1087 ///
1088 FoldingSet<DIEValue> ValuesSet;
1089
1090 /// Values - A list of all the unique values in use.
1091 ///
1092 std::vector<DIEValue *> Values;
1093
1094 /// StringPool - A UniqueVector of strings used by indirect references.
1095 ///
1096 UniqueVector<std::string> StringPool;
1097
1098 /// UnitMap - Map debug information descriptor to compile unit.
1099 ///
1100 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1101
1102 /// SectionMap - Provides a unique id per text section.
1103 ///
1104 UniqueVector<std::string> SectionMap;
1105
1106 /// SectionSourceLines - Tracks line numbers per text section.
1107 ///
1108 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1109
1110 /// didInitial - Flag to indicate if initial emission has been done.
1111 ///
1112 bool didInitial;
1113
1114 /// shouldEmit - Flag to indicate if debug information should be emitted.
1115 ///
1116 bool shouldEmit;
1117
1118 struct FunctionDebugFrameInfo {
1119 unsigned Number;
1120 std::vector<MachineMove> Moves;
1121
1122 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
Dan Gohman9ba5d4d2007-08-27 14:50:10 +00001123 Number(Num), Moves(M) { }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 };
1125
1126 std::vector<FunctionDebugFrameInfo> DebugFrames;
1127
1128public:
1129
1130 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1131 ///
1132 bool ShouldEmitDwarf() const { return shouldEmit; }
1133
1134 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1135 ///
1136 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1137 // Profile the node so that we can make it unique.
1138 FoldingSetNodeID ID;
1139 Abbrev.Profile(ID);
1140
1141 // Check the set for priors.
1142 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1143
1144 // If it's newly added.
1145 if (InSet == &Abbrev) {
1146 // Add to abbreviation list.
1147 Abbreviations.push_back(&Abbrev);
1148 // Assign the vector position + 1 as its number.
1149 Abbrev.setNumber(Abbreviations.size());
1150 } else {
1151 // Assign existing abbreviation number.
1152 Abbrev.setNumber(InSet->getNumber());
1153 }
1154 }
1155
1156 /// NewString - Add a string to the constant pool and returns a label.
1157 ///
1158 DWLabel NewString(const std::string &String) {
1159 unsigned StringID = StringPool.insert(String);
1160 return DWLabel("string", StringID);
1161 }
1162
1163 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1164 /// entry.
1165 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1166 DIEntry *Value;
1167
1168 if (Entry) {
1169 FoldingSetNodeID ID;
1170 DIEntry::Profile(ID, Entry);
1171 void *Where;
1172 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1173
1174 if (Value) return Value;
1175
1176 Value = new DIEntry(Entry);
1177 ValuesSet.InsertNode(Value, Where);
1178 } else {
1179 Value = new DIEntry(Entry);
1180 }
1181
1182 Values.push_back(Value);
1183 return Value;
1184 }
1185
1186 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1187 ///
1188 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1189 Value->Entry = Entry;
1190 // Add to values set if not already there. If it is, we merely have a
1191 // duplicate in the values list (no harm.)
1192 ValuesSet.GetOrInsertNode(Value);
1193 }
1194
1195 /// AddUInt - Add an unsigned integer attribute data and value.
1196 ///
1197 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1198 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1199
1200 FoldingSetNodeID ID;
1201 DIEInteger::Profile(ID, Integer);
1202 void *Where;
1203 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1204 if (!Value) {
1205 Value = new DIEInteger(Integer);
1206 ValuesSet.InsertNode(Value, Where);
1207 Values.push_back(Value);
1208 }
1209
1210 Die->AddValue(Attribute, Form, Value);
1211 }
1212
1213 /// AddSInt - Add an signed integer attribute data and value.
1214 ///
1215 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1216 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1217
1218 FoldingSetNodeID ID;
1219 DIEInteger::Profile(ID, (uint64_t)Integer);
1220 void *Where;
1221 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1222 if (!Value) {
1223 Value = new DIEInteger(Integer);
1224 ValuesSet.InsertNode(Value, Where);
1225 Values.push_back(Value);
1226 }
1227
1228 Die->AddValue(Attribute, Form, Value);
1229 }
1230
1231 /// AddString - Add a std::string attribute data and value.
1232 ///
1233 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1234 const std::string &String) {
1235 FoldingSetNodeID ID;
1236 DIEString::Profile(ID, String);
1237 void *Where;
1238 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1239 if (!Value) {
1240 Value = new DIEString(String);
1241 ValuesSet.InsertNode(Value, Where);
1242 Values.push_back(Value);
1243 }
1244
1245 Die->AddValue(Attribute, Form, Value);
1246 }
1247
1248 /// AddLabel - Add a Dwarf label attribute data and value.
1249 ///
1250 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1251 const DWLabel &Label) {
1252 FoldingSetNodeID ID;
1253 DIEDwarfLabel::Profile(ID, Label);
1254 void *Where;
1255 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1256 if (!Value) {
1257 Value = new DIEDwarfLabel(Label);
1258 ValuesSet.InsertNode(Value, Where);
1259 Values.push_back(Value);
1260 }
1261
1262 Die->AddValue(Attribute, Form, Value);
1263 }
1264
1265 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1266 ///
1267 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1268 const std::string &Label) {
1269 FoldingSetNodeID ID;
1270 DIEObjectLabel::Profile(ID, Label);
1271 void *Where;
1272 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1273 if (!Value) {
1274 Value = new DIEObjectLabel(Label);
1275 ValuesSet.InsertNode(Value, Where);
1276 Values.push_back(Value);
1277 }
1278
1279 Die->AddValue(Attribute, Form, Value);
1280 }
1281
1282 /// AddDelta - Add a label delta attribute data and value.
1283 ///
1284 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1285 const DWLabel &Hi, const DWLabel &Lo) {
1286 FoldingSetNodeID ID;
1287 DIEDelta::Profile(ID, Hi, Lo);
1288 void *Where;
1289 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1290 if (!Value) {
1291 Value = new DIEDelta(Hi, Lo);
1292 ValuesSet.InsertNode(Value, Where);
1293 Values.push_back(Value);
1294 }
1295
1296 Die->AddValue(Attribute, Form, Value);
1297 }
1298
1299 /// AddDIEntry - Add a DIE attribute data and value.
1300 ///
1301 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1302 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1303 }
1304
1305 /// AddBlock - Add block data.
1306 ///
1307 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1308 Block->ComputeSize(*this);
1309 FoldingSetNodeID ID;
1310 Block->Profile(ID);
1311 void *Where;
1312 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1313 if (!Value) {
1314 Value = Block;
1315 ValuesSet.InsertNode(Value, Where);
1316 Values.push_back(Value);
1317 } else {
Chris Lattner3de66892007-09-21 18:25:53 +00001318 // Already exists, reuse the previous one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 delete Block;
Chris Lattner3de66892007-09-21 18:25:53 +00001320 Block = cast<DIEBlock>(Value);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 }
1322
1323 Die->AddValue(Attribute, Block->BestForm(), Value);
1324 }
1325
1326private:
1327
1328 /// AddSourceLine - Add location information to specified debug information
1329 /// entry.
1330 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1331 if (File && Line) {
1332 CompileUnit *FileUnit = FindCompileUnit(File);
1333 unsigned FileID = FileUnit->getID();
1334 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1335 AddUInt(Die, DW_AT_decl_line, 0, Line);
1336 }
1337 }
1338
1339 /// AddAddress - Add an address attribute to a die based on the location
1340 /// provided.
1341 void AddAddress(DIE *Die, unsigned Attribute,
1342 const MachineLocation &Location) {
Dale Johannesenf5a11532007-11-13 19:13:01 +00001343 unsigned Reg = RI->getDwarfRegNum(Location.getRegister(), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 DIEBlock *Block = new DIEBlock();
1345
1346 if (Location.isRegister()) {
1347 if (Reg < 32) {
1348 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1349 } else {
1350 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1351 AddUInt(Block, 0, DW_FORM_udata, Reg);
1352 }
1353 } else {
1354 if (Reg < 32) {
1355 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1356 } else {
1357 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1358 AddUInt(Block, 0, DW_FORM_udata, Reg);
1359 }
1360 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1361 }
1362
1363 AddBlock(Die, Attribute, 0, Block);
1364 }
1365
1366 /// AddBasicType - Add a new basic type attribute to the specified entity.
1367 ///
1368 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1369 const std::string &Name,
1370 unsigned Encoding, unsigned Size) {
1371 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1372 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1373 }
1374
1375 /// ConstructBasicType - Construct a new basic type.
1376 ///
1377 DIE *ConstructBasicType(CompileUnit *Unit,
1378 const std::string &Name,
1379 unsigned Encoding, unsigned Size) {
1380 DIE Buffer(DW_TAG_base_type);
1381 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1382 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1383 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1384 return Unit->AddDie(Buffer);
1385 }
1386
1387 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1388 ///
1389 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1390 DIE *Die = ConstructPointerType(Unit, Name);
1391 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1392 }
1393
1394 /// ConstructPointerType - Construct a new pointer type.
1395 ///
1396 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1397 DIE Buffer(DW_TAG_pointer_type);
Dan Gohmancfb72b22007-09-27 23:12:31 +00001398 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001399 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1400 return Unit->AddDie(Buffer);
1401 }
1402
1403 /// AddType - Add a new type attribute to the specified entity.
1404 ///
1405 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1406 if (!TyDesc) {
1407 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1408 } else {
1409 // Check for pre-existence.
1410 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1411
1412 // If it exists then use the existing value.
1413 if (Slot) {
1414 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1415 return;
1416 }
1417
1418 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1419 // FIXME - Not sure why programs and variables are coming through here.
1420 // Short cut for handling subprogram types (not really a TyDesc.)
1421 AddPointerType(Entity, Unit, SubprogramTy->getName());
1422 } else if (GlobalVariableDesc *GlobalTy =
1423 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1424 // FIXME - Not sure why programs and variables are coming through here.
1425 // Short cut for handling global variable types (not really a TyDesc.)
1426 AddPointerType(Entity, Unit, GlobalTy->getName());
1427 } else {
1428 // Set up proxy.
1429 Slot = NewDIEntry();
1430
1431 // Construct type.
1432 DIE Buffer(DW_TAG_base_type);
1433 ConstructType(Buffer, TyDesc, Unit);
1434
1435 // Add debug information entry to entity and unit.
1436 DIE *Die = Unit->AddDie(Buffer);
1437 SetDIEntry(Slot, Die);
1438 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1439 }
1440 }
1441 }
1442
1443 /// ConstructType - Adds all the required attributes to the type.
1444 ///
1445 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1446 // Get core information.
1447 const std::string &Name = TyDesc->getName();
1448 uint64_t Size = TyDesc->getSize() >> 3;
1449
1450 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1451 // Fundamental types like int, float, bool
1452 Buffer.setTag(DW_TAG_base_type);
1453 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1454 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1455 // Fetch tag.
1456 unsigned Tag = DerivedTy->getTag();
1457 // FIXME - Workaround for templates.
1458 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1459 // Pointers, typedefs et al.
1460 Buffer.setTag(Tag);
1461 // Map to main type, void will not have a type.
1462 if (TypeDesc *FromTy = DerivedTy->getFromType())
1463 AddType(&Buffer, FromTy, Unit);
1464 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1465 // Fetch tag.
1466 unsigned Tag = CompTy->getTag();
1467
1468 // Set tag accordingly.
1469 if (Tag == DW_TAG_vector_type)
1470 Buffer.setTag(DW_TAG_array_type);
1471 else
1472 Buffer.setTag(Tag);
1473
1474 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1475
1476 switch (Tag) {
1477 case DW_TAG_vector_type:
1478 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1479 // Fall thru
1480 case DW_TAG_array_type: {
1481 // Add element type.
1482 if (TypeDesc *FromTy = CompTy->getFromType())
1483 AddType(&Buffer, FromTy, Unit);
1484
1485 // Don't emit size attribute.
1486 Size = 0;
1487
1488 // Construct an anonymous type for index type.
1489 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1490 sizeof(int32_t));
1491
1492 // Add subranges to array type.
1493 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1494 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1495 int64_t Lo = SRD->getLo();
1496 int64_t Hi = SRD->getHi();
1497 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1498
1499 // If a range is available.
1500 if (Lo != Hi) {
1501 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1502 // Only add low if non-zero.
1503 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1504 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1505 }
1506
1507 Buffer.AddChild(Subrange);
1508 }
1509 break;
1510 }
1511 case DW_TAG_structure_type:
1512 case DW_TAG_union_type: {
1513 // Add elements to structure type.
1514 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1515 DebugInfoDesc *Element = Elements[i];
1516
1517 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1518 // Add field or base class.
1519
1520 unsigned Tag = MemberDesc->getTag();
1521
1522 // Extract the basic information.
1523 const std::string &Name = MemberDesc->getName();
1524 uint64_t Size = MemberDesc->getSize();
1525 uint64_t Align = MemberDesc->getAlign();
1526 uint64_t Offset = MemberDesc->getOffset();
1527
1528 // Construct member debug information entry.
1529 DIE *Member = new DIE(Tag);
1530
1531 // Add name if not "".
1532 if (!Name.empty())
1533 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1534 // Add location if available.
1535 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1536
1537 // Most of the time the field info is the same as the members.
1538 uint64_t FieldSize = Size;
1539 uint64_t FieldAlign = Align;
1540 uint64_t FieldOffset = Offset;
1541
1542 // Set the member type.
1543 TypeDesc *FromTy = MemberDesc->getFromType();
1544 AddType(Member, FromTy, Unit);
1545
1546 // Walk up typedefs until a real size is found.
1547 while (FromTy) {
1548 if (FromTy->getTag() != DW_TAG_typedef) {
1549 FieldSize = FromTy->getSize();
1550 FieldAlign = FromTy->getSize();
1551 break;
1552 }
1553
Dan Gohman53491e92007-07-23 20:24:29 +00001554 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555 }
1556
1557 // Unless we have a bit field.
1558 if (Tag == DW_TAG_member && FieldSize != Size) {
1559 // Construct the alignment mask.
1560 uint64_t AlignMask = ~(FieldAlign - 1);
1561 // Determine the high bit + 1 of the declared size.
1562 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1563 // Work backwards to determine the base offset of the field.
1564 FieldOffset = HiMark - FieldSize;
1565 // Now normalize offset to the field.
1566 Offset -= FieldOffset;
1567
1568 // Maybe we need to work from the other end.
1569 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1570
1571 // Add size and offset.
1572 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1573 AddUInt(Member, DW_AT_bit_size, 0, Size);
1574 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1575 }
1576
1577 // Add computation for offset.
1578 DIEBlock *Block = new DIEBlock();
1579 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1580 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1581 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1582
1583 // Add accessibility (public default unless is base class.
1584 if (MemberDesc->isProtected()) {
1585 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1586 } else if (MemberDesc->isPrivate()) {
1587 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1588 } else if (Tag == DW_TAG_inheritance) {
1589 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1590 }
1591
1592 Buffer.AddChild(Member);
1593 } else if (GlobalVariableDesc *StaticDesc =
1594 dyn_cast<GlobalVariableDesc>(Element)) {
1595 // Add static member.
1596
1597 // Construct member debug information entry.
1598 DIE *Static = new DIE(DW_TAG_variable);
1599
1600 // Add name and mangled name.
1601 const std::string &Name = StaticDesc->getName();
1602 const std::string &LinkageName = StaticDesc->getLinkageName();
1603 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1604 if (!LinkageName.empty()) {
1605 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1606 LinkageName);
1607 }
1608
1609 // Add location.
1610 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1611
1612 // Add type.
1613 if (TypeDesc *StaticTy = StaticDesc->getType())
1614 AddType(Static, StaticTy, Unit);
1615
1616 // Add flags.
1617 if (!StaticDesc->isStatic())
1618 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1619 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1620
1621 Buffer.AddChild(Static);
1622 } else if (SubprogramDesc *MethodDesc =
1623 dyn_cast<SubprogramDesc>(Element)) {
1624 // Add member function.
1625
1626 // Construct member debug information entry.
1627 DIE *Method = new DIE(DW_TAG_subprogram);
1628
1629 // Add name and mangled name.
1630 const std::string &Name = MethodDesc->getName();
1631 const std::string &LinkageName = MethodDesc->getLinkageName();
1632
1633 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1634 bool IsCTor = TyDesc->getName() == Name;
1635
1636 if (!LinkageName.empty()) {
1637 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1638 LinkageName);
1639 }
1640
1641 // Add location.
1642 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1643
1644 // Add type.
1645 if (CompositeTypeDesc *MethodTy =
1646 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1647 // Get argument information.
1648 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1649
1650 // If not a ctor.
1651 if (!IsCTor) {
1652 // Add return type.
1653 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1654 }
1655
1656 // Add arguments.
1657 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1658 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1659 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1660 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1661 Method->AddChild(Arg);
1662 }
1663 }
1664
1665 // Add flags.
1666 if (!MethodDesc->isStatic())
1667 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1668 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1669
1670 Buffer.AddChild(Method);
1671 }
1672 }
1673 break;
1674 }
1675 case DW_TAG_enumeration_type: {
1676 // Add enumerators to enumeration type.
1677 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1678 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1679 const std::string &Name = ED->getName();
1680 int64_t Value = ED->getValue();
1681 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1682 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1683 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1684 Buffer.AddChild(Enumerator);
1685 }
1686
1687 break;
1688 }
1689 case DW_TAG_subroutine_type: {
1690 // Add prototype flag.
1691 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1692 // Add return type.
1693 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1694
1695 // Add arguments.
1696 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1697 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1698 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1699 Buffer.AddChild(Arg);
1700 }
1701
1702 break;
1703 }
1704 default: break;
1705 }
1706 }
1707
1708 // Add size if non-zero (derived types don't have a size.)
1709 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1710 // Add name if not anonymous or intermediate type.
1711 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1712 // Add source line info if available.
1713 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1714 }
1715
1716 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1717 ///
1718 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1719 // Construct debug information entry.
1720 DIE *Die = new DIE(DW_TAG_compile_unit);
1721 if (TAI->isAbsoluteDebugSectionOffsets())
1722 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1723 else
1724 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1725 DWLabel("section_line", 0));
1726 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1727 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1728 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1729 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1730
1731 // Construct compile unit.
1732 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1733
1734 // Add Unit to compile unit map.
1735 DescToUnitMap[UnitDesc] = Unit;
1736
1737 return Unit;
1738 }
1739
1740 /// GetBaseCompileUnit - Get the main compile unit.
1741 ///
1742 CompileUnit *GetBaseCompileUnit() const {
1743 CompileUnit *Unit = CompileUnits[0];
1744 assert(Unit && "Missing compile unit.");
1745 return Unit;
1746 }
1747
1748 /// FindCompileUnit - Get the compile unit for the given descriptor.
1749 ///
1750 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1751 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1752 assert(Unit && "Missing compile unit.");
1753 return Unit;
1754 }
1755
1756 /// NewGlobalVariable - Add a new global variable DIE.
1757 ///
1758 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1759 // Get the compile unit context.
1760 CompileUnitDesc *UnitDesc =
1761 static_cast<CompileUnitDesc *>(GVD->getContext());
1762 CompileUnit *Unit = GetBaseCompileUnit();
1763
1764 // Check for pre-existence.
1765 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1766 if (Slot) return Slot;
1767
1768 // Get the global variable itself.
1769 GlobalVariable *GV = GVD->getGlobalVariable();
1770
1771 const std::string &Name = GVD->getName();
1772 const std::string &FullName = GVD->getFullName();
1773 const std::string &LinkageName = GVD->getLinkageName();
1774 // Create the global's variable DIE.
1775 DIE *VariableDie = new DIE(DW_TAG_variable);
1776 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1777 if (!LinkageName.empty()) {
1778 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1779 LinkageName);
1780 }
1781 AddType(VariableDie, GVD->getType(), Unit);
1782 if (!GVD->isStatic())
1783 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1784
1785 // Add source line info if available.
1786 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1787
1788 // Add address.
1789 DIEBlock *Block = new DIEBlock();
1790 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1791 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1792 AddBlock(VariableDie, DW_AT_location, 0, Block);
1793
1794 // Add to map.
1795 Slot = VariableDie;
1796
1797 // Add to context owner.
1798 Unit->getDie()->AddChild(VariableDie);
1799
1800 // Expose as global.
1801 // FIXME - need to check external flag.
1802 Unit->AddGlobal(FullName, VariableDie);
1803
1804 return VariableDie;
1805 }
1806
1807 /// NewSubprogram - Add a new subprogram DIE.
1808 ///
1809 DIE *NewSubprogram(SubprogramDesc *SPD) {
1810 // Get the compile unit context.
1811 CompileUnitDesc *UnitDesc =
1812 static_cast<CompileUnitDesc *>(SPD->getContext());
1813 CompileUnit *Unit = GetBaseCompileUnit();
1814
1815 // Check for pre-existence.
1816 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1817 if (Slot) return Slot;
1818
1819 // Gather the details (simplify add attribute code.)
1820 const std::string &Name = SPD->getName();
1821 const std::string &FullName = SPD->getFullName();
1822 const std::string &LinkageName = SPD->getLinkageName();
1823
1824 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1825 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1826 if (!LinkageName.empty()) {
1827 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1828 LinkageName);
1829 }
1830 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1831 if (!SPD->isStatic())
1832 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1833 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1834
1835 // Add source line info if available.
1836 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1837
1838 // Add to map.
1839 Slot = SubprogramDie;
1840
1841 // Add to context owner.
1842 Unit->getDie()->AddChild(SubprogramDie);
1843
1844 // Expose as global.
1845 Unit->AddGlobal(FullName, SubprogramDie);
1846
1847 return SubprogramDie;
1848 }
1849
1850 /// NewScopeVariable - Create a new scope variable.
1851 ///
1852 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1853 // Get the descriptor.
1854 VariableDesc *VD = DV->getDesc();
1855
1856 // Translate tag to proper Dwarf tag. The result variable is dropped for
1857 // now.
1858 unsigned Tag;
1859 switch (VD->getTag()) {
1860 case DW_TAG_return_variable: return NULL;
1861 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1862 case DW_TAG_auto_variable: // fall thru
1863 default: Tag = DW_TAG_variable; break;
1864 }
1865
1866 // Define variable debug information entry.
1867 DIE *VariableDie = new DIE(Tag);
1868 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1869
1870 // Add source line info if available.
1871 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1872
1873 // Add variable type.
1874 AddType(VariableDie, VD->getType(), Unit);
1875
1876 // Add variable address.
1877 MachineLocation Location;
Evan Cheng38948832008-01-31 03:37:28 +00001878 Location.set(RI->getFrameRegister(*MF),
1879 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 AddAddress(VariableDie, DW_AT_location, Location);
1881
1882 return VariableDie;
1883 }
1884
1885 /// ConstructScope - Construct the components of a scope.
1886 ///
1887 void ConstructScope(DebugScope *ParentScope,
1888 unsigned ParentStartID, unsigned ParentEndID,
1889 DIE *ParentDie, CompileUnit *Unit) {
1890 // Add variables to scope.
1891 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1892 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1893 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1894 if (VariableDie) ParentDie->AddChild(VariableDie);
1895 }
1896
1897 // Add nested scopes.
1898 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1899 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1900 // Define the Scope debug information entry.
1901 DebugScope *Scope = Scopes[j];
1902 // FIXME - Ignore inlined functions for the time being.
1903 if (!Scope->getParent()) continue;
1904
1905 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1906 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1907
1908 // Ignore empty scopes.
1909 if (StartID == EndID && StartID != 0) continue;
1910 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1911
1912 if (StartID == ParentStartID && EndID == ParentEndID) {
1913 // Just add stuff to the parent scope.
1914 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1915 } else {
1916 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1917
1918 // Add the scope bounds.
1919 if (StartID) {
1920 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1921 DWLabel("label", StartID));
1922 } else {
1923 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1924 DWLabel("func_begin", SubprogramCount));
1925 }
1926 if (EndID) {
1927 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1928 DWLabel("label", EndID));
1929 } else {
1930 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1931 DWLabel("func_end", SubprogramCount));
1932 }
1933
1934 // Add the scope contents.
1935 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1936 ParentDie->AddChild(ScopeDie);
1937 }
1938 }
1939 }
1940
1941 /// ConstructRootScope - Construct the scope for the subprogram.
1942 ///
1943 void ConstructRootScope(DebugScope *RootScope) {
1944 // Exit if there is no root scope.
1945 if (!RootScope) return;
1946
1947 // Get the subprogram debug information entry.
1948 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1949
1950 // Get the compile unit context.
1951 CompileUnit *Unit = GetBaseCompileUnit();
1952
1953 // Get the subprogram die.
1954 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1955 assert(SPDie && "Missing subprogram descriptor");
1956
1957 // Add the function bounds.
1958 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1959 DWLabel("func_begin", SubprogramCount));
1960 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1961 DWLabel("func_end", SubprogramCount));
1962 MachineLocation Location(RI->getFrameRegister(*MF));
1963 AddAddress(SPDie, DW_AT_frame_base, Location);
1964
1965 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1966 }
1967
1968 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1969 /// tools to recognize the object file contains Dwarf information.
1970 void EmitInitial() {
1971 // Check to see if we already emitted intial headers.
1972 if (didInitial) return;
1973 didInitial = true;
1974
1975 // Dwarf sections base addresses.
1976 if (TAI->doesDwarfRequireFrameSection()) {
1977 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1978 EmitLabel("section_debug_frame", 0);
1979 }
1980 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1981 EmitLabel("section_info", 0);
1982 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1983 EmitLabel("section_abbrev", 0);
1984 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1985 EmitLabel("section_aranges", 0);
1986 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1987 EmitLabel("section_macinfo", 0);
1988 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1989 EmitLabel("section_line", 0);
1990 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1991 EmitLabel("section_loc", 0);
1992 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1993 EmitLabel("section_pubnames", 0);
1994 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1995 EmitLabel("section_str", 0);
1996 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1997 EmitLabel("section_ranges", 0);
1998
1999 Asm->SwitchToTextSection(TAI->getTextSection());
2000 EmitLabel("text_begin", 0);
2001 Asm->SwitchToDataSection(TAI->getDataSection());
2002 EmitLabel("data_begin", 0);
2003 }
2004
2005 /// EmitDIE - Recusively Emits a debug information entry.
2006 ///
2007 void EmitDIE(DIE *Die) {
2008 // Get the abbreviation for this DIE.
2009 unsigned AbbrevNumber = Die->getAbbrevNumber();
2010 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2011
2012 Asm->EOL();
2013
2014 // Emit the code (index) for the abbreviation.
2015 Asm->EmitULEB128Bytes(AbbrevNumber);
2016 Asm->EOL(std::string("Abbrev [" +
2017 utostr(AbbrevNumber) +
2018 "] 0x" + utohexstr(Die->getOffset()) +
2019 ":0x" + utohexstr(Die->getSize()) + " " +
2020 TagString(Abbrev->getTag())));
2021
2022 std::vector<DIEValue *> &Values = Die->getValues();
2023 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2024
2025 // Emit the DIE attribute values.
2026 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2027 unsigned Attr = AbbrevData[i].getAttribute();
2028 unsigned Form = AbbrevData[i].getForm();
2029 assert(Form && "Too many attributes for DIE (check abbreviation)");
2030
2031 switch (Attr) {
2032 case DW_AT_sibling: {
2033 Asm->EmitInt32(Die->SiblingOffset());
2034 break;
2035 }
2036 default: {
2037 // Emit an attribute using the defined form.
2038 Values[i]->EmitValue(*this, Form);
2039 break;
2040 }
2041 }
2042
2043 Asm->EOL(AttributeString(Attr));
2044 }
2045
2046 // Emit the DIE children if any.
2047 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2048 const std::vector<DIE *> &Children = Die->getChildren();
2049
2050 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2051 EmitDIE(Children[j]);
2052 }
2053
2054 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2055 }
2056 }
2057
2058 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2059 ///
2060 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2061 // Get the children.
2062 const std::vector<DIE *> &Children = Die->getChildren();
2063
2064 // If not last sibling and has children then add sibling offset attribute.
2065 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2066
2067 // Record the abbreviation.
2068 AssignAbbrevNumber(Die->getAbbrev());
2069
2070 // Get the abbreviation for this DIE.
2071 unsigned AbbrevNumber = Die->getAbbrevNumber();
2072 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2073
2074 // Set DIE offset
2075 Die->setOffset(Offset);
2076
2077 // Start the size with the size of abbreviation code.
2078 Offset += Asm->SizeULEB128(AbbrevNumber);
2079
2080 const std::vector<DIEValue *> &Values = Die->getValues();
2081 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2082
2083 // Size the DIE attribute values.
2084 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2085 // Size attribute value.
2086 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2087 }
2088
2089 // Size the DIE children if any.
2090 if (!Children.empty()) {
2091 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2092 "Children flag not set");
2093
2094 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2095 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2096 }
2097
2098 // End of children marker.
2099 Offset += sizeof(int8_t);
2100 }
2101
2102 Die->setSize(Offset - Die->getOffset());
2103 return Offset;
2104 }
2105
2106 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2107 ///
2108 void SizeAndOffsets() {
2109 // Process base compile unit.
2110 CompileUnit *Unit = GetBaseCompileUnit();
2111 // Compute size of compile unit header
2112 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2113 sizeof(int16_t) + // DWARF version number
2114 sizeof(int32_t) + // Offset Into Abbrev. Section
2115 sizeof(int8_t); // Pointer Size (in bytes)
2116 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2117 }
2118
2119 /// EmitDebugInfo - Emit the debug info section.
2120 ///
2121 void EmitDebugInfo() {
2122 // Start debug info section.
2123 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2124
2125 CompileUnit *Unit = GetBaseCompileUnit();
2126 DIE *Die = Unit->getDie();
2127 // Emit the compile units header.
2128 EmitLabel("info_begin", Unit->getID());
2129 // Emit size of content not including length itself
2130 unsigned ContentSize = Die->getSize() +
2131 sizeof(int16_t) + // DWARF version number
2132 sizeof(int32_t) + // Offset Into Abbrev. Section
2133 sizeof(int8_t) + // Pointer Size (in bytes)
2134 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2135
2136 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2137 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2138 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2139 Asm->EOL("Offset Into Abbrev. Section");
Dan Gohmancfb72b22007-09-27 23:12:31 +00002140 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141
2142 EmitDIE(Die);
2143 // FIXME - extra padding for gdb bug.
2144 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2145 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2146 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2147 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2148 EmitLabel("info_end", Unit->getID());
2149
2150 Asm->EOL();
2151 }
2152
2153 /// EmitAbbreviations - Emit the abbreviation section.
2154 ///
2155 void EmitAbbreviations() const {
2156 // Check to see if it is worth the effort.
2157 if (!Abbreviations.empty()) {
2158 // Start the debug abbrev section.
2159 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2160
2161 EmitLabel("abbrev_begin", 0);
2162
2163 // For each abbrevation.
2164 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2165 // Get abbreviation data
2166 const DIEAbbrev *Abbrev = Abbreviations[i];
2167
2168 // Emit the abbrevations code (base 1 index.)
2169 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2170 Asm->EOL("Abbreviation Code");
2171
2172 // Emit the abbreviations data.
2173 Abbrev->Emit(*this);
2174
2175 Asm->EOL();
2176 }
2177
2178 // Mark end of abbreviations.
2179 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2180
2181 EmitLabel("abbrev_end", 0);
2182
2183 Asm->EOL();
2184 }
2185 }
2186
2187 /// EmitDebugLines - Emit source line information.
2188 ///
2189 void EmitDebugLines() {
Dan Gohmanc55b34a2007-09-24 21:43:52 +00002190 // If there are no lines to emit (such as when we're using .loc directives
2191 // to emit .debug_line information) don't emit a .debug_line header.
2192 if (SectionSourceLines.empty())
2193 return;
2194
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002195 // Minimum line delta, thus ranging from -10..(255-10).
2196 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2197 // Maximum line delta, thus ranging from -10..(255-10).
2198 const int MaxLineDelta = 255 + MinLineDelta;
2199
2200 // Start the dwarf line section.
2201 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2202
2203 // Construct the section header.
2204
2205 EmitDifference("line_end", 0, "line_begin", 0, true);
2206 Asm->EOL("Length of Source Line Info");
2207 EmitLabel("line_begin", 0);
2208
2209 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2210
2211 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2212 Asm->EOL("Prolog Length");
2213 EmitLabel("line_prolog_begin", 0);
2214
2215 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2216
2217 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2218
2219 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2220
2221 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2222
2223 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2224
2225 // Line number standard opcode encodings argument count
2226 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2227 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2228 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2229 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2230 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2231 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2232 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2233 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2234 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2235
2236 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2237 const UniqueVector<SourceFileInfo>
2238 &SourceFiles = MMI->getSourceFiles();
2239
2240 // Emit directories.
2241 for (unsigned DirectoryID = 1, NDID = Directories.size();
2242 DirectoryID <= NDID; ++DirectoryID) {
2243 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2244 }
2245 Asm->EmitInt8(0); Asm->EOL("End of directories");
2246
2247 // Emit files.
2248 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2249 SourceID <= NSID; ++SourceID) {
2250 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2251 Asm->EmitString(SourceFile.getName());
2252 Asm->EOL("Source");
2253 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2254 Asm->EOL("Directory #");
2255 Asm->EmitULEB128Bytes(0);
2256 Asm->EOL("Mod date");
2257 Asm->EmitULEB128Bytes(0);
2258 Asm->EOL("File size");
2259 }
2260 Asm->EmitInt8(0); Asm->EOL("End of files");
2261
2262 EmitLabel("line_prolog_end", 0);
2263
2264 // A sequence for each text section.
2265 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2266 // Isolate current sections line info.
2267 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2268
2269 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2270
2271 // Dwarf assumes we start with first line of first source file.
2272 unsigned Source = 1;
2273 unsigned Line = 1;
2274
2275 // Construct rows of the address, source, line, column matrix.
2276 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2277 const SourceLineInfo &LineInfo = LineInfos[i];
2278 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2279 if (!LabelID) continue;
2280
2281 unsigned SourceID = LineInfo.getSourceID();
2282 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2283 unsigned DirectoryID = SourceFile.getDirectoryID();
2284 Asm->EOL(Directories[DirectoryID]
2285 + SourceFile.getName()
2286 + ":"
2287 + utostr_32(LineInfo.getLine()));
2288
2289 // Define the line address.
2290 Asm->EmitInt8(0); Asm->EOL("Extended Op");
Dan Gohmancfb72b22007-09-27 23:12:31 +00002291 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002292 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2293 EmitReference("label", LabelID); Asm->EOL("Location label");
2294
2295 // If change of source, then switch to the new source.
2296 if (Source != LineInfo.getSourceID()) {
2297 Source = LineInfo.getSourceID();
2298 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2299 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2300 }
2301
2302 // If change of line.
2303 if (Line != LineInfo.getLine()) {
2304 // Determine offset.
2305 int Offset = LineInfo.getLine() - Line;
2306 int Delta = Offset - MinLineDelta;
2307
2308 // Update line.
2309 Line = LineInfo.getLine();
2310
2311 // If delta is small enough and in range...
2312 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2313 // ... then use fast opcode.
2314 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2315 } else {
2316 // ... otherwise use long hand.
2317 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2318 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2319 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2320 }
2321 } else {
2322 // Copy the previous row (different address or source)
2323 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2324 }
2325 }
2326
2327 // Define last address of section.
2328 Asm->EmitInt8(0); Asm->EOL("Extended Op");
Dan Gohmancfb72b22007-09-27 23:12:31 +00002329 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2331 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2332
2333 // Mark end of matrix.
2334 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2335 Asm->EmitULEB128Bytes(1); Asm->EOL();
2336 Asm->EmitInt8(1); Asm->EOL();
2337 }
2338
2339 EmitLabel("line_end", 0);
2340
2341 Asm->EOL();
2342 }
2343
2344 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2345 ///
2346 void EmitCommonDebugFrame() {
2347 if (!TAI->doesDwarfRequireFrameSection())
2348 return;
2349
2350 int stackGrowth =
2351 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2352 TargetFrameInfo::StackGrowsUp ?
Dan Gohmancfb72b22007-09-27 23:12:31 +00002353 TD->getPointerSize() : -TD->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002354
2355 // Start the dwarf frame section.
2356 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2357
2358 EmitLabel("debug_frame_common", 0);
2359 EmitDifference("debug_frame_common_end", 0,
2360 "debug_frame_common_begin", 0, true);
2361 Asm->EOL("Length of Common Information Entry");
2362
2363 EmitLabel("debug_frame_common_begin", 0);
2364 Asm->EmitInt32((int)DW_CIE_ID);
2365 Asm->EOL("CIE Identifier Tag");
2366 Asm->EmitInt8(DW_CIE_VERSION);
2367 Asm->EOL("CIE Version");
2368 Asm->EmitString("");
2369 Asm->EOL("CIE Augmentation");
2370 Asm->EmitULEB128Bytes(1);
2371 Asm->EOL("CIE Code Alignment Factor");
2372 Asm->EmitSLEB128Bytes(stackGrowth);
2373 Asm->EOL("CIE Data Alignment Factor");
Dale Johannesenf5a11532007-11-13 19:13:01 +00002374 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002375 Asm->EOL("CIE RA Column");
2376
2377 std::vector<MachineMove> Moves;
2378 RI->getInitialFrameState(Moves);
2379
Dale Johannesenf5a11532007-11-13 19:13:01 +00002380 EmitFrameMoves(NULL, 0, Moves, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002381
2382 Asm->EmitAlignment(2);
2383 EmitLabel("debug_frame_common_end", 0);
2384
2385 Asm->EOL();
2386 }
2387
2388 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2389 /// section.
2390 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2391 if (!TAI->doesDwarfRequireFrameSection())
2392 return;
2393
2394 // Start the dwarf frame section.
2395 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2396
2397 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2398 "debug_frame_begin", DebugFrameInfo.Number, true);
2399 Asm->EOL("Length of Frame Information Entry");
2400
2401 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2402
2403 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2404 0, 0, true, false);
2405 Asm->EOL("FDE CIE offset");
2406
2407 EmitReference("func_begin", DebugFrameInfo.Number);
2408 Asm->EOL("FDE initial location");
2409 EmitDifference("func_end", DebugFrameInfo.Number,
2410 "func_begin", DebugFrameInfo.Number);
2411 Asm->EOL("FDE address range");
2412
Dale Johannesenf5a11532007-11-13 19:13:01 +00002413 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414
2415 Asm->EmitAlignment(2);
2416 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2417
2418 Asm->EOL();
2419 }
2420
2421 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2422 ///
2423 void EmitDebugPubNames() {
2424 // Start the dwarf pubnames section.
2425 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2426
2427 CompileUnit *Unit = GetBaseCompileUnit();
2428
2429 EmitDifference("pubnames_end", Unit->getID(),
2430 "pubnames_begin", Unit->getID(), true);
2431 Asm->EOL("Length of Public Names Info");
2432
2433 EmitLabel("pubnames_begin", Unit->getID());
2434
2435 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2436
2437 EmitSectionOffset("info_begin", "section_info",
2438 Unit->getID(), 0, true, false);
2439 Asm->EOL("Offset of Compilation Unit Info");
2440
2441 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2442 Asm->EOL("Compilation Unit Length");
2443
2444 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2445
2446 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2447 GE = Globals.end();
2448 GI != GE; ++GI) {
2449 const std::string &Name = GI->first;
2450 DIE * Entity = GI->second;
2451
2452 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2453 Asm->EmitString(Name); Asm->EOL("External Name");
2454 }
2455
2456 Asm->EmitInt32(0); Asm->EOL("End Mark");
2457 EmitLabel("pubnames_end", Unit->getID());
2458
2459 Asm->EOL();
2460 }
2461
2462 /// EmitDebugStr - Emit visible names into a debug str section.
2463 ///
2464 void EmitDebugStr() {
2465 // Check to see if it is worth the effort.
2466 if (!StringPool.empty()) {
2467 // Start the dwarf str section.
2468 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2469
2470 // For each of strings in the string pool.
2471 for (unsigned StringID = 1, N = StringPool.size();
2472 StringID <= N; ++StringID) {
2473 // Emit a label for reference from debug information entries.
2474 EmitLabel("string", StringID);
2475 // Emit the string itself.
2476 const std::string &String = StringPool[StringID];
2477 Asm->EmitString(String); Asm->EOL();
2478 }
2479
2480 Asm->EOL();
2481 }
2482 }
2483
2484 /// EmitDebugLoc - Emit visible names into a debug loc section.
2485 ///
2486 void EmitDebugLoc() {
2487 // Start the dwarf loc section.
2488 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2489
2490 Asm->EOL();
2491 }
2492
2493 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2494 ///
2495 void EmitDebugARanges() {
2496 // Start the dwarf aranges section.
2497 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2498
2499 // FIXME - Mock up
2500 #if 0
2501 CompileUnit *Unit = GetBaseCompileUnit();
2502
2503 // Don't include size of length
2504 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2505
2506 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2507
2508 EmitReference("info_begin", Unit->getID());
2509 Asm->EOL("Offset of Compilation Unit Info");
2510
Dan Gohmancfb72b22007-09-27 23:12:31 +00002511 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002512
2513 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2514
2515 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2516 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2517
2518 // Range 1
2519 EmitReference("text_begin", 0); Asm->EOL("Address");
2520 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2521
2522 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2523 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
Dan Gohman111540b2007-09-24 21:36:21 +00002524 #endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525
2526 Asm->EOL();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527 }
2528
2529 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2530 ///
2531 void EmitDebugRanges() {
2532 // Start the dwarf ranges section.
2533 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2534
2535 Asm->EOL();
2536 }
2537
2538 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2539 ///
2540 void EmitDebugMacInfo() {
2541 // Start the dwarf macinfo section.
2542 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2543
2544 Asm->EOL();
2545 }
2546
2547 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2548 /// header file.
2549 void ConstructCompileUnitDIEs() {
2550 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2551
2552 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2553 unsigned ID = MMI->RecordSource(CUW[i]);
2554 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2555 CompileUnits.push_back(Unit);
2556 }
2557 }
2558
2559 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2560 /// global variables.
2561 void ConstructGlobalDIEs() {
2562 std::vector<GlobalVariableDesc *> GlobalVariables =
2563 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2564
2565 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2566 GlobalVariableDesc *GVD = GlobalVariables[i];
2567 NewGlobalVariable(GVD);
2568 }
2569 }
2570
2571 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2572 /// subprograms.
2573 void ConstructSubprogramDIEs() {
2574 std::vector<SubprogramDesc *> Subprograms =
2575 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2576
2577 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2578 SubprogramDesc *SPD = Subprograms[i];
2579 NewSubprogram(SPD);
2580 }
2581 }
2582
2583public:
2584 //===--------------------------------------------------------------------===//
2585 // Main entry points.
2586 //
2587 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
Chris Lattnerb3876c72007-09-24 03:35:37 +00002588 : Dwarf(OS, A, T, "dbg")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589 , CompileUnits()
2590 , AbbreviationsSet(InitAbbreviationsSetSize)
2591 , Abbreviations()
2592 , ValuesSet(InitValuesSetSize)
2593 , Values()
2594 , StringPool()
2595 , DescToUnitMap()
2596 , SectionMap()
2597 , SectionSourceLines()
2598 , didInitial(false)
2599 , shouldEmit(false)
2600 {
2601 }
2602 virtual ~DwarfDebug() {
2603 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2604 delete CompileUnits[i];
2605 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2606 delete Values[j];
2607 }
2608
2609 /// SetModuleInfo - Set machine module information when it's known that pass
2610 /// manager has created it. Set by the target AsmPrinter.
2611 void SetModuleInfo(MachineModuleInfo *mmi) {
2612 // Make sure initial declarations are made.
2613 if (!MMI && mmi->hasDebugInfo()) {
2614 MMI = mmi;
2615 shouldEmit = true;
2616
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617 // Create all the compile unit DIEs.
2618 ConstructCompileUnitDIEs();
2619
2620 // Create DIEs for each of the externally visible global variables.
2621 ConstructGlobalDIEs();
2622
2623 // Create DIEs for each of the externally visible subprograms.
2624 ConstructSubprogramDIEs();
2625
2626 // Prime section data.
2627 SectionMap.insert(TAI->getTextSection());
Dan Gohman6d6c2402007-10-01 22:40:20 +00002628
2629 // Print out .file directives to specify files for .loc directives. These
2630 // are printed out early so that they precede any .loc directives.
2631 if (TAI->hasDotLocAndDotFile()) {
2632 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2633 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2634 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2635 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2636 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2637 assert(AppendOk && "Could not append filename to directory!");
2638 Asm->EmitFile(i, FullPath.toString());
2639 Asm->EOL();
2640 }
2641 }
2642
2643 // Emit initial sections
2644 EmitInitial();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 }
2646 }
2647
2648 /// BeginModule - Emit all Dwarf sections that should come prior to the
2649 /// content.
2650 void BeginModule(Module *M) {
2651 this->M = M;
2652
2653 if (!ShouldEmitDwarf()) return;
2654 }
2655
2656 /// EndModule - Emit all Dwarf sections that should come after the content.
2657 ///
2658 void EndModule() {
2659 if (!ShouldEmitDwarf()) return;
2660
2661 // Standard sections final addresses.
2662 Asm->SwitchToTextSection(TAI->getTextSection());
2663 EmitLabel("text_end", 0);
2664 Asm->SwitchToDataSection(TAI->getDataSection());
2665 EmitLabel("data_end", 0);
2666
2667 // End text sections.
2668 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2669 Asm->SwitchToTextSection(SectionMap[i].c_str());
2670 EmitLabel("section_end", i);
2671 }
2672
2673 // Emit common frame information.
2674 EmitCommonDebugFrame();
2675
2676 // Emit function debug frame information
2677 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2678 E = DebugFrames.end(); I != E; ++I)
2679 EmitFunctionDebugFrame(*I);
2680
2681 // Compute DIE offsets and sizes.
2682 SizeAndOffsets();
2683
2684 // Emit all the DIEs into a debug info section
2685 EmitDebugInfo();
2686
2687 // Corresponding abbreviations into a abbrev section.
2688 EmitAbbreviations();
2689
2690 // Emit source line correspondence into a debug line section.
2691 EmitDebugLines();
2692
2693 // Emit info into a debug pubnames section.
2694 EmitDebugPubNames();
2695
2696 // Emit info into a debug str section.
2697 EmitDebugStr();
2698
2699 // Emit info into a debug loc section.
2700 EmitDebugLoc();
2701
2702 // Emit info into a debug aranges section.
2703 EmitDebugARanges();
2704
2705 // Emit info into a debug ranges section.
2706 EmitDebugRanges();
2707
2708 // Emit info into a debug macinfo section.
2709 EmitDebugMacInfo();
2710 }
2711
2712 /// BeginFunction - Gather pre-function debug information. Assumes being
2713 /// emitted immediately after the function entry point.
2714 void BeginFunction(MachineFunction *MF) {
2715 this->MF = MF;
2716
2717 if (!ShouldEmitDwarf()) return;
2718
2719 // Begin accumulating function debug information.
2720 MMI->BeginFunction(MF);
2721
2722 // Assumes in correct section after the entry point.
2723 EmitLabel("func_begin", ++SubprogramCount);
Evan Chenga53c40a2008-02-01 09:10:45 +00002724
2725 // Emit label for the implicitly defined dbg.stoppoint at the start of
2726 // the function.
2727 const SourceLineInfo &LineInfo = MMI->getSourceLines()[0];
2728 Asm->printLabel(LineInfo.getLabelID());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002729 }
2730
2731 /// EndFunction - Gather and emit post-function debug information.
2732 ///
2733 void EndFunction() {
2734 if (!ShouldEmitDwarf()) return;
2735
2736 // Define end label for subprogram.
2737 EmitLabel("func_end", SubprogramCount);
2738
2739 // Get function line info.
2740 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2741
2742 if (!LineInfos.empty()) {
2743 // Get section line info.
2744 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2745 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2746 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2747 // Append the function info to section info.
2748 SectionLineInfos.insert(SectionLineInfos.end(),
2749 LineInfos.begin(), LineInfos.end());
2750 }
2751
2752 // Construct scopes for subprogram.
2753 ConstructRootScope(MMI->getRootScope());
2754
2755 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2756 MMI->getFrameMoves()));
2757 }
2758};
2759
2760//===----------------------------------------------------------------------===//
2761/// DwarfException - Emits Dwarf exception handling directives.
2762///
2763class DwarfException : public Dwarf {
2764
2765private:
2766 struct FunctionEHFrameInfo {
2767 std::string FnName;
2768 unsigned Number;
2769 unsigned PersonalityIndex;
2770 bool hasCalls;
2771 bool hasLandingPads;
2772 std::vector<MachineMove> Moves;
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002773 const Function * function;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002774
2775 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2776 bool hC, bool hL,
Dale Johannesenfb3ac732007-11-20 23:24:42 +00002777 const std::vector<MachineMove> &M,
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002778 const Function *f):
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 FnName(FN), Number(Num), PersonalityIndex(P),
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002780 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002781 };
2782
2783 std::vector<FunctionEHFrameInfo> EHFrames;
2784
2785 /// shouldEmit - Flag to indicate if debug information should be emitted.
2786 ///
2787 bool shouldEmit;
2788
2789 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2790 ///
2791 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2792 // Size and sign of stack growth.
2793 int stackGrowth =
2794 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2795 TargetFrameInfo::StackGrowsUp ?
Dan Gohmancfb72b22007-09-27 23:12:31 +00002796 TD->getPointerSize() : -TD->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797
2798 // Begin eh frame section.
2799 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2800 O << "EH_frame" << Index << ":\n";
2801 EmitLabel("section_eh_frame", Index);
2802
2803 // Define base labels.
2804 EmitLabel("eh_frame_common", Index);
2805
2806 // Define the eh frame length.
2807 EmitDifference("eh_frame_common_end", Index,
2808 "eh_frame_common_begin", Index, true);
2809 Asm->EOL("Length of Common Information Entry");
2810
2811 // EH frame header.
2812 EmitLabel("eh_frame_common_begin", Index);
2813 Asm->EmitInt32((int)0);
2814 Asm->EOL("CIE Identifier Tag");
2815 Asm->EmitInt8(DW_CIE_VERSION);
2816 Asm->EOL("CIE Version");
2817
2818 // The personality presence indicates that language specific information
2819 // will show up in the eh frame.
2820 Asm->EmitString(Personality ? "zPLR" : "zR");
2821 Asm->EOL("CIE Augmentation");
2822
2823 // Round out reader.
2824 Asm->EmitULEB128Bytes(1);
2825 Asm->EOL("CIE Code Alignment Factor");
2826 Asm->EmitSLEB128Bytes(stackGrowth);
2827 Asm->EOL("CIE Data Alignment Factor");
Dale Johannesenf5a11532007-11-13 19:13:01 +00002828 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002829 Asm->EOL("CIE RA Column");
2830
2831 // If there is a personality, we need to indicate the functions location.
2832 if (Personality) {
2833 Asm->EmitULEB128Bytes(7);
2834 Asm->EOL("Augmentation Size");
Bill Wendling2d369922007-09-11 17:20:55 +00002835
2836 if (TAI->getNeedsIndirectEncoding())
2837 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2838 else
2839 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2840
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00002841 Asm->EOL("Personality (pcrel sdata4 indirect)");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842
Dale Johannesen4670be42008-01-15 23:24:56 +00002843 PrintRelDirective(TAI->getShortenEHDataOn64Bit());
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00002844 O << TAI->getPersonalityPrefix();
2845 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2846 O << TAI->getPersonalitySuffix();
Dale Johannesen4670be42008-01-15 23:24:56 +00002847 if (!TAI->getShortenEHDataOn64Bit()) {
2848 O << "-" << TAI->getPCSymbol();
2849 }
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00002850 Asm->EOL("Personality");
Bill Wendling38cb7c92007-08-25 00:51:55 +00002851
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002852 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2853 Asm->EOL("LSDA Encoding (pcrel)");
2854 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2855 Asm->EOL("FDE Encoding (pcrel)");
2856 } else {
2857 Asm->EmitULEB128Bytes(1);
2858 Asm->EOL("Augmentation Size");
2859 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2860 Asm->EOL("FDE Encoding (pcrel)");
2861 }
2862
2863 // Indicate locations of general callee saved registers in frame.
2864 std::vector<MachineMove> Moves;
2865 RI->getInitialFrameState(Moves);
Dale Johannesenf5a11532007-11-13 19:13:01 +00002866 EmitFrameMoves(NULL, 0, Moves, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867
2868 Asm->EmitAlignment(2);
2869 EmitLabel("eh_frame_common_end", Index);
2870
2871 Asm->EOL();
2872 }
2873
2874 /// EmitEHFrame - Emit function exception frame information.
2875 ///
2876 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002877 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
2878
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2880
2881 // Externally visible entry into the functions eh frame info.
Dale Johannesenfb3ac732007-11-20 23:24:42 +00002882 // If the corresponding function is static, this should not be
2883 // externally visible.
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002884 if (linkage != Function::InternalLinkage) {
Dale Johannesenfb3ac732007-11-20 23:24:42 +00002885 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
2886 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
2887 }
2888
Dale Johannesenf09b5992008-01-10 02:03:30 +00002889 // If corresponding function is weak definition, this should be too.
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002890 if ((linkage == Function::WeakLinkage ||
2891 linkage == Function::LinkOnceLinkage) &&
Dale Johannesenf09b5992008-01-10 02:03:30 +00002892 TAI->getWeakDefDirective())
2893 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
2894
2895 // If there are no calls then you can't unwind. This may mean we can
2896 // omit the EH Frame, but some environments do not handle weak absolute
2897 // symbols.
2898 if (!EHFrameInfo.hasCalls &&
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002899 ((linkage != Function::WeakLinkage &&
2900 linkage != Function::LinkOnceLinkage) ||
Dale Johannesenf09b5992008-01-10 02:03:30 +00002901 !TAI->getWeakDefDirective() ||
2902 TAI->getSupportsWeakOmittedEHFrame()))
2903 {
Bill Wendlingef9211a2007-09-18 01:47:22 +00002904 O << EHFrameInfo.FnName << " = 0\n";
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002905 // This name has no connection to the function, so it might get
2906 // dead-stripped when the function is not, erroneously. Prohibit
2907 // dead-stripping unconditionally.
2908 if (const char *UsedDirective = TAI->getUsedDirective())
2909 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 } else {
Bill Wendlingef9211a2007-09-18 01:47:22 +00002911 O << EHFrameInfo.FnName << ":\n";
Dale Johannesenfb3ac732007-11-20 23:24:42 +00002912
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 // EH frame header.
2914 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2915 "eh_frame_begin", EHFrameInfo.Number, true);
2916 Asm->EOL("Length of Frame Information Entry");
2917
2918 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2919
2920 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2921 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2922 true, true);
2923 Asm->EOL("FDE CIE offset");
2924
2925 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2926 Asm->EOL("FDE initial location");
2927 EmitDifference("eh_func_end", EHFrameInfo.Number,
2928 "eh_func_begin", EHFrameInfo.Number);
2929 Asm->EOL("FDE address range");
2930
2931 // If there is a personality and landing pads then point to the language
2932 // specific data area in the exception table.
2933 if (EHFrameInfo.PersonalityIndex) {
Dale Johannesen4670be42008-01-15 23:24:56 +00002934 Asm->EmitULEB128Bytes(TAI->getShortenEHDataOn64Bit() ? 8 : 4);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002935 Asm->EOL("Augmentation size");
2936
2937 if (EHFrameInfo.hasLandingPads) {
2938 EmitReference("exception", EHFrameInfo.Number, true);
Dan Gohmancfb72b22007-09-27 23:12:31 +00002939 } else if (TD->getPointerSize() == 8) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 Asm->EmitInt64((int)0);
2941 } else {
2942 Asm->EmitInt32((int)0);
2943 }
2944 Asm->EOL("Language Specific Data Area");
2945 } else {
2946 Asm->EmitULEB128Bytes(0);
2947 Asm->EOL("Augmentation size");
2948 }
2949
2950 // Indicate locations of function specific callee saved registers in
2951 // frame.
Dale Johannesenf5a11532007-11-13 19:13:01 +00002952 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953
2954 Asm->EmitAlignment(2);
2955 EmitLabel("eh_frame_end", EHFrameInfo.Number);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956
Dale Johannesen3dadeb32008-01-16 19:59:28 +00002957 // If the function is marked used, this table should be also. We cannot
2958 // make the mark unconditional in this case, since retaining the table
2959 // also retains the function in this case, and there is code around
2960 // that depends on unused functions (calling undefined externals) being
2961 // dead-stripped to link correctly. Yes, there really is.
2962 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
2963 if (const char *UsedDirective = TAI->getUsedDirective())
2964 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2965 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 }
2967
Duncan Sands241a0c92007-09-05 11:27:52 +00002968 /// EmitExceptionTable - Emit landing pads and actions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 ///
2970 /// The general organization of the table is complex, but the basic concepts
2971 /// are easy. First there is a header which describes the location and
2972 /// organization of the three components that follow.
2973 /// 1. The landing pad site information describes the range of code covered
2974 /// by the try. In our case it's an accumulation of the ranges covered
2975 /// by the invokes in the try. There is also a reference to the landing
2976 /// pad that handles the exception once processed. Finally an index into
2977 /// the actions table.
2978 /// 2. The action table, in our case, is composed of pairs of type ids
2979 /// and next action offset. Starting with the action index from the
2980 /// landing pad site, each type Id is checked for a match to the current
2981 /// exception. If it matches then the exception and type id are passed
2982 /// on to the landing pad. Otherwise the next action is looked up. This
2983 /// chain is terminated with a next action of zero. If no type id is
2984 /// found the the frame is unwound and handling continues.
2985 /// 3. Type id table contains references to all the C++ typeinfo for all
2986 /// catches in the function. This tables is reversed indexed base 1.
2987
2988 /// SharedTypeIds - How many leading type ids two landing pads have in common.
2989 static unsigned SharedTypeIds(const LandingPadInfo *L,
2990 const LandingPadInfo *R) {
2991 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2992 unsigned LSize = LIds.size(), RSize = RIds.size();
2993 unsigned MinSize = LSize < RSize ? LSize : RSize;
2994 unsigned Count = 0;
2995
2996 for (; Count != MinSize; ++Count)
2997 if (LIds[Count] != RIds[Count])
2998 return Count;
2999
3000 return Count;
3001 }
3002
3003 /// PadLT - Order landing pads lexicographically by type id.
3004 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3005 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3006 unsigned LSize = LIds.size(), RSize = RIds.size();
3007 unsigned MinSize = LSize < RSize ? LSize : RSize;
3008
3009 for (unsigned i = 0; i != MinSize; ++i)
3010 if (LIds[i] != RIds[i])
3011 return LIds[i] < RIds[i];
3012
3013 return LSize < RSize;
3014 }
3015
3016 struct KeyInfo {
3017 static inline unsigned getEmptyKey() { return -1U; }
3018 static inline unsigned getTombstoneKey() { return -2U; }
3019 static unsigned getHashValue(const unsigned &Key) { return Key; }
Chris Lattner92eea072007-09-17 18:34:04 +00003020 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 static bool isPod() { return true; }
3022 };
3023
Duncan Sands241a0c92007-09-05 11:27:52 +00003024 /// ActionEntry - Structure describing an entry in the actions table.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025 struct ActionEntry {
3026 int ValueForTypeID; // The value to write - may not be equal to the type id.
3027 int NextAction;
3028 struct ActionEntry *Previous;
3029 };
3030
Duncan Sands241a0c92007-09-05 11:27:52 +00003031 /// PadRange - Structure holding a try-range and the associated landing pad.
3032 struct PadRange {
3033 // The index of the landing pad.
3034 unsigned PadIndex;
3035 // The index of the begin and end labels in the landing pad's label lists.
3036 unsigned RangeIndex;
3037 };
3038
3039 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3040
3041 /// CallSiteEntry - Structure describing an entry in the call-site table.
3042 struct CallSiteEntry {
Duncan Sands4ff179f2007-12-19 07:36:31 +00003043 // The 'try-range' is BeginLabel .. EndLabel.
Duncan Sands241a0c92007-09-05 11:27:52 +00003044 unsigned BeginLabel; // zero indicates the start of the function.
3045 unsigned EndLabel; // zero indicates the end of the function.
Duncan Sands4ff179f2007-12-19 07:36:31 +00003046 // The landing pad starts at PadLabel.
Duncan Sands241a0c92007-09-05 11:27:52 +00003047 unsigned PadLabel; // zero indicates that there is no landing pad.
3048 unsigned Action;
3049 };
3050
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 void EmitExceptionTable() {
3052 // Map all labels and get rid of any dead landing pads.
3053 MMI->TidyLandingPads();
3054
3055 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3056 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3057 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3058 if (PadInfos.empty()) return;
3059
3060 // Sort the landing pads in order of their type ids. This is used to fold
3061 // duplicate actions.
3062 SmallVector<const LandingPadInfo *, 64> LandingPads;
3063 LandingPads.reserve(PadInfos.size());
3064 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3065 LandingPads.push_back(&PadInfos[i]);
3066 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3067
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068 // Negative type ids index into FilterIds, positive type ids index into
3069 // TypeInfos. The value written for a positive type id is just the type
3070 // id itself. For a negative type id, however, the value written is the
3071 // (negative) byte offset of the corresponding FilterIds entry. The byte
3072 // offset is usually equal to the type id, because the FilterIds entries
3073 // are written using a variable width encoding which outputs one byte per
3074 // entry as long as the value written is not too large, but can differ.
3075 // This kind of complication does not occur for positive type ids because
3076 // type infos are output using a fixed width encoding.
3077 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3078 SmallVector<int, 16> FilterOffsets;
3079 FilterOffsets.reserve(FilterIds.size());
3080 int Offset = -1;
3081 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3082 E = FilterIds.end(); I != E; ++I) {
3083 FilterOffsets.push_back(Offset);
3084 Offset -= Asm->SizeULEB128(*I);
3085 }
3086
Duncan Sands241a0c92007-09-05 11:27:52 +00003087 // Compute the actions table and gather the first action index for each
3088 // landing pad site.
3089 SmallVector<ActionEntry, 32> Actions;
3090 SmallVector<unsigned, 64> FirstActions;
3091 FirstActions.reserve(LandingPads.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003092
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093 int FirstAction = 0;
Duncan Sands241a0c92007-09-05 11:27:52 +00003094 unsigned SizeActions = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3096 const LandingPadInfo *LP = LandingPads[i];
3097 const std::vector<int> &TypeIds = LP->TypeIds;
3098 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3099 unsigned SizeSiteActions = 0;
3100
3101 if (NumShared < TypeIds.size()) {
3102 unsigned SizeAction = 0;
3103 ActionEntry *PrevAction = 0;
3104
3105 if (NumShared) {
3106 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3107 assert(Actions.size());
3108 PrevAction = &Actions.back();
3109 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3110 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3111 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3112 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3113 SizeAction += -PrevAction->NextAction;
3114 PrevAction = PrevAction->Previous;
3115 }
3116 }
3117
3118 // Compute the actions.
3119 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3120 int TypeID = TypeIds[I];
3121 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3122 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3123 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3124
3125 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3126 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3127 SizeSiteActions += SizeAction;
3128
3129 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3130 Actions.push_back(Action);
3131
3132 PrevAction = &Actions.back();
3133 }
3134
3135 // Record the first action of the landing pad site.
3136 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3137 } // else identical - re-use previous FirstAction
3138
3139 FirstActions.push_back(FirstAction);
3140
3141 // Compute this sites contribution to size.
3142 SizeActions += SizeSiteActions;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003144
Duncan Sands4ff179f2007-12-19 07:36:31 +00003145 // Compute the call-site table. The entry for an invoke has a try-range
3146 // containing the call, a non-zero landing pad and an appropriate action.
3147 // The entry for an ordinary call has a try-range containing the call and
3148 // zero for the landing pad and the action. Calls marked 'nounwind' have
3149 // no entry and must not be contained in the try-range of any entry - they
3150 // form gaps in the table. Entries must be ordered by try-range address.
Duncan Sands241a0c92007-09-05 11:27:52 +00003151 SmallVector<CallSiteEntry, 64> CallSites;
3152
3153 RangeMapType PadMap;
Duncan Sands4ff179f2007-12-19 07:36:31 +00003154 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3155 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3156 // try-ranges for them need be deduced.
Duncan Sands241a0c92007-09-05 11:27:52 +00003157 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3158 const LandingPadInfo *LandingPad = LandingPads[i];
Duncan Sands4ff179f2007-12-19 07:36:31 +00003159 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
Duncan Sands241a0c92007-09-05 11:27:52 +00003160 unsigned BeginLabel = LandingPad->BeginLabels[j];
3161 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3162 PadRange P = { i, j };
3163 PadMap[BeginLabel] = P;
3164 }
3165 }
3166
Duncan Sands4ff179f2007-12-19 07:36:31 +00003167 // The end label of the previous invoke or nounwind try-range.
Duncan Sands241a0c92007-09-05 11:27:52 +00003168 unsigned LastLabel = 0;
Duncan Sands4ff179f2007-12-19 07:36:31 +00003169
3170 // Whether there is a potentially throwing instruction (currently this means
3171 // an ordinary call) between the end of the previous try-range and now.
3172 bool SawPotentiallyThrowing = false;
3173
3174 // Whether the last callsite entry was for an invoke.
3175 bool PreviousIsInvoke = false;
3176
Duncan Sands4ff179f2007-12-19 07:36:31 +00003177 // Visit all instructions in order of address.
Duncan Sands241a0c92007-09-05 11:27:52 +00003178 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3179 I != E; ++I) {
3180 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3181 MI != E; ++MI) {
3182 if (MI->getOpcode() != TargetInstrInfo::LABEL) {
Chris Lattner5b930372008-01-07 07:27:27 +00003183 SawPotentiallyThrowing |= MI->getDesc().isCall();
Duncan Sands241a0c92007-09-05 11:27:52 +00003184 continue;
3185 }
3186
Chris Lattnerda4cff12007-12-30 20:50:28 +00003187 unsigned BeginLabel = MI->getOperand(0).getImm();
Duncan Sands241a0c92007-09-05 11:27:52 +00003188 assert(BeginLabel && "Invalid label!");
Duncan Sands89372f62007-09-05 14:12:46 +00003189
Duncan Sands4ff179f2007-12-19 07:36:31 +00003190 // End of the previous try-range?
Duncan Sands89372f62007-09-05 14:12:46 +00003191 if (BeginLabel == LastLabel)
Duncan Sands4ff179f2007-12-19 07:36:31 +00003192 SawPotentiallyThrowing = false;
Duncan Sands241a0c92007-09-05 11:27:52 +00003193
Duncan Sands4ff179f2007-12-19 07:36:31 +00003194 // Beginning of a new try-range?
Duncan Sands241a0c92007-09-05 11:27:52 +00003195 RangeMapType::iterator L = PadMap.find(BeginLabel);
Duncan Sands241a0c92007-09-05 11:27:52 +00003196 if (L == PadMap.end())
Duncan Sands4ff179f2007-12-19 07:36:31 +00003197 // Nope, it was just some random label.
Duncan Sands241a0c92007-09-05 11:27:52 +00003198 continue;
3199
3200 PadRange P = L->second;
3201 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3202
3203 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3204 "Inconsistent landing pad map!");
3205
3206 // If some instruction between the previous try-range and this one may
3207 // throw, create a call-site entry with no landing pad for the region
3208 // between the try-ranges.
Duncan Sands4ff179f2007-12-19 07:36:31 +00003209 if (SawPotentiallyThrowing) {
Duncan Sands241a0c92007-09-05 11:27:52 +00003210 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3211 CallSites.push_back(Site);
Duncan Sands4ff179f2007-12-19 07:36:31 +00003212 PreviousIsInvoke = false;
Duncan Sands241a0c92007-09-05 11:27:52 +00003213 }
3214
3215 LastLabel = LandingPad->EndLabels[P.RangeIndex];
Duncan Sands4ff179f2007-12-19 07:36:31 +00003216 assert(BeginLabel && LastLabel && "Invalid landing pad!");
Duncan Sands241a0c92007-09-05 11:27:52 +00003217
Duncan Sands4ff179f2007-12-19 07:36:31 +00003218 if (LandingPad->LandingPadLabel) {
3219 // This try-range is for an invoke.
3220 CallSiteEntry Site = {BeginLabel, LastLabel,
3221 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
Duncan Sands241a0c92007-09-05 11:27:52 +00003222
Duncan Sands4ff179f2007-12-19 07:36:31 +00003223 // Try to merge with the previous call-site.
3224 if (PreviousIsInvoke) {
3225 CallSiteEntry &Prev = CallSites[CallSites.size()-1];
3226 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3227 // Extend the range of the previous entry.
3228 Prev.EndLabel = Site.EndLabel;
3229 continue;
3230 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003231 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003232
Duncan Sands4ff179f2007-12-19 07:36:31 +00003233 // Otherwise, create a new call-site.
3234 CallSites.push_back(Site);
3235 PreviousIsInvoke = true;
3236 } else {
3237 // Create a gap.
3238 PreviousIsInvoke = false;
3239 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003240 }
3241 }
3242 // If some instruction between the previous try-range and the end of the
3243 // function may throw, create a call-site entry with no landing pad for the
3244 // region following the try-range.
Duncan Sands4ff179f2007-12-19 07:36:31 +00003245 if (SawPotentiallyThrowing) {
Duncan Sands241a0c92007-09-05 11:27:52 +00003246 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3247 CallSites.push_back(Site);
3248 }
3249
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003250 // Final tallies.
Duncan Sands241a0c92007-09-05 11:27:52 +00003251 unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
3252 sizeof(int32_t) + // Site length.
3253 sizeof(int32_t)); // Landing pad.
3254 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3255 SizeSites += Asm->SizeULEB128(CallSites[i].Action);
3256
Dan Gohmancfb72b22007-09-27 23:12:31 +00003257 unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003258
3259 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3260 Asm->SizeULEB128(SizeSites) + // Call-site table length
3261 SizeSites + SizeActions + SizeTypes;
3262
3263 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3264 sizeof(int8_t) + // TType format
3265 Asm->SizeULEB128(TypeOffset) + // TType base offset
3266 TypeOffset;
3267
3268 unsigned SizeAlign = (4 - TotalSize) & 3;
3269
3270 // Begin the exception table.
3271 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3272 O << "GCC_except_table" << SubprogramCount << ":\n";
3273 Asm->EmitAlignment(2);
3274 for (unsigned i = 0; i != SizeAlign; ++i) {
3275 Asm->EmitInt8(0);
3276 Asm->EOL("Padding");
3277 }
3278 EmitLabel("exception", SubprogramCount);
3279
3280 // Emit the header.
3281 Asm->EmitInt8(DW_EH_PE_omit);
3282 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3283 Asm->EmitInt8(DW_EH_PE_absptr);
3284 Asm->EOL("TType format (DW_EH_PE_absptr)");
3285 Asm->EmitULEB128Bytes(TypeOffset);
3286 Asm->EOL("TType base offset");
3287 Asm->EmitInt8(DW_EH_PE_udata4);
3288 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3289 Asm->EmitULEB128Bytes(SizeSites);
3290 Asm->EOL("Call-site table length");
3291
Duncan Sands241a0c92007-09-05 11:27:52 +00003292 // Emit the landing pad site information.
3293 for (unsigned i = 0; i < CallSites.size(); ++i) {
3294 CallSiteEntry &S = CallSites[i];
3295 const char *BeginTag;
3296 unsigned BeginNumber;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003297
Duncan Sands241a0c92007-09-05 11:27:52 +00003298 if (!S.BeginLabel) {
3299 BeginTag = "eh_func_begin";
3300 BeginNumber = SubprogramCount;
3301 } else {
3302 BeginTag = "label";
3303 BeginNumber = S.BeginLabel;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003304 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305
Duncan Sands241a0c92007-09-05 11:27:52 +00003306 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
Dale Johannesen4670be42008-01-15 23:24:56 +00003307 TAI->getShortenEHDataOn64Bit(), true);
Duncan Sands241a0c92007-09-05 11:27:52 +00003308 Asm->EOL("Region start");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003309
Duncan Sands241a0c92007-09-05 11:27:52 +00003310 if (!S.EndLabel) {
Dale Johannesen4670be42008-01-15 23:24:56 +00003311 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3312 TAI->getShortenEHDataOn64Bit());
Duncan Sands241a0c92007-09-05 11:27:52 +00003313 } else {
Dale Johannesen4670be42008-01-15 23:24:56 +00003314 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber,
3315 TAI->getShortenEHDataOn64Bit());
Duncan Sands241a0c92007-09-05 11:27:52 +00003316 }
3317 Asm->EOL("Region length");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318
Duncan Sands241a0c92007-09-05 11:27:52 +00003319 if (!S.PadLabel) {
Dale Johannesen4670be42008-01-15 23:24:56 +00003320 if (TD->getPointerSize() == sizeof(int32_t) || TAI->getShortenEHDataOn64Bit())
Duncan Sands241a0c92007-09-05 11:27:52 +00003321 Asm->EmitInt32(0);
3322 else
3323 Asm->EmitInt64(0);
3324 } else {
3325 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
Dale Johannesen4670be42008-01-15 23:24:56 +00003326 TAI->getShortenEHDataOn64Bit(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003328 Asm->EOL("Landing pad");
3329
3330 Asm->EmitULEB128Bytes(S.Action);
3331 Asm->EOL("Action");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332 }
3333
3334 // Emit the actions.
3335 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3336 ActionEntry &Action = Actions[I];
3337
3338 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3339 Asm->EOL("TypeInfo index");
3340 Asm->EmitSLEB128Bytes(Action.NextAction);
3341 Asm->EOL("Next action");
3342 }
3343
3344 // Emit the type ids.
3345 for (unsigned M = TypeInfos.size(); M; --M) {
3346 GlobalVariable *GV = TypeInfos[M - 1];
Anton Korobeynikov5ef86702007-09-02 22:07:21 +00003347
3348 PrintRelDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003349
3350 if (GV)
3351 O << Asm->getGlobalLinkName(GV);
3352 else
3353 O << "0";
Duncan Sands241a0c92007-09-05 11:27:52 +00003354
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003355 Asm->EOL("TypeInfo");
3356 }
3357
3358 // Emit the filter typeids.
3359 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3360 unsigned TypeID = FilterIds[j];
3361 Asm->EmitULEB128Bytes(TypeID);
3362 Asm->EOL("Filter TypeInfo index");
3363 }
Duncan Sands241a0c92007-09-05 11:27:52 +00003364
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 Asm->EmitAlignment(2);
3366 }
3367
3368public:
3369 //===--------------------------------------------------------------------===//
3370 // Main entry points.
3371 //
3372 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
Chris Lattnerb3876c72007-09-24 03:35:37 +00003373 : Dwarf(OS, A, T, "eh")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 , shouldEmit(false)
3375 {}
3376
3377 virtual ~DwarfException() {}
3378
3379 /// SetModuleInfo - Set machine module information when it's known that pass
3380 /// manager has created it. Set by the target AsmPrinter.
3381 void SetModuleInfo(MachineModuleInfo *mmi) {
3382 MMI = mmi;
3383 }
3384
3385 /// BeginModule - Emit all exception information that should come prior to the
3386 /// content.
3387 void BeginModule(Module *M) {
3388 this->M = M;
3389 }
3390
3391 /// EndModule - Emit all exception information that should come after the
3392 /// content.
3393 void EndModule() {
3394 if (!shouldEmit) return;
3395
3396 const std::vector<Function *> Personalities = MMI->getPersonalities();
3397 for (unsigned i =0; i < Personalities.size(); ++i)
3398 EmitCommonEHFrame(Personalities[i], i);
Bill Wendlingd1bda4f2007-09-11 08:27:17 +00003399
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3401 E = EHFrames.end(); I != E; ++I)
3402 EmitEHFrame(*I);
3403 }
3404
3405 /// BeginFunction - Gather pre-function exception information. Assumes being
3406 /// emitted immediately after the function entry point.
3407 void BeginFunction(MachineFunction *MF) {
3408 this->MF = MF;
3409
3410 if (MMI &&
3411 ExceptionHandling &&
3412 TAI->doesSupportExceptionHandling()) {
3413 shouldEmit = true;
3414 // Assumes in correct section after the entry point.
3415 EmitLabel("eh_func_begin", ++SubprogramCount);
3416 }
3417 }
3418
3419 /// EndFunction - Gather and emit post-function exception information.
3420 ///
3421 void EndFunction() {
3422 if (!shouldEmit) return;
3423
3424 EmitLabel("eh_func_end", SubprogramCount);
3425 EmitExceptionTable();
3426
3427 // Save EH frame information
Bill Wendlingef9211a2007-09-18 01:47:22 +00003428 EHFrames.
3429 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3430 SubprogramCount,
3431 MMI->getPersonalityIndex(),
3432 MF->getFrameInfo()->hasCalls(),
3433 !MMI->getLandingPads().empty(),
Dale Johannesenfb3ac732007-11-20 23:24:42 +00003434 MMI->getFrameMoves(),
Dale Johannesen3dadeb32008-01-16 19:59:28 +00003435 MF->getFunction()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436 }
3437};
3438
3439} // End of namespace llvm
3440
3441//===----------------------------------------------------------------------===//
3442
3443/// Emit - Print the abbreviation using the specified Dwarf writer.
3444///
3445void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3446 // Emit its Dwarf tag type.
3447 DD.getAsm()->EmitULEB128Bytes(Tag);
3448 DD.getAsm()->EOL(TagString(Tag));
3449
3450 // Emit whether it has children DIEs.
3451 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3452 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3453
3454 // For each attribute description.
3455 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3456 const DIEAbbrevData &AttrData = Data[i];
3457
3458 // Emit attribute type.
3459 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3460 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3461
3462 // Emit form type.
3463 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3464 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3465 }
3466
3467 // Mark end of abbreviation.
3468 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3469 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3470}
3471
3472#ifndef NDEBUG
3473void DIEAbbrev::print(std::ostream &O) {
3474 O << "Abbreviation @"
3475 << std::hex << (intptr_t)this << std::dec
3476 << " "
3477 << TagString(Tag)
3478 << " "
3479 << ChildrenString(ChildrenFlag)
3480 << "\n";
3481
3482 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3483 O << " "
3484 << AttributeString(Data[i].getAttribute())
3485 << " "
3486 << FormEncodingString(Data[i].getForm())
3487 << "\n";
3488 }
3489}
3490void DIEAbbrev::dump() { print(cerr); }
3491#endif
3492
3493//===----------------------------------------------------------------------===//
3494
3495#ifndef NDEBUG
3496void DIEValue::dump() {
3497 print(cerr);
3498}
3499#endif
3500
3501//===----------------------------------------------------------------------===//
3502
3503/// EmitValue - Emit integer of appropriate size.
3504///
3505void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3506 switch (Form) {
3507 case DW_FORM_flag: // Fall thru
3508 case DW_FORM_ref1: // Fall thru
3509 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3510 case DW_FORM_ref2: // Fall thru
3511 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3512 case DW_FORM_ref4: // Fall thru
3513 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3514 case DW_FORM_ref8: // Fall thru
3515 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3516 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3517 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3518 default: assert(0 && "DIE Value form not supported yet"); break;
3519 }
3520}
3521
3522/// SizeOf - Determine size of integer value in bytes.
3523///
3524unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3525 switch (Form) {
3526 case DW_FORM_flag: // Fall thru
3527 case DW_FORM_ref1: // Fall thru
3528 case DW_FORM_data1: return sizeof(int8_t);
3529 case DW_FORM_ref2: // Fall thru
3530 case DW_FORM_data2: return sizeof(int16_t);
3531 case DW_FORM_ref4: // Fall thru
3532 case DW_FORM_data4: return sizeof(int32_t);
3533 case DW_FORM_ref8: // Fall thru
3534 case DW_FORM_data8: return sizeof(int64_t);
3535 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3536 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3537 default: assert(0 && "DIE Value form not supported yet"); break;
3538 }
3539 return 0;
3540}
3541
3542//===----------------------------------------------------------------------===//
3543
3544/// EmitValue - Emit string value.
3545///
3546void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3547 DD.getAsm()->EmitString(String);
3548}
3549
3550//===----------------------------------------------------------------------===//
3551
3552/// EmitValue - Emit label value.
3553///
3554void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
Dan Gohman597b4842007-09-28 16:50:28 +00003555 bool IsSmall = Form == DW_FORM_data4;
3556 DD.EmitReference(Label, false, IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557}
3558
3559/// SizeOf - Determine size of label value in bytes.
3560///
3561unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
Dan Gohman597b4842007-09-28 16:50:28 +00003562 if (Form == DW_FORM_data4) return 4;
Dan Gohmancfb72b22007-09-27 23:12:31 +00003563 return DD.getTargetData()->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003564}
3565
3566//===----------------------------------------------------------------------===//
3567
3568/// EmitValue - Emit label value.
3569///
3570void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
Dan Gohman597b4842007-09-28 16:50:28 +00003571 bool IsSmall = Form == DW_FORM_data4;
3572 DD.EmitReference(Label, false, IsSmall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003573}
3574
3575/// SizeOf - Determine size of label value in bytes.
3576///
3577unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
Dan Gohman597b4842007-09-28 16:50:28 +00003578 if (Form == DW_FORM_data4) return 4;
Dan Gohmancfb72b22007-09-27 23:12:31 +00003579 return DD.getTargetData()->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003580}
3581
3582//===----------------------------------------------------------------------===//
3583
3584/// EmitValue - Emit delta value.
3585///
3586void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3587 bool IsSmall = Form == DW_FORM_data4;
3588 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3589}
3590
3591/// SizeOf - Determine size of delta value in bytes.
3592///
3593unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3594 if (Form == DW_FORM_data4) return 4;
Dan Gohmancfb72b22007-09-27 23:12:31 +00003595 return DD.getTargetData()->getPointerSize();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003596}
3597
3598//===----------------------------------------------------------------------===//
3599
3600/// EmitValue - Emit debug information entry offset.
3601///
3602void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3603 DD.getAsm()->EmitInt32(Entry->getOffset());
3604}
3605
3606//===----------------------------------------------------------------------===//
3607
3608/// ComputeSize - calculate the size of the block.
3609///
3610unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3611 if (!Size) {
3612 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3613
3614 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3615 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3616 }
3617 }
3618 return Size;
3619}
3620
3621/// EmitValue - Emit block data.
3622///
3623void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3624 switch (Form) {
3625 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3626 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3627 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3628 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3629 default: assert(0 && "Improper form for block"); break;
3630 }
3631
3632 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3633
3634 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3635 DD.getAsm()->EOL();
3636 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3637 }
3638}
3639
3640/// SizeOf - Determine size of block data in bytes.
3641///
3642unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3643 switch (Form) {
3644 case DW_FORM_block1: return Size + sizeof(int8_t);
3645 case DW_FORM_block2: return Size + sizeof(int16_t);
3646 case DW_FORM_block4: return Size + sizeof(int32_t);
3647 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3648 default: assert(0 && "Improper form for block"); break;
3649 }
3650 return 0;
3651}
3652
3653//===----------------------------------------------------------------------===//
3654/// DIE Implementation
3655
3656DIE::~DIE() {
3657 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3658 delete Children[i];
3659}
3660
3661/// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3662///
3663void DIE::AddSiblingOffset() {
3664 DIEInteger *DI = new DIEInteger(0);
3665 Values.insert(Values.begin(), DI);
3666 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3667}
3668
3669/// Profile - Used to gather unique data for the value folding set.
3670///
3671void DIE::Profile(FoldingSetNodeID &ID) {
3672 Abbrev.Profile(ID);
3673
3674 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3675 ID.AddPointer(Children[i]);
3676
3677 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3678 ID.AddPointer(Values[j]);
3679}
3680
3681#ifndef NDEBUG
3682void DIE::print(std::ostream &O, unsigned IncIndent) {
3683 static unsigned IndentCount = 0;
3684 IndentCount += IncIndent;
3685 const std::string Indent(IndentCount, ' ');
3686 bool isBlock = Abbrev.getTag() == 0;
3687
3688 if (!isBlock) {
3689 O << Indent
3690 << "Die: "
3691 << "0x" << std::hex << (intptr_t)this << std::dec
3692 << ", Offset: " << Offset
3693 << ", Size: " << Size
3694 << "\n";
3695
3696 O << Indent
3697 << TagString(Abbrev.getTag())
3698 << " "
3699 << ChildrenString(Abbrev.getChildrenFlag());
3700 } else {
3701 O << "Size: " << Size;
3702 }
3703 O << "\n";
3704
3705 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3706
3707 IndentCount += 2;
3708 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3709 O << Indent;
3710 if (!isBlock) {
3711 O << AttributeString(Data[i].getAttribute());
3712 } else {
3713 O << "Blk[" << i << "]";
3714 }
3715 O << " "
3716 << FormEncodingString(Data[i].getForm())
3717 << " ";
3718 Values[i]->print(O);
3719 O << "\n";
3720 }
3721 IndentCount -= 2;
3722
3723 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3724 Children[j]->print(O, 4);
3725 }
3726
3727 if (!isBlock) O << "\n";
3728 IndentCount -= IncIndent;
3729}
3730
3731void DIE::dump() {
3732 print(cerr);
3733}
3734#endif
3735
3736//===----------------------------------------------------------------------===//
3737/// DwarfWriter Implementation
3738///
3739
3740DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3741 const TargetAsmInfo *T) {
3742 DE = new DwarfException(OS, A, T);
3743 DD = new DwarfDebug(OS, A, T);
3744}
3745
3746DwarfWriter::~DwarfWriter() {
3747 delete DE;
3748 delete DD;
3749}
3750
3751/// SetModuleInfo - Set machine module info when it's known that pass manager
3752/// has created it. Set by the target AsmPrinter.
3753void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3754 DD->SetModuleInfo(MMI);
3755 DE->SetModuleInfo(MMI);
3756}
3757
3758/// BeginModule - Emit all Dwarf sections that should come prior to the
3759/// content.
3760void DwarfWriter::BeginModule(Module *M) {
3761 DE->BeginModule(M);
3762 DD->BeginModule(M);
3763}
3764
3765/// EndModule - Emit all Dwarf sections that should come after the content.
3766///
3767void DwarfWriter::EndModule() {
3768 DE->EndModule();
3769 DD->EndModule();
3770}
3771
3772/// BeginFunction - Gather pre-function debug information. Assumes being
3773/// emitted immediately after the function entry point.
3774void DwarfWriter::BeginFunction(MachineFunction *MF) {
3775 DE->BeginFunction(MF);
3776 DD->BeginFunction(MF);
3777}
3778
3779/// EndFunction - Gather and emit post-function debug information.
3780///
3781void DwarfWriter::EndFunction() {
3782 DD->EndFunction();
3783 DE->EndFunction();
3784
3785 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3786 // Clear function debug information.
3787 MMI->EndFunction();
3788 }
3789}