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