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