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