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