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