fcdf30d9c9652d26048aa4aa16aee9ff362a0e18
[oota-llvm.git] / lib / CodeGen / MachineDebugInfo.cpp
1 //===-- llvm/CodeGen/MachineDebugInfo.cpp -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/MachineDebugInfo.h"
11
12 #include "llvm/Constants.h"
13 #include "llvm/CodeGen/MachineLocation.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/Support/Dwarf.h"
20
21 #include <iostream>
22
23 using namespace llvm;
24 using namespace llvm::dwarf;
25
26 // Handle the Pass registration stuff necessary to use TargetData's.
27 namespace {
28   RegisterPass<MachineDebugInfo> X("machinedebuginfo", "Debug Information");
29 }
30
31 //===----------------------------------------------------------------------===//
32
33 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
34 /// specified value in their initializer somewhere.
35 static void
36 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
37   // Scan though value users.
38   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
39     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
40       // If the user is a GlobalVariable then add to result.
41       Result.push_back(GV);
42     } else if (Constant *C = dyn_cast<Constant>(*I)) {
43       // If the user is a constant variable then scan its users
44       getGlobalVariablesUsing(C, Result);
45     }
46   }
47 }
48
49 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
50 /// named GlobalVariable.
51 static std::vector<GlobalVariable*>
52 getGlobalVariablesUsing(Module &M, const std::string &RootName) {
53   std::vector<GlobalVariable*> Result;  // GlobalVariables matching criteria.
54   
55   std::vector<const Type*> FieldTypes;
56   FieldTypes.push_back(Type::UIntTy);
57   FieldTypes.push_back(Type::UIntTy);
58
59   // Get the GlobalVariable root.
60   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
61                                                 StructType::get(FieldTypes));
62
63   // If present and linkonce then scan for users.
64   if (UseRoot && UseRoot->hasLinkOnceLinkage()) {
65     getGlobalVariablesUsing(UseRoot, Result);
66   }
67   
68   return Result;
69 }
70   
71 /// isStringValue - Return true if the given value can be coerced to a string.
72 ///
73 static bool isStringValue(Value *V) {
74   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
75     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
76       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
77       return Init->isString();
78     }
79   } else if (Constant *C = dyn_cast<Constant>(V)) {
80     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
81       return isStringValue(GV);
82     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
83       if (CE->getOpcode() == Instruction::GetElementPtr) {
84         if (CE->getNumOperands() == 3 &&
85             cast<Constant>(CE->getOperand(1))->isNullValue() &&
86             isa<ConstantInt>(CE->getOperand(2))) {
87           return isStringValue(CE->getOperand(0));
88         }
89       }
90     }
91   }
92   return false;
93 }
94
95 /// getGlobalVariable - Return either a direct or cast Global value.
96 ///
97 static GlobalVariable *getGlobalVariable(Value *V) {
98   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
99     return GV;
100   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
101     if (CE->getOpcode() == Instruction::Cast) {
102       return dyn_cast<GlobalVariable>(CE->getOperand(0));
103     }
104   }
105   return NULL;
106 }
107
108 /// isGlobalVariable - Return true if the given value can be coerced to a
109 /// GlobalVariable.
110 static bool isGlobalVariable(Value *V) {
111   if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
112     return true;
113   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
114     if (CE->getOpcode() == Instruction::Cast) {
115       return isa<GlobalVariable>(CE->getOperand(0));
116     }
117   }
118   return false;
119 }
120
121 /// getUIntOperand - Return ith operand if it is an unsigned integer.
122 ///
123 static ConstantUInt *getUIntOperand(GlobalVariable *GV, unsigned i) {
124   // Make sure the GlobalVariable has an initializer.
125   if (!GV->hasInitializer()) return NULL;
126   
127   // Get the initializer constant.
128   ConstantStruct *CI = dyn_cast<ConstantStruct>(GV->getInitializer());
129   if (!CI) return NULL;
130   
131   // Check if there is at least i + 1 operands.
132   unsigned N = CI->getNumOperands();
133   if (i >= N) return NULL;
134
135   // Check constant.
136   return dyn_cast<ConstantUInt>(CI->getOperand(i));
137 }
138 //===----------------------------------------------------------------------===//
139
140 /// ApplyToFields - Target the visitor to each field of the debug information
141 /// descriptor.
142 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
143   DD->ApplyToFields(this);
144 }
145
146 //===----------------------------------------------------------------------===//
147 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
148 /// the supplied DebugInfoDesc.
149 class DICountVisitor : public DIVisitor {
150 private:
151   unsigned Count;                       // Running count of fields.
152   
153 public:
154   DICountVisitor() : DIVisitor(), Count(0) {}
155   
156   // Accessors.
157   unsigned getCount() const { return Count; }
158   
159   /// Apply - Count each of the fields.
160   ///
161   virtual void Apply(int &Field)             { ++Count; }
162   virtual void Apply(unsigned &Field)        { ++Count; }
163   virtual void Apply(int64_t &Field)         { ++Count; }
164   virtual void Apply(uint64_t &Field)        { ++Count; }
165   virtual void Apply(bool &Field)            { ++Count; }
166   virtual void Apply(std::string &Field)     { ++Count; }
167   virtual void Apply(DebugInfoDesc *&Field)  { ++Count; }
168   virtual void Apply(GlobalVariable *&Field) { ++Count; }
169   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
170     ++Count;
171   }
172 };
173
174 //===----------------------------------------------------------------------===//
175 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
176 /// supplied DebugInfoDesc.
177 class DIDeserializeVisitor : public DIVisitor {
178 private:
179   DIDeserializer &DR;                   // Active deserializer.
180   unsigned I;                           // Current operand index.
181   ConstantStruct *CI;                   // GlobalVariable constant initializer.
182
183 public:
184   DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
185   : DIVisitor()
186   , DR(D)
187   , I(0)
188   , CI(cast<ConstantStruct>(GV->getInitializer()))
189   {}
190   
191   /// Apply - Set the value of each of the fields.
192   ///
193   virtual void Apply(int &Field) {
194     Constant *C = CI->getOperand(I++);
195     Field = cast<ConstantSInt>(C)->getValue();
196   }
197   virtual void Apply(unsigned &Field) {
198     Constant *C = CI->getOperand(I++);
199     Field = cast<ConstantUInt>(C)->getValue();
200   }
201   virtual void Apply(int64_t &Field) {
202     Constant *C = CI->getOperand(I++);
203     Field = cast<ConstantSInt>(C)->getValue();
204   }
205   virtual void Apply(uint64_t &Field) {
206     Constant *C = CI->getOperand(I++);
207     Field = cast<ConstantUInt>(C)->getValue();
208   }
209   virtual void Apply(bool &Field) {
210     Constant *C = CI->getOperand(I++);
211     Field = cast<ConstantBool>(C)->getValue();
212   }
213   virtual void Apply(std::string &Field) {
214     Constant *C = CI->getOperand(I++);
215     Field = C->getStringValue();
216   }
217   virtual void Apply(DebugInfoDesc *&Field) {
218     Constant *C = CI->getOperand(I++);
219     Field = DR.Deserialize(C);
220   }
221   virtual void Apply(GlobalVariable *&Field) {
222     Constant *C = CI->getOperand(I++);
223     Field = getGlobalVariable(C);
224   }
225   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
226     Constant *C = CI->getOperand(I++);
227     GlobalVariable *GV = getGlobalVariable(C);
228     Field.resize(0);
229     // Have to be able to deal with the empty array case (zero initializer)
230     if (!GV->hasInitializer()) return;
231     if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
232       for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
233         GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
234         DebugInfoDesc *DE = DR.Deserialize(GVE);
235         Field.push_back(DE);
236       }
237     }
238   }
239 };
240
241 //===----------------------------------------------------------------------===//
242 /// DISerializeVisitor - This DIVisitor serializes all the fields in
243 /// the supplied DebugInfoDesc.
244 class DISerializeVisitor : public DIVisitor {
245 private:
246   DISerializer &SR;                     // Active serializer.
247   std::vector<Constant*> &Elements;     // Element accumulator.
248   
249 public:
250   DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
251   : DIVisitor()
252   , SR(S)
253   , Elements(E)
254   {}
255   
256   /// Apply - Set the value of each of the fields.
257   ///
258   virtual void Apply(int &Field) {
259     Elements.push_back(ConstantSInt::get(Type::IntTy, Field));
260   }
261   virtual void Apply(unsigned &Field) {
262     Elements.push_back(ConstantUInt::get(Type::UIntTy, Field));
263   }
264   virtual void Apply(int64_t &Field) {
265     Elements.push_back(ConstantSInt::get(Type::LongTy, Field));
266   }
267   virtual void Apply(uint64_t &Field) {
268     Elements.push_back(ConstantUInt::get(Type::ULongTy, Field));
269   }
270   virtual void Apply(bool &Field) {
271     Elements.push_back(ConstantBool::get(Field));
272   }
273   virtual void Apply(std::string &Field) {
274       Elements.push_back(SR.getString(Field));
275   }
276   virtual void Apply(DebugInfoDesc *&Field) {
277     GlobalVariable *GV = NULL;
278     
279     // If non-NULL then convert to global.
280     if (Field) GV = SR.Serialize(Field);
281     
282     // FIXME - At some point should use specific type.
283     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
284     
285     if (GV) {
286       // Set to pointer to global.
287       Elements.push_back(ConstantExpr::getCast(GV, EmptyTy));
288     } else {
289       // Use NULL.
290       Elements.push_back(ConstantPointerNull::get(EmptyTy));
291     }
292   }
293   virtual void Apply(GlobalVariable *&Field) {
294     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
295     if (Field) {
296       Elements.push_back(ConstantExpr::getCast(Field, EmptyTy));
297     } else {
298       Elements.push_back(ConstantPointerNull::get(EmptyTy));
299     }
300   }
301   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
302     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
303     unsigned N = Field.size();
304     ArrayType *AT = ArrayType::get(EmptyTy, N);
305     std::vector<Constant *> ArrayElements;
306
307     for (unsigned i = 0, N = Field.size(); i < N; ++i) {
308       GlobalVariable *GVE = SR.Serialize(Field[i]);
309       Constant *CE = ConstantExpr::getCast(GVE, EmptyTy);
310       ArrayElements.push_back(cast<Constant>(CE));
311     }
312     
313     Constant *CA = ConstantArray::get(AT, ArrayElements);
314     GlobalVariable *CAGV = new GlobalVariable(AT, true,
315                                               GlobalValue::InternalLinkage,
316                                               CA, "llvm.dbg.array",
317                                               SR.getModule());
318     CAGV->setSection("llvm.metadata");
319     Constant *CAE = ConstantExpr::getCast(CAGV, EmptyTy);
320     Elements.push_back(CAE);
321   }
322 };
323
324 //===----------------------------------------------------------------------===//
325 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
326 /// the supplied DebugInfoDesc.
327 class DIGetTypesVisitor : public DIVisitor {
328 private:
329   DISerializer &SR;                     // Active serializer.
330   std::vector<const Type*> &Fields;     // Type accumulator.
331   
332 public:
333   DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
334   : DIVisitor()
335   , SR(S)
336   , Fields(F)
337   {}
338   
339   /// Apply - Set the value of each of the fields.
340   ///
341   virtual void Apply(int &Field) {
342     Fields.push_back(Type::IntTy);
343   }
344   virtual void Apply(unsigned &Field) {
345     Fields.push_back(Type::UIntTy);
346   }
347   virtual void Apply(int64_t &Field) {
348     Fields.push_back(Type::LongTy);
349   }
350   virtual void Apply(uint64_t &Field) {
351     Fields.push_back(Type::ULongTy);
352   }
353   virtual void Apply(bool &Field) {
354     Fields.push_back(Type::BoolTy);
355   }
356   virtual void Apply(std::string &Field) {
357     Fields.push_back(SR.getStrPtrType());
358   }
359   virtual void Apply(DebugInfoDesc *&Field) {
360     // FIXME - At some point should use specific type.
361     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
362     Fields.push_back(EmptyTy);
363   }
364   virtual void Apply(GlobalVariable *&Field) {
365     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
366     Fields.push_back(EmptyTy);
367   }
368   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
369     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
370     Fields.push_back(EmptyTy);
371   }
372 };
373
374 //===----------------------------------------------------------------------===//
375 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
376 /// a constant initializer.
377 class DIVerifyVisitor : public DIVisitor {
378 private:
379   DIVerifier &VR;                       // Active verifier.
380   bool IsValid;                         // Validity status.
381   unsigned I;                           // Current operand index.
382   ConstantStruct *CI;                   // GlobalVariable constant initializer.
383   
384 public:
385   DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
386   : DIVisitor()
387   , VR(V)
388   , IsValid(true)
389   , I(0)
390   , CI(cast<ConstantStruct>(GV->getInitializer()))
391   {
392   }
393   
394   // Accessors.
395   bool isValid() const { return IsValid; }
396   
397   /// Apply - Set the value of each of the fields.
398   ///
399   virtual void Apply(int &Field) {
400     Constant *C = CI->getOperand(I++);
401     IsValid = IsValid && isa<ConstantInt>(C);
402   }
403   virtual void Apply(unsigned &Field) {
404     Constant *C = CI->getOperand(I++);
405     IsValid = IsValid && isa<ConstantInt>(C);
406   }
407   virtual void Apply(int64_t &Field) {
408     Constant *C = CI->getOperand(I++);
409     IsValid = IsValid && isa<ConstantInt>(C);
410   }
411   virtual void Apply(uint64_t &Field) {
412     Constant *C = CI->getOperand(I++);
413     IsValid = IsValid && isa<ConstantInt>(C);
414   }
415   virtual void Apply(bool &Field) {
416     Constant *C = CI->getOperand(I++);
417     IsValid = IsValid && isa<ConstantBool>(C);
418   }
419   virtual void Apply(std::string &Field) {
420     Constant *C = CI->getOperand(I++);
421     IsValid = IsValid && (!C || isStringValue(C));
422   }
423   virtual void Apply(DebugInfoDesc *&Field) {
424     // FIXME - Prepare the correct descriptor.
425     Constant *C = CI->getOperand(I++);
426     IsValid = IsValid && isGlobalVariable(C);
427   }
428   virtual void Apply(GlobalVariable *&Field) {
429     Constant *C = CI->getOperand(I++);
430     IsValid = IsValid && isGlobalVariable(C);
431   }
432   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
433     Constant *C = CI->getOperand(I++);
434     IsValid = IsValid && isGlobalVariable(C);
435     if (!IsValid) return;
436
437     GlobalVariable *GV = getGlobalVariable(C);
438     IsValid = IsValid && GV && GV->hasInitializer();
439     if (!IsValid) return;
440     
441     ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
442     IsValid = IsValid && CA;
443     if (!IsValid) return;
444
445     for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
446       IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
447       if (!IsValid) return;
448     
449       GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
450       VR.Verify(GVE);
451     }
452   }
453 };
454
455
456 //===----------------------------------------------------------------------===//
457
458 /// TagFromGlobal - Returns the tag number from a debug info descriptor
459 /// GlobalVariable.   Return DIIValid if operand is not an unsigned int. 
460 unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
461   ConstantUInt *C = getUIntOperand(GV, 0);
462   return C ? ((unsigned)C->getValue() & tag_mask) : (unsigned)DW_TAG_invalid;
463 }
464
465 /// VersionFromGlobal - Returns the version number from a debug info
466 /// descriptor GlobalVariable.  Return DIIValid if operand is not an unsigned
467 /// int.
468 unsigned  DebugInfoDesc::VersionFromGlobal(GlobalVariable *GV) {
469   ConstantUInt *C = getUIntOperand(GV, 0);
470   return C ? ((unsigned)C->getValue() >> version_shift) :
471              (unsigned)DW_TAG_invalid;
472 }
473
474 /// DescFactory - Create an instance of debug info descriptor based on Tag.
475 /// Return NULL if not a recognized Tag.
476 DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
477   switch (Tag) {
478   case DW_TAG_anchor:           return new AnchorDesc();
479   case DW_TAG_compile_unit:     return new CompileUnitDesc();
480   case DW_TAG_variable:         return new GlobalVariableDesc();
481   case DW_TAG_subprogram:       return new SubprogramDesc();
482   case DW_TAG_lexical_block:    return new BlockDesc();
483   case DW_TAG_base_type:        return new BasicTypeDesc();
484   case DW_TAG_typedef:
485   case DW_TAG_pointer_type:        
486   case DW_TAG_reference_type:
487   case DW_TAG_const_type:
488   case DW_TAG_volatile_type:        
489   case DW_TAG_restrict_type:
490   case DW_TAG_member:           return new DerivedTypeDesc(Tag);
491   case DW_TAG_array_type:
492   case DW_TAG_structure_type:
493   case DW_TAG_union_type:
494   case DW_TAG_enumeration_type: return new CompositeTypeDesc(Tag);
495   case DW_TAG_subrange_type:    return new SubrangeDesc();
496   case DW_TAG_enumerator:       return new EnumeratorDesc();
497   case DW_TAG_return_variable:
498   case DW_TAG_arg_variable:
499   case DW_TAG_auto_variable:    return new VariableDesc(Tag);
500   default: break;
501   }
502   return NULL;
503 }
504
505 /// getLinkage - get linkage appropriate for this type of descriptor.
506 ///
507 GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
508   return GlobalValue::InternalLinkage;
509 }
510
511 /// ApplyToFields - Target the vistor to the fields of the descriptor.
512 ///
513 void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
514   Visitor->Apply(Tag);
515 }
516
517 //===----------------------------------------------------------------------===//
518
519 AnchorDesc::AnchorDesc()
520 : DebugInfoDesc(DW_TAG_anchor)
521 , AnchorTag(0)
522 {}
523 AnchorDesc::AnchorDesc(AnchoredDesc *D)
524 : DebugInfoDesc(DW_TAG_anchor)
525 , AnchorTag(D->getTag())
526 {}
527
528 // Implement isa/cast/dyncast.
529 bool AnchorDesc::classof(const DebugInfoDesc *D) {
530   return D->getTag() == DW_TAG_anchor;
531 }
532   
533 /// getLinkage - get linkage appropriate for this type of descriptor.
534 ///
535 GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
536   return GlobalValue::LinkOnceLinkage;
537 }
538
539 /// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
540 ///
541 void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
542   DebugInfoDesc::ApplyToFields(Visitor);
543   
544   Visitor->Apply(AnchorTag);
545 }
546
547 /// getDescString - Return a string used to compose global names and labels. A
548 /// A global variable name needs to be defined for each debug descriptor that is
549 /// anchored. NOTE: that each global variable named here also needs to be added
550 /// to the list of names left external in the internalizer.
551 ///   ExternalNames.insert("llvm.dbg.compile_units");
552 ///   ExternalNames.insert("llvm.dbg.global_variables");
553 ///   ExternalNames.insert("llvm.dbg.subprograms");
554 const char *AnchorDesc::getDescString() const {
555   switch (AnchorTag) {
556   case DW_TAG_compile_unit: return CompileUnitDesc::AnchorString;
557   case DW_TAG_variable:     return GlobalVariableDesc::AnchorString;
558   case DW_TAG_subprogram:   return SubprogramDesc::AnchorString;
559   default: break;
560   }
561
562   assert(0 && "Tag does not have a case for anchor string");
563   return "";
564 }
565
566 /// getTypeString - Return a string used to label this descriptors type.
567 ///
568 const char *AnchorDesc::getTypeString() const {
569   return "llvm.dbg.anchor.type";
570 }
571
572 #ifndef NDEBUG
573 void AnchorDesc::dump() {
574   std::cerr << getDescString() << " "
575             << "Version(" << getVersion() << "), "
576             << "Tag(" << getTag() << "), "
577             << "AnchorTag(" << AnchorTag << ")\n";
578 }
579 #endif
580
581 //===----------------------------------------------------------------------===//
582
583 AnchoredDesc::AnchoredDesc(unsigned T)
584 : DebugInfoDesc(T)
585 , Anchor(NULL)
586 {}
587
588 /// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
589 ///
590 void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
591   DebugInfoDesc::ApplyToFields(Visitor);
592
593   DebugInfoDesc *Tmp = Anchor;
594   Visitor->Apply(Tmp);
595   Anchor = (AnchorDesc*)Tmp;
596 }
597
598 //===----------------------------------------------------------------------===//
599
600 CompileUnitDesc::CompileUnitDesc()
601 : AnchoredDesc(DW_TAG_compile_unit)
602 , Language(0)
603 , FileName("")
604 , Directory("")
605 , Producer("")
606 {}
607
608 // Implement isa/cast/dyncast.
609 bool CompileUnitDesc::classof(const DebugInfoDesc *D) {
610   return D->getTag() == DW_TAG_compile_unit;
611 }
612
613 /// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
614 ///
615 void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
616   AnchoredDesc::ApplyToFields(Visitor);
617
618   Visitor->Apply(Language);
619   Visitor->Apply(FileName);
620   Visitor->Apply(Directory);
621   Visitor->Apply(Producer);
622 }
623
624 /// getDescString - Return a string used to compose global names and labels.
625 ///
626 const char *CompileUnitDesc::getDescString() const {
627   return "llvm.dbg.compile_unit";
628 }
629
630 /// getTypeString - Return a string used to label this descriptors type.
631 ///
632 const char *CompileUnitDesc::getTypeString() const {
633   return "llvm.dbg.compile_unit.type";
634 }
635
636 /// getAnchorString - Return a string used to label this descriptor's anchor.
637 ///
638 const char *CompileUnitDesc::AnchorString = "llvm.dbg.compile_units";
639 const char *CompileUnitDesc::getAnchorString() const {
640   return AnchorString;
641 }
642
643 #ifndef NDEBUG
644 void CompileUnitDesc::dump() {
645   std::cerr << getDescString() << " "
646             << "Version(" << getVersion() << "), "
647             << "Tag(" << getTag() << "), "
648             << "Anchor(" << getAnchor() << "), "
649             << "Language(" << Language << "), "
650             << "FileName(\"" << FileName << "\"), "
651             << "Directory(\"" << Directory << "\"), "
652             << "Producer(\"" << Producer << "\")\n";
653 }
654 #endif
655
656 //===----------------------------------------------------------------------===//
657
658 TypeDesc::TypeDesc(unsigned T)
659 : DebugInfoDesc(T)
660 , Context(NULL)
661 , Name("")
662 , File(NULL)
663 , Line(0)
664 , Size(0)
665 , Align(0)
666 , Offset(0)
667 {}
668
669 /// ApplyToFields - Target the visitor to the fields of the TypeDesc.
670 ///
671 void TypeDesc::ApplyToFields(DIVisitor *Visitor) {
672   DebugInfoDesc::ApplyToFields(Visitor);
673   
674   Visitor->Apply(Context);
675   Visitor->Apply(Name);
676   DebugInfoDesc* Tmp = File;
677   Visitor->Apply(Tmp);
678   File = (CompileUnitDesc*)Tmp;
679   Visitor->Apply(Line);
680   Visitor->Apply(Size);
681   Visitor->Apply(Align);
682   Visitor->Apply(Offset);
683 }
684
685 /// getDescString - Return a string used to compose global names and labels.
686 ///
687 const char *TypeDesc::getDescString() const {
688   return "llvm.dbg.type";
689 }
690
691 /// getTypeString - Return a string used to label this descriptor's type.
692 ///
693 const char *TypeDesc::getTypeString() const {
694   return "llvm.dbg.type.type";
695 }
696
697 #ifndef NDEBUG
698 void TypeDesc::dump() {
699   std::cerr << getDescString() << " "
700             << "Version(" << getVersion() << "), "
701             << "Tag(" << getTag() << "), "
702             << "Context(" << Context << "), "
703             << "Name(\"" << Name << "\"), "
704             << "File(" << File << "), "
705             << "Line(" << Line << "), "
706             << "Size(" << Size << "), "
707             << "Align(" << Align << "), "
708             << "Offset(" << Offset << ")\n";
709 }
710 #endif
711
712 //===----------------------------------------------------------------------===//
713
714 BasicTypeDesc::BasicTypeDesc()
715 : TypeDesc(DW_TAG_base_type)
716 , Encoding(0)
717 {}
718
719 // Implement isa/cast/dyncast.
720 bool BasicTypeDesc::classof(const DebugInfoDesc *D) {
721   return D->getTag() == DW_TAG_base_type;
722 }
723
724 /// ApplyToFields - Target the visitor to the fields of the BasicTypeDesc.
725 ///
726 void BasicTypeDesc::ApplyToFields(DIVisitor *Visitor) {
727   TypeDesc::ApplyToFields(Visitor);
728   
729   Visitor->Apply(Encoding);
730 }
731
732 /// getDescString - Return a string used to compose global names and labels.
733 ///
734 const char *BasicTypeDesc::getDescString() const {
735   return "llvm.dbg.basictype";
736 }
737
738 /// getTypeString - Return a string used to label this descriptor's type.
739 ///
740 const char *BasicTypeDesc::getTypeString() const {
741   return "llvm.dbg.basictype.type";
742 }
743
744 #ifndef NDEBUG
745 void BasicTypeDesc::dump() {
746   std::cerr << getDescString() << " "
747             << "Version(" << getVersion() << "), "
748             << "Tag(" << getTag() << "), "
749             << "Context(" << getContext() << "), "
750             << "Name(\"" << getName() << "\"), "
751             << "Size(" << getSize() << "), "
752             << "Encoding(" << Encoding << ")\n";
753 }
754 #endif
755
756 //===----------------------------------------------------------------------===//
757
758 DerivedTypeDesc::DerivedTypeDesc(unsigned T)
759 : TypeDesc(T)
760 , FromType(NULL)
761 {}
762
763 // Implement isa/cast/dyncast.
764 bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
765   unsigned T =  D->getTag();
766   switch (T) {
767   case DW_TAG_typedef:
768   case DW_TAG_pointer_type:
769   case DW_TAG_reference_type:
770   case DW_TAG_const_type:
771   case DW_TAG_volatile_type:
772   case DW_TAG_restrict_type:
773   case DW_TAG_member:
774     return true;
775   default: break;
776   }
777   return false;
778 }
779
780 /// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
781 ///
782 void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
783   TypeDesc::ApplyToFields(Visitor);
784   
785   DebugInfoDesc* Tmp = FromType;
786   Visitor->Apply(Tmp);
787   FromType = (TypeDesc*)Tmp;
788 }
789
790 /// getDescString - Return a string used to compose global names and labels.
791 ///
792 const char *DerivedTypeDesc::getDescString() const {
793   return "llvm.dbg.derivedtype";
794 }
795
796 /// getTypeString - Return a string used to label this descriptor's type.
797 ///
798 const char *DerivedTypeDesc::getTypeString() const {
799   return "llvm.dbg.derivedtype.type";
800 }
801
802 #ifndef NDEBUG
803 void DerivedTypeDesc::dump() {
804   std::cerr << getDescString() << " "
805             << "Version(" << getVersion() << "), "
806             << "Tag(" << getTag() << "), "
807             << "Context(" << getContext() << "), "
808             << "Name(\"" << getName() << "\"), "
809             << "Size(" << getSize() << "), "
810             << "File(" << getFile() << "), "
811             << "Line(" << getLine() << "), "
812             << "FromType(" << FromType << ")\n";
813 }
814 #endif
815
816 //===----------------------------------------------------------------------===//
817
818 CompositeTypeDesc::CompositeTypeDesc(unsigned T)
819 : DerivedTypeDesc(T)
820 , Elements()
821 {}
822   
823 // Implement isa/cast/dyncast.
824 bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
825   unsigned T =  D->getTag();
826   switch (T) {
827   case DW_TAG_array_type:
828   case DW_TAG_structure_type:
829   case DW_TAG_union_type:
830   case DW_TAG_enumeration_type:
831     return true;
832   default: break;
833   }
834   return false;
835 }
836
837 /// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
838 ///
839 void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
840   DerivedTypeDesc::ApplyToFields(Visitor);
841   
842   Visitor->Apply(Elements);
843 }
844
845 /// getDescString - Return a string used to compose global names and labels.
846 ///
847 const char *CompositeTypeDesc::getDescString() const {
848   return "llvm.dbg.compositetype";
849 }
850
851 /// getTypeString - Return a string used to label this descriptor's type.
852 ///
853 const char *CompositeTypeDesc::getTypeString() const {
854   return "llvm.dbg.compositetype.type";
855 }
856
857 #ifndef NDEBUG
858 void CompositeTypeDesc::dump() {
859   std::cerr << getDescString() << " "
860             << "Version(" << getVersion() << "), "
861             << "Tag(" << getTag() << "), "
862             << "Context(" << getContext() << "), "
863             << "Name(\"" << getName() << "\"), "
864             << "Size(" << getSize() << "), "
865             << "File(" << getFile() << "), "
866             << "Line(" << getLine() << "), "
867             << "FromType(" << getFromType() << "), "
868             << "Elements.size(" << Elements.size() << ")\n";
869 }
870 #endif
871
872 //===----------------------------------------------------------------------===//
873
874 SubrangeDesc::SubrangeDesc()
875 : DebugInfoDesc(DW_TAG_subrange_type)
876 , Lo(0)
877 , Hi(0)
878 {}
879
880 // Implement isa/cast/dyncast.
881 bool SubrangeDesc::classof(const DebugInfoDesc *D) {
882   return D->getTag() == DW_TAG_subrange_type;
883 }
884
885 /// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
886 ///
887 void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
888   DebugInfoDesc::ApplyToFields(Visitor);
889
890   Visitor->Apply(Lo);
891   Visitor->Apply(Hi);
892 }
893
894 /// getDescString - Return a string used to compose global names and labels.
895 ///
896 const char *SubrangeDesc::getDescString() const {
897   return "llvm.dbg.subrange";
898 }
899   
900 /// getTypeString - Return a string used to label this descriptor's type.
901 ///
902 const char *SubrangeDesc::getTypeString() const {
903   return "llvm.dbg.subrange.type";
904 }
905
906 #ifndef NDEBUG
907 void SubrangeDesc::dump() {
908   std::cerr << getDescString() << " "
909             << "Version(" << getVersion() << "), "
910             << "Tag(" << getTag() << "), "
911             << "Lo(" << Lo << "), "
912             << "Hi(" << Hi << ")\n";
913 }
914 #endif
915
916 //===----------------------------------------------------------------------===//
917
918 EnumeratorDesc::EnumeratorDesc()
919 : DebugInfoDesc(DW_TAG_enumerator)
920 , Name("")
921 , Value(0)
922 {}
923
924 // Implement isa/cast/dyncast.
925 bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
926   return D->getTag() == DW_TAG_enumerator;
927 }
928
929 /// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
930 ///
931 void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
932   DebugInfoDesc::ApplyToFields(Visitor);
933
934   Visitor->Apply(Name);
935   Visitor->Apply(Value);
936 }
937
938 /// getDescString - Return a string used to compose global names and labels.
939 ///
940 const char *EnumeratorDesc::getDescString() const {
941   return "llvm.dbg.enumerator";
942 }
943   
944 /// getTypeString - Return a string used to label this descriptor's type.
945 ///
946 const char *EnumeratorDesc::getTypeString() const {
947   return "llvm.dbg.enumerator.type";
948 }
949
950 #ifndef NDEBUG
951 void EnumeratorDesc::dump() {
952   std::cerr << getDescString() << " "
953             << "Version(" << getVersion() << "), "
954             << "Tag(" << getTag() << "), "
955             << "Name(" << Name << "), "
956             << "Value(" << Value << ")\n";
957 }
958 #endif
959
960 //===----------------------------------------------------------------------===//
961
962 VariableDesc::VariableDesc(unsigned T)
963 : DebugInfoDesc(T)
964 , Context(NULL)
965 , Name("")
966 , File(NULL)
967 , Line(0)
968 , TyDesc(0)
969 {}
970
971 // Implement isa/cast/dyncast.
972 bool VariableDesc::classof(const DebugInfoDesc *D) {
973   unsigned T =  D->getTag();
974   switch (T) {
975   case DW_TAG_auto_variable:
976   case DW_TAG_arg_variable:
977   case DW_TAG_return_variable:
978     return true;
979   default: break;
980   }
981   return false;
982 }
983
984 /// ApplyToFields - Target the visitor to the fields of the VariableDesc.
985 ///
986 void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
987   DebugInfoDesc::ApplyToFields(Visitor);
988   
989   Visitor->Apply(Context);
990   Visitor->Apply(Name);
991   DebugInfoDesc* Tmp1 = File;
992   Visitor->Apply(Tmp1);
993   File = (CompileUnitDesc*)Tmp1;
994   Visitor->Apply(Line);
995   DebugInfoDesc* Tmp2 = TyDesc;
996   Visitor->Apply(Tmp2);
997   TyDesc = (TypeDesc*)Tmp2;
998 }
999
1000 /// getDescString - Return a string used to compose global names and labels.
1001 ///
1002 const char *VariableDesc::getDescString() const {
1003   return "llvm.dbg.variable";
1004 }
1005
1006 /// getTypeString - Return a string used to label this descriptor's type.
1007 ///
1008 const char *VariableDesc::getTypeString() const {
1009   return "llvm.dbg.variable.type";
1010 }
1011
1012 #ifndef NDEBUG
1013 void VariableDesc::dump() {
1014   std::cerr << getDescString() << " "
1015             << "Version(" << getVersion() << "), "
1016             << "Tag(" << getTag() << "), "
1017             << "Context(" << Context << "), "
1018             << "Name(\"" << Name << "\"), "
1019             << "File(" << File << "), "
1020             << "Line(" << Line << "), "
1021             << "TyDesc(" << TyDesc << ")\n";
1022 }
1023 #endif
1024
1025 //===----------------------------------------------------------------------===//
1026
1027 GlobalDesc::GlobalDesc(unsigned T)
1028 : AnchoredDesc(T)
1029 , Context(0)
1030 , Name("")
1031 , File(NULL)
1032 , Line(0)
1033 , TyDesc(NULL)
1034 , IsStatic(false)
1035 , IsDefinition(false)
1036 {}
1037
1038 /// ApplyToFields - Target the visitor to the fields of the global.
1039 ///
1040 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1041   AnchoredDesc::ApplyToFields(Visitor);
1042
1043   Visitor->Apply(Context);
1044   Visitor->Apply(Name);
1045   DebugInfoDesc* Tmp1 = File;
1046   Visitor->Apply(Tmp1);
1047   File = (CompileUnitDesc*)Tmp1;
1048   Visitor->Apply(Line);
1049   DebugInfoDesc* Tmp2 = TyDesc;
1050   Visitor->Apply(Tmp2);
1051   TyDesc = (TypeDesc*)Tmp2;
1052   Visitor->Apply(IsStatic);
1053   Visitor->Apply(IsDefinition);
1054 }
1055
1056 //===----------------------------------------------------------------------===//
1057
1058 GlobalVariableDesc::GlobalVariableDesc()
1059 : GlobalDesc(DW_TAG_variable)
1060 , Global(NULL)
1061 {}
1062
1063 // Implement isa/cast/dyncast.
1064 bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1065   return D->getTag() == DW_TAG_variable; 
1066 }
1067
1068 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1069 ///
1070 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1071   GlobalDesc::ApplyToFields(Visitor);
1072
1073   Visitor->Apply(Global);
1074 }
1075
1076 /// getDescString - Return a string used to compose global names and labels.
1077 ///
1078 const char *GlobalVariableDesc::getDescString() const {
1079   return "llvm.dbg.global_variable";
1080 }
1081
1082 /// getTypeString - Return a string used to label this descriptors type.
1083 ///
1084 const char *GlobalVariableDesc::getTypeString() const {
1085   return "llvm.dbg.global_variable.type";
1086 }
1087
1088 /// getAnchorString - Return a string used to label this descriptor's anchor.
1089 ///
1090 const char *GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1091 const char *GlobalVariableDesc::getAnchorString() const {
1092   return AnchorString;
1093 }
1094
1095 #ifndef NDEBUG
1096 void GlobalVariableDesc::dump() {
1097   std::cerr << getDescString() << " "
1098             << "Version(" << getVersion() << "), "
1099             << "Tag(" << getTag() << "), "
1100             << "Anchor(" << getAnchor() << "), "
1101             << "Name(\"" << getName() << "\"), "
1102             << "File(" << getFile() << "),"
1103             << "Line(" << getLine() << "),"
1104             << "Type(\"" << getType() << "\"), "
1105             << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1106             << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1107             << "Global(" << Global << ")\n";
1108 }
1109 #endif
1110
1111 //===----------------------------------------------------------------------===//
1112
1113 SubprogramDesc::SubprogramDesc()
1114 : GlobalDesc(DW_TAG_subprogram)
1115 {}
1116
1117 // Implement isa/cast/dyncast.
1118 bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1119   return D->getTag() == DW_TAG_subprogram;
1120 }
1121
1122 /// ApplyToFields - Target the visitor to the fields of the
1123 /// SubprogramDesc.
1124 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1125   GlobalDesc::ApplyToFields(Visitor);
1126 }
1127
1128 /// getDescString - Return a string used to compose global names and labels.
1129 ///
1130 const char *SubprogramDesc::getDescString() const {
1131   return "llvm.dbg.subprogram";
1132 }
1133
1134 /// getTypeString - Return a string used to label this descriptors type.
1135 ///
1136 const char *SubprogramDesc::getTypeString() const {
1137   return "llvm.dbg.subprogram.type";
1138 }
1139
1140 /// getAnchorString - Return a string used to label this descriptor's anchor.
1141 ///
1142 const char *SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1143 const char *SubprogramDesc::getAnchorString() const {
1144   return AnchorString;
1145 }
1146
1147 #ifndef NDEBUG
1148 void SubprogramDesc::dump() {
1149   std::cerr << getDescString() << " "
1150             << "Version(" << getVersion() << "), "
1151             << "Tag(" << getTag() << "), "
1152             << "Anchor(" << getAnchor() << "), "
1153             << "Name(\"" << getName() << "\"), "
1154             << "File(" << getFile() << "),"
1155             << "Line(" << getLine() << "),"
1156             << "Type(\"" << getType() << "\"), "
1157             << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1158             << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1159 }
1160 #endif
1161
1162 //===----------------------------------------------------------------------===//
1163
1164 BlockDesc::BlockDesc()
1165 : DebugInfoDesc(DW_TAG_lexical_block)
1166 , Context(NULL)
1167 {}
1168
1169 // Implement isa/cast/dyncast.
1170 bool BlockDesc::classof(const DebugInfoDesc *D) {
1171   return D->getTag() == DW_TAG_lexical_block;
1172 }
1173
1174 /// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1175 ///
1176 void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1177   DebugInfoDesc::ApplyToFields(Visitor);
1178
1179   Visitor->Apply(Context);
1180 }
1181
1182 /// getDescString - Return a string used to compose global names and labels.
1183 ///
1184 const char *BlockDesc::getDescString() const {
1185   return "llvm.dbg.block";
1186 }
1187
1188 /// getTypeString - Return a string used to label this descriptors type.
1189 ///
1190 const char *BlockDesc::getTypeString() const {
1191   return "llvm.dbg.block.type";
1192 }
1193
1194 #ifndef NDEBUG
1195 void BlockDesc::dump() {
1196   std::cerr << getDescString() << " "
1197             << "Version(" << getVersion() << "), "
1198             << "Tag(" << getTag() << "),"
1199             << "Context(" << Context << ")\n";
1200 }
1201 #endif
1202
1203 //===----------------------------------------------------------------------===//
1204
1205 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1206   return Deserialize(getGlobalVariable(V));
1207 }
1208 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1209   // Handle NULL.
1210   if (!GV) return NULL;
1211
1212   // Check to see if it has been already deserialized.
1213   DebugInfoDesc *&Slot = GlobalDescs[GV];
1214   if (Slot) return Slot;
1215
1216   // Get the Tag from the global.
1217   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1218   
1219   // Create an empty instance of the correct sort.
1220   Slot = DebugInfoDesc::DescFactory(Tag);
1221   
1222   // If not a user defined descriptor.
1223   if (Slot) {
1224     // Deserialize the fields.
1225     DIDeserializeVisitor DRAM(*this, GV);
1226     DRAM.ApplyToFields(Slot);
1227   }
1228   
1229   return Slot;
1230 }
1231
1232 //===----------------------------------------------------------------------===//
1233
1234 /// getStrPtrType - Return a "sbyte *" type.
1235 ///
1236 const PointerType *DISerializer::getStrPtrType() {
1237   // If not already defined.
1238   if (!StrPtrTy) {
1239     // Construct the pointer to signed bytes.
1240     StrPtrTy = PointerType::get(Type::SByteTy);
1241   }
1242   
1243   return StrPtrTy;
1244 }
1245
1246 /// getEmptyStructPtrType - Return a "{ }*" type.
1247 ///
1248 const PointerType *DISerializer::getEmptyStructPtrType() {
1249   // If not already defined.
1250   if (!EmptyStructPtrTy) {
1251     // Construct the empty structure type.
1252     const StructType *EmptyStructTy =
1253                                     StructType::get(std::vector<const Type*>());
1254     // Construct the pointer to empty structure type.
1255     EmptyStructPtrTy = PointerType::get(EmptyStructTy);
1256   }
1257   
1258   return EmptyStructPtrTy;
1259 }
1260
1261 /// getTagType - Return the type describing the specified descriptor (via tag.)
1262 ///
1263 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1264   // Attempt to get the previously defined type.
1265   StructType *&Ty = TagTypes[DD->getTag()];
1266   
1267   // If not already defined.
1268   if (!Ty) {
1269     // Set up fields vector.
1270     std::vector<const Type*> Fields;
1271     // Get types of fields.
1272     DIGetTypesVisitor GTAM(*this, Fields);
1273     GTAM.ApplyToFields(DD);
1274
1275     // Construct structured type.
1276     Ty = StructType::get(Fields);
1277     
1278     // Register type name with module.
1279     M->addTypeName(DD->getTypeString(), Ty);
1280   }
1281   
1282   return Ty;
1283 }
1284
1285 /// getString - Construct the string as constant string global.
1286 ///
1287 Constant *DISerializer::getString(const std::string &String) {
1288   // Check string cache for previous edition.
1289   Constant *&Slot = StringCache[String];
1290   // Return Constant if previously defined.
1291   if (Slot) return Slot;
1292   // If empty string then use a sbyte* null instead.
1293   if (String.empty()) {
1294     Slot = ConstantPointerNull::get(getStrPtrType());
1295   } else {
1296     // Construct string as an llvm constant.
1297     Constant *ConstStr = ConstantArray::get(String);
1298     // Otherwise create and return a new string global.
1299     GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1300                                                GlobalVariable::InternalLinkage,
1301                                                ConstStr, "str", M);
1302     StrGV->setSection("llvm.metadata");
1303     // Convert to generic string pointer.
1304     Slot = ConstantExpr::getCast(StrGV, getStrPtrType());
1305   }
1306   return Slot;
1307   
1308 }
1309
1310 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1311 /// so that it can be serialized to a .bc or .ll file.
1312 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1313   // Check if the DebugInfoDesc is already in the map.
1314   GlobalVariable *&Slot = DescGlobals[DD];
1315   
1316   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1317   if (Slot) return Slot;
1318   
1319   // Get the type associated with the Tag.
1320   const StructType *Ty = getTagType(DD);
1321
1322   // Create the GlobalVariable early to prevent infinite recursion.
1323   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1324                                           NULL, DD->getDescString(), M);
1325   GV->setSection("llvm.metadata");
1326
1327   // Insert new GlobalVariable in DescGlobals map.
1328   Slot = GV;
1329  
1330   // Set up elements vector
1331   std::vector<Constant*> Elements;
1332   // Add fields.
1333   DISerializeVisitor SRAM(*this, Elements);
1334   SRAM.ApplyToFields(DD);
1335   
1336   // Set the globals initializer.
1337   GV->setInitializer(ConstantStruct::get(Ty, Elements));
1338   
1339   return GV;
1340 }
1341
1342 //===----------------------------------------------------------------------===//
1343
1344 /// Verify - Return true if the GlobalVariable appears to be a valid
1345 /// serialization of a DebugInfoDesc.
1346 bool DIVerifier::Verify(Value *V) {
1347   return !V || Verify(getGlobalVariable(V));
1348 }
1349 bool DIVerifier::Verify(GlobalVariable *GV) {
1350   // NULLs are valid.
1351   if (!GV) return true;
1352   
1353   // Check prior validity.
1354   unsigned &ValiditySlot = Validity[GV];
1355   
1356   // If visited before then use old state.
1357   if (ValiditySlot) return ValiditySlot == Valid;
1358   
1359   // Assume validity for the time being (recursion.)
1360   ValiditySlot = Valid;
1361   
1362   // Make sure the global is internal or link once (anchor.)
1363   if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1364       GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1365     ValiditySlot = Invalid;
1366     return false;
1367   }
1368
1369   // Get the Tag
1370   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1371   
1372   // Check for user defined descriptors.
1373   if (Tag == DW_TAG_invalid) return true;
1374
1375   // Construct an empty DebugInfoDesc.
1376   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1377   
1378   // Allow for user defined descriptors.
1379   if (!DD) return true;
1380   
1381   // Get the initializer constant.
1382   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1383   
1384   // Get the operand count.
1385   unsigned N = CI->getNumOperands();
1386   
1387   // Get the field count.
1388   unsigned &CountSlot = Counts[Tag];
1389   if (!CountSlot) {
1390     // Check the operand count to the field count
1391     DICountVisitor CTAM;
1392     CTAM.ApplyToFields(DD);
1393     CountSlot = CTAM.getCount();
1394   }
1395   
1396   // Field count must be at most equal operand count.
1397   if (CountSlot >  N) {
1398     delete DD;
1399     ValiditySlot = Invalid;
1400     return false;
1401   }
1402   
1403   // Check each field for valid type.
1404   DIVerifyVisitor VRAM(*this, GV);
1405   VRAM.ApplyToFields(DD);
1406   
1407   // Release empty DebugInfoDesc.
1408   delete DD;
1409   
1410   // If fields are not valid.
1411   if (!VRAM.isValid()) {
1412     ValiditySlot = Invalid;
1413     return false;
1414   }
1415   
1416   return true;
1417 }
1418
1419 //===----------------------------------------------------------------------===//
1420
1421 DebugScope::~DebugScope() {
1422   for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1423   for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1424 }
1425
1426 //===----------------------------------------------------------------------===//
1427
1428 MachineDebugInfo::MachineDebugInfo()
1429 : DR()
1430 , VR()
1431 , CompileUnits()
1432 , Directories()
1433 , SourceFiles()
1434 , Lines()
1435 , LabelID(0)
1436 , ScopeMap()
1437 , RootScope(NULL)
1438 , FrameMoves()
1439 {}
1440 MachineDebugInfo::~MachineDebugInfo() {
1441
1442 }
1443
1444 /// doInitialization - Initialize the debug state for a new module.
1445 ///
1446 bool MachineDebugInfo::doInitialization() {
1447   return false;
1448 }
1449
1450 /// doFinalization - Tear down the debug state after completion of a module.
1451 ///
1452 bool MachineDebugInfo::doFinalization() {
1453   return false;
1454 }
1455
1456 /// BeginFunction - Begin gathering function debug information.
1457 ///
1458 void MachineDebugInfo::BeginFunction(MachineFunction *MF) {
1459   // Coming soon.
1460 }
1461
1462 /// MachineDebugInfo::EndFunction - Discard function debug information.
1463 ///
1464 void MachineDebugInfo::EndFunction() {
1465   // Clean up scope information.
1466   if (RootScope) {
1467     delete RootScope;
1468     ScopeMap.clear();
1469     RootScope = NULL;
1470   }
1471   
1472   // Clean up frame info.
1473   for (unsigned i = 0, N = FrameMoves.size(); i < N; ++i) delete FrameMoves[i];
1474   FrameMoves.clear();
1475 }
1476
1477 /// getDescFor - Convert a Value to a debug information descriptor.
1478 ///
1479 // FIXME - use new Value type when available.
1480 DebugInfoDesc *MachineDebugInfo::getDescFor(Value *V) {
1481   return DR.Deserialize(V);
1482 }
1483
1484 /// Verify - Verify that a Value is debug information descriptor.
1485 ///
1486 bool MachineDebugInfo::Verify(Value *V) {
1487   return VR.Verify(V);
1488 }
1489
1490 /// AnalyzeModule - Scan the module for global debug information.
1491 ///
1492 void MachineDebugInfo::AnalyzeModule(Module &M) {
1493   SetupCompileUnits(M);
1494 }
1495
1496 /// SetupCompileUnits - Set up the unique vector of compile units.
1497 ///
1498 void MachineDebugInfo::SetupCompileUnits(Module &M) {
1499   std::vector<CompileUnitDesc *>CU = getAnchoredDescriptors<CompileUnitDesc>(M);
1500   
1501   for (unsigned i = 0, N = CU.size(); i < N; i++) {
1502     CompileUnits.insert(CU[i]);
1503   }
1504 }
1505
1506 /// getCompileUnits - Return a vector of debug compile units.
1507 ///
1508 const UniqueVector<CompileUnitDesc *> MachineDebugInfo::getCompileUnits()const{
1509   return CompileUnits;
1510 }
1511
1512 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
1513 /// named GlobalVariable.
1514 std::vector<GlobalVariable*>
1515 MachineDebugInfo::getGlobalVariablesUsing(Module &M,
1516                                           const std::string &RootName) {
1517   return ::getGlobalVariablesUsing(M, RootName);
1518 }
1519
1520 /// RecordLabel - Records location information and associates it with a
1521 /// debug label.  Returns a unique label ID used to generate a label and 
1522 /// provide correspondence to the source line list.
1523 unsigned MachineDebugInfo::RecordLabel(unsigned Line, unsigned Column,
1524                                        unsigned Source) {
1525   unsigned ID = NextLabelID();
1526   Lines.push_back(new SourceLineInfo(Line, Column, Source, ID));
1527   return ID;
1528 }
1529
1530 /// RecordSource - Register a source file with debug info. Returns an source
1531 /// ID.
1532 unsigned MachineDebugInfo::RecordSource(const std::string &Directory,
1533                                         const std::string &Source) {
1534   unsigned DirectoryID = Directories.insert(Directory);
1535   return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
1536 }
1537 unsigned MachineDebugInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
1538   return RecordSource(CompileUnit->getDirectory(),
1539                       CompileUnit->getFileName());
1540 }
1541
1542 /// RecordRegionStart - Indicate the start of a region.
1543 ///
1544 unsigned MachineDebugInfo::RecordRegionStart(Value *V) {
1545   // FIXME - need to be able to handle split scopes because of bb cloning.
1546   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1547   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1548   unsigned ID = NextLabelID();
1549   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1550   return ID;
1551 }
1552
1553 /// RecordRegionEnd - Indicate the end of a region.
1554 ///
1555 unsigned MachineDebugInfo::RecordRegionEnd(Value *V) {
1556   // FIXME - need to be able to handle split scopes because of bb cloning.
1557   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1558   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1559   unsigned ID = NextLabelID();
1560   Scope->setEndLabelID(ID);
1561   return ID;
1562 }
1563
1564 /// RecordVariable - Indicate the declaration of  a local variable.
1565 ///
1566 void MachineDebugInfo::RecordVariable(Value *V, unsigned FrameIndex) {
1567   VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(V));
1568   DebugScope *Scope = getOrCreateScope(VD->getContext());
1569   DebugVariable *DV = new DebugVariable(VD, FrameIndex);
1570   Scope->AddVariable(DV);
1571 }
1572
1573 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1574 ///
1575 DebugScope *MachineDebugInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
1576   DebugScope *&Slot = ScopeMap[ScopeDesc];
1577   if (!Slot) {
1578     // FIXME - breaks down when the context is an inlined function.
1579     DebugInfoDesc *ParentDesc = NULL;
1580     if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
1581       ParentDesc = Block->getContext();
1582     }
1583     DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
1584     Slot = new DebugScope(Parent, ScopeDesc);
1585     if (Parent) {
1586       Parent->AddScope(Slot);
1587     } else if (RootScope) {
1588       // FIXME - Add inlined function scopes to the root so we can delete
1589       // them later.  Long term, handle inlined functions properly.
1590       RootScope->AddScope(Slot);
1591     } else {
1592       // First function is top level function.
1593       RootScope = Slot;
1594     }
1595   }
1596   return Slot;
1597 }
1598
1599