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