Use StringMap for greater justice!
[oota-llvm.git] / lib / CodeGen / MachineModuleInfo.cpp
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/MachineModuleInfo.h"
11
12 #include "llvm/Constants.h"
13 #include "llvm/Analysis/ValueTracking.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineLocation.h"
17 #include "llvm/Target/TargetInstrInfo.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetOptions.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/Streams.h"
27 using namespace llvm;
28 using namespace llvm::dwarf;
29
30 // Handle the Pass registration stuff necessary to use TargetData's.
31 static RegisterPass<MachineModuleInfo>
32 X("machinemoduleinfo", "Module Information");
33 char MachineModuleInfo::ID = 0;
34
35 //===----------------------------------------------------------------------===//
36
37 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
38 /// specified value in their initializer somewhere.
39 static void
40 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
41   // Scan though value users.
42   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
43     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
44       // If the user is a GlobalVariable then add to result.
45       Result.push_back(GV);
46     } else if (Constant *C = dyn_cast<Constant>(*I)) {
47       // If the user is a constant variable then scan its users
48       getGlobalVariablesUsing(C, Result);
49     }
50   }
51 }
52
53 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
54 /// named GlobalVariable.
55 static void
56 getGlobalVariablesUsing(Module &M, const std::string &RootName,
57                         std::vector<GlobalVariable*> &Result) {
58   std::vector<const Type*> FieldTypes;
59   FieldTypes.push_back(Type::Int32Ty);
60   FieldTypes.push_back(Type::Int32Ty);
61
62   // Get the GlobalVariable root.
63   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
64                                                 StructType::get(FieldTypes));
65
66   // If present and linkonce then scan for users.
67   if (UseRoot && UseRoot->hasLinkOnceLinkage())
68     getGlobalVariablesUsing(UseRoot, 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::BitCast) {
102       return dyn_cast<GlobalVariable>(CE->getOperand(0));
103     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
104       for (unsigned int i=1; i<CE->getNumOperands(); i++) {
105         if (!CE->getOperand(i)->isNullValue())
106           return NULL;
107       }
108       return dyn_cast<GlobalVariable>(CE->getOperand(0));
109     }
110   }
111   return NULL;
112 }
113
114 /// isGlobalVariable - Return true if the given value can be coerced to a
115 /// GlobalVariable.
116 static bool isGlobalVariable(Value *V) {
117   if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
118     return true;
119   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
120     if (CE->getOpcode() == Instruction::BitCast) {
121       return isa<GlobalVariable>(CE->getOperand(0));
122     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
123       for (unsigned int i=1; i<CE->getNumOperands(); i++) {
124         if (!CE->getOperand(i)->isNullValue())
125           return false;
126       }
127       return isa<GlobalVariable>(CE->getOperand(0));
128     }
129   }
130   return false;
131 }
132
133 /// getUIntOperand - Return ith operand if it is an unsigned integer.
134 ///
135 static ConstantInt *getUIntOperand(GlobalVariable *GV, unsigned i) {
136   // Make sure the GlobalVariable has an initializer.
137   if (!GV->hasInitializer()) return NULL;
138   
139   // Get the initializer constant.
140   ConstantStruct *CI = dyn_cast<ConstantStruct>(GV->getInitializer());
141   if (!CI) return NULL;
142   
143   // Check if there is at least i + 1 operands.
144   unsigned N = CI->getNumOperands();
145   if (i >= N) return NULL;
146
147   // Check constant.
148   return dyn_cast<ConstantInt>(CI->getOperand(i));
149 }
150
151 //===----------------------------------------------------------------------===//
152
153 /// ApplyToFields - Target the visitor to each field of the debug information
154 /// descriptor.
155 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
156   DD->ApplyToFields(this);
157 }
158
159 namespace {
160
161 //===----------------------------------------------------------------------===//
162 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
163 /// the supplied DebugInfoDesc.
164 class DICountVisitor : public DIVisitor {
165 private:
166   unsigned Count;                       // Running count of fields.
167   
168 public:
169   DICountVisitor() : DIVisitor(), Count(0) {}
170   
171   // Accessors.
172   unsigned getCount() const { return Count; }
173   
174   /// Apply - Count each of the fields.
175   ///
176   virtual void Apply(int &Field)             { ++Count; }
177   virtual void Apply(unsigned &Field)        { ++Count; }
178   virtual void Apply(int64_t &Field)         { ++Count; }
179   virtual void Apply(uint64_t &Field)        { ++Count; }
180   virtual void Apply(bool &Field)            { ++Count; }
181   virtual void Apply(std::string &Field)     { ++Count; }
182   virtual void Apply(DebugInfoDesc *&Field)  { ++Count; }
183   virtual void Apply(GlobalVariable *&Field) { ++Count; }
184   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
185     ++Count;
186   }
187 };
188
189 //===----------------------------------------------------------------------===//
190 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
191 /// supplied DebugInfoDesc.
192 class DIDeserializeVisitor : public DIVisitor {
193 private:
194   DIDeserializer &DR;                   // Active deserializer.
195   unsigned I;                           // Current operand index.
196   ConstantStruct *CI;                   // GlobalVariable constant initializer.
197
198 public:
199   DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
200     : DIVisitor(), DR(D), I(0), CI(cast<ConstantStruct>(GV->getInitializer()))
201   {}
202   
203   /// Apply - Set the value of each of the fields.
204   ///
205   virtual void Apply(int &Field) {
206     Constant *C = CI->getOperand(I++);
207     Field = cast<ConstantInt>(C)->getSExtValue();
208   }
209   virtual void Apply(unsigned &Field) {
210     Constant *C = CI->getOperand(I++);
211     Field = cast<ConstantInt>(C)->getZExtValue();
212   }
213   virtual void Apply(int64_t &Field) {
214     Constant *C = CI->getOperand(I++);
215     Field = cast<ConstantInt>(C)->getSExtValue();
216   }
217   virtual void Apply(uint64_t &Field) {
218     Constant *C = CI->getOperand(I++);
219     Field = cast<ConstantInt>(C)->getZExtValue();
220   }
221   virtual void Apply(bool &Field) {
222     Constant *C = CI->getOperand(I++);
223     Field = cast<ConstantInt>(C)->getZExtValue();
224   }
225   virtual void Apply(std::string &Field) {
226     Constant *C = CI->getOperand(I++);
227     // Fills in the string if it succeeds
228     if (!GetConstantStringInfo(C, Field))
229       Field.clear();
230   }
231   virtual void Apply(DebugInfoDesc *&Field) {
232     Constant *C = CI->getOperand(I++);
233     Field = DR.Deserialize(C);
234   }
235   virtual void Apply(GlobalVariable *&Field) {
236     Constant *C = CI->getOperand(I++);
237     Field = getGlobalVariable(C);
238   }
239   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
240     Field.resize(0);
241     Constant *C = CI->getOperand(I++);
242     GlobalVariable *GV = getGlobalVariable(C);
243     if (GV->hasInitializer()) {
244       if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
245         for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
246           GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
247           DebugInfoDesc *DE = DR.Deserialize(GVE);
248           Field.push_back(DE);
249         }
250       } else if (GV->getInitializer()->isNullValue()) {
251         if (const ArrayType *T =
252             dyn_cast<ArrayType>(GV->getType()->getElementType())) {
253           Field.resize(T->getNumElements());
254         }
255       }
256     }
257   }
258 };
259
260 //===----------------------------------------------------------------------===//
261 /// DISerializeVisitor - This DIVisitor serializes all the fields in
262 /// the supplied DebugInfoDesc.
263 class DISerializeVisitor : public DIVisitor {
264 private:
265   DISerializer &SR;                     // Active serializer.
266   std::vector<Constant*> &Elements;     // Element accumulator.
267   
268 public:
269   DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
270   : DIVisitor()
271   , SR(S)
272   , Elements(E)
273   {}
274   
275   /// Apply - Set the value of each of the fields.
276   ///
277   virtual void Apply(int &Field) {
278     Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field)));
279   }
280   virtual void Apply(unsigned &Field) {
281     Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
282   }
283   virtual void Apply(int64_t &Field) {
284     Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
285   }
286   virtual void Apply(uint64_t &Field) {
287     Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
288   }
289   virtual void Apply(bool &Field) {
290     Elements.push_back(ConstantInt::get(Type::Int1Ty, Field));
291   }
292   virtual void Apply(std::string &Field) {
293     Elements.push_back(SR.getString(Field));
294   }
295   virtual void Apply(DebugInfoDesc *&Field) {
296     GlobalVariable *GV = NULL;
297     
298     // If non-NULL then convert to global.
299     if (Field) GV = SR.Serialize(Field);
300     
301     // FIXME - At some point should use specific type.
302     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
303     
304     if (GV) {
305       // Set to pointer to global.
306       Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy));
307     } else {
308       // Use NULL.
309       Elements.push_back(ConstantPointerNull::get(EmptyTy));
310     }
311   }
312   virtual void Apply(GlobalVariable *&Field) {
313     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
314     if (Field) {
315       Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy));
316     } else {
317       Elements.push_back(ConstantPointerNull::get(EmptyTy));
318     }
319   }
320   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
321     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
322     unsigned N = Field.size();
323     ArrayType *AT = ArrayType::get(EmptyTy, N);
324     std::vector<Constant *> ArrayElements;
325
326     for (unsigned i = 0, N = Field.size(); i < N; ++i) {
327       if (DebugInfoDesc *Element = Field[i]) {
328         GlobalVariable *GVE = SR.Serialize(Element);
329         Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy);
330         ArrayElements.push_back(cast<Constant>(CE));
331       } else {
332         ArrayElements.push_back(ConstantPointerNull::get(EmptyTy));
333       }
334     }
335     
336     Constant *CA = ConstantArray::get(AT, ArrayElements);
337     GlobalVariable *CAGV = new GlobalVariable(AT, true,
338                                               GlobalValue::InternalLinkage,
339                                               CA, "llvm.dbg.array",
340                                               SR.getModule());
341     CAGV->setSection("llvm.metadata");
342     Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy);
343     Elements.push_back(CAE);
344   }
345 };
346
347 //===----------------------------------------------------------------------===//
348 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
349 /// the supplied DebugInfoDesc.
350 class DIGetTypesVisitor : public DIVisitor {
351 private:
352   DISerializer &SR;                     // Active serializer.
353   std::vector<const Type*> &Fields;     // Type accumulator.
354   
355 public:
356   DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
357   : DIVisitor()
358   , SR(S)
359   , Fields(F)
360   {}
361   
362   /// Apply - Set the value of each of the fields.
363   ///
364   virtual void Apply(int &Field) {
365     Fields.push_back(Type::Int32Ty);
366   }
367   virtual void Apply(unsigned &Field) {
368     Fields.push_back(Type::Int32Ty);
369   }
370   virtual void Apply(int64_t &Field) {
371     Fields.push_back(Type::Int64Ty);
372   }
373   virtual void Apply(uint64_t &Field) {
374     Fields.push_back(Type::Int64Ty);
375   }
376   virtual void Apply(bool &Field) {
377     Fields.push_back(Type::Int1Ty);
378   }
379   virtual void Apply(std::string &Field) {
380     Fields.push_back(SR.getStrPtrType());
381   }
382   virtual void Apply(DebugInfoDesc *&Field) {
383     // FIXME - At some point should use specific type.
384     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
385     Fields.push_back(EmptyTy);
386   }
387   virtual void Apply(GlobalVariable *&Field) {
388     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
389     Fields.push_back(EmptyTy);
390   }
391   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
392     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
393     Fields.push_back(EmptyTy);
394   }
395 };
396
397 //===----------------------------------------------------------------------===//
398 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
399 /// a constant initializer.
400 class DIVerifyVisitor : public DIVisitor {
401 private:
402   DIVerifier &VR;                       // Active verifier.
403   bool IsValid;                         // Validity status.
404   unsigned I;                           // Current operand index.
405   ConstantStruct *CI;                   // GlobalVariable constant initializer.
406   
407 public:
408   DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
409   : DIVisitor()
410   , VR(V)
411   , IsValid(true)
412   , I(0)
413   , CI(cast<ConstantStruct>(GV->getInitializer()))
414   {
415   }
416   
417   // Accessors.
418   bool isValid() const { return IsValid; }
419   
420   /// Apply - Set the value of each of the fields.
421   ///
422   virtual void Apply(int &Field) {
423     Constant *C = CI->getOperand(I++);
424     IsValid = IsValid && isa<ConstantInt>(C);
425   }
426   virtual void Apply(unsigned &Field) {
427     Constant *C = CI->getOperand(I++);
428     IsValid = IsValid && isa<ConstantInt>(C);
429   }
430   virtual void Apply(int64_t &Field) {
431     Constant *C = CI->getOperand(I++);
432     IsValid = IsValid && isa<ConstantInt>(C);
433   }
434   virtual void Apply(uint64_t &Field) {
435     Constant *C = CI->getOperand(I++);
436     IsValid = IsValid && isa<ConstantInt>(C);
437   }
438   virtual void Apply(bool &Field) {
439     Constant *C = CI->getOperand(I++);
440     IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty;
441   }
442   virtual void Apply(std::string &Field) {
443     Constant *C = CI->getOperand(I++);
444     IsValid = IsValid &&
445               (!C || isStringValue(C) || C->isNullValue());
446   }
447   virtual void Apply(DebugInfoDesc *&Field) {
448     // FIXME - Prepare the correct descriptor.
449     Constant *C = CI->getOperand(I++);
450     IsValid = IsValid && isGlobalVariable(C);
451   }
452   virtual void Apply(GlobalVariable *&Field) {
453     Constant *C = CI->getOperand(I++);
454     IsValid = IsValid && isGlobalVariable(C);
455   }
456   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
457     Constant *C = CI->getOperand(I++);
458     IsValid = IsValid && isGlobalVariable(C);
459     if (!IsValid) return;
460
461     GlobalVariable *GV = getGlobalVariable(C);
462     IsValid = IsValid && GV && GV->hasInitializer();
463     if (!IsValid) return;
464     
465     ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
466     IsValid = IsValid && CA;
467     if (!IsValid) return;
468
469     for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
470       IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
471       if (!IsValid) return;
472     
473       GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
474       VR.Verify(GVE);
475     }
476   }
477 };
478
479 }
480
481 //===----------------------------------------------------------------------===//
482
483 /// TagFromGlobal - Returns the tag number from a debug info descriptor
484 /// GlobalVariable.   Return DIIValid if operand is not an unsigned int. 
485 unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
486   ConstantInt *C = getUIntOperand(GV, 0);
487   return C ? ((unsigned)C->getZExtValue() & ~LLVMDebugVersionMask) :
488              (unsigned)DW_TAG_invalid;
489 }
490
491 /// VersionFromGlobal - Returns the version number from a debug info
492 /// descriptor GlobalVariable.  Return DIIValid if operand is not an unsigned
493 /// int.
494 unsigned  DebugInfoDesc::VersionFromGlobal(GlobalVariable *GV) {
495   ConstantInt *C = getUIntOperand(GV, 0);
496   return C ? ((unsigned)C->getZExtValue() & LLVMDebugVersionMask) :
497              (unsigned)DW_TAG_invalid;
498 }
499
500 /// DescFactory - Create an instance of debug info descriptor based on Tag.
501 /// Return NULL if not a recognized Tag.
502 DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
503   switch (Tag) {
504   case DW_TAG_anchor:           return new AnchorDesc();
505   case DW_TAG_compile_unit:     return new CompileUnitDesc();
506   case DW_TAG_variable:         return new GlobalVariableDesc();
507   case DW_TAG_subprogram:       return new SubprogramDesc();
508   case DW_TAG_lexical_block:    return new BlockDesc();
509   case DW_TAG_base_type:        return new BasicTypeDesc();
510   case DW_TAG_typedef:
511   case DW_TAG_pointer_type:        
512   case DW_TAG_reference_type:
513   case DW_TAG_const_type:
514   case DW_TAG_volatile_type:        
515   case DW_TAG_restrict_type:
516   case DW_TAG_member:
517   case DW_TAG_inheritance:      return new DerivedTypeDesc(Tag);
518   case DW_TAG_array_type:
519   case DW_TAG_structure_type:
520   case DW_TAG_union_type:
521   case DW_TAG_enumeration_type:
522   case DW_TAG_vector_type:
523   case DW_TAG_subroutine_type:  return new CompositeTypeDesc(Tag);
524   case DW_TAG_subrange_type:    return new SubrangeDesc();
525   case DW_TAG_enumerator:       return new EnumeratorDesc();
526   case DW_TAG_return_variable:
527   case DW_TAG_arg_variable:
528   case DW_TAG_auto_variable:    return new VariableDesc(Tag);
529   default: break;
530   }
531   return NULL;
532 }
533
534 /// getLinkage - get linkage appropriate for this type of descriptor.
535 ///
536 GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
537   return GlobalValue::InternalLinkage;
538 }
539
540 /// ApplyToFields - Target the vistor to the fields of the descriptor.
541 ///
542 void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
543   Visitor->Apply(Tag);
544 }
545
546 //===----------------------------------------------------------------------===//
547
548 AnchorDesc::AnchorDesc()
549 : DebugInfoDesc(DW_TAG_anchor)
550 , AnchorTag(0)
551 {}
552 AnchorDesc::AnchorDesc(AnchoredDesc *D)
553 : DebugInfoDesc(DW_TAG_anchor)
554 , AnchorTag(D->getTag())
555 {}
556
557 // Implement isa/cast/dyncast.
558 bool AnchorDesc::classof(const DebugInfoDesc *D) {
559   return D->getTag() == DW_TAG_anchor;
560 }
561   
562 /// getLinkage - get linkage appropriate for this type of descriptor.
563 ///
564 GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
565   return GlobalValue::LinkOnceLinkage;
566 }
567
568 /// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
569 ///
570 void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
571   DebugInfoDesc::ApplyToFields(Visitor);
572   
573   Visitor->Apply(AnchorTag);
574 }
575
576 /// getDescString - Return a string used to compose global names and labels. A
577 /// A global variable name needs to be defined for each debug descriptor that is
578 /// anchored. NOTE: that each global variable named here also needs to be added
579 /// to the list of names left external in the internalizer.
580 ///   ExternalNames.insert("llvm.dbg.compile_units");
581 ///   ExternalNames.insert("llvm.dbg.global_variables");
582 ///   ExternalNames.insert("llvm.dbg.subprograms");
583 const char *AnchorDesc::getDescString() const {
584   switch (AnchorTag) {
585   case DW_TAG_compile_unit: return CompileUnitDesc::AnchorString;
586   case DW_TAG_variable:     return GlobalVariableDesc::AnchorString;
587   case DW_TAG_subprogram:   return SubprogramDesc::AnchorString;
588   default: break;
589   }
590
591   assert(0 && "Tag does not have a case for anchor string");
592   return "";
593 }
594
595 /// getTypeString - Return a string used to label this descriptors type.
596 ///
597 const char *AnchorDesc::getTypeString() const {
598   return "llvm.dbg.anchor.type";
599 }
600
601 #ifndef NDEBUG
602 void AnchorDesc::dump() {
603   cerr << getDescString() << " "
604        << "Version(" << getVersion() << "), "
605        << "Tag(" << getTag() << "), "
606        << "AnchorTag(" << AnchorTag << ")\n";
607 }
608 #endif
609
610 //===----------------------------------------------------------------------===//
611
612 AnchoredDesc::AnchoredDesc(unsigned T)
613 : DebugInfoDesc(T)
614 , Anchor(NULL)
615 {}
616
617 /// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
618 ///
619 void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
620   DebugInfoDesc::ApplyToFields(Visitor);
621
622   Visitor->Apply(Anchor);
623 }
624
625 //===----------------------------------------------------------------------===//
626
627 CompileUnitDesc::CompileUnitDesc()
628 : AnchoredDesc(DW_TAG_compile_unit)
629 , Language(0)
630 , FileName("")
631 , Directory("")
632 , Producer("")
633 {}
634
635 // Implement isa/cast/dyncast.
636 bool CompileUnitDesc::classof(const DebugInfoDesc *D) {
637   return D->getTag() == DW_TAG_compile_unit;
638 }
639
640 /// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
641 ///
642 void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
643   AnchoredDesc::ApplyToFields(Visitor);
644   
645   // Handle cases out of sync with compiler.
646   if (getVersion() == 0) {
647     unsigned DebugVersion;
648     Visitor->Apply(DebugVersion);
649   }
650
651   Visitor->Apply(Language);
652   Visitor->Apply(FileName);
653   Visitor->Apply(Directory);
654   Visitor->Apply(Producer);
655 }
656
657 /// getDescString - Return a string used to compose global names and labels.
658 ///
659 const char *CompileUnitDesc::getDescString() const {
660   return "llvm.dbg.compile_unit";
661 }
662
663 /// getTypeString - Return a string used to label this descriptors type.
664 ///
665 const char *CompileUnitDesc::getTypeString() const {
666   return "llvm.dbg.compile_unit.type";
667 }
668
669 /// getAnchorString - Return a string used to label this descriptor's anchor.
670 ///
671 const char *const CompileUnitDesc::AnchorString = "llvm.dbg.compile_units";
672 const char *CompileUnitDesc::getAnchorString() const {
673   return AnchorString;
674 }
675
676 #ifndef NDEBUG
677 void CompileUnitDesc::dump() {
678   cerr << getDescString() << " "
679        << "Version(" << getVersion() << "), "
680        << "Tag(" << getTag() << "), "
681        << "Anchor(" << getAnchor() << "), "
682        << "Language(" << Language << "), "
683        << "FileName(\"" << FileName << "\"), "
684        << "Directory(\"" << Directory << "\"), "
685        << "Producer(\"" << Producer << "\")\n";
686 }
687 #endif
688
689 //===----------------------------------------------------------------------===//
690
691 TypeDesc::TypeDesc(unsigned T)
692 : DebugInfoDesc(T)
693 , Context(NULL)
694 , Name("")
695 , File(NULL)
696 , Line(0)
697 , Size(0)
698 , Align(0)
699 , Offset(0)
700 , Flags(0)
701 {}
702
703 /// ApplyToFields - Target the visitor to the fields of the TypeDesc.
704 ///
705 void TypeDesc::ApplyToFields(DIVisitor *Visitor) {
706   DebugInfoDesc::ApplyToFields(Visitor);
707   
708   Visitor->Apply(Context);
709   Visitor->Apply(Name);
710   Visitor->Apply(File);
711   Visitor->Apply(Line);
712   Visitor->Apply(Size);
713   Visitor->Apply(Align);
714   Visitor->Apply(Offset);
715   if (getVersion() > LLVMDebugVersion4) Visitor->Apply(Flags);
716 }
717
718 /// getDescString - Return a string used to compose global names and labels.
719 ///
720 const char *TypeDesc::getDescString() const {
721   return "llvm.dbg.type";
722 }
723
724 /// getTypeString - Return a string used to label this descriptor's type.
725 ///
726 const char *TypeDesc::getTypeString() const {
727   return "llvm.dbg.type.type";
728 }
729
730 #ifndef NDEBUG
731 void TypeDesc::dump() {
732   cerr << getDescString() << " "
733        << "Version(" << getVersion() << "), "
734        << "Tag(" << getTag() << "), "
735        << "Context(" << Context << "), "
736        << "Name(\"" << Name << "\"), "
737        << "File(" << File << "), "
738        << "Line(" << Line << "), "
739        << "Size(" << Size << "), "
740        << "Align(" << Align << "), "
741        << "Offset(" << Offset << "), "
742        << "Flags(" << Flags << ")\n";
743 }
744 #endif
745
746 //===----------------------------------------------------------------------===//
747
748 BasicTypeDesc::BasicTypeDesc()
749 : TypeDesc(DW_TAG_base_type)
750 , Encoding(0)
751 {}
752
753 // Implement isa/cast/dyncast.
754 bool BasicTypeDesc::classof(const DebugInfoDesc *D) {
755   return D->getTag() == DW_TAG_base_type;
756 }
757
758 /// ApplyToFields - Target the visitor to the fields of the BasicTypeDesc.
759 ///
760 void BasicTypeDesc::ApplyToFields(DIVisitor *Visitor) {
761   TypeDesc::ApplyToFields(Visitor);
762   
763   Visitor->Apply(Encoding);
764 }
765
766 /// getDescString - Return a string used to compose global names and labels.
767 ///
768 const char *BasicTypeDesc::getDescString() const {
769   return "llvm.dbg.basictype";
770 }
771
772 /// getTypeString - Return a string used to label this descriptor's type.
773 ///
774 const char *BasicTypeDesc::getTypeString() const {
775   return "llvm.dbg.basictype.type";
776 }
777
778 #ifndef NDEBUG
779 void BasicTypeDesc::dump() {
780   cerr << getDescString() << " "
781        << "Version(" << getVersion() << "), "
782        << "Tag(" << getTag() << "), "
783        << "Context(" << getContext() << "), "
784        << "Name(\"" << getName() << "\"), "
785        << "Size(" << getSize() << "), "
786        << "Encoding(" << Encoding << ")\n";
787 }
788 #endif
789
790 //===----------------------------------------------------------------------===//
791
792 DerivedTypeDesc::DerivedTypeDesc(unsigned T)
793 : TypeDesc(T)
794 , FromType(NULL)
795 {}
796
797 // Implement isa/cast/dyncast.
798 bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
799   unsigned T =  D->getTag();
800   switch (T) {
801   case DW_TAG_typedef:
802   case DW_TAG_pointer_type:
803   case DW_TAG_reference_type:
804   case DW_TAG_const_type:
805   case DW_TAG_volatile_type:
806   case DW_TAG_restrict_type:
807   case DW_TAG_member:
808   case DW_TAG_inheritance:
809     return true;
810   default: break;
811   }
812   return false;
813 }
814
815 /// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
816 ///
817 void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
818   TypeDesc::ApplyToFields(Visitor);
819   
820   Visitor->Apply(FromType);
821 }
822
823 /// getDescString - Return a string used to compose global names and labels.
824 ///
825 const char *DerivedTypeDesc::getDescString() const {
826   return "llvm.dbg.derivedtype";
827 }
828
829 /// getTypeString - Return a string used to label this descriptor's type.
830 ///
831 const char *DerivedTypeDesc::getTypeString() const {
832   return "llvm.dbg.derivedtype.type";
833 }
834
835 #ifndef NDEBUG
836 void DerivedTypeDesc::dump() {
837   cerr << getDescString() << " "
838        << "Version(" << getVersion() << "), "
839        << "Tag(" << getTag() << "), "
840        << "Context(" << getContext() << "), "
841        << "Name(\"" << getName() << "\"), "
842        << "Size(" << getSize() << "), "
843        << "File(" << getFile() << "), "
844        << "Line(" << getLine() << "), "
845        << "FromType(" << FromType << ")\n";
846 }
847 #endif
848
849 //===----------------------------------------------------------------------===//
850
851 CompositeTypeDesc::CompositeTypeDesc(unsigned T)
852 : DerivedTypeDesc(T)
853 , Elements()
854 {}
855   
856 // Implement isa/cast/dyncast.
857 bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
858   unsigned T =  D->getTag();
859   switch (T) {
860   case DW_TAG_array_type:
861   case DW_TAG_structure_type:
862   case DW_TAG_union_type:
863   case DW_TAG_enumeration_type:
864   case DW_TAG_vector_type:
865   case DW_TAG_subroutine_type:
866     return true;
867   default: break;
868   }
869   return false;
870 }
871
872 /// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
873 ///
874 void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
875   DerivedTypeDesc::ApplyToFields(Visitor);  
876
877   Visitor->Apply(Elements);
878 }
879
880 /// getDescString - Return a string used to compose global names and labels.
881 ///
882 const char *CompositeTypeDesc::getDescString() const {
883   return "llvm.dbg.compositetype";
884 }
885
886 /// getTypeString - Return a string used to label this descriptor's type.
887 ///
888 const char *CompositeTypeDesc::getTypeString() const {
889   return "llvm.dbg.compositetype.type";
890 }
891
892 #ifndef NDEBUG
893 void CompositeTypeDesc::dump() {
894   cerr << getDescString() << " "
895        << "Version(" << getVersion() << "), "
896        << "Tag(" << getTag() << "), "
897        << "Context(" << getContext() << "), "
898        << "Name(\"" << getName() << "\"), "
899        << "Size(" << getSize() << "), "
900        << "File(" << getFile() << "), "
901        << "Line(" << getLine() << "), "
902        << "FromType(" << getFromType() << "), "
903        << "Elements.size(" << Elements.size() << ")\n";
904 }
905 #endif
906
907 //===----------------------------------------------------------------------===//
908
909 SubrangeDesc::SubrangeDesc()
910 : DebugInfoDesc(DW_TAG_subrange_type)
911 , Lo(0)
912 , Hi(0)
913 {}
914
915 // Implement isa/cast/dyncast.
916 bool SubrangeDesc::classof(const DebugInfoDesc *D) {
917   return D->getTag() == DW_TAG_subrange_type;
918 }
919
920 /// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
921 ///
922 void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
923   DebugInfoDesc::ApplyToFields(Visitor);
924
925   Visitor->Apply(Lo);
926   Visitor->Apply(Hi);
927 }
928
929 /// getDescString - Return a string used to compose global names and labels.
930 ///
931 const char *SubrangeDesc::getDescString() const {
932   return "llvm.dbg.subrange";
933 }
934   
935 /// getTypeString - Return a string used to label this descriptor's type.
936 ///
937 const char *SubrangeDesc::getTypeString() const {
938   return "llvm.dbg.subrange.type";
939 }
940
941 #ifndef NDEBUG
942 void SubrangeDesc::dump() {
943   cerr << getDescString() << " "
944        << "Version(" << getVersion() << "), "
945        << "Tag(" << getTag() << "), "
946        << "Lo(" << Lo << "), "
947        << "Hi(" << Hi << ")\n";
948 }
949 #endif
950
951 //===----------------------------------------------------------------------===//
952
953 EnumeratorDesc::EnumeratorDesc()
954 : DebugInfoDesc(DW_TAG_enumerator)
955 , Name("")
956 , Value(0)
957 {}
958
959 // Implement isa/cast/dyncast.
960 bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
961   return D->getTag() == DW_TAG_enumerator;
962 }
963
964 /// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
965 ///
966 void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
967   DebugInfoDesc::ApplyToFields(Visitor);
968
969   Visitor->Apply(Name);
970   Visitor->Apply(Value);
971 }
972
973 /// getDescString - Return a string used to compose global names and labels.
974 ///
975 const char *EnumeratorDesc::getDescString() const {
976   return "llvm.dbg.enumerator";
977 }
978   
979 /// getTypeString - Return a string used to label this descriptor's type.
980 ///
981 const char *EnumeratorDesc::getTypeString() const {
982   return "llvm.dbg.enumerator.type";
983 }
984
985 #ifndef NDEBUG
986 void EnumeratorDesc::dump() {
987   cerr << getDescString() << " "
988        << "Version(" << getVersion() << "), "
989        << "Tag(" << getTag() << "), "
990        << "Name(" << Name << "), "
991        << "Value(" << Value << ")\n";
992 }
993 #endif
994
995 //===----------------------------------------------------------------------===//
996
997 VariableDesc::VariableDesc(unsigned T)
998 : DebugInfoDesc(T)
999 , Context(NULL)
1000 , Name("")
1001 , File(NULL)
1002 , Line(0)
1003 , TyDesc(0)
1004 {}
1005
1006 // Implement isa/cast/dyncast.
1007 bool VariableDesc::classof(const DebugInfoDesc *D) {
1008   unsigned T =  D->getTag();
1009   switch (T) {
1010   case DW_TAG_auto_variable:
1011   case DW_TAG_arg_variable:
1012   case DW_TAG_return_variable:
1013     return true;
1014   default: break;
1015   }
1016   return false;
1017 }
1018
1019 /// ApplyToFields - Target the visitor to the fields of the VariableDesc.
1020 ///
1021 void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
1022   DebugInfoDesc::ApplyToFields(Visitor);
1023   
1024   Visitor->Apply(Context);
1025   Visitor->Apply(Name);
1026   Visitor->Apply(File);
1027   Visitor->Apply(Line);
1028   Visitor->Apply(TyDesc);
1029 }
1030
1031 /// getDescString - Return a string used to compose global names and labels.
1032 ///
1033 const char *VariableDesc::getDescString() const {
1034   return "llvm.dbg.variable";
1035 }
1036
1037 /// getTypeString - Return a string used to label this descriptor's type.
1038 ///
1039 const char *VariableDesc::getTypeString() const {
1040   return "llvm.dbg.variable.type";
1041 }
1042
1043 #ifndef NDEBUG
1044 void VariableDesc::dump() {
1045   cerr << getDescString() << " "
1046        << "Version(" << getVersion() << "), "
1047        << "Tag(" << getTag() << "), "
1048        << "Context(" << Context << "), "
1049        << "Name(\"" << Name << "\"), "
1050        << "File(" << File << "), "
1051        << "Line(" << Line << "), "
1052        << "TyDesc(" << TyDesc << ")\n";
1053 }
1054 #endif
1055
1056 //===----------------------------------------------------------------------===//
1057
1058 GlobalDesc::GlobalDesc(unsigned T)
1059 : AnchoredDesc(T)
1060 , Context(0)
1061 , Name("")
1062 , FullName("")
1063 , LinkageName("")
1064 , File(NULL)
1065 , Line(0)
1066 , TyDesc(NULL)
1067 , IsStatic(false)
1068 , IsDefinition(false)
1069 {}
1070
1071 /// ApplyToFields - Target the visitor to the fields of the global.
1072 ///
1073 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1074   AnchoredDesc::ApplyToFields(Visitor);
1075
1076   Visitor->Apply(Context);
1077   Visitor->Apply(Name);
1078   Visitor->Apply(FullName);
1079   Visitor->Apply(LinkageName);
1080   Visitor->Apply(File);
1081   Visitor->Apply(Line);
1082   Visitor->Apply(TyDesc);
1083   Visitor->Apply(IsStatic);
1084   Visitor->Apply(IsDefinition);
1085 }
1086
1087 //===----------------------------------------------------------------------===//
1088
1089 GlobalVariableDesc::GlobalVariableDesc()
1090 : GlobalDesc(DW_TAG_variable)
1091 , Global(NULL)
1092 {}
1093
1094 // Implement isa/cast/dyncast.
1095 bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1096   return D->getTag() == DW_TAG_variable; 
1097 }
1098
1099 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1100 ///
1101 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1102   GlobalDesc::ApplyToFields(Visitor);
1103
1104   Visitor->Apply(Global);
1105 }
1106
1107 /// getDescString - Return a string used to compose global names and labels.
1108 ///
1109 const char *GlobalVariableDesc::getDescString() const {
1110   return "llvm.dbg.global_variable";
1111 }
1112
1113 /// getTypeString - Return a string used to label this descriptors type.
1114 ///
1115 const char *GlobalVariableDesc::getTypeString() const {
1116   return "llvm.dbg.global_variable.type";
1117 }
1118
1119 /// getAnchorString - Return a string used to label this descriptor's anchor.
1120 ///
1121 const char *const GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1122 const char *GlobalVariableDesc::getAnchorString() const {
1123   return AnchorString;
1124 }
1125
1126 #ifndef NDEBUG
1127 void GlobalVariableDesc::dump() {
1128   cerr << getDescString() << " "
1129        << "Version(" << getVersion() << "), "
1130        << "Tag(" << getTag() << "), "
1131        << "Anchor(" << getAnchor() << "), "
1132        << "Name(\"" << getName() << "\"), "
1133        << "FullName(\"" << getFullName() << "\"), "
1134        << "LinkageName(\"" << getLinkageName() << "\"), "
1135        << "File(" << getFile() << "),"
1136        << "Line(" << getLine() << "),"
1137        << "Type(" << getType() << "), "
1138        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1139        << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1140        << "Global(" << Global << ")\n";
1141 }
1142 #endif
1143
1144 //===----------------------------------------------------------------------===//
1145
1146 SubprogramDesc::SubprogramDesc()
1147 : GlobalDesc(DW_TAG_subprogram)
1148 {}
1149
1150 // Implement isa/cast/dyncast.
1151 bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1152   return D->getTag() == DW_TAG_subprogram;
1153 }
1154
1155 /// ApplyToFields - Target the visitor to the fields of the
1156 /// SubprogramDesc.
1157 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1158   GlobalDesc::ApplyToFields(Visitor);
1159 }
1160
1161 /// getDescString - Return a string used to compose global names and labels.
1162 ///
1163 const char *SubprogramDesc::getDescString() const {
1164   return "llvm.dbg.subprogram";
1165 }
1166
1167 /// getTypeString - Return a string used to label this descriptors type.
1168 ///
1169 const char *SubprogramDesc::getTypeString() const {
1170   return "llvm.dbg.subprogram.type";
1171 }
1172
1173 /// getAnchorString - Return a string used to label this descriptor's anchor.
1174 ///
1175 const char *const SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1176 const char *SubprogramDesc::getAnchorString() const {
1177   return AnchorString;
1178 }
1179
1180 #ifndef NDEBUG
1181 void SubprogramDesc::dump() {
1182   cerr << getDescString() << " "
1183        << "Version(" << getVersion() << "), "
1184        << "Tag(" << getTag() << "), "
1185        << "Anchor(" << getAnchor() << "), "
1186        << "Name(\"" << getName() << "\"), "
1187        << "FullName(\"" << getFullName() << "\"), "
1188        << "LinkageName(\"" << getLinkageName() << "\"), "
1189        << "File(" << getFile() << "),"
1190        << "Line(" << getLine() << "),"
1191        << "Type(" << getType() << "), "
1192        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1193        << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1194 }
1195 #endif
1196
1197 //===----------------------------------------------------------------------===//
1198
1199 BlockDesc::BlockDesc()
1200 : DebugInfoDesc(DW_TAG_lexical_block)
1201 , Context(NULL)
1202 {}
1203
1204 // Implement isa/cast/dyncast.
1205 bool BlockDesc::classof(const DebugInfoDesc *D) {
1206   return D->getTag() == DW_TAG_lexical_block;
1207 }
1208
1209 /// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1210 ///
1211 void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1212   DebugInfoDesc::ApplyToFields(Visitor);
1213
1214   Visitor->Apply(Context);
1215 }
1216
1217 /// getDescString - Return a string used to compose global names and labels.
1218 ///
1219 const char *BlockDesc::getDescString() const {
1220   return "llvm.dbg.block";
1221 }
1222
1223 /// getTypeString - Return a string used to label this descriptors type.
1224 ///
1225 const char *BlockDesc::getTypeString() const {
1226   return "llvm.dbg.block.type";
1227 }
1228
1229 #ifndef NDEBUG
1230 void BlockDesc::dump() {
1231   cerr << getDescString() << " "
1232        << "Version(" << getVersion() << "), "
1233        << "Tag(" << getTag() << "),"
1234        << "Context(" << Context << ")\n";
1235 }
1236 #endif
1237
1238 //===----------------------------------------------------------------------===//
1239
1240 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1241   return Deserialize(getGlobalVariable(V));
1242 }
1243 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1244   // Handle NULL.
1245   if (!GV) return NULL;
1246
1247   // Check to see if it has been already deserialized.
1248   DebugInfoDesc *&Slot = GlobalDescs[GV];
1249   if (Slot) return Slot;
1250
1251   // Get the Tag from the global.
1252   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1253   
1254   // Create an empty instance of the correct sort.
1255   Slot = DebugInfoDesc::DescFactory(Tag);
1256   
1257   // If not a user defined descriptor.
1258   if (Slot) {
1259     // Deserialize the fields.
1260     DIDeserializeVisitor DRAM(*this, GV);
1261     DRAM.ApplyToFields(Slot);
1262   }
1263   
1264   return Slot;
1265 }
1266
1267 //===----------------------------------------------------------------------===//
1268
1269 /// getStrPtrType - Return a "sbyte *" type.
1270 ///
1271 const PointerType *DISerializer::getStrPtrType() {
1272   // If not already defined.
1273   if (!StrPtrTy) {
1274     // Construct the pointer to signed bytes.
1275     StrPtrTy = PointerType::getUnqual(Type::Int8Ty);
1276   }
1277   
1278   return StrPtrTy;
1279 }
1280
1281 /// getEmptyStructPtrType - Return a "{ }*" type.
1282 ///
1283 const PointerType *DISerializer::getEmptyStructPtrType() {
1284   // If not already defined.
1285   if (EmptyStructPtrTy) return EmptyStructPtrTy;
1286
1287   // Construct the pointer to empty structure type.
1288   const StructType *EmptyStructTy =
1289     StructType::get(std::vector<const Type*>());
1290
1291   // Construct the pointer to empty structure type.
1292   EmptyStructPtrTy = PointerType::getUnqual(EmptyStructTy);
1293   return EmptyStructPtrTy;
1294 }
1295
1296 /// getTagType - Return the type describing the specified descriptor (via tag.)
1297 ///
1298 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1299   // Attempt to get the previously defined type.
1300   StructType *&Ty = TagTypes[DD->getTag()];
1301   
1302   // If not already defined.
1303   if (!Ty) {
1304     // Set up fields vector.
1305     std::vector<const Type*> Fields;
1306     // Get types of fields.
1307     DIGetTypesVisitor GTAM(*this, Fields);
1308     GTAM.ApplyToFields(DD);
1309
1310     // Construct structured type.
1311     Ty = StructType::get(Fields);
1312     
1313     // Register type name with module.
1314     M->addTypeName(DD->getTypeString(), Ty);
1315   }
1316   
1317   return Ty;
1318 }
1319
1320 /// getString - Construct the string as constant string global.
1321 ///
1322 Constant *DISerializer::getString(const std::string &String) {
1323   // Check string cache for previous edition.
1324   Constant *&Slot = StringCache[String];
1325
1326   // Return Constant if previously defined.
1327   if (Slot) return Slot;
1328
1329   // If empty string then use a sbyte* null instead.
1330   if (String.empty()) {
1331     Slot = ConstantPointerNull::get(getStrPtrType());
1332   } else {
1333     // Construct string as an llvm constant.
1334     Constant *ConstStr = ConstantArray::get(String);
1335
1336     // Otherwise create and return a new string global.
1337     GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1338                                                GlobalVariable::InternalLinkage,
1339                                                ConstStr, ".str", M);
1340     StrGV->setSection("llvm.metadata");
1341
1342     // Convert to generic string pointer.
1343     Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
1344   }
1345
1346   return Slot;
1347   
1348 }
1349
1350 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1351 /// so that it can be serialized to a .bc or .ll file.
1352 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1353   // Check if the DebugInfoDesc is already in the map.
1354   GlobalVariable *&Slot = DescGlobals[DD];
1355   
1356   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1357   if (Slot) return Slot;
1358   
1359   // Get the type associated with the Tag.
1360   const StructType *Ty = getTagType(DD);
1361
1362   // Create the GlobalVariable early to prevent infinite recursion.
1363   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1364                                           NULL, DD->getDescString(), M);
1365   GV->setSection("llvm.metadata");
1366
1367   // Insert new GlobalVariable in DescGlobals map.
1368   Slot = GV;
1369  
1370   // Set up elements vector
1371   std::vector<Constant*> Elements;
1372   // Add fields.
1373   DISerializeVisitor SRAM(*this, Elements);
1374   SRAM.ApplyToFields(DD);
1375
1376   // Set the globals initializer.
1377   GV->setInitializer(ConstantStruct::get(Ty, Elements));
1378   
1379   return GV;
1380 }
1381
1382 /// addDescriptor - Directly connect DD with existing GV.
1383 void DISerializer::addDescriptor(DebugInfoDesc *DD,
1384                                  GlobalVariable *GV) {
1385   DescGlobals[DD] = GV;
1386 }
1387
1388 //===----------------------------------------------------------------------===//
1389
1390 /// Verify - Return true if the GlobalVariable appears to be a valid
1391 /// serialization of a DebugInfoDesc.
1392 bool DIVerifier::Verify(Value *V) {
1393   return !V || Verify(getGlobalVariable(V));
1394 }
1395 bool DIVerifier::Verify(GlobalVariable *GV) {
1396   // NULLs are valid.
1397   if (!GV) return true;
1398   
1399   // Check prior validity.
1400   unsigned &ValiditySlot = Validity[GV];
1401   
1402   // If visited before then use old state.
1403   if (ValiditySlot) return ValiditySlot == Valid;
1404   
1405   // Assume validity for the time being (recursion.)
1406   ValiditySlot = Valid;
1407   
1408   // Make sure the global is internal or link once (anchor.)
1409   if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1410       GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1411     ValiditySlot = Invalid;
1412     return false;
1413   }
1414
1415   // Get the Tag.
1416   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1417   
1418   // Check for user defined descriptors.
1419   if (Tag == DW_TAG_invalid) {
1420     ValiditySlot = Valid;
1421     return true;
1422   }
1423   
1424   // Get the Version.
1425   unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
1426   
1427   // Check for version mismatch.
1428   if (Version != LLVMDebugVersion) {
1429     ValiditySlot = Invalid;
1430     return false;
1431   }
1432
1433   // Construct an empty DebugInfoDesc.
1434   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1435   
1436   // Allow for user defined descriptors.
1437   if (!DD) return true;
1438   
1439   // Get the initializer constant.
1440   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1441   
1442   // Get the operand count.
1443   unsigned N = CI->getNumOperands();
1444   
1445   // Get the field count.
1446   unsigned &CountSlot = Counts[Tag];
1447   if (!CountSlot) {
1448     // Check the operand count to the field count
1449     DICountVisitor CTAM;
1450     CTAM.ApplyToFields(DD);
1451     CountSlot = CTAM.getCount();
1452   }
1453   
1454   // Field count must be at most equal operand count.
1455   if (CountSlot >  N) {
1456     delete DD;
1457     ValiditySlot = Invalid;
1458     return false;
1459   }
1460   
1461   // Check each field for valid type.
1462   DIVerifyVisitor VRAM(*this, GV);
1463   VRAM.ApplyToFields(DD);
1464   
1465   // Release empty DebugInfoDesc.
1466   delete DD;
1467   
1468   // If fields are not valid.
1469   if (!VRAM.isValid()) {
1470     ValiditySlot = Invalid;
1471     return false;
1472   }
1473   
1474   return true;
1475 }
1476
1477 /// isVerified - Return true if the specified GV has already been
1478 /// verified as a debug information descriptor.
1479 bool DIVerifier::isVerified(GlobalVariable *GV) {
1480   unsigned &ValiditySlot = Validity[GV];
1481   if (ValiditySlot) return ValiditySlot == Valid;
1482   return false;
1483 }
1484
1485 //===----------------------------------------------------------------------===//
1486
1487 DebugScope::~DebugScope() {
1488   for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1489   for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1490 }
1491
1492 //===----------------------------------------------------------------------===//
1493
1494 MachineModuleInfo::MachineModuleInfo()
1495 : ImmutablePass((intptr_t)&ID)
1496 , DR()
1497 , VR()
1498 , CompileUnits()
1499 , Directories()
1500 , SourceFiles()
1501 , Lines()
1502 , LabelIDList()
1503 , ScopeMap()
1504 , RootScope(NULL)
1505 , FrameMoves()
1506 , LandingPads()
1507 , Personalities()
1508 , CallsEHReturn(0)
1509 , CallsUnwindInit(0)
1510 {
1511   // Always emit "no personality" info
1512   Personalities.push_back(NULL);
1513 }
1514 MachineModuleInfo::~MachineModuleInfo() {
1515
1516 }
1517
1518 /// doInitialization - Initialize the state for a new module.
1519 ///
1520 bool MachineModuleInfo::doInitialization() {
1521   return false;
1522 }
1523
1524 /// doFinalization - Tear down the state after completion of a module.
1525 ///
1526 bool MachineModuleInfo::doFinalization() {
1527   return false;
1528 }
1529
1530 /// BeginFunction - Begin gathering function meta information.
1531 ///
1532 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
1533   // Coming soon.
1534 }
1535
1536 /// EndFunction - Discard function meta information.
1537 ///
1538 void MachineModuleInfo::EndFunction() {
1539   // Clean up scope information.
1540   if (RootScope) {
1541     delete RootScope;
1542     ScopeMap.clear();
1543     RootScope = NULL;
1544   }
1545   
1546   // Clean up line info.
1547   Lines.clear();
1548
1549   // Clean up frame info.
1550   FrameMoves.clear();
1551   
1552   // Clean up exception info.
1553   LandingPads.clear();
1554   TypeInfos.clear();
1555   FilterIds.clear();
1556   FilterEnds.clear();
1557   CallsEHReturn = 0;
1558   CallsUnwindInit = 0;
1559 }
1560
1561 /// getDescFor - Convert a Value to a debug information descriptor.
1562 ///
1563 // FIXME - use new Value type when available.
1564 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
1565   return DR.Deserialize(V);
1566 }
1567
1568 /// AnalyzeModule - Scan the module for global debug information.
1569 ///
1570 void MachineModuleInfo::AnalyzeModule(Module &M) {
1571   SetupCompileUnits(M);
1572
1573   // Insert functions in the llvm.used array into UsedFunctions.
1574   GlobalVariable *GV = M.getGlobalVariable("llvm.used");
1575   if (!GV || !GV->hasInitializer()) return;
1576
1577   // Should be an array of 'i8*'.
1578   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1579   if (InitList == 0) return;
1580
1581   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1582     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))
1583       if (CE->getOpcode() == Instruction::BitCast)
1584         if (Function *F = dyn_cast<Function>(CE->getOperand(0)))
1585           UsedFunctions.insert(F);
1586   }
1587 }
1588
1589 /// SetupCompileUnits - Set up the unique vector of compile units.
1590 ///
1591 void MachineModuleInfo::SetupCompileUnits(Module &M) {
1592   std::vector<CompileUnitDesc *> CU;
1593   getAnchoredDescriptors<CompileUnitDesc>(M, CU);
1594   
1595   for (unsigned i = 0, N = CU.size(); i < N; i++) {
1596     CompileUnits.insert(CU[i]);
1597   }
1598 }
1599
1600 /// getCompileUnits - Return a vector of debug compile units.
1601 ///
1602 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
1603   return CompileUnits;
1604 }
1605
1606 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
1607 /// named GlobalVariable.
1608 void
1609 MachineModuleInfo::getGlobalVariablesUsing(Module &M,
1610                                            const std::string &RootName,
1611                                            std::vector<GlobalVariable*>&Result){
1612   return ::getGlobalVariablesUsing(M, RootName, Result);
1613 }
1614
1615 /// RecordSourceLine - Records location information and associates it with a
1616 /// debug label.  Returns a unique label ID used to generate a label and 
1617 /// provide correspondence to the source line list.
1618 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column,
1619                                              unsigned Source) {
1620   unsigned ID = NextLabelID();
1621   Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
1622   return ID;
1623 }
1624
1625 /// RecordSource - Register a source file with debug info. Returns an source
1626 /// ID.
1627 unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
1628                                          const std::string &Source) {
1629   unsigned DirectoryID = Directories.insert(Directory);
1630   return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
1631 }
1632 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
1633   return RecordSource(CompileUnit->getDirectory(),
1634                       CompileUnit->getFileName());
1635 }
1636
1637 /// RecordRegionStart - Indicate the start of a region.
1638 ///
1639 unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
1640   // FIXME - need to be able to handle split scopes because of bb cloning.
1641   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1642   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1643   unsigned ID = NextLabelID();
1644   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1645   return ID;
1646 }
1647
1648 /// RecordRegionEnd - Indicate the end of a region.
1649 ///
1650 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
1651   // FIXME - need to be able to handle split scopes because of bb cloning.
1652   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1653   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1654   unsigned ID = NextLabelID();
1655   Scope->setEndLabelID(ID);
1656   return ID;
1657 }
1658
1659 /// RecordVariable - Indicate the declaration of  a local variable.
1660 ///
1661 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) {
1662   VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV));
1663   DebugScope *Scope = getOrCreateScope(VD->getContext());
1664   DebugVariable *DV = new DebugVariable(VD, FrameIndex);
1665   Scope->AddVariable(DV);
1666 }
1667
1668 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1669 ///
1670 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
1671   DebugScope *&Slot = ScopeMap[ScopeDesc];
1672   if (!Slot) {
1673     // FIXME - breaks down when the context is an inlined function.
1674     DebugInfoDesc *ParentDesc = NULL;
1675     if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
1676       ParentDesc = Block->getContext();
1677     }
1678     DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
1679     Slot = new DebugScope(Parent, ScopeDesc);
1680     if (Parent) {
1681       Parent->AddScope(Slot);
1682     } else if (RootScope) {
1683       // FIXME - Add inlined function scopes to the root so we can delete
1684       // them later.  Long term, handle inlined functions properly.
1685       RootScope->AddScope(Slot);
1686     } else {
1687       // First function is top level function.
1688       RootScope = Slot;
1689     }
1690   }
1691   return Slot;
1692 }
1693
1694 //===-EH-------------------------------------------------------------------===//
1695
1696 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
1697 /// specified MachineBasicBlock.
1698 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
1699     (MachineBasicBlock *LandingPad) {
1700   unsigned N = LandingPads.size();
1701   for (unsigned i = 0; i < N; ++i) {
1702     LandingPadInfo &LP = LandingPads[i];
1703     if (LP.LandingPadBlock == LandingPad)
1704       return LP;
1705   }
1706   
1707   LandingPads.push_back(LandingPadInfo(LandingPad));
1708   return LandingPads[N];
1709 }
1710
1711 /// addInvoke - Provide the begin and end labels of an invoke style call and
1712 /// associate it with a try landing pad block.
1713 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
1714                                   unsigned BeginLabel, unsigned EndLabel) {
1715   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1716   LP.BeginLabels.push_back(BeginLabel);
1717   LP.EndLabels.push_back(EndLabel);
1718 }
1719
1720 /// addLandingPad - Provide the label of a try LandingPad block.
1721 ///
1722 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
1723   unsigned LandingPadLabel = NextLabelID();
1724   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1725   LP.LandingPadLabel = LandingPadLabel;  
1726   return LandingPadLabel;
1727 }
1728
1729 /// addPersonality - Provide the personality function for the exception
1730 /// information.
1731 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
1732                                        Function *Personality) {
1733   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1734   LP.Personality = Personality;
1735
1736   for (unsigned i = 0; i < Personalities.size(); ++i)
1737     if (Personalities[i] == Personality)
1738       return;
1739   
1740   Personalities.push_back(Personality);
1741 }
1742
1743 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
1744 ///
1745 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
1746                                         std::vector<GlobalVariable *> &TyInfo) {
1747   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1748   for (unsigned N = TyInfo.size(); N; --N)
1749     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
1750 }
1751
1752 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
1753 ///
1754 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
1755                                         std::vector<GlobalVariable *> &TyInfo) {
1756   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1757   std::vector<unsigned> IdsInFilter (TyInfo.size());
1758   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
1759     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1760   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1761 }
1762
1763 /// addCleanup - Add a cleanup action for a landing pad.
1764 ///
1765 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
1766   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1767   LP.TypeIds.push_back(0);
1768 }
1769
1770 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1771 /// pads.
1772 void MachineModuleInfo::TidyLandingPads() {
1773   for (unsigned i = 0; i != LandingPads.size(); ) {
1774     LandingPadInfo &LandingPad = LandingPads[i];
1775     LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1776
1777     // Special case: we *should* emit LPs with null LP MBB. This indicates
1778     // "nounwind" case.
1779     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1780       LandingPads.erase(LandingPads.begin() + i);
1781       continue;
1782     }
1783
1784     for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
1785       unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1786       unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1787
1788       if (!BeginLabel || !EndLabel) {
1789         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1790         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1791         continue;
1792       }
1793
1794       LandingPad.BeginLabels[j] = BeginLabel;
1795       LandingPad.EndLabels[j] = EndLabel;
1796       ++j;
1797     }
1798
1799     // Remove landing pads with no try-ranges.
1800     if (LandingPads[i].BeginLabels.empty()) {
1801       LandingPads.erase(LandingPads.begin() + i);
1802       continue;
1803     }
1804
1805     // If there is no landing pad, ensure that the list of typeids is empty.
1806     // If the only typeid is a cleanup, this is the same as having no typeids.
1807     if (!LandingPad.LandingPadBlock ||
1808         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
1809       LandingPad.TypeIds.clear();
1810
1811     ++i;
1812   }
1813 }
1814
1815 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is 
1816 /// function wide.
1817 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1818   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
1819     if (TypeInfos[i] == TI) return i + 1;
1820
1821   TypeInfos.push_back(TI);
1822   return TypeInfos.size();
1823 }
1824
1825 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
1826 /// function wide.
1827 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1828   // If the new filter coincides with the tail of an existing filter, then
1829   // re-use the existing filter.  Folding filters more than this requires
1830   // re-ordering filters and/or their elements - probably not worth it.
1831   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
1832        E = FilterEnds.end(); I != E; ++I) {
1833     unsigned i = *I, j = TyIds.size();
1834
1835     while (i && j)
1836       if (FilterIds[--i] != TyIds[--j])
1837         goto try_next;
1838
1839     if (!j)
1840       // The new filter coincides with range [i, end) of the existing filter.
1841       return -(1 + i);
1842
1843 try_next:;
1844   }
1845
1846   // Add the new filter.
1847   int FilterID = -(1 + FilterIds.size());
1848   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1849   for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1850     FilterIds.push_back(TyIds[I]);
1851   FilterEnds.push_back(FilterIds.size());
1852   FilterIds.push_back(0); // terminator
1853   return FilterID;
1854 }
1855
1856 /// getPersonality - Return the personality function for the current function.
1857 Function *MachineModuleInfo::getPersonality() const {
1858   // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1859   // function
1860   return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1861 }
1862
1863 /// getPersonalityIndex - Return unique index for current personality
1864 /// function. NULL personality function should always get zero index.
1865 unsigned MachineModuleInfo::getPersonalityIndex() const {
1866   const Function* Personality = NULL;
1867   
1868   // Scan landing pads. If there is at least one non-NULL personality - use it.
1869   for (unsigned i = 0; i != LandingPads.size(); ++i)
1870     if (LandingPads[i].Personality) {
1871       Personality = LandingPads[i].Personality;
1872       break;
1873     }
1874   
1875   for (unsigned i = 0; i < Personalities.size(); ++i) {
1876     if (Personalities[i] == Personality)
1877       return i;
1878   }
1879
1880   // This should never happen
1881   assert(0 && "Personality function should be set!");
1882   return 0;
1883 }
1884
1885 //===----------------------------------------------------------------------===//
1886 /// DebugLabelFolding pass - This pass prunes out redundant labels.  This allows
1887 /// a info consumer to determine if the range of two labels is empty, by seeing
1888 /// if the labels map to the same reduced label.
1889
1890 namespace llvm {
1891
1892 struct DebugLabelFolder : public MachineFunctionPass {
1893   static char ID;
1894   DebugLabelFolder() : MachineFunctionPass((intptr_t)&ID) {}
1895
1896   virtual bool runOnMachineFunction(MachineFunction &MF);
1897   virtual const char *getPassName() const { return "Label Folder"; }
1898 };
1899
1900 char DebugLabelFolder::ID = 0;
1901
1902 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
1903   // Get machine module info.
1904   MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
1905   if (!MMI) return false;
1906   
1907   // Track if change is made.
1908   bool MadeChange = false;
1909   // No prior label to begin.
1910   unsigned PriorLabel = 0;
1911   
1912   // Iterate through basic blocks.
1913   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
1914        BB != E; ++BB) {
1915     // Iterate through instructions.
1916     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1917       // Is it a label.
1918       if (I->isDebugLabel()) {
1919         // The label ID # is always operand #0, an immediate.
1920         unsigned NextLabel = I->getOperand(0).getImm();
1921         
1922         // If there was an immediate prior label.
1923         if (PriorLabel) {
1924           // Remap the current label to prior label.
1925           MMI->RemapLabel(NextLabel, PriorLabel);
1926           // Delete the current label.
1927           I = BB->erase(I);
1928           // Indicate a change has been made.
1929           MadeChange = true;
1930           continue;
1931         } else {
1932           // Start a new round.
1933           PriorLabel = NextLabel;
1934         }
1935        } else {
1936         // No consecutive labels.
1937         PriorLabel = 0;
1938       }
1939       
1940       ++I;
1941     }
1942   }
1943   
1944   return MadeChange;
1945 }
1946
1947 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }
1948
1949 }
1950