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