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