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