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