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