Remove isPod() from DenseMapInfo, splitting it out to its own
[oota-llvm.git] / lib / Analysis / DebugInfo.cpp
1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
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 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/DebugLoc.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29 using namespace llvm::dwarf;
30
31 //===----------------------------------------------------------------------===//
32 // DIDescriptor
33 //===----------------------------------------------------------------------===//
34
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 /// FIXME : Add DIDescriptor.isValid()
37 bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) {
38   if (!N)
39     return false;
40
41   DIDescriptor DI(N);
42
43   // Check current version. Allow Version6 for now.
44   unsigned Version = DI.getVersion();
45   if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
46     return false;
47
48   unsigned Tag = DI.getTag();
49   switch (Tag) {
50   case DW_TAG_variable:
51     assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
52     break;
53   case DW_TAG_compile_unit:
54     assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
55     break;
56   case DW_TAG_subprogram:
57     assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
58     break;
59   case DW_TAG_lexical_block:
60     // FIXME: This interfers with the quality of generated code during
61     // optimization.
62     if (OptLevel != CodeGenOpt::None)
63       return false;
64     // FALLTHROUGH
65   default:
66     break;
67   }
68
69   return true;
70 }
71
72 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
73   DbgNode = N;
74
75   // If this is non-null, check to see if the Tag matches. If not, set to null.
76   if (N && getTag() != RequiredTag) {
77     DbgNode = 0;
78   }
79 }
80
81 StringRef 
82 DIDescriptor::getStringField(unsigned Elt) const {
83   if (DbgNode == 0)
84     return StringRef();
85
86   if (Elt < DbgNode->getNumElements())
87     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt)))
88       return MDS->getString();
89
90   return StringRef();
91 }
92
93 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
94   if (DbgNode == 0)
95     return 0;
96
97   if (Elt < DbgNode->getNumElements())
98     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
99       return CI->getZExtValue();
100
101   return 0;
102 }
103
104 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
105   if (DbgNode == 0)
106     return DIDescriptor();
107
108   if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
109     return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
110
111   return DIDescriptor();
112 }
113
114 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
115   if (DbgNode == 0)
116     return 0;
117
118   if (Elt < DbgNode->getNumElements())
119       return dyn_cast_or_null<GlobalVariable>(DbgNode->getElement(Elt));
120   return 0;
121 }
122
123 //===----------------------------------------------------------------------===//
124 // Predicates
125 //===----------------------------------------------------------------------===//
126
127 /// isBasicType - Return true if the specified tag is legal for
128 /// DIBasicType.
129 bool DIDescriptor::isBasicType() const {
130   assert (!isNull() && "Invalid descriptor!");
131   unsigned Tag = getTag();
132
133   return Tag == dwarf::DW_TAG_base_type;
134 }
135
136 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
137 bool DIDescriptor::isDerivedType() const {
138   assert (!isNull() && "Invalid descriptor!");
139   unsigned Tag = getTag();
140
141   switch (Tag) {
142   case dwarf::DW_TAG_typedef:
143   case dwarf::DW_TAG_pointer_type:
144   case dwarf::DW_TAG_reference_type:
145   case dwarf::DW_TAG_const_type:
146   case dwarf::DW_TAG_volatile_type:
147   case dwarf::DW_TAG_restrict_type:
148   case dwarf::DW_TAG_member:
149   case dwarf::DW_TAG_inheritance:
150     return true;
151   default:
152     // CompositeTypes are currently modelled as DerivedTypes.
153     return isCompositeType();
154   }
155 }
156
157 /// isCompositeType - Return true if the specified tag is legal for
158 /// DICompositeType.
159 bool DIDescriptor::isCompositeType() const {
160   assert (!isNull() && "Invalid descriptor!");
161   unsigned Tag = getTag();
162
163   switch (Tag) {
164   case dwarf::DW_TAG_array_type:
165   case dwarf::DW_TAG_structure_type:
166   case dwarf::DW_TAG_union_type:
167   case dwarf::DW_TAG_enumeration_type:
168   case dwarf::DW_TAG_vector_type:
169   case dwarf::DW_TAG_subroutine_type:
170   case dwarf::DW_TAG_class_type:
171     return true;
172   default:
173     return false;
174   }
175 }
176
177 /// isVariable - Return true if the specified tag is legal for DIVariable.
178 bool DIDescriptor::isVariable() const {
179   assert (!isNull() && "Invalid descriptor!");
180   unsigned Tag = getTag();
181
182   switch (Tag) {
183   case dwarf::DW_TAG_auto_variable:
184   case dwarf::DW_TAG_arg_variable:
185   case dwarf::DW_TAG_return_variable:
186     return true;
187   default:
188     return false;
189   }
190 }
191
192 /// isType - Return true if the specified tag is legal for DIType.
193 bool DIDescriptor::isType() const {
194   return isBasicType() || isCompositeType() || isDerivedType();
195 }
196
197 /// isSubprogram - Return true if the specified tag is legal for
198 /// DISubprogram.
199 bool DIDescriptor::isSubprogram() const {
200   assert (!isNull() && "Invalid descriptor!");
201   unsigned Tag = getTag();
202
203   return Tag == dwarf::DW_TAG_subprogram;
204 }
205
206 /// isGlobalVariable - Return true if the specified tag is legal for
207 /// DIGlobalVariable.
208 bool DIDescriptor::isGlobalVariable() const {
209   assert (!isNull() && "Invalid descriptor!");
210   unsigned Tag = getTag();
211
212   return Tag == dwarf::DW_TAG_variable;
213 }
214
215 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
216 bool DIDescriptor::isGlobal() const {
217   return isGlobalVariable();
218 }
219
220 /// isScope - Return true if the specified tag is one of the scope
221 /// related tag.
222 bool DIDescriptor::isScope() const {
223   assert (!isNull() && "Invalid descriptor!");
224   unsigned Tag = getTag();
225
226   switch (Tag) {
227     case dwarf::DW_TAG_compile_unit:
228     case dwarf::DW_TAG_lexical_block:
229     case dwarf::DW_TAG_subprogram:
230       return true;
231     default:
232       break;
233   }
234   return false;
235 }
236
237 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
238 bool DIDescriptor::isCompileUnit() const {
239   assert (!isNull() && "Invalid descriptor!");
240   unsigned Tag = getTag();
241
242   return Tag == dwarf::DW_TAG_compile_unit;
243 }
244
245 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
246 bool DIDescriptor::isLexicalBlock() const {
247   assert (!isNull() && "Invalid descriptor!");
248   unsigned Tag = getTag();
249
250   return Tag == dwarf::DW_TAG_lexical_block;
251 }
252
253 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
254 bool DIDescriptor::isSubrange() const {
255   assert (!isNull() && "Invalid descriptor!");
256   unsigned Tag = getTag();
257
258   return Tag == dwarf::DW_TAG_subrange_type;
259 }
260
261 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
262 bool DIDescriptor::isEnumerator() const {
263   assert (!isNull() && "Invalid descriptor!");
264   unsigned Tag = getTag();
265
266   return Tag == dwarf::DW_TAG_enumerator;
267 }
268
269 //===----------------------------------------------------------------------===//
270 // Simple Descriptor Constructors and other Methods
271 //===----------------------------------------------------------------------===//
272
273 DIType::DIType(MDNode *N) : DIDescriptor(N) {
274   if (!N) return;
275   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
276     DbgNode = 0;
277   }
278 }
279
280 unsigned DIArray::getNumElements() const {
281   assert (DbgNode && "Invalid DIArray");
282   return DbgNode->getNumElements();
283 }
284
285 /// replaceAllUsesWith - Replace all uses of debug info referenced by
286 /// this descriptor. After this completes, the current debug info value
287 /// is erased.
288 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
289   if (isNull())
290     return;
291
292   assert (!D.isNull() && "Can not replace with null");
293
294   // Since we use a TrackingVH for the node, its easy for clients to manufacture
295   // legitimate situations where they want to replaceAllUsesWith() on something
296   // which, due to uniquing, has merged with the source. We shield clients from
297   // this detail by allowing a value to be replaced with replaceAllUsesWith()
298   // itself.
299   if (getNode() != D.getNode()) {
300     MDNode *Node = DbgNode;
301     Node->replaceAllUsesWith(D.getNode());
302     delete Node;
303   }
304 }
305
306 /// Verify - Verify that a compile unit is well formed.
307 bool DICompileUnit::Verify() const {
308   if (isNull())
309     return false;
310   StringRef N = getFilename();
311   if (N.empty())
312     return false;
313   // It is possible that directory and produce string is empty.
314   return true;
315 }
316
317 /// Verify - Verify that a type descriptor is well formed.
318 bool DIType::Verify() const {
319   if (isNull())
320     return false;
321   if (getContext().isNull())
322     return false;
323
324   DICompileUnit CU = getCompileUnit();
325   if (!CU.isNull() && !CU.Verify())
326     return false;
327   return true;
328 }
329
330 /// Verify - Verify that a composite type descriptor is well formed.
331 bool DICompositeType::Verify() const {
332   if (isNull())
333     return false;
334   if (getContext().isNull())
335     return false;
336
337   DICompileUnit CU = getCompileUnit();
338   if (!CU.isNull() && !CU.Verify())
339     return false;
340   return true;
341 }
342
343 /// Verify - Verify that a subprogram descriptor is well formed.
344 bool DISubprogram::Verify() const {
345   if (isNull())
346     return false;
347
348   if (getContext().isNull())
349     return false;
350
351   DICompileUnit CU = getCompileUnit();
352   if (!CU.Verify())
353     return false;
354
355   DICompositeType Ty = getType();
356   if (!Ty.isNull() && !Ty.Verify())
357     return false;
358   return true;
359 }
360
361 /// Verify - Verify that a global variable descriptor is well formed.
362 bool DIGlobalVariable::Verify() const {
363   if (isNull())
364     return false;
365
366   if (getDisplayName().empty())
367     return false;
368
369   if (getContext().isNull())
370     return false;
371
372   DICompileUnit CU = getCompileUnit();
373   if (!CU.isNull() && !CU.Verify())
374     return false;
375
376   DIType Ty = getType();
377   if (!Ty.Verify())
378     return false;
379
380   if (!getGlobal())
381     return false;
382
383   return true;
384 }
385
386 /// Verify - Verify that a variable descriptor is well formed.
387 bool DIVariable::Verify() const {
388   if (isNull())
389     return false;
390
391   if (getContext().isNull())
392     return false;
393
394   DIType Ty = getType();
395   if (!Ty.Verify())
396     return false;
397
398   return true;
399 }
400
401 /// getOriginalTypeSize - If this type is derived from a base type then
402 /// return base type size.
403 uint64_t DIDerivedType::getOriginalTypeSize() const {
404   unsigned Tag = getTag();
405   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
406       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
407       Tag == dwarf::DW_TAG_restrict_type) {
408     DIType BaseType = getTypeDerivedFrom();
409     // If this type is not derived from any type then take conservative 
410     // approach.
411     if (BaseType.isNull())
412       return getSizeInBits();
413     if (BaseType.isDerivedType())
414       return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
415     else
416       return BaseType.getSizeInBits();
417   }
418     
419   return getSizeInBits();
420 }
421
422 /// describes - Return true if this subprogram provides debugging
423 /// information for the function F.
424 bool DISubprogram::describes(const Function *F) {
425   assert (F && "Invalid function");
426   StringRef Name = getLinkageName();
427   if (Name.empty())
428     Name = getName();
429   if (F->getName() == Name)
430     return true;
431   return false;
432 }
433
434 StringRef DIScope::getFilename() const {
435   if (isLexicalBlock()) 
436     return DILexicalBlock(DbgNode).getFilename();
437   else if (isSubprogram())
438     return DISubprogram(DbgNode).getFilename();
439   else if (isCompileUnit())
440     return DICompileUnit(DbgNode).getFilename();
441   else 
442     assert (0 && "Invalid DIScope!");
443   return StringRef();
444 }
445
446 StringRef DIScope::getDirectory() const {
447   if (isLexicalBlock()) 
448     return DILexicalBlock(DbgNode).getDirectory();
449   else if (isSubprogram())
450     return DISubprogram(DbgNode).getDirectory();
451   else if (isCompileUnit())
452     return DICompileUnit(DbgNode).getDirectory();
453   else 
454     assert (0 && "Invalid DIScope!");
455   return StringRef();
456 }
457
458 //===----------------------------------------------------------------------===//
459 // DIDescriptor: dump routines for all descriptors.
460 //===----------------------------------------------------------------------===//
461
462
463 /// dump - Print descriptor.
464 void DIDescriptor::dump() const {
465   errs() << "[" << dwarf::TagString(getTag()) << "] ";
466   errs().write_hex((intptr_t) &*DbgNode) << ']';
467 }
468
469 /// dump - Print compile unit.
470 void DICompileUnit::dump() const {
471   if (getLanguage())
472     errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
473
474   errs() << " [" << getDirectory() << "/" << getFilename() << " ]";
475 }
476
477 /// dump - Print type.
478 void DIType::dump() const {
479   if (isNull()) return;
480
481   StringRef Res = getName();
482   if (!Res.empty())
483     errs() << " [" << Res << "] ";
484
485   unsigned Tag = getTag();
486   errs() << " [" << dwarf::TagString(Tag) << "] ";
487
488   // TODO : Print context
489   getCompileUnit().dump();
490   errs() << " ["
491          << getLineNumber() << ", "
492          << getSizeInBits() << ", "
493          << getAlignInBits() << ", "
494          << getOffsetInBits()
495          << "] ";
496
497   if (isPrivate())
498     errs() << " [private] ";
499   else if (isProtected())
500     errs() << " [protected] ";
501
502   if (isForwardDecl())
503     errs() << " [fwd] ";
504
505   if (isBasicType())
506     DIBasicType(DbgNode).dump();
507   else if (isDerivedType())
508     DIDerivedType(DbgNode).dump();
509   else if (isCompositeType())
510     DICompositeType(DbgNode).dump();
511   else {
512     errs() << "Invalid DIType\n";
513     return;
514   }
515
516   errs() << "\n";
517 }
518
519 /// dump - Print basic type.
520 void DIBasicType::dump() const {
521   errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
522 }
523
524 /// dump - Print derived type.
525 void DIDerivedType::dump() const {
526   errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
527 }
528
529 /// dump - Print composite type.
530 void DICompositeType::dump() const {
531   DIArray A = getTypeArray();
532   if (A.isNull())
533     return;
534   errs() << " [" << A.getNumElements() << " elements]";
535 }
536
537 /// dump - Print global.
538 void DIGlobal::dump() const {
539   StringRef Res = getName();
540   if (!Res.empty())
541     errs() << " [" << Res << "] ";
542
543   unsigned Tag = getTag();
544   errs() << " [" << dwarf::TagString(Tag) << "] ";
545
546   // TODO : Print context
547   getCompileUnit().dump();
548   errs() << " [" << getLineNumber() << "] ";
549
550   if (isLocalToUnit())
551     errs() << " [local] ";
552
553   if (isDefinition())
554     errs() << " [def] ";
555
556   if (isGlobalVariable())
557     DIGlobalVariable(DbgNode).dump();
558
559   errs() << "\n";
560 }
561
562 /// dump - Print subprogram.
563 void DISubprogram::dump() const {
564   StringRef Res = getName();
565   if (!Res.empty())
566     errs() << " [" << Res << "] ";
567
568   unsigned Tag = getTag();
569   errs() << " [" << dwarf::TagString(Tag) << "] ";
570
571   // TODO : Print context
572   getCompileUnit().dump();
573   errs() << " [" << getLineNumber() << "] ";
574
575   if (isLocalToUnit())
576     errs() << " [local] ";
577
578   if (isDefinition())
579     errs() << " [def] ";
580
581   errs() << "\n";
582 }
583
584 /// dump - Print global variable.
585 void DIGlobalVariable::dump() const {
586   errs() << " [";
587   getGlobal()->dump();
588   errs() << "] ";
589 }
590
591 /// dump - Print variable.
592 void DIVariable::dump() const {
593   StringRef Res = getName();
594   if (!Res.empty())
595     errs() << " [" << Res << "] ";
596
597   getCompileUnit().dump();
598   errs() << " [" << getLineNumber() << "] ";
599   getType().dump();
600   errs() << "\n";
601
602   // FIXME: Dump complex addresses
603 }
604
605 //===----------------------------------------------------------------------===//
606 // DIFactory: Basic Helpers
607 //===----------------------------------------------------------------------===//
608
609 DIFactory::DIFactory(Module &m)
610   : M(m), VMContext(M.getContext()), DeclareFn(0) {
611   EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
612 }
613
614 Constant *DIFactory::GetTagConstant(unsigned TAG) {
615   assert((TAG & LLVMDebugVersionMask) == 0 &&
616          "Tag too large for debug encoding!");
617   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
618 }
619
620 //===----------------------------------------------------------------------===//
621 // DIFactory: Primary Constructors
622 //===----------------------------------------------------------------------===//
623
624 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
625 /// This implicitly uniques the arrays created.
626 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
627   SmallVector<Value*, 16> Elts;
628
629   if (NumTys == 0)
630     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
631   else
632     for (unsigned i = 0; i != NumTys; ++i)
633       Elts.push_back(Tys[i].getNode());
634
635   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
636 }
637
638 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
639 /// implicitly uniques the values returned.
640 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
641   Value *Elts[] = {
642     GetTagConstant(dwarf::DW_TAG_subrange_type),
643     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
644     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
645   };
646
647   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
648 }
649
650
651
652 /// CreateCompileUnit - Create a new descriptor for the specified compile
653 /// unit.  Note that this does not unique compile units within the module.
654 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
655                                            StringRef Filename,
656                                            StringRef Directory,
657                                            StringRef Producer,
658                                            bool isMain,
659                                            bool isOptimized,
660                                            StringRef Flags,
661                                            unsigned RunTimeVer) {
662   Value *Elts[] = {
663     GetTagConstant(dwarf::DW_TAG_compile_unit),
664     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
665     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
666     MDString::get(VMContext, Filename),
667     MDString::get(VMContext, Directory),
668     MDString::get(VMContext, Producer),
669     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
670     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
671     MDString::get(VMContext, Flags),
672     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
673   };
674
675   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
676 }
677
678 /// CreateEnumerator - Create a single enumerator value.
679 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
680   Value *Elts[] = {
681     GetTagConstant(dwarf::DW_TAG_enumerator),
682     MDString::get(VMContext, Name),
683     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
684   };
685   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
686 }
687
688
689 /// CreateBasicType - Create a basic type like int, float, etc.
690 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
691                                        StringRef Name,
692                                        DICompileUnit CompileUnit,
693                                        unsigned LineNumber,
694                                        uint64_t SizeInBits,
695                                        uint64_t AlignInBits,
696                                        uint64_t OffsetInBits, unsigned Flags,
697                                        unsigned Encoding) {
698   Value *Elts[] = {
699     GetTagConstant(dwarf::DW_TAG_base_type),
700     Context.getNode(),
701     MDString::get(VMContext, Name),
702     CompileUnit.getNode(),
703     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
704     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
705     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
706     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
707     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
708     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
709   };
710   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
711 }
712
713
714 /// CreateBasicType - Create a basic type like int, float, etc.
715 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
716                                          StringRef Name,
717                                          DICompileUnit CompileUnit,
718                                          unsigned LineNumber,
719                                          Constant *SizeInBits,
720                                          Constant *AlignInBits,
721                                          Constant *OffsetInBits, unsigned Flags,
722                                          unsigned Encoding) {
723   Value *Elts[] = {
724     GetTagConstant(dwarf::DW_TAG_base_type),
725     Context.getNode(),
726     MDString::get(VMContext, Name),
727     CompileUnit.getNode(),
728     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
729     SizeInBits,
730     AlignInBits,
731     OffsetInBits,
732     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
733     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
734   };
735   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
736 }
737
738
739 /// CreateDerivedType - Create a derived type like const qualified type,
740 /// pointer, typedef, etc.
741 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
742                                            DIDescriptor Context,
743                                            StringRef Name,
744                                            DICompileUnit CompileUnit,
745                                            unsigned LineNumber,
746                                            uint64_t SizeInBits,
747                                            uint64_t AlignInBits,
748                                            uint64_t OffsetInBits,
749                                            unsigned Flags,
750                                            DIType DerivedFrom) {
751   Value *Elts[] = {
752     GetTagConstant(Tag),
753     Context.getNode(),
754     MDString::get(VMContext, Name),
755     CompileUnit.getNode(),
756     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
757     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
758     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
759     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
760     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
761     DerivedFrom.getNode(),
762   };
763   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
764 }
765
766
767 /// CreateDerivedType - Create a derived type like const qualified type,
768 /// pointer, typedef, etc.
769 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
770                                              DIDescriptor Context,
771                                              StringRef Name,
772                                              DICompileUnit CompileUnit,
773                                              unsigned LineNumber,
774                                              Constant *SizeInBits,
775                                              Constant *AlignInBits,
776                                              Constant *OffsetInBits,
777                                              unsigned Flags,
778                                              DIType DerivedFrom) {
779   Value *Elts[] = {
780     GetTagConstant(Tag),
781     Context.getNode(),
782     MDString::get(VMContext, Name),
783     CompileUnit.getNode(),
784     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
785     SizeInBits,
786     AlignInBits,
787     OffsetInBits,
788     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
789     DerivedFrom.getNode(),
790   };
791   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
792 }
793
794
795 /// CreateCompositeType - Create a composite type like array, struct, etc.
796 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
797                                                DIDescriptor Context,
798                                                StringRef Name,
799                                                DICompileUnit CompileUnit,
800                                                unsigned LineNumber,
801                                                uint64_t SizeInBits,
802                                                uint64_t AlignInBits,
803                                                uint64_t OffsetInBits,
804                                                unsigned Flags,
805                                                DIType DerivedFrom,
806                                                DIArray Elements,
807                                                unsigned RuntimeLang) {
808
809   Value *Elts[] = {
810     GetTagConstant(Tag),
811     Context.getNode(),
812     MDString::get(VMContext, Name),
813     CompileUnit.getNode(),
814     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
815     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
816     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
817     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
818     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
819     DerivedFrom.getNode(),
820     Elements.getNode(),
821     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
822   };
823   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
824 }
825
826
827 /// CreateCompositeType - Create a composite type like array, struct, etc.
828 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
829                                                  DIDescriptor Context,
830                                                  StringRef Name,
831                                                  DICompileUnit CompileUnit,
832                                                  unsigned LineNumber,
833                                                  Constant *SizeInBits,
834                                                  Constant *AlignInBits,
835                                                  Constant *OffsetInBits,
836                                                  unsigned Flags,
837                                                  DIType DerivedFrom,
838                                                  DIArray Elements,
839                                                  unsigned RuntimeLang) {
840
841   Value *Elts[] = {
842     GetTagConstant(Tag),
843     Context.getNode(),
844     MDString::get(VMContext, Name),
845     CompileUnit.getNode(),
846     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
847     SizeInBits,
848     AlignInBits,
849     OffsetInBits,
850     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
851     DerivedFrom.getNode(),
852     Elements.getNode(),
853     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
854   };
855   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
856 }
857
858
859 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
860 /// See comments in DISubprogram for descriptions of these fields.  This
861 /// method does not unique the generated descriptors.
862 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
863                                          StringRef Name,
864                                          StringRef DisplayName,
865                                          StringRef LinkageName,
866                                          DICompileUnit CompileUnit,
867                                          unsigned LineNo, DIType Type,
868                                          bool isLocalToUnit,
869                                          bool isDefinition,
870                                          unsigned VK, unsigned VIndex,
871                                          DIType ContainingType) {
872
873   Value *Elts[] = {
874     GetTagConstant(dwarf::DW_TAG_subprogram),
875     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
876     Context.getNode(),
877     MDString::get(VMContext, Name),
878     MDString::get(VMContext, DisplayName),
879     MDString::get(VMContext, LinkageName),
880     CompileUnit.getNode(),
881     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
882     Type.getNode(),
883     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
884     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
885     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
886     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
887     ContainingType.getNode()
888   };
889   return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
890 }
891
892 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
893 /// given declaration. 
894 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
895   if (SPDeclaration.isDefinition())
896     return DISubprogram(SPDeclaration.getNode());
897
898   MDNode *DeclNode = SPDeclaration.getNode();
899   Value *Elts[] = {
900     GetTagConstant(dwarf::DW_TAG_subprogram),
901     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
902     DeclNode->getElement(2), // Context
903     DeclNode->getElement(3), // Name
904     DeclNode->getElement(4), // DisplayName
905     DeclNode->getElement(5), // LinkageName
906     DeclNode->getElement(6), // CompileUnit
907     DeclNode->getElement(7), // LineNo
908     DeclNode->getElement(8), // Type
909     DeclNode->getElement(9), // isLocalToUnit
910     ConstantInt::get(Type::getInt1Ty(VMContext), true),
911     DeclNode->getElement(11), // Virtuality
912     DeclNode->getElement(12), // VIndex
913     DeclNode->getElement(13)  // Containting Type
914   };
915   return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
916 }
917
918 /// CreateGlobalVariable - Create a new descriptor for the specified global.
919 DIGlobalVariable
920 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
921                                 StringRef DisplayName,
922                                 StringRef LinkageName,
923                                 DICompileUnit CompileUnit,
924                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
925                                 bool isDefinition, llvm::GlobalVariable *Val) {
926   Value *Elts[] = {
927     GetTagConstant(dwarf::DW_TAG_variable),
928     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
929     Context.getNode(),
930     MDString::get(VMContext, Name),
931     MDString::get(VMContext, DisplayName),
932     MDString::get(VMContext, LinkageName),
933     CompileUnit.getNode(),
934     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
935     Type.getNode(),
936     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
937     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
938     Val
939   };
940
941   Value *const *Vs = &Elts[0];
942   MDNode *Node = MDNode::get(VMContext,Vs, 12);
943
944   // Create a named metadata so that we do not lose this mdnode.
945   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
946   NMD->addElement(Node);
947
948   return DIGlobalVariable(Node);
949 }
950
951
952 /// CreateVariable - Create a new descriptor for the specified variable.
953 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
954                                      StringRef Name,
955                                      DICompileUnit CompileUnit, unsigned LineNo,
956                                      DIType Type) {
957   Value *Elts[] = {
958     GetTagConstant(Tag),
959     Context.getNode(),
960     MDString::get(VMContext, Name),
961     CompileUnit.getNode(),
962     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
963     Type.getNode(),
964   };
965   return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
966 }
967
968
969 /// CreateComplexVariable - Create a new descriptor for the specified variable
970 /// which has a complex address expression for its address.
971 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
972                                             const std::string &Name,
973                                             DICompileUnit CompileUnit,
974                                             unsigned LineNo,
975                                    DIType Type, SmallVector<Value *, 9> &addr) {
976   SmallVector<Value *, 9> Elts;
977   Elts.push_back(GetTagConstant(Tag));
978   Elts.push_back(Context.getNode());
979   Elts.push_back(MDString::get(VMContext, Name));
980   Elts.push_back(CompileUnit.getNode());
981   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
982   Elts.push_back(Type.getNode());
983   Elts.insert(Elts.end(), addr.begin(), addr.end());
984
985   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
986 }
987
988
989 /// CreateBlock - This creates a descriptor for a lexical block with the
990 /// specified parent VMContext.
991 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
992   Value *Elts[] = {
993     GetTagConstant(dwarf::DW_TAG_lexical_block),
994     Context.getNode()
995   };
996   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
997 }
998
999 /// CreateLocation - Creates a debug info location.
1000 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1001                                      DIScope S, DILocation OrigLoc) {
1002   Value *Elts[] = {
1003     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1004     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1005     S.getNode(),
1006     OrigLoc.getNode(),
1007   };
1008   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1009 }
1010
1011 /// CreateLocation - Creates a debug info location.
1012 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1013                                      DIScope S, MDNode *OrigLoc) {
1014  Value *Elts[] = {
1015     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1016     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1017     S.getNode(),
1018     OrigLoc
1019   };
1020   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1021 }
1022
1023 //===----------------------------------------------------------------------===//
1024 // DIFactory: Routines for inserting code into a function
1025 //===----------------------------------------------------------------------===//
1026
1027 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1028 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1029                               Instruction *InsertBefore) {
1030   // Cast the storage to a {}* for the call to llvm.dbg.declare.
1031   Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1032
1033   if (!DeclareFn)
1034     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1035
1036   Value *Args[] = { Storage, D.getNode() };
1037   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1038 }
1039
1040 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1041 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1042                               BasicBlock *InsertAtEnd) {
1043   // Cast the storage to a {}* for the call to llvm.dbg.declare.
1044   Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1045
1046   if (!DeclareFn)
1047     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1048
1049   Value *Args[] = { Storage, D.getNode() };
1050   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1051 }
1052
1053 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1054 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1055                                                 DIVariable D,
1056                                                 Instruction *InsertBefore) {
1057   assert(V && "no value passed to dbg.value");
1058   assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1059          "offset must be i64");
1060   if (!ValueFn)
1061     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1062
1063   Value *Elts[] = { V };
1064   Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1065                     D.getNode() };
1066   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1067 }
1068
1069 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1070 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1071                                                 DIVariable D,
1072                                                 BasicBlock *InsertAtEnd) {
1073   assert(V && "no value passed to dbg.value");
1074   assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1075          "offset must be i64");
1076   if (!ValueFn)
1077     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1078
1079   Value *Elts[] = { V };
1080   Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1081                     D.getNode() };
1082   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1083 }
1084
1085 //===----------------------------------------------------------------------===//
1086 // DebugInfoFinder implementations.
1087 //===----------------------------------------------------------------------===//
1088
1089 /// processModule - Process entire module and collect debug info.
1090 void DebugInfoFinder::processModule(Module &M) {
1091
1092   MetadataContext &TheMetadata = M.getContext().getMetadata();
1093   unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
1094
1095   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1096     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1097       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1098            ++BI) {
1099         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1100           processDeclare(DDI);
1101         else if (MDDbgKind) 
1102           if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) 
1103             processLocation(DILocation(L));
1104       }
1105
1106   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1107   if (!NMD)
1108     return;
1109
1110   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1111     DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1112     if (addGlobalVariable(DIG)) {
1113       addCompileUnit(DIG.getCompileUnit());
1114       processType(DIG.getType());
1115     }
1116   }
1117 }
1118
1119 /// processLocation - Process DILocation.
1120 void DebugInfoFinder::processLocation(DILocation Loc) {
1121   if (Loc.isNull()) return;
1122   DIScope S(Loc.getScope().getNode());
1123   if (S.isNull()) return;
1124   if (S.isCompileUnit())
1125     addCompileUnit(DICompileUnit(S.getNode()));
1126   else if (S.isSubprogram())
1127     processSubprogram(DISubprogram(S.getNode()));
1128   else if (S.isLexicalBlock())
1129     processLexicalBlock(DILexicalBlock(S.getNode()));
1130   processLocation(Loc.getOrigLocation());
1131 }
1132
1133 /// processType - Process DIType.
1134 void DebugInfoFinder::processType(DIType DT) {
1135   if (!addType(DT))
1136     return;
1137
1138   addCompileUnit(DT.getCompileUnit());
1139   if (DT.isCompositeType()) {
1140     DICompositeType DCT(DT.getNode());
1141     processType(DCT.getTypeDerivedFrom());
1142     DIArray DA = DCT.getTypeArray();
1143     if (!DA.isNull())
1144       for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1145         DIDescriptor D = DA.getElement(i);
1146         DIType TypeE = DIType(D.getNode());
1147         if (!TypeE.isNull())
1148           processType(TypeE);
1149         else
1150           processSubprogram(DISubprogram(D.getNode()));
1151       }
1152   } else if (DT.isDerivedType()) {
1153     DIDerivedType DDT(DT.getNode());
1154     if (!DDT.isNull())
1155       processType(DDT.getTypeDerivedFrom());
1156   }
1157 }
1158
1159 /// processLexicalBlock
1160 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1161   if (LB.isNull())
1162     return;
1163   DIScope Context = LB.getContext();
1164   if (Context.isLexicalBlock())
1165     return processLexicalBlock(DILexicalBlock(Context.getNode()));
1166   else
1167     return processSubprogram(DISubprogram(Context.getNode()));
1168 }
1169
1170 /// processSubprogram - Process DISubprogram.
1171 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1172   if (SP.isNull())
1173     return;
1174   if (!addSubprogram(SP))
1175     return;
1176   addCompileUnit(SP.getCompileUnit());
1177   processType(SP.getType());
1178 }
1179
1180 /// processDeclare - Process DbgDeclareInst.
1181 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1182   DIVariable DV(cast<MDNode>(DDI->getVariable()));
1183   if (DV.isNull())
1184     return;
1185
1186   if (!NodesSeen.insert(DV.getNode()))
1187     return;
1188
1189   addCompileUnit(DV.getCompileUnit());
1190   processType(DV.getType());
1191 }
1192
1193 /// addType - Add type into Tys.
1194 bool DebugInfoFinder::addType(DIType DT) {
1195   if (DT.isNull())
1196     return false;
1197
1198   if (!NodesSeen.insert(DT.getNode()))
1199     return false;
1200
1201   TYs.push_back(DT.getNode());
1202   return true;
1203 }
1204
1205 /// addCompileUnit - Add compile unit into CUs.
1206 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1207   if (CU.isNull())
1208     return false;
1209
1210   if (!NodesSeen.insert(CU.getNode()))
1211     return false;
1212
1213   CUs.push_back(CU.getNode());
1214   return true;
1215 }
1216
1217 /// addGlobalVariable - Add global variable into GVs.
1218 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1219   if (DIG.isNull())
1220     return false;
1221
1222   if (!NodesSeen.insert(DIG.getNode()))
1223     return false;
1224
1225   GVs.push_back(DIG.getNode());
1226   return true;
1227 }
1228
1229 // addSubprogram - Add subprgoram into SPs.
1230 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1231   if (SP.isNull())
1232     return false;
1233
1234   if (!NodesSeen.insert(SP.getNode()))
1235     return false;
1236
1237   SPs.push_back(SP.getNode());
1238   return true;
1239 }
1240
1241 namespace llvm {
1242   /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1243   /// is the stoppoint that dominates this instruction.
1244   const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1245     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1246       return DSI;
1247
1248     const BasicBlock *BB = Inst->getParent();
1249     BasicBlock::const_iterator I = Inst, B;
1250     while (BB) {
1251       B = BB->begin();
1252
1253       // A BB consisting only of a terminator can't have a stoppoint.
1254       while (I != B) {
1255         --I;
1256         if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1257           return DSI;
1258       }
1259
1260       // This BB didn't have a stoppoint: if there is only one predecessor, look
1261       // for a stoppoint there. We could use getIDom(), but that would require
1262       // dominator info.
1263       BB = I->getParent()->getUniquePredecessor();
1264       if (BB)
1265         I = BB->getTerminator();
1266     }
1267
1268     return 0;
1269   }
1270
1271   /// findBBStopPoint - Find the stoppoint corresponding to first real
1272   /// (non-debug intrinsic) instruction in this Basic Block, and return the
1273   /// stoppoint for it.
1274   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1275     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1276       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1277         return DSI;
1278
1279     // Fallback to looking for stoppoint of unique predecessor. Useful if this
1280     // BB contains no stoppoints, but unique predecessor does.
1281     BB = BB->getUniquePredecessor();
1282     if (BB)
1283       return findStopPoint(BB->getTerminator());
1284
1285     return 0;
1286   }
1287
1288   Value *findDbgGlobalDeclare(GlobalVariable *V) {
1289     const Module *M = V->getParent();
1290     NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1291     if (!NMD)
1292       return 0;
1293
1294     for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1295       DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1296       if (DIG.isNull())
1297         continue;
1298       if (DIG.getGlobal() == V)
1299         return DIG.getNode();
1300     }
1301     return 0;
1302   }
1303
1304   /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1305   /// It looks through pointer casts too.
1306   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1307     if (stripCasts) {
1308       V = V->stripPointerCasts();
1309
1310       // Look for the bitcast.
1311       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1312             I != E; ++I)
1313         if (isa<BitCastInst>(I)) {
1314           const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1315           if (DDI) return DDI;
1316         }
1317       return 0;
1318     }
1319
1320     // Find llvm.dbg.declare among uses of the instruction.
1321     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1322           I != E; ++I)
1323       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1324         return DDI;
1325
1326     return 0;
1327   }
1328
1329 bool getLocationInfo(const Value *V, std::string &DisplayName,
1330                      std::string &Type, unsigned &LineNo, std::string &File,
1331                        std::string &Dir) {
1332     DICompileUnit Unit;
1333     DIType TypeD;
1334
1335     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1336       Value *DIGV = findDbgGlobalDeclare(GV);
1337       if (!DIGV) return false;
1338       DIGlobalVariable Var(cast<MDNode>(DIGV));
1339
1340       StringRef D = Var.getDisplayName();
1341       if (!D.empty())
1342         DisplayName = D;
1343       LineNo = Var.getLineNumber();
1344       Unit = Var.getCompileUnit();
1345       TypeD = Var.getType();
1346     } else {
1347       const DbgDeclareInst *DDI = findDbgDeclare(V);
1348       if (!DDI) return false;
1349       DIVariable Var(cast<MDNode>(DDI->getVariable()));
1350
1351       StringRef D = Var.getName();
1352       if (!D.empty())
1353         DisplayName = D;
1354       LineNo = Var.getLineNumber();
1355       Unit = Var.getCompileUnit();
1356       TypeD = Var.getType();
1357     }
1358
1359     StringRef T = TypeD.getName();
1360     if (!T.empty())
1361       Type = T;
1362     StringRef F = Unit.getFilename();
1363     if (!F.empty())
1364       File = F;
1365     StringRef D = Unit.getDirectory();
1366     if (!D.empty())
1367       Dir = D;
1368     return true;
1369   }
1370
1371   /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1372   /// info intrinsic.
1373   bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1374                                  CodeGenOpt::Level OptLev) {
1375     return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1376   }
1377
1378   /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1379   /// info intrinsic.
1380   bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1381                                  CodeGenOpt::Level OptLev) {
1382     return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1383   }
1384
1385   /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1386   /// info intrinsic.
1387   bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1388                                  CodeGenOpt::Level OptLev) {
1389     return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1390   }
1391
1392   /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1393   /// info intrinsic.
1394   bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1395                                  CodeGenOpt::Level OptLev) {
1396     return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1397   }
1398
1399
1400   /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1401   /// info intrinsic.
1402   bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1403                                  CodeGenOpt::Level OptLev) {
1404     return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1405   }
1406
1407   /// ExtractDebugLocation - Extract debug location information
1408   /// from llvm.dbg.stoppoint intrinsic.
1409   DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1410                                 DebugLocTracker &DebugLocInfo) {
1411     DebugLoc DL;
1412     Value *Context = SPI.getContext();
1413
1414     // If this location is already tracked then use it.
1415     DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1416                         SPI.getColumn());
1417     DenseMap<DebugLocTuple, unsigned>::iterator II
1418       = DebugLocInfo.DebugIdMap.find(Tuple);
1419     if (II != DebugLocInfo.DebugIdMap.end())
1420       return DebugLoc::get(II->second);
1421
1422     // Add a new location entry.
1423     unsigned Id = DebugLocInfo.DebugLocations.size();
1424     DebugLocInfo.DebugLocations.push_back(Tuple);
1425     DebugLocInfo.DebugIdMap[Tuple] = Id;
1426
1427     return DebugLoc::get(Id);
1428   }
1429
1430   /// ExtractDebugLocation - Extract debug location information
1431   /// from DILocation.
1432   DebugLoc ExtractDebugLocation(DILocation &Loc,
1433                                 DebugLocTracker &DebugLocInfo) {
1434     DebugLoc DL;
1435     MDNode *Context = Loc.getScope().getNode();
1436     MDNode *InlinedLoc = NULL;
1437     if (!Loc.getOrigLocation().isNull())
1438       InlinedLoc = Loc.getOrigLocation().getNode();
1439     // If this location is already tracked then use it.
1440     DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1441                         Loc.getColumnNumber());
1442     DenseMap<DebugLocTuple, unsigned>::iterator II
1443       = DebugLocInfo.DebugIdMap.find(Tuple);
1444     if (II != DebugLocInfo.DebugIdMap.end())
1445       return DebugLoc::get(II->second);
1446
1447     // Add a new location entry.
1448     unsigned Id = DebugLocInfo.DebugLocations.size();
1449     DebugLocInfo.DebugLocations.push_back(Tuple);
1450     DebugLocInfo.DebugIdMap[Tuple] = Id;
1451
1452     return DebugLoc::get(Id);
1453   }
1454
1455   /// ExtractDebugLocation - Extract debug location information
1456   /// from llvm.dbg.func_start intrinsic.
1457   DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1458                                 DebugLocTracker &DebugLocInfo) {
1459     DebugLoc DL;
1460     Value *SP = FSI.getSubprogram();
1461
1462     DISubprogram Subprogram(cast<MDNode>(SP));
1463     unsigned Line = Subprogram.getLineNumber();
1464     DICompileUnit CU(Subprogram.getCompileUnit());
1465
1466     // If this location is already tracked then use it.
1467     DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1468     DenseMap<DebugLocTuple, unsigned>::iterator II
1469       = DebugLocInfo.DebugIdMap.find(Tuple);
1470     if (II != DebugLocInfo.DebugIdMap.end())
1471       return DebugLoc::get(II->second);
1472
1473     // Add a new location entry.
1474     unsigned Id = DebugLocInfo.DebugLocations.size();
1475     DebugLocInfo.DebugLocations.push_back(Tuple);
1476     DebugLocInfo.DebugIdMap[Tuple] = Id;
1477
1478     return DebugLoc::get(Id);
1479   }
1480
1481   /// getDISubprogram - Find subprogram that is enclosing this scope.
1482   DISubprogram getDISubprogram(MDNode *Scope) {
1483     DIDescriptor D(Scope);
1484     if (D.isNull())
1485       return DISubprogram();
1486     
1487     if (D.isCompileUnit())
1488       return DISubprogram();
1489     
1490     if (D.isSubprogram())
1491       return DISubprogram(Scope);
1492     
1493     if (D.isLexicalBlock())
1494       return getDISubprogram(DILexicalBlock(Scope).getContext().getNode());
1495     
1496     return DISubprogram();
1497   }
1498
1499   /// getDICompositeType - Find underlying composite type.
1500   DICompositeType getDICompositeType(DIType T) {
1501     if (T.isNull())
1502       return DICompositeType();
1503     
1504     if (T.isCompositeType())
1505       return DICompositeType(T.getNode());
1506     
1507     if (T.isDerivedType())
1508       return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom());
1509     
1510     return DICompositeType();
1511   }
1512 }