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