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