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