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