rename getMDKind -> getMDKindID, make it autoinsert if an MD Kind
[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/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::dwarf;
31
32 //===----------------------------------------------------------------------===//
33 // DIDescriptor
34 //===----------------------------------------------------------------------===//
35
36 /// ValidDebugInfo - Return true if V represents valid debug info value.
37 /// FIXME : Add DIDescriptor.isValid()
38 bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) {
39   if (!N)
40     return false;
41
42   DIDescriptor DI(N);
43
44   // Check current version. Allow Version6 for now.
45   unsigned Version = DI.getVersion();
46   if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
47     return false;
48
49   unsigned Tag = DI.getTag();
50   switch (Tag) {
51   case DW_TAG_variable:
52     assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
53     break;
54   case DW_TAG_compile_unit:
55     assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
56     break;
57   case DW_TAG_subprogram:
58     assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
59     break;
60   case DW_TAG_lexical_block:
61     // FIXME: This interfers with the quality of generated code during
62     // optimization.
63     if (OptLevel != CodeGenOpt::None)
64       return false;
65     // FALLTHROUGH
66   default:
67     break;
68   }
69
70   return true;
71 }
72
73 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
74   DbgNode = N;
75
76   // If this is non-null, check to see if the Tag matches. If not, set to null.
77   if (N && getTag() != RequiredTag) {
78     DbgNode = 0;
79   }
80 }
81
82 StringRef 
83 DIDescriptor::getStringField(unsigned Elt) const {
84   if (DbgNode == 0)
85     return StringRef();
86
87   if (Elt < DbgNode->getNumElements())
88     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt)))
89       return MDS->getString();
90
91   return StringRef();
92 }
93
94 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
95   if (DbgNode == 0)
96     return 0;
97
98   if (Elt < DbgNode->getNumElements())
99     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
100       return CI->getZExtValue();
101
102   return 0;
103 }
104
105 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
106   if (DbgNode == 0)
107     return DIDescriptor();
108
109   if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
110     return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
111
112   return DIDescriptor();
113 }
114
115 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
116   if (DbgNode == 0)
117     return 0;
118
119   if (Elt < DbgNode->getNumElements())
120       return dyn_cast_or_null<GlobalVariable>(DbgNode->getElement(Elt));
121   return 0;
122 }
123
124 //===----------------------------------------------------------------------===//
125 // Predicates
126 //===----------------------------------------------------------------------===//
127
128 /// isBasicType - Return true if the specified tag is legal for
129 /// DIBasicType.
130 bool DIDescriptor::isBasicType() const {
131   assert (!isNull() && "Invalid descriptor!");
132   unsigned Tag = getTag();
133
134   return Tag == dwarf::DW_TAG_base_type;
135 }
136
137 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
138 bool DIDescriptor::isDerivedType() const {
139   assert (!isNull() && "Invalid descriptor!");
140   unsigned Tag = getTag();
141
142   switch (Tag) {
143   case dwarf::DW_TAG_typedef:
144   case dwarf::DW_TAG_pointer_type:
145   case dwarf::DW_TAG_reference_type:
146   case dwarf::DW_TAG_const_type:
147   case dwarf::DW_TAG_volatile_type:
148   case dwarf::DW_TAG_restrict_type:
149   case dwarf::DW_TAG_member:
150   case dwarf::DW_TAG_inheritance:
151     return true;
152   default:
153     // CompositeTypes are currently modelled as DerivedTypes.
154     return isCompositeType();
155   }
156 }
157
158 /// isCompositeType - Return true if the specified tag is legal for
159 /// DICompositeType.
160 bool DIDescriptor::isCompositeType() const {
161   assert (!isNull() && "Invalid descriptor!");
162   unsigned Tag = getTag();
163
164   switch (Tag) {
165   case dwarf::DW_TAG_array_type:
166   case dwarf::DW_TAG_structure_type:
167   case dwarf::DW_TAG_union_type:
168   case dwarf::DW_TAG_enumeration_type:
169   case dwarf::DW_TAG_vector_type:
170   case dwarf::DW_TAG_subroutine_type:
171   case dwarf::DW_TAG_class_type:
172     return true;
173   default:
174     return false;
175   }
176 }
177
178 /// isVariable - Return true if the specified tag is legal for DIVariable.
179 bool DIDescriptor::isVariable() const {
180   assert (!isNull() && "Invalid descriptor!");
181   unsigned Tag = getTag();
182
183   switch (Tag) {
184   case dwarf::DW_TAG_auto_variable:
185   case dwarf::DW_TAG_arg_variable:
186   case dwarf::DW_TAG_return_variable:
187     return true;
188   default:
189     return false;
190   }
191 }
192
193 /// isType - Return true if the specified tag is legal for DIType.
194 bool DIDescriptor::isType() const {
195   return isBasicType() || isCompositeType() || isDerivedType();
196 }
197
198 /// isSubprogram - Return true if the specified tag is legal for
199 /// DISubprogram.
200 bool DIDescriptor::isSubprogram() const {
201   assert (!isNull() && "Invalid descriptor!");
202   unsigned Tag = getTag();
203
204   return Tag == dwarf::DW_TAG_subprogram;
205 }
206
207 /// isGlobalVariable - Return true if the specified tag is legal for
208 /// DIGlobalVariable.
209 bool DIDescriptor::isGlobalVariable() const {
210   assert (!isNull() && "Invalid descriptor!");
211   unsigned Tag = getTag();
212
213   return Tag == dwarf::DW_TAG_variable;
214 }
215
216 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
217 bool DIDescriptor::isGlobal() const {
218   return isGlobalVariable();
219 }
220
221 /// isScope - Return true if the specified tag is one of the scope
222 /// related tag.
223 bool DIDescriptor::isScope() const {
224   assert (!isNull() && "Invalid descriptor!");
225   unsigned Tag = getTag();
226
227   switch (Tag) {
228     case dwarf::DW_TAG_compile_unit:
229     case dwarf::DW_TAG_lexical_block:
230     case dwarf::DW_TAG_subprogram:
231     case dwarf::DW_TAG_namespace:
232       return true;
233     default:
234       break;
235   }
236   return false;
237 }
238
239 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
240 bool DIDescriptor::isCompileUnit() const {
241   assert (!isNull() && "Invalid descriptor!");
242   unsigned Tag = getTag();
243
244   return Tag == dwarf::DW_TAG_compile_unit;
245 }
246
247 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
248 bool DIDescriptor::isNameSpace() const {
249   assert (!isNull() && "Invalid descriptor!");
250   unsigned Tag = getTag();
251
252   return Tag == dwarf::DW_TAG_namespace;
253 }
254
255 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
256 bool DIDescriptor::isLexicalBlock() const {
257   assert (!isNull() && "Invalid descriptor!");
258   unsigned Tag = getTag();
259
260   return Tag == dwarf::DW_TAG_lexical_block;
261 }
262
263 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
264 bool DIDescriptor::isSubrange() const {
265   assert (!isNull() && "Invalid descriptor!");
266   unsigned Tag = getTag();
267
268   return Tag == dwarf::DW_TAG_subrange_type;
269 }
270
271 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
272 bool DIDescriptor::isEnumerator() const {
273   assert (!isNull() && "Invalid descriptor!");
274   unsigned Tag = getTag();
275
276   return Tag == dwarf::DW_TAG_enumerator;
277 }
278
279 //===----------------------------------------------------------------------===//
280 // Simple Descriptor Constructors and other Methods
281 //===----------------------------------------------------------------------===//
282
283 DIType::DIType(MDNode *N) : DIDescriptor(N) {
284   if (!N) return;
285   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
286     DbgNode = 0;
287   }
288 }
289
290 unsigned DIArray::getNumElements() const {
291   assert (DbgNode && "Invalid DIArray");
292   return DbgNode->getNumElements();
293 }
294
295 /// replaceAllUsesWith - Replace all uses of debug info referenced by
296 /// this descriptor. After this completes, the current debug info value
297 /// is erased.
298 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
299   if (isNull())
300     return;
301
302   assert (!D.isNull() && "Can not replace with null");
303
304   // Since we use a TrackingVH for the node, its easy for clients to manufacture
305   // legitimate situations where they want to replaceAllUsesWith() on something
306   // which, due to uniquing, has merged with the source. We shield clients from
307   // this detail by allowing a value to be replaced with replaceAllUsesWith()
308   // itself.
309   if (getNode() != D.getNode()) {
310     MDNode *Node = DbgNode;
311     Node->replaceAllUsesWith(D.getNode());
312     delete Node;
313   }
314 }
315
316 /// Verify - Verify that a compile unit is well formed.
317 bool DICompileUnit::Verify() const {
318   if (isNull())
319     return false;
320   StringRef N = getFilename();
321   if (N.empty())
322     return false;
323   // It is possible that directory and produce string is empty.
324   return true;
325 }
326
327 /// Verify - Verify that a type descriptor is well formed.
328 bool DIType::Verify() const {
329   if (isNull())
330     return false;
331   if (getContext().isNull())
332     return false;
333
334   DICompileUnit CU = getCompileUnit();
335   if (!CU.isNull() && !CU.Verify())
336     return false;
337   return true;
338 }
339
340 /// Verify - Verify that a composite type descriptor is well formed.
341 bool DICompositeType::Verify() const {
342   if (isNull())
343     return false;
344   if (getContext().isNull())
345     return false;
346
347   DICompileUnit CU = getCompileUnit();
348   if (!CU.isNull() && !CU.Verify())
349     return false;
350   return true;
351 }
352
353 /// Verify - Verify that a subprogram descriptor is well formed.
354 bool DISubprogram::Verify() const {
355   if (isNull())
356     return false;
357
358   if (getContext().isNull())
359     return false;
360
361   DICompileUnit CU = getCompileUnit();
362   if (!CU.Verify())
363     return false;
364
365   DICompositeType Ty = getType();
366   if (!Ty.isNull() && !Ty.Verify())
367     return false;
368   return true;
369 }
370
371 /// Verify - Verify that a global variable descriptor is well formed.
372 bool DIGlobalVariable::Verify() const {
373   if (isNull())
374     return false;
375
376   if (getDisplayName().empty())
377     return false;
378
379   if (getContext().isNull())
380     return false;
381
382   DICompileUnit CU = getCompileUnit();
383   if (!CU.isNull() && !CU.Verify())
384     return false;
385
386   DIType Ty = getType();
387   if (!Ty.Verify())
388     return false;
389
390   if (!getGlobal())
391     return false;
392
393   return true;
394 }
395
396 /// Verify - Verify that a variable descriptor is well formed.
397 bool DIVariable::Verify() const {
398   if (isNull())
399     return false;
400
401   if (getContext().isNull())
402     return false;
403
404   DIType Ty = getType();
405   if (!Ty.Verify())
406     return false;
407
408   return true;
409 }
410
411 /// getOriginalTypeSize - If this type is derived from a base type then
412 /// return base type size.
413 uint64_t DIDerivedType::getOriginalTypeSize() const {
414   unsigned Tag = getTag();
415   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
416       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
417       Tag == dwarf::DW_TAG_restrict_type) {
418     DIType BaseType = getTypeDerivedFrom();
419     // If this type is not derived from any type then take conservative 
420     // approach.
421     if (BaseType.isNull())
422       return getSizeInBits();
423     if (BaseType.isDerivedType())
424       return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
425     else
426       return BaseType.getSizeInBits();
427   }
428     
429   return getSizeInBits();
430 }
431
432 /// describes - Return true if this subprogram provides debugging
433 /// information for the function F.
434 bool DISubprogram::describes(const Function *F) {
435   assert (F && "Invalid function");
436   StringRef Name = getLinkageName();
437   if (Name.empty())
438     Name = getName();
439   if (F->getName() == Name)
440     return true;
441   return false;
442 }
443
444 StringRef DIScope::getFilename() const {
445   if (isLexicalBlock()) 
446     return DILexicalBlock(DbgNode).getFilename();
447   else if (isSubprogram())
448     return DISubprogram(DbgNode).getFilename();
449   else if (isCompileUnit())
450     return DICompileUnit(DbgNode).getFilename();
451   else if (isNameSpace())
452     return DINameSpace(DbgNode).getFilename();
453   else 
454     assert (0 && "Invalid DIScope!");
455   return StringRef();
456 }
457
458 StringRef DIScope::getDirectory() const {
459   if (isLexicalBlock()) 
460     return DILexicalBlock(DbgNode).getDirectory();
461   else if (isSubprogram())
462     return DISubprogram(DbgNode).getDirectory();
463   else if (isCompileUnit())
464     return DICompileUnit(DbgNode).getDirectory();
465   else if (isNameSpace())
466     return DINameSpace(DbgNode).getDirectory();
467   else 
468     assert (0 && "Invalid DIScope!");
469   return StringRef();
470 }
471
472 //===----------------------------------------------------------------------===//
473 // DIDescriptor: dump routines for all descriptors.
474 //===----------------------------------------------------------------------===//
475
476
477 /// dump - Print descriptor.
478 void DIDescriptor::dump() const {
479   dbgs() << "[" << dwarf::TagString(getTag()) << "] ";
480   dbgs().write_hex((intptr_t) &*DbgNode) << ']';
481 }
482
483 /// dump - Print compile unit.
484 void DICompileUnit::dump() const {
485   if (getLanguage())
486     dbgs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
487
488   dbgs() << " [" << getDirectory() << "/" << getFilename() << " ]";
489 }
490
491 /// dump - Print type.
492 void DIType::dump() const {
493   if (isNull()) return;
494
495   StringRef Res = getName();
496   if (!Res.empty())
497     dbgs() << " [" << Res << "] ";
498
499   unsigned Tag = getTag();
500   dbgs() << " [" << dwarf::TagString(Tag) << "] ";
501
502   // TODO : Print context
503   getCompileUnit().dump();
504   dbgs() << " ["
505          << getLineNumber() << ", "
506          << getSizeInBits() << ", "
507          << getAlignInBits() << ", "
508          << getOffsetInBits()
509          << "] ";
510
511   if (isPrivate())
512     dbgs() << " [private] ";
513   else if (isProtected())
514     dbgs() << " [protected] ";
515
516   if (isForwardDecl())
517     dbgs() << " [fwd] ";
518
519   if (isBasicType())
520     DIBasicType(DbgNode).dump();
521   else if (isDerivedType())
522     DIDerivedType(DbgNode).dump();
523   else if (isCompositeType())
524     DICompositeType(DbgNode).dump();
525   else {
526     dbgs() << "Invalid DIType\n";
527     return;
528   }
529
530   dbgs() << "\n";
531 }
532
533 /// dump - Print basic type.
534 void DIBasicType::dump() const {
535   dbgs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
536 }
537
538 /// dump - Print derived type.
539 void DIDerivedType::dump() const {
540   dbgs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
541 }
542
543 /// dump - Print composite type.
544 void DICompositeType::dump() const {
545   DIArray A = getTypeArray();
546   if (A.isNull())
547     return;
548   dbgs() << " [" << A.getNumElements() << " elements]";
549 }
550
551 /// dump - Print global.
552 void DIGlobal::dump() const {
553   StringRef Res = getName();
554   if (!Res.empty())
555     dbgs() << " [" << Res << "] ";
556
557   unsigned Tag = getTag();
558   dbgs() << " [" << dwarf::TagString(Tag) << "] ";
559
560   // TODO : Print context
561   getCompileUnit().dump();
562   dbgs() << " [" << getLineNumber() << "] ";
563
564   if (isLocalToUnit())
565     dbgs() << " [local] ";
566
567   if (isDefinition())
568     dbgs() << " [def] ";
569
570   if (isGlobalVariable())
571     DIGlobalVariable(DbgNode).dump();
572
573   dbgs() << "\n";
574 }
575
576 /// dump - Print subprogram.
577 void DISubprogram::dump() const {
578   StringRef Res = getName();
579   if (!Res.empty())
580     dbgs() << " [" << Res << "] ";
581
582   unsigned Tag = getTag();
583   dbgs() << " [" << dwarf::TagString(Tag) << "] ";
584
585   // TODO : Print context
586   getCompileUnit().dump();
587   dbgs() << " [" << getLineNumber() << "] ";
588
589   if (isLocalToUnit())
590     dbgs() << " [local] ";
591
592   if (isDefinition())
593     dbgs() << " [def] ";
594
595   dbgs() << "\n";
596 }
597
598 /// dump - Print global variable.
599 void DIGlobalVariable::dump() const {
600   dbgs() << " [";
601   getGlobal()->dump();
602   dbgs() << "] ";
603 }
604
605 /// dump - Print variable.
606 void DIVariable::dump() const {
607   StringRef Res = getName();
608   if (!Res.empty())
609     dbgs() << " [" << Res << "] ";
610
611   getCompileUnit().dump();
612   dbgs() << " [" << getLineNumber() << "] ";
613   getType().dump();
614   dbgs() << "\n";
615
616   // FIXME: Dump complex addresses
617 }
618
619 //===----------------------------------------------------------------------===//
620 // DIFactory: Basic Helpers
621 //===----------------------------------------------------------------------===//
622
623 DIFactory::DIFactory(Module &m)
624   : M(m), VMContext(M.getContext()), DeclareFn(0) {
625   EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
626 }
627
628 Constant *DIFactory::GetTagConstant(unsigned TAG) {
629   assert((TAG & LLVMDebugVersionMask) == 0 &&
630          "Tag too large for debug encoding!");
631   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
632 }
633
634 //===----------------------------------------------------------------------===//
635 // DIFactory: Primary Constructors
636 //===----------------------------------------------------------------------===//
637
638 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
639 /// This implicitly uniques the arrays created.
640 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
641   SmallVector<Value*, 16> Elts;
642
643   if (NumTys == 0)
644     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
645   else
646     for (unsigned i = 0; i != NumTys; ++i)
647       Elts.push_back(Tys[i].getNode());
648
649   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
650 }
651
652 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
653 /// implicitly uniques the values returned.
654 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
655   Value *Elts[] = {
656     GetTagConstant(dwarf::DW_TAG_subrange_type),
657     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
658     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
659   };
660
661   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
662 }
663
664
665
666 /// CreateCompileUnit - Create a new descriptor for the specified compile
667 /// unit.  Note that this does not unique compile units within the module.
668 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
669                                            StringRef Filename,
670                                            StringRef Directory,
671                                            StringRef Producer,
672                                            bool isMain,
673                                            bool isOptimized,
674                                            StringRef Flags,
675                                            unsigned RunTimeVer) {
676   Value *Elts[] = {
677     GetTagConstant(dwarf::DW_TAG_compile_unit),
678     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
679     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
680     MDString::get(VMContext, Filename),
681     MDString::get(VMContext, Directory),
682     MDString::get(VMContext, Producer),
683     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
684     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
685     MDString::get(VMContext, Flags),
686     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
687   };
688
689   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
690 }
691
692 /// CreateEnumerator - Create a single enumerator value.
693 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
694   Value *Elts[] = {
695     GetTagConstant(dwarf::DW_TAG_enumerator),
696     MDString::get(VMContext, Name),
697     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
698   };
699   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
700 }
701
702
703 /// CreateBasicType - Create a basic type like int, float, etc.
704 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
705                                        StringRef Name,
706                                        DICompileUnit CompileUnit,
707                                        unsigned LineNumber,
708                                        uint64_t SizeInBits,
709                                        uint64_t AlignInBits,
710                                        uint64_t OffsetInBits, unsigned Flags,
711                                        unsigned Encoding) {
712   Value *Elts[] = {
713     GetTagConstant(dwarf::DW_TAG_base_type),
714     Context.getNode(),
715     MDString::get(VMContext, Name),
716     CompileUnit.getNode(),
717     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
718     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
719     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
720     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
721     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
722     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
723   };
724   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
725 }
726
727
728 /// CreateBasicType - Create a basic type like int, float, etc.
729 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
730                                          StringRef Name,
731                                          DICompileUnit CompileUnit,
732                                          unsigned LineNumber,
733                                          Constant *SizeInBits,
734                                          Constant *AlignInBits,
735                                          Constant *OffsetInBits, unsigned Flags,
736                                          unsigned Encoding) {
737   Value *Elts[] = {
738     GetTagConstant(dwarf::DW_TAG_base_type),
739     Context.getNode(),
740     MDString::get(VMContext, Name),
741     CompileUnit.getNode(),
742     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
743     SizeInBits,
744     AlignInBits,
745     OffsetInBits,
746     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
747     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
748   };
749   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
750 }
751
752
753 /// CreateDerivedType - Create a derived type like const qualified type,
754 /// pointer, typedef, etc.
755 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
756                                            DIDescriptor Context,
757                                            StringRef Name,
758                                            DICompileUnit CompileUnit,
759                                            unsigned LineNumber,
760                                            uint64_t SizeInBits,
761                                            uint64_t AlignInBits,
762                                            uint64_t OffsetInBits,
763                                            unsigned Flags,
764                                            DIType DerivedFrom) {
765   Value *Elts[] = {
766     GetTagConstant(Tag),
767     Context.getNode(),
768     MDString::get(VMContext, Name),
769     CompileUnit.getNode(),
770     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
771     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
772     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
773     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
774     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
775     DerivedFrom.getNode(),
776   };
777   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
778 }
779
780
781 /// CreateDerivedType - Create a derived type like const qualified type,
782 /// pointer, typedef, etc.
783 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
784                                              DIDescriptor Context,
785                                              StringRef Name,
786                                              DICompileUnit CompileUnit,
787                                              unsigned LineNumber,
788                                              Constant *SizeInBits,
789                                              Constant *AlignInBits,
790                                              Constant *OffsetInBits,
791                                              unsigned Flags,
792                                              DIType DerivedFrom) {
793   Value *Elts[] = {
794     GetTagConstant(Tag),
795     Context.getNode(),
796     MDString::get(VMContext, Name),
797     CompileUnit.getNode(),
798     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
799     SizeInBits,
800     AlignInBits,
801     OffsetInBits,
802     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
803     DerivedFrom.getNode(),
804   };
805   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
806 }
807
808
809 /// CreateCompositeType - Create a composite type like array, struct, etc.
810 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
811                                                DIDescriptor Context,
812                                                StringRef Name,
813                                                DICompileUnit CompileUnit,
814                                                unsigned LineNumber,
815                                                uint64_t SizeInBits,
816                                                uint64_t AlignInBits,
817                                                uint64_t OffsetInBits,
818                                                unsigned Flags,
819                                                DIType DerivedFrom,
820                                                DIArray Elements,
821                                                unsigned RuntimeLang) {
822
823   Value *Elts[] = {
824     GetTagConstant(Tag),
825     Context.getNode(),
826     MDString::get(VMContext, Name),
827     CompileUnit.getNode(),
828     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
829     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
830     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
831     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
832     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
833     DerivedFrom.getNode(),
834     Elements.getNode(),
835     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
836   };
837   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
838 }
839
840
841 /// CreateCompositeType - Create a composite type like array, struct, etc.
842 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
843                                                  DIDescriptor Context,
844                                                  StringRef Name,
845                                                  DICompileUnit CompileUnit,
846                                                  unsigned LineNumber,
847                                                  Constant *SizeInBits,
848                                                  Constant *AlignInBits,
849                                                  Constant *OffsetInBits,
850                                                  unsigned Flags,
851                                                  DIType DerivedFrom,
852                                                  DIArray Elements,
853                                                  unsigned RuntimeLang) {
854
855   Value *Elts[] = {
856     GetTagConstant(Tag),
857     Context.getNode(),
858     MDString::get(VMContext, Name),
859     CompileUnit.getNode(),
860     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
861     SizeInBits,
862     AlignInBits,
863     OffsetInBits,
864     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
865     DerivedFrom.getNode(),
866     Elements.getNode(),
867     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
868   };
869   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
870 }
871
872
873 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
874 /// See comments in DISubprogram for descriptions of these fields.  This
875 /// method does not unique the generated descriptors.
876 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
877                                          StringRef Name,
878                                          StringRef DisplayName,
879                                          StringRef LinkageName,
880                                          DICompileUnit CompileUnit,
881                                          unsigned LineNo, DIType Type,
882                                          bool isLocalToUnit,
883                                          bool isDefinition,
884                                          unsigned VK, unsigned VIndex,
885                                          DIType ContainingType) {
886
887   Value *Elts[] = {
888     GetTagConstant(dwarf::DW_TAG_subprogram),
889     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
890     Context.getNode(),
891     MDString::get(VMContext, Name),
892     MDString::get(VMContext, DisplayName),
893     MDString::get(VMContext, LinkageName),
894     CompileUnit.getNode(),
895     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
896     Type.getNode(),
897     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
898     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
899     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
900     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
901     ContainingType.getNode()
902   };
903   return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
904 }
905
906 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
907 /// given declaration. 
908 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
909   if (SPDeclaration.isDefinition())
910     return DISubprogram(SPDeclaration.getNode());
911
912   MDNode *DeclNode = SPDeclaration.getNode();
913   Value *Elts[] = {
914     GetTagConstant(dwarf::DW_TAG_subprogram),
915     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
916     DeclNode->getElement(2), // Context
917     DeclNode->getElement(3), // Name
918     DeclNode->getElement(4), // DisplayName
919     DeclNode->getElement(5), // LinkageName
920     DeclNode->getElement(6), // CompileUnit
921     DeclNode->getElement(7), // LineNo
922     DeclNode->getElement(8), // Type
923     DeclNode->getElement(9), // isLocalToUnit
924     ConstantInt::get(Type::getInt1Ty(VMContext), true),
925     DeclNode->getElement(11), // Virtuality
926     DeclNode->getElement(12), // VIndex
927     DeclNode->getElement(13)  // Containting Type
928   };
929   return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
930 }
931
932 /// CreateGlobalVariable - Create a new descriptor for the specified global.
933 DIGlobalVariable
934 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
935                                 StringRef DisplayName,
936                                 StringRef LinkageName,
937                                 DICompileUnit CompileUnit,
938                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
939                                 bool isDefinition, llvm::GlobalVariable *Val) {
940   Value *Elts[] = {
941     GetTagConstant(dwarf::DW_TAG_variable),
942     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
943     Context.getNode(),
944     MDString::get(VMContext, Name),
945     MDString::get(VMContext, DisplayName),
946     MDString::get(VMContext, LinkageName),
947     CompileUnit.getNode(),
948     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
949     Type.getNode(),
950     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
951     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
952     Val
953   };
954
955   Value *const *Vs = &Elts[0];
956   MDNode *Node = MDNode::get(VMContext,Vs, 12);
957
958   // Create a named metadata so that we do not lose this mdnode.
959   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
960   NMD->addElement(Node);
961
962   return DIGlobalVariable(Node);
963 }
964
965
966 /// CreateVariable - Create a new descriptor for the specified variable.
967 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
968                                      StringRef Name,
969                                      DICompileUnit CompileUnit, unsigned LineNo,
970                                      DIType Type) {
971   Value *Elts[] = {
972     GetTagConstant(Tag),
973     Context.getNode(),
974     MDString::get(VMContext, Name),
975     CompileUnit.getNode(),
976     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
977     Type.getNode(),
978   };
979   return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
980 }
981
982
983 /// CreateComplexVariable - Create a new descriptor for the specified variable
984 /// which has a complex address expression for its address.
985 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
986                                             const std::string &Name,
987                                             DICompileUnit CompileUnit,
988                                             unsigned LineNo,
989                                    DIType Type, SmallVector<Value *, 9> &addr) {
990   SmallVector<Value *, 9> Elts;
991   Elts.push_back(GetTagConstant(Tag));
992   Elts.push_back(Context.getNode());
993   Elts.push_back(MDString::get(VMContext, Name));
994   Elts.push_back(CompileUnit.getNode());
995   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
996   Elts.push_back(Type.getNode());
997   Elts.insert(Elts.end(), addr.begin(), addr.end());
998
999   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1000 }
1001
1002
1003 /// CreateBlock - This creates a descriptor for a lexical block with the
1004 /// specified parent VMContext.
1005 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
1006   Value *Elts[] = {
1007     GetTagConstant(dwarf::DW_TAG_lexical_block),
1008     Context.getNode()
1009   };
1010   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
1011 }
1012
1013 /// CreateNameSpace - This creates new descriptor for a namespace
1014 /// with the specified parent context.
1015 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1016                                        DICompileUnit CompileUnit, 
1017                                        unsigned LineNo) {
1018   Value *Elts[] = {
1019     GetTagConstant(dwarf::DW_TAG_namespace),
1020     Context.getNode(),
1021     MDString::get(VMContext, Name),
1022     CompileUnit.getNode(),
1023     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1024   };
1025   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1026 }
1027
1028 /// CreateLocation - Creates a debug info location.
1029 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1030                                      DIScope S, DILocation OrigLoc) {
1031   Value *Elts[] = {
1032     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1033     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1034     S.getNode(),
1035     OrigLoc.getNode(),
1036   };
1037   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1038 }
1039
1040 /// CreateLocation - Creates a debug info location.
1041 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1042                                      DIScope S, MDNode *OrigLoc) {
1043  Value *Elts[] = {
1044     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1045     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1046     S.getNode(),
1047     OrigLoc
1048   };
1049   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1050 }
1051
1052 //===----------------------------------------------------------------------===//
1053 // DIFactory: Routines for inserting code into a function
1054 //===----------------------------------------------------------------------===//
1055
1056 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1057 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1058                               Instruction *InsertBefore) {
1059   // Cast the storage to a {}* for the call to llvm.dbg.declare.
1060   Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1061
1062   if (!DeclareFn)
1063     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1064
1065   Value *Args[] = { Storage, D.getNode() };
1066   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1067 }
1068
1069 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1070 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1071                               BasicBlock *InsertAtEnd) {
1072   // Cast the storage to a {}* for the call to llvm.dbg.declare.
1073   Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1074
1075   if (!DeclareFn)
1076     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1077
1078   Value *Args[] = { Storage, D.getNode() };
1079   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1080 }
1081
1082 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1083 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1084                                                 DIVariable D,
1085                                                 Instruction *InsertBefore) {
1086   assert(V && "no value passed to dbg.value");
1087   assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1088          "offset must be i64");
1089   if (!ValueFn)
1090     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1091
1092   Value *Elts[] = { V };
1093   Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1094                     D.getNode() };
1095   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1096 }
1097
1098 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1099 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1100                                                 DIVariable D,
1101                                                 BasicBlock *InsertAtEnd) {
1102   assert(V && "no value passed to dbg.value");
1103   assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1104          "offset must be i64");
1105   if (!ValueFn)
1106     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1107
1108   Value *Elts[] = { V };
1109   Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1110                     D.getNode() };
1111   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1112 }
1113
1114 //===----------------------------------------------------------------------===//
1115 // DebugInfoFinder implementations.
1116 //===----------------------------------------------------------------------===//
1117
1118 /// processModule - Process entire module and collect debug info.
1119 void DebugInfoFinder::processModule(Module &M) {
1120
1121   MetadataContext &TheMetadata = M.getContext().getMetadata();
1122   unsigned MDDbgKind = TheMetadata.getMDKindID("dbg");
1123
1124   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1125     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1126       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1127            ++BI) {
1128         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1129           processDeclare(DDI);
1130         else 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 }