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