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