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