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