Coordinate activities with llvm-gcc4 and dwarf.
[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/DerivedTypes.h"
14 #include "llvm/GlobalVariable.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Module.h"
18 #include "llvm/Support/Dwarf.h"
19
20 #include <iostream>
21
22 using namespace llvm;
23
24 // Handle the Pass registration stuff necessary to use TargetData's.
25 namespace {
26   RegisterPass<MachineDebugInfo> X("machinedebuginfo", "Debug Information");
27 }
28
29 //===----------------------------------------------------------------------===//
30
31 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
32 /// specified value in their initializer somewhere.
33 static void
34 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
35   // Scan though value users.
36   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
37     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
38       // If the user is a GlobalVariable then add to result.
39       Result.push_back(GV);
40     } else if (Constant *C = dyn_cast<Constant>(*I)) {
41       // If the user is a constant variable then scan its users
42       getGlobalVariablesUsing(C, Result);
43     }
44   }
45 }
46
47 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
48 /// named GlobalVariable.
49 static std::vector<GlobalVariable*>
50 getGlobalVariablesUsing(Module &M, const std::string &RootName) {
51   std::vector<GlobalVariable*> Result;  // GlobalVariables matching criteria.
52   
53   std::vector<const Type*> FieldTypes;
54   FieldTypes.push_back(Type::UIntTy);
55   FieldTypes.push_back(PointerType::get(Type::SByteTy));
56
57   // Get the GlobalVariable root.
58   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
59                                                 StructType::get(FieldTypes));
60
61   // If present and linkonce then scan for users.
62   if (UseRoot && UseRoot->hasLinkOnceLinkage()) {
63     getGlobalVariablesUsing(UseRoot, Result);
64   }
65   
66   return Result;
67 }
68   
69 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
70 /// global into a string value.  Return an empty string if we can't do it.
71 ///
72 static const std::string getStringValue(Value *V, unsigned Offset = 0) {
73   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
74     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
75       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
76       if (Init->isString()) {
77         std::string Result = Init->getAsString();
78         if (Offset < Result.size()) {
79           // If we are pointing INTO The string, erase the beginning...
80           Result.erase(Result.begin(), Result.begin()+Offset);
81
82           // Take off the null terminator, and any string fragments after it.
83           std::string::size_type NullPos = Result.find_first_of((char)0);
84           if (NullPos != std::string::npos)
85             Result.erase(Result.begin()+NullPos, Result.end());
86           return Result;
87         }
88       }
89     }
90   } else if (Constant *C = dyn_cast<Constant>(V)) {
91     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
92       return getStringValue(GV, Offset);
93     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
94       if (CE->getOpcode() == Instruction::GetElementPtr) {
95         // Turn a gep into the specified offset.
96         if (CE->getNumOperands() == 3 &&
97             cast<Constant>(CE->getOperand(1))->isNullValue() &&
98             isa<ConstantInt>(CE->getOperand(2))) {
99           return getStringValue(CE->getOperand(0),
100                    Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
101         }
102       }
103     }
104   }
105   return "";
106 }
107
108 /// isStringValue - Return true if the given value can be coerced to a string.
109 ///
110 static bool isStringValue(Value *V) {
111   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
112     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
113       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
114       return Init->isString();
115     }
116   } else if (Constant *C = dyn_cast<Constant>(V)) {
117     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
118       return isStringValue(GV);
119     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
120       if (CE->getOpcode() == Instruction::GetElementPtr) {
121         if (CE->getNumOperands() == 3 &&
122             cast<Constant>(CE->getOperand(1))->isNullValue() &&
123             isa<ConstantInt>(CE->getOperand(2))) {
124           return isStringValue(CE->getOperand(0));
125         }
126       }
127     }
128   }
129   return false;
130 }
131
132 /// getGlobalVariable - Return either a direct or cast Global value.
133 ///
134 static GlobalVariable *getGlobalVariable(Value *V) {
135   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
136     return GV;
137   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
138     if (CE->getOpcode() == Instruction::Cast) {
139       return dyn_cast<GlobalVariable>(CE->getOperand(0));
140     }
141   }
142   return NULL;
143 }
144
145 /// isGlobalVariable - Return true if the given value can be coerced to a
146 /// GlobalVariable.
147 static bool isGlobalVariable(Value *V) {
148   if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
149     return true;
150   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
151     if (CE->getOpcode() == Instruction::Cast) {
152       return isa<GlobalVariable>(CE->getOperand(0));
153     }
154   }
155   return false;
156 }
157
158 /// getUIntOperand - Return ith operand if it is an unsigned integer.
159 ///
160 static ConstantUInt *getUIntOperand(GlobalVariable *GV, unsigned i) {
161   // Make sure the GlobalVariable has an initializer.
162   if (!GV->hasInitializer()) return NULL;
163   
164   // Get the initializer constant.
165   ConstantStruct *CI = dyn_cast<ConstantStruct>(GV->getInitializer());
166   if (!CI) return NULL;
167   
168   // Check if there is at least i + 1 operands.
169   unsigned N = CI->getNumOperands();
170   if (i >= N) return NULL;
171
172   // Check constant.
173   return dyn_cast<ConstantUInt>(CI->getOperand(i));
174 }
175 //===----------------------------------------------------------------------===//
176
177 /// ApplyToFields - Target the visitor to each field of the debug information
178 /// descriptor.
179 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
180   DD->ApplyToFields(this);
181 }
182
183 //===----------------------------------------------------------------------===//
184 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
185 /// the supplied DebugInfoDesc.
186 class DICountVisitor : public DIVisitor {
187 private:
188   unsigned Count;                       // Running count of fields.
189   
190 public:
191   DICountVisitor() : DIVisitor(), Count(0) {}
192   
193   // Accessors.
194   unsigned getCount() const { return Count; }
195   
196   /// Apply - Count each of the fields.
197   ///
198   virtual void Apply(int &Field)             { ++Count; }
199   virtual void Apply(unsigned &Field)        { ++Count; }
200   virtual void Apply(bool &Field)            { ++Count; }
201   virtual void Apply(std::string &Field)     { ++Count; }
202   virtual void Apply(DebugInfoDesc *&Field)  { ++Count; }
203   virtual void Apply(GlobalVariable *&Field) { ++Count; }
204 };
205
206 //===----------------------------------------------------------------------===//
207 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
208 /// supplied DebugInfoDesc.
209 class DIDeserializeVisitor : public DIVisitor {
210 private:
211   DIDeserializer &DR;                   // Active deserializer.
212   unsigned I;                           // Current operand index.
213   ConstantStruct *CI;                   // GlobalVariable constant initializer.
214
215 public:
216   DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
217   : DIVisitor()
218   , DR(D)
219   , I(0)
220   , CI(cast<ConstantStruct>(GV->getInitializer()))
221   {}
222   
223   /// Apply - Set the value of each of the fields.
224   ///
225   virtual void Apply(int &Field) {
226     Constant *C = CI->getOperand(I++);
227     Field = cast<ConstantSInt>(C)->getValue();
228   }
229   virtual void Apply(unsigned &Field) {
230     Constant *C = CI->getOperand(I++);
231     Field = cast<ConstantUInt>(C)->getValue();
232   }
233   virtual void Apply(bool &Field) {
234     Constant *C = CI->getOperand(I++);
235     Field = cast<ConstantBool>(C)->getValue();
236   }
237   virtual void Apply(std::string &Field) {
238     Constant *C = CI->getOperand(I++);
239     Field = getStringValue(C);
240   }
241   virtual void Apply(DebugInfoDesc *&Field) {
242     Constant *C = CI->getOperand(I++);
243     Field = DR.Deserialize(C);
244   }
245   virtual void Apply(GlobalVariable *&Field) {
246     Constant *C = CI->getOperand(I++);
247     Field = getGlobalVariable(C);
248   }
249 };
250
251 //===----------------------------------------------------------------------===//
252 /// DISerializeVisitor - This DIVisitor serializes all the fields in
253 /// the supplied DebugInfoDesc.
254 class DISerializeVisitor : public DIVisitor {
255 private:
256   DISerializer &SR;                     // Active serializer.
257   std::vector<Constant*> &Elements;     // Element accumulator.
258   
259 public:
260   DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
261   : DIVisitor()
262   , SR(S)
263   , Elements(E)
264   {}
265   
266   /// Apply - Set the value of each of the fields.
267   ///
268   virtual void Apply(int &Field) {
269     Elements.push_back(ConstantSInt::get(Type::IntTy, Field));
270   }
271   virtual void Apply(unsigned &Field) {
272     Elements.push_back(ConstantUInt::get(Type::UIntTy, Field));
273   }
274   virtual void Apply(bool &Field) {
275     Elements.push_back(ConstantBool::get(Field));
276   }
277   virtual void Apply(std::string &Field) {
278     Elements.push_back(SR.getString(Field));
279   }
280   virtual void Apply(DebugInfoDesc *&Field) {
281     GlobalVariable *GV = NULL;
282     
283     // If non-NULL the convert to global.
284     if (Field) GV = SR.Serialize(Field);
285     
286     // FIXME - At some point should use specific type.
287     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
288     
289     if (GV) {
290       // Set to pointer to global.
291       Elements.push_back(ConstantExpr::getCast(GV, EmptyTy));
292     } else {
293       // Use NULL.
294       Elements.push_back(ConstantPointerNull::get(EmptyTy));
295     }
296   }
297   virtual void Apply(GlobalVariable *&Field) {
298     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
299     if (Field) {
300       Elements.push_back(ConstantExpr::getCast(Field, EmptyTy));
301     } else {
302       Elements.push_back(ConstantPointerNull::get(EmptyTy));
303     }
304   }
305 };
306
307 //===----------------------------------------------------------------------===//
308 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
309 /// the supplied DebugInfoDesc.
310 class DIGetTypesVisitor : public DIVisitor {
311 private:
312   DISerializer &SR;                     // Active serializer.
313   std::vector<const Type*> &Fields;     // Type accumulator.
314   
315 public:
316   DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
317   : DIVisitor()
318   , SR(S)
319   , Fields(F)
320   {}
321   
322   /// Apply - Set the value of each of the fields.
323   ///
324   virtual void Apply(int &Field) {
325     Fields.push_back(Type::IntTy);
326   }
327   virtual void Apply(unsigned &Field) {
328     Fields.push_back(Type::UIntTy);
329   }
330   virtual void Apply(bool &Field) {
331     Fields.push_back(Type::BoolTy);
332   }
333   virtual void Apply(std::string &Field) {
334     Fields.push_back(SR.getStrPtrType());
335   }
336   virtual void Apply(DebugInfoDesc *&Field) {
337     // FIXME - At some point should use specific type.
338     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
339     Fields.push_back(EmptyTy);
340   }
341   virtual void Apply(GlobalVariable *&Field) {
342     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
343     Fields.push_back(EmptyTy);
344   }
345 };
346
347 //===----------------------------------------------------------------------===//
348 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
349 /// a constant initializer.
350 class DIVerifyVisitor : public DIVisitor {
351 private:
352   DIVerifier &VR;                       // Active verifier.
353   bool IsValid;                         // Validity status.
354   unsigned I;                           // Current operand index.
355   ConstantStruct *CI;                   // GlobalVariable constant initializer.
356   
357 public:
358   DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
359   : DIVisitor()
360   , VR(V)
361   , IsValid(true)
362   , I(0)
363   , CI(cast<ConstantStruct>(GV->getInitializer()))
364   {
365   }
366   
367   // Accessors.
368   bool isValid() const { return IsValid; }
369   
370   /// Apply - Set the value of each of the fields.
371   ///
372   virtual void Apply(int &Field) {
373     Constant *C = CI->getOperand(I++);
374     IsValid = IsValid && isa<ConstantInt>(C);
375   }
376   virtual void Apply(unsigned &Field) {
377     Constant *C = CI->getOperand(I++);
378     IsValid = IsValid && isa<ConstantInt>(C);
379   }
380   virtual void Apply(bool &Field) {
381     Constant *C = CI->getOperand(I++);
382     IsValid = IsValid && isa<ConstantBool>(C);
383   }
384   virtual void Apply(std::string &Field) {
385     Constant *C = CI->getOperand(I++);
386     IsValid = IsValid && isStringValue(C);
387   }
388   virtual void Apply(DebugInfoDesc *&Field) {
389     // FIXME - Prepare the correct descriptor.
390     Constant *C = CI->getOperand(I++);
391     IsValid = IsValid && isGlobalVariable(C);
392   }
393   virtual void Apply(GlobalVariable *&Field) {
394     Constant *C = CI->getOperand(I++);
395     IsValid = IsValid && isGlobalVariable(C);
396   }
397 };
398
399
400 //===----------------------------------------------------------------------===//
401
402 /// TagFromGlobal - Returns the Tag number from a debug info descriptor
403 /// GlobalVariable.  
404 unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
405   ConstantUInt *C = getUIntOperand(GV, 0);
406   return C ? (unsigned)C->getValue() : (unsigned)DIInvalid;
407 }
408
409 /// DescFactory - Create an instance of debug info descriptor based on Tag.
410 /// Return NULL if not a recognized Tag.
411 DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
412   switch (Tag) {
413   case DI_TAG_anchor:          return new AnchorDesc();
414   case DI_TAG_compile_unit:    return new CompileUnitDesc();
415   case DI_TAG_global_variable: return new GlobalVariableDesc();
416   case DI_TAG_subprogram:      return new SubprogramDesc();
417   default: break;
418   }
419   return NULL;
420 }
421
422 /// getLinkage - get linkage appropriate for this type of descriptor.
423 ///
424 GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
425   return GlobalValue::InternalLinkage;
426 }
427
428 /// ApplyToFields - Target the vistor to the fields of the descriptor.
429 ///
430 void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
431   Visitor->Apply(Tag);
432 }
433
434 //===----------------------------------------------------------------------===//
435
436 /// getLinkage - get linkage appropriate for this type of descriptor.
437 ///
438 GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
439   return GlobalValue::LinkOnceLinkage;
440 }
441
442 /// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
443 ///
444 void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
445   DebugInfoDesc::ApplyToFields(Visitor);
446   
447   Visitor->Apply(Name);
448 }
449
450 /// getDescString - Return a string used to compose global names and labels.
451 ///
452 const char *AnchorDesc::getDescString() const {
453   return Name.c_str();
454 }
455
456 /// getTypeString - Return a string used to label this descriptors type.
457 ///
458 const char *AnchorDesc::getTypeString() const {
459   return "llvm.dbg.anchor.type";
460 }
461
462 #ifndef NDEBUG
463 void AnchorDesc::dump() {
464   std::cerr << getDescString() << " "
465             << "Tag(" << getTag() << "), "
466             << "Name(" << Name << ")\n";
467 }
468 #endif
469
470 //===----------------------------------------------------------------------===//
471
472 AnchoredDesc::AnchoredDesc(unsigned T)
473 : DebugInfoDesc(T)
474 , Anchor(NULL)
475 {}
476
477 /// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
478 ///
479 void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
480   DebugInfoDesc::ApplyToFields(Visitor);
481
482   Visitor->Apply((DebugInfoDesc *&)Anchor);
483 }
484
485 //===----------------------------------------------------------------------===//
486
487 CompileUnitDesc::CompileUnitDesc()
488 : AnchoredDesc(DI_TAG_compile_unit)
489 , DebugVersion(LLVMDebugVersion)
490 , Language(0)
491 , FileName("")
492 , Directory("")
493 , Producer("")
494 {}
495
496 /// DebugVersionFromGlobal - Returns the version number from a compile unit
497 /// GlobalVariable.
498 unsigned CompileUnitDesc::DebugVersionFromGlobal(GlobalVariable *GV) {
499   ConstantUInt *C = getUIntOperand(GV, 2);
500   return C ? (unsigned)C->getValue() : (unsigned)DIInvalid;
501 }
502   
503 /// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
504 ///
505 void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
506   AnchoredDesc::ApplyToFields(Visitor);
507
508   Visitor->Apply(DebugVersion);
509   Visitor->Apply(Language);
510   Visitor->Apply(FileName);
511   Visitor->Apply(Directory);
512   Visitor->Apply(Producer);
513 }
514
515 /// getDescString - Return a string used to compose global names and labels.
516 ///
517 const char *CompileUnitDesc::getDescString() const {
518   return "llvm.dbg.compile_unit";
519 }
520
521 /// getTypeString - Return a string used to label this descriptors type.
522 ///
523 const char *CompileUnitDesc::getTypeString() const {
524   return "llvm.dbg.compile_unit.type";
525 }
526
527 /// getAnchorString - Return a string used to label this descriptor's anchor.
528 ///
529 const char *CompileUnitDesc::getAnchorString() const {
530   return "llvm.dbg.compile_units";
531 }
532
533 #ifndef NDEBUG
534 void CompileUnitDesc::dump() {
535   std::cerr << getDescString() << " "
536             << "Tag(" << getTag() << "), "
537             << "Anchor(" << getAnchor() << "), "
538             << "DebugVersion(" << DebugVersion << "), "
539             << "Language(" << Language << "), "
540             << "FileName(\"" << FileName << "\"), "
541             << "Directory(\"" << Directory << "\"), "
542             << "Producer(\"" << Producer << "\")\n";
543 }
544 #endif
545
546 //===----------------------------------------------------------------------===//
547
548 GlobalDesc::GlobalDesc(unsigned T)
549 : AnchoredDesc(T)
550 , Context(0)
551 , Name("")
552 , TyDesc(NULL)
553 , IsStatic(false)
554 , IsDefinition(false)
555 {}
556
557 /// ApplyToFields - Target the visitor to the fields of the global.
558 ///
559 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
560   AnchoredDesc::ApplyToFields(Visitor);
561
562   Visitor->Apply(Context);
563   Visitor->Apply(Name);
564   Visitor->Apply(TyDesc);
565   Visitor->Apply(IsStatic);
566   Visitor->Apply(IsDefinition);
567 }
568
569 //===----------------------------------------------------------------------===//
570
571 GlobalVariableDesc::GlobalVariableDesc()
572 : GlobalDesc(DI_TAG_global_variable)
573 , Global(NULL)
574 {}
575
576 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
577 ///
578 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
579   GlobalDesc::ApplyToFields(Visitor);
580
581   Visitor->Apply(Global);
582   Visitor->Apply(Line);
583 }
584
585 /// getDescString - Return a string used to compose global names and labels.
586 ///
587 const char *GlobalVariableDesc::getDescString() const {
588   return "llvm.dbg.global_variable";
589 }
590
591 /// getTypeString - Return a string used to label this descriptors type.
592 ///
593 const char *GlobalVariableDesc::getTypeString() const {
594   return "llvm.dbg.global_variable.type";
595 }
596
597 /// getAnchorString - Return a string used to label this descriptor's anchor.
598 ///
599 const char *GlobalVariableDesc::getAnchorString() const {
600   return "llvm.dbg.global_variables";
601 }
602
603 #ifndef NDEBUG
604 void GlobalVariableDesc::dump() {
605   std::cerr << getDescString() << " "
606             << "Tag(" << getTag() << "), "
607             << "Anchor(" << getAnchor() << "), "
608             << "Name(\"" << getName() << "\"), "
609             << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
610             << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
611             << "Global(" << Global << "), "
612             << "Line(" << Line << ")\n";
613 }
614 #endif
615
616 //===----------------------------------------------------------------------===//
617
618 SubprogramDesc::SubprogramDesc()
619 : GlobalDesc(DI_TAG_subprogram)
620 {}
621
622 /// ApplyToFields - Target the visitor to the fields of the
623 /// SubprogramDesc.
624 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
625   GlobalDesc::ApplyToFields(Visitor);
626 }
627
628 /// getDescString - Return a string used to compose global names and labels.
629 ///
630 const char *SubprogramDesc::getDescString() const {
631   return "llvm.dbg.subprogram";
632 }
633
634 /// getTypeString - Return a string used to label this descriptors type.
635 ///
636 const char *SubprogramDesc::getTypeString() const {
637   return "llvm.dbg.subprogram.type";
638 }
639
640 /// getAnchorString - Return a string used to label this descriptor's anchor.
641 ///
642 const char *SubprogramDesc::getAnchorString() const {
643   return "llvm.dbg.subprograms";
644 }
645
646 #ifndef NDEBUG
647 void SubprogramDesc::dump() {
648   std::cerr << getDescString() << " "
649             << "Tag(" << getTag() << "), "
650             << "Anchor(" << getAnchor() << "), "
651             << "Name(\"" << getName() << "\"), "
652             << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
653             << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
654 }
655 #endif
656
657 //===----------------------------------------------------------------------===//
658
659 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
660   return Deserialize(getGlobalVariable(V));
661 }
662 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
663   // Handle NULL.
664   if (!GV) return NULL;
665
666   // Check to see if it has been already deserialized.
667   DebugInfoDesc *&Slot = GlobalDescs[GV];
668   if (Slot) return Slot;
669
670   // Get the Tag from the global.
671   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
672   
673   // Get the debug version if a compile unit.
674   if (Tag == DI_TAG_compile_unit) {
675     DebugVersion = CompileUnitDesc::DebugVersionFromGlobal(GV);
676   }
677   
678   // Create an empty instance of the correct sort.
679   Slot = DebugInfoDesc::DescFactory(Tag);
680   assert(Slot && "Unknown Tag");
681   
682   // Deserialize the fields.
683   DIDeserializeVisitor DRAM(*this, GV);
684   DRAM.ApplyToFields(Slot);
685   
686   return Slot;
687 }
688
689 //===----------------------------------------------------------------------===//
690
691 /// getStrPtrType - Return a "sbyte *" type.
692 ///
693 const PointerType *DISerializer::getStrPtrType() {
694   // If not already defined.
695   if (!StrPtrTy) {
696     // Construct the pointer to signed bytes.
697     StrPtrTy = PointerType::get(Type::SByteTy);
698   }
699   
700   return StrPtrTy;
701 }
702
703 /// getEmptyStructPtrType - Return a "{ }*" type.
704 ///
705 const PointerType *DISerializer::getEmptyStructPtrType() {
706   // If not already defined.
707   if (!EmptyStructPtrTy) {
708     // Construct the empty structure type.
709     const StructType *EmptyStructTy =
710                                     StructType::get(std::vector<const Type*>());
711     // Construct the pointer to empty structure type.
712     EmptyStructPtrTy = PointerType::get(EmptyStructTy);
713   }
714   
715   return EmptyStructPtrTy;
716 }
717
718 /// getTagType - Return the type describing the specified descriptor (via tag.)
719 ///
720 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
721   // Attempt to get the previously defined type.
722   StructType *&Ty = TagTypes[DD->getTag()];
723   
724   // If not already defined.
725   if (!Ty) {
726     // Set up fields vector.
727     std::vector<const Type*> Fields;
728     // Get types of fields.
729     DIGetTypesVisitor GTAM(*this, Fields);
730     GTAM.ApplyToFields(DD);
731
732     // Construct structured type.
733     Ty = StructType::get(Fields);
734     
735     // Register type name with module.
736     M->addTypeName(DD->getTypeString(), Ty);
737   }
738   
739   return Ty;
740 }
741
742 /// getString - Construct the string as constant string global.
743 ///
744 Constant *DISerializer::getString(const std::string &String) {
745   // Check string cache for previous edition.
746   Constant *&Slot = StringCache[String];
747   // return Constant if previously defined.
748   if (Slot) return Slot;
749   // Construct string as an llvm constant.
750   Constant *ConstStr = ConstantArray::get(String);
751   // Otherwise create and return a new string global.
752   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
753                                              GlobalVariable::InternalLinkage,
754                                              ConstStr, "str", M);
755   // Convert to generic string pointer.
756   Slot = ConstantExpr::getCast(StrGV, getStrPtrType());
757   return Slot;
758   
759 }
760
761 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
762 /// so that it can be serialized to a .bc or .ll file.
763 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
764   // Check if the DebugInfoDesc is already in the map.
765   GlobalVariable *&Slot = DescGlobals[DD];
766   
767   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
768   if (Slot) return Slot;
769   
770   // Get the type associated with the Tag.
771   const StructType *Ty = getTagType(DD);
772
773   // Create the GlobalVariable early to prevent infinite recursion.
774   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
775                                           NULL, DD->getDescString(), M);
776
777   // Insert new GlobalVariable in DescGlobals map.
778   Slot = GV;
779  
780   // Set up elements vector
781   std::vector<Constant*> Elements;
782   // Add fields.
783   DISerializeVisitor SRAM(*this, Elements);
784   SRAM.ApplyToFields(DD);
785   
786   // Set the globals initializer.
787   GV->setInitializer(ConstantStruct::get(Ty, Elements));
788   
789   return GV;
790 }
791
792 //===----------------------------------------------------------------------===//
793
794 /// markVisited - Return true if the GlobalVariable hase been "seen" before.
795 /// Mark visited otherwise.
796 bool DIVerifier::markVisited(GlobalVariable *GV) {
797   // Check if the GlobalVariable is already in the Visited set.
798   std::set<GlobalVariable *>::iterator VI = Visited.lower_bound(GV);
799   
800   // See if GlobalVariable exists.
801   bool Exists = VI != Visited.end() && *VI == GV;
802
803   // Insert in set.
804   if (!Exists) Visited.insert(VI, GV);
805   
806   return Exists;
807 }
808
809 /// Verify - Return true if the GlobalVariable appears to be a valid
810 /// serialization of a DebugInfoDesc.
811 bool DIVerifier::Verify(Value *V) {
812   return Verify(getGlobalVariable(V));
813 }
814 bool DIVerifier::Verify(GlobalVariable *GV) {
815   // Check if seen before.
816   if (markVisited(GV)) return true;
817   
818   // Get the Tag
819   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
820   if (Tag == DIInvalid) return false;
821
822   // If a compile unit we need the debug version.
823   if (Tag == DI_TAG_compile_unit) {
824     DebugVersion = CompileUnitDesc::DebugVersionFromGlobal(GV);
825     if (DebugVersion == DIInvalid) return false;
826   }
827
828   // Construct an empty DebugInfoDesc.
829   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
830   if (!DD) return false;
831   
832   // Get the initializer constant.
833   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
834   
835   // Get the operand count.
836   unsigned N = CI->getNumOperands();
837   
838   // Get the field count.
839   unsigned &Slot = Counts[Tag];
840   if (!Slot) {
841     // Check the operand count to the field count
842     DICountVisitor CTAM;
843     CTAM.ApplyToFields(DD);
844     Slot = CTAM.getCount();
845   }
846   
847   // Field count must equal operand count.
848   if (Slot != N) {
849     delete DD;
850     return false;
851   }
852   
853   // Check each field for valid type.
854   DIVerifyVisitor VRAM(*this, GV);
855   VRAM.ApplyToFields(DD);
856   
857   // Release empty DebugInfoDesc.
858   delete DD;
859   
860   // Return result of field tests.
861   return VRAM.isValid();
862 }
863
864 //===----------------------------------------------------------------------===//
865
866
867 MachineDebugInfo::MachineDebugInfo()
868 : DR()
869 , CompileUnits()
870 , Directories()
871 , SourceFiles()
872 , Lines()
873 {
874   
875 }
876 MachineDebugInfo::~MachineDebugInfo() {
877
878 }
879
880 /// doInitialization - Initialize the debug state for a new module.
881 ///
882 bool MachineDebugInfo::doInitialization() {
883   return false;
884 }
885
886 /// doFinalization - Tear down the debug state after completion of a module.
887 ///
888 bool MachineDebugInfo::doFinalization() {
889   return false;
890 }
891
892 /// getDescFor - Convert a Value to a debug information descriptor.
893 ///
894 // FIXME - use new Value type when available.
895 DebugInfoDesc *MachineDebugInfo::getDescFor(Value *V) {
896   return DR.Deserialize(V);
897 }
898
899 /// Verify - Verify that a Value is debug information descriptor.
900 ///
901 bool MachineDebugInfo::Verify(Value *V) {
902   DIVerifier VR;
903   return VR.Verify(V);
904 }
905
906 /// AnalyzeModule - Scan the module for global debug information.
907 ///
908 void MachineDebugInfo::AnalyzeModule(Module &M) {
909   SetupCompileUnits(M);
910 }
911
912 /// SetupCompileUnits - Set up the unique vector of compile units.
913 ///
914 void MachineDebugInfo::SetupCompileUnits(Module &M) {
915   std::vector<CompileUnitDesc *>CU = getAnchoredDescriptors<CompileUnitDesc>(M);
916   
917   for (unsigned i = 0, N = CU.size(); i < N; i++) {
918     CompileUnits.insert(CU[i]);
919   }
920 }
921
922 /// getCompileUnits - Return a vector of debug compile units.
923 ///
924 const UniqueVector<CompileUnitDesc *> MachineDebugInfo::getCompileUnits()const{
925   return CompileUnits;
926 }
927
928 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
929 /// named GlobalVariable.
930 std::vector<GlobalVariable*>
931 MachineDebugInfo::getGlobalVariablesUsing(Module &M,
932                                           const std::string &RootName) {
933   return ::getGlobalVariablesUsing(M, RootName);
934 }