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