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