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