Oops...I committed too much.
[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/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Support/Streams.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // DIDescriptor
28 //===----------------------------------------------------------------------===//
29
30 DIDescriptor::DIDescriptor(GlobalVariable *gv, unsigned RequiredTag) {
31   GV = gv;
32   
33   // If this is non-null, check to see if the Tag matches.  If not, set to null.
34   if (GV && getTag() != RequiredTag)
35     GV = 0;
36 }
37
38 const std::string &
39 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
40   if (GV == 0) {
41     Result.clear();
42     return Result;
43   }
44
45   Constant *C = GV->getInitializer();
46   if (C == 0 || Elt >= C->getNumOperands()) {
47     Result.clear();
48     return Result;
49   }
50   
51   // Fills in the string if it succeeds
52   if (!GetConstantStringInfo(C->getOperand(Elt), Result))
53     Result.clear();
54
55   return Result;
56 }
57
58 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
59   if (GV == 0) return 0;
60   Constant *C = GV->getInitializer();
61   if (C == 0 || Elt >= C->getNumOperands())
62     return 0;
63   if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
64     return CI->getZExtValue();
65   return 0;
66 }
67
68 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
69   if (GV == 0) return DIDescriptor();
70   Constant *C = GV->getInitializer();
71   if (C == 0 || Elt >= C->getNumOperands())
72     return DIDescriptor();
73   C = C->getOperand(Elt);
74   return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
75 }
76
77 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
78   if (GV == 0) return 0;
79   Constant *C = GV->getInitializer();
80   if (C == 0 || Elt >= C->getNumOperands())
81     return 0;
82   C = C->getOperand(Elt);
83   
84   return dyn_cast<GlobalVariable>(C->stripPointerCasts());
85 }
86
87
88
89 //===----------------------------------------------------------------------===//
90 // Simple Descriptor Constructors and other Methods
91 //===----------------------------------------------------------------------===//
92
93 DIAnchor::DIAnchor(GlobalVariable *GV)
94   : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
95 DIEnumerator::DIEnumerator(GlobalVariable *GV)
96   : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
97 DISubrange::DISubrange(GlobalVariable *GV)
98   : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
99 DICompileUnit::DICompileUnit(GlobalVariable *GV)
100   : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
101 DIBasicType::DIBasicType(GlobalVariable *GV)
102   : DIType(GV, dwarf::DW_TAG_base_type) {}
103 DISubprogram::DISubprogram(GlobalVariable *GV)
104   : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
105 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
106   : DIGlobal(GV, dwarf::DW_TAG_variable) {}
107 DIBlock::DIBlock(GlobalVariable *GV)
108   : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
109 // needed by DIVariable::getType()
110 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
111   if (!gv) return;
112   unsigned tag = getTag();
113   if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
114       !DICompositeType::isCompositeType(tag))
115     GV = 0;
116 }
117
118 /// isDerivedType - Return true if the specified tag is legal for
119 /// DIDerivedType.
120 bool DIType::isDerivedType(unsigned Tag) {
121   switch (Tag) {
122   case dwarf::DW_TAG_typedef:
123   case dwarf::DW_TAG_pointer_type:
124   case dwarf::DW_TAG_reference_type:
125   case dwarf::DW_TAG_const_type:
126   case dwarf::DW_TAG_volatile_type:
127   case dwarf::DW_TAG_restrict_type:
128   case dwarf::DW_TAG_member:
129   case dwarf::DW_TAG_inheritance:
130     return true;
131   default:
132     // FIXME: Even though it doesn't make sense, CompositeTypes are current
133     // modelled as DerivedTypes, this should return true for them as well.
134     return false;
135   }
136 }
137
138 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
139   if (GV && !isDerivedType(getTag()))
140     GV = 0;
141 }
142
143 /// isCompositeType - Return true if the specified tag is legal for
144 /// DICompositeType.
145 bool DIType::isCompositeType(unsigned TAG) {
146   switch (TAG) {
147   case dwarf::DW_TAG_array_type:
148   case dwarf::DW_TAG_structure_type:
149   case dwarf::DW_TAG_union_type:
150   case dwarf::DW_TAG_enumeration_type:
151   case dwarf::DW_TAG_vector_type:
152   case dwarf::DW_TAG_subroutine_type:
153     return true;
154   default:
155     return false;
156   }
157 }
158
159 DICompositeType::DICompositeType(GlobalVariable *GV)
160   : DIDerivedType(GV, true, true) {
161   if (GV && !isCompositeType(getTag()))
162     GV = 0;
163 }
164
165 /// isVariable - Return true if the specified tag is legal for DIVariable.
166 bool DIVariable::isVariable(unsigned Tag) {
167   switch (Tag) {
168   case dwarf::DW_TAG_auto_variable:
169   case dwarf::DW_TAG_arg_variable:
170   case dwarf::DW_TAG_return_variable:
171     return true;
172   default:
173     return false;
174   }
175 }
176
177 DIVariable::DIVariable(GlobalVariable *gv) : DIDescriptor(gv) {
178   if (gv && !isVariable(getTag()))
179     GV = 0;
180 }
181
182 unsigned DIArray::getNumElements() const {
183   assert (GV && "Invalid DIArray");
184   Constant *C = GV->getInitializer();
185   assert (C && "Invalid DIArray initializer");
186   return C->getNumOperands();
187 }
188
189 /// Verify - Verify that a compile unit is well formed.
190 bool DICompileUnit::Verify() const {
191   if (isNull()) 
192     return false;
193   std::string Res;
194   if (getFilename(Res).empty()) 
195     return false;
196   // It is possible that directory and produce string is empty.
197   return true;
198 }
199
200 /// Verify - Verify that a type descriptor is well formed.
201 bool DIType::Verify() const {
202   if (isNull()) 
203     return false;
204   if (getContext().isNull()) 
205     return false;
206
207   DICompileUnit CU = getCompileUnit();
208   if (!CU.isNull() && !CU.Verify()) 
209     return false;
210   return true;
211 }
212
213 /// Verify - Verify that a composite type descriptor is well formed.
214 bool DICompositeType::Verify() const {
215   if (isNull()) 
216     return false;
217   if (getContext().isNull()) 
218     return false;
219
220   DICompileUnit CU = getCompileUnit();
221   if (!CU.isNull() && !CU.Verify()) 
222     return false;
223   return true;
224 }
225
226 /// Verify - Verify that a subprogram descriptor is well formed.
227 bool DISubprogram::Verify() const {
228   if (isNull())
229     return false;
230   
231   if (getContext().isNull())
232     return false;
233
234   DICompileUnit CU = getCompileUnit();
235   if (!CU.Verify()) 
236     return false;
237
238   DICompositeType Ty = getType();
239   if (!Ty.isNull() && !Ty.Verify())
240     return false;
241   return true;
242 }
243
244 /// Verify - Verify that a global variable descriptor is well formed.
245 bool DIGlobalVariable::Verify() const {
246   if (isNull())
247     return false;
248   
249   if (getContext().isNull())
250     return false;
251
252   DICompileUnit CU = getCompileUnit();
253   if (!CU.Verify()) 
254     return false;
255
256   DIType Ty = getType();
257   if (!Ty.Verify())
258     return false;
259
260   if (!getGlobal())
261     return false;
262
263   return true;
264 }
265
266 /// Verify - Verify that a variable descriptor is well formed.
267 bool DIVariable::Verify() const {
268   if (isNull())
269     return false;
270   
271   if (getContext().isNull())
272     return false;
273
274   DIType Ty = getType();
275   if (!Ty.Verify())
276     return false;
277
278
279   return true;
280 }
281
282 /// getOriginalTypeSize - If this type is derived from a base type then
283 /// return base type size.
284 uint64_t DIDerivedType::getOriginalTypeSize() const {
285   if (getTag() != dwarf::DW_TAG_member)
286     return getSizeInBits();
287   DIType BT = getTypeDerivedFrom();
288   if (BT.getTag() != dwarf::DW_TAG_base_type)
289     return getSizeInBits();
290   return BT.getSizeInBits();
291 }
292
293 //===----------------------------------------------------------------------===//
294 // DIFactory: Basic Helpers
295 //===----------------------------------------------------------------------===//
296
297 DIFactory::DIFactory(Module &m) : M(m) {
298   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
299   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
300 }
301
302 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
303 /// This is only valid when the descriptor is non-null.
304 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
305   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
306   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
307 }
308
309 Constant *DIFactory::GetTagConstant(unsigned TAG) {
310   assert((TAG & LLVMDebugVersionMask) == 0 &&
311          "Tag too large for debug encoding!");
312   return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
313 }
314
315 Constant *DIFactory::GetStringConstant(const std::string &String) {
316   // Check string cache for previous edition.
317   Constant *&Slot = StringCache[String];
318   
319   // Return Constant if previously defined.
320   if (Slot) return Slot;
321   
322   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
323   
324   // If empty string then use a sbyte* null instead.
325   if (String.empty())
326     return Slot = ConstantPointerNull::get(DestTy);
327
328   // Construct string as an llvm constant.
329   Constant *ConstStr = ConstantArray::get(String);
330     
331   // Otherwise create and return a new string global.
332   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
333                                              GlobalVariable::InternalLinkage,
334                                              ConstStr, ".str", &M);
335   StrGV->setSection("llvm.metadata");
336   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
337 }
338
339 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
340 /// already exists, return it.  If not, create a new one and return it.
341 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
342   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
343   
344   // Otherwise, create the global or return it if already in the module.
345   Constant *C = M.getOrInsertGlobal(Name, EltTy);
346   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
347   GlobalVariable *GV = cast<GlobalVariable>(C);
348   
349   // If it has an initializer, it is already in the module.
350   if (GV->hasInitializer()) 
351     return SubProgramAnchor = DIAnchor(GV);
352   
353   GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
354   GV->setSection("llvm.metadata");
355   GV->setConstant(true);
356   M.addTypeName("llvm.dbg.anchor.type", EltTy);
357   
358   // Otherwise, set the initializer.
359   Constant *Elts[] = {
360     GetTagConstant(dwarf::DW_TAG_anchor),
361     ConstantInt::get(Type::Int32Ty, TAG)
362   };
363   
364   GV->setInitializer(ConstantStruct::get(Elts, 2));
365   return DIAnchor(GV);
366 }
367
368
369
370 //===----------------------------------------------------------------------===//
371 // DIFactory: Primary Constructors
372 //===----------------------------------------------------------------------===//
373
374 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
375 /// creating a new one if there isn't already one in the module.
376 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
377   // If we already created one, just return it.
378   if (!CompileUnitAnchor.isNull())
379     return CompileUnitAnchor;
380   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
381                                                "llvm.dbg.compile_units");
382 }
383
384 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
385 /// creating a new one if there isn't already one in the module.
386 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
387   // If we already created one, just return it.
388   if (!SubProgramAnchor.isNull())
389     return SubProgramAnchor;
390   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
391                                               "llvm.dbg.subprograms");
392 }
393
394 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
395 /// creating a new one if there isn't already one in the module.
396 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
397   // If we already created one, just return it.
398   if (!GlobalVariableAnchor.isNull())
399     return GlobalVariableAnchor;
400   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
401                                                   "llvm.dbg.global_variables");
402 }
403
404 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
405 /// This implicitly uniques the arrays created.
406 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
407   SmallVector<Constant*, 16> Elts;
408   
409   for (unsigned i = 0; i != NumTys; ++i)
410     Elts.push_back(getCastToEmpty(Tys[i]));
411   
412   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
413                                                      Elts.size()),
414                                       &Elts[0], Elts.size());
415   // If we already have this array, just return the uniqued version.
416   DIDescriptor &Entry = SimpleConstantCache[Init];
417   if (!Entry.isNull()) return DIArray(Entry.getGV());
418   
419   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
420                                           GlobalValue::InternalLinkage,
421                                           Init, "llvm.dbg.array", &M);
422   GV->setSection("llvm.metadata");
423   Entry = DIDescriptor(GV);
424   return DIArray(GV);
425 }
426
427 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
428 /// implicitly uniques the values returned.
429 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
430   Constant *Elts[] = {
431     GetTagConstant(dwarf::DW_TAG_subrange_type),
432     ConstantInt::get(Type::Int64Ty, Lo),
433     ConstantInt::get(Type::Int64Ty, Hi)
434   };
435   
436   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
437
438   // If we already have this range, just return the uniqued version.
439   DIDescriptor &Entry = SimpleConstantCache[Init];
440   if (!Entry.isNull()) return DISubrange(Entry.getGV());
441   
442   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
443
444   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
445                                           GlobalValue::InternalLinkage,
446                                           Init, "llvm.dbg.subrange", &M);
447   GV->setSection("llvm.metadata");
448   Entry = DIDescriptor(GV);
449   return DISubrange(GV);
450 }
451
452
453
454 /// CreateCompileUnit - Create a new descriptor for the specified compile
455 /// unit.  Note that this does not unique compile units within the module.
456 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
457                                            const std::string &Filename,
458                                            const std::string &Directory,
459                                            const std::string &Producer,
460                                            bool isMain,
461                                            bool isOptimized,
462                                            const char *Flags,
463                                            unsigned RunTimeVer) {
464   Constant *Elts[] = {
465     GetTagConstant(dwarf::DW_TAG_compile_unit),
466     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
467     ConstantInt::get(Type::Int32Ty, LangID),
468     GetStringConstant(Filename),
469     GetStringConstant(Directory),
470     GetStringConstant(Producer),
471     ConstantInt::get(Type::Int1Ty, isMain),
472     ConstantInt::get(Type::Int1Ty, isOptimized),
473     GetStringConstant(Flags),
474     ConstantInt::get(Type::Int32Ty, RunTimeVer)
475   };
476   
477   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
478   
479   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
480   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
481                                           GlobalValue::InternalLinkage,
482                                           Init, "llvm.dbg.compile_unit", &M);
483   GV->setSection("llvm.metadata");
484   return DICompileUnit(GV);
485 }
486
487 /// CreateEnumerator - Create a single enumerator value.
488 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
489   Constant *Elts[] = {
490     GetTagConstant(dwarf::DW_TAG_enumerator),
491     GetStringConstant(Name),
492     ConstantInt::get(Type::Int64Ty, Val)
493   };
494   
495   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
496   
497   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
498   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
499                                           GlobalValue::InternalLinkage,
500                                           Init, "llvm.dbg.enumerator", &M);
501   GV->setSection("llvm.metadata");
502   return DIEnumerator(GV);
503 }
504
505
506 /// CreateBasicType - Create a basic type like int, float, etc.
507 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
508                                       const std::string &Name,
509                                        DICompileUnit CompileUnit,
510                                        unsigned LineNumber,
511                                        uint64_t SizeInBits,
512                                        uint64_t AlignInBits,
513                                        uint64_t OffsetInBits, unsigned Flags,
514                                        unsigned Encoding) {
515   Constant *Elts[] = {
516     GetTagConstant(dwarf::DW_TAG_base_type),
517     getCastToEmpty(Context),
518     GetStringConstant(Name),
519     getCastToEmpty(CompileUnit),
520     ConstantInt::get(Type::Int32Ty, LineNumber),
521     ConstantInt::get(Type::Int64Ty, SizeInBits),
522     ConstantInt::get(Type::Int64Ty, AlignInBits),
523     ConstantInt::get(Type::Int64Ty, OffsetInBits),
524     ConstantInt::get(Type::Int32Ty, Flags),
525     ConstantInt::get(Type::Int32Ty, Encoding)
526   };
527   
528   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
529   
530   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
531   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
532                                           GlobalValue::InternalLinkage,
533                                           Init, "llvm.dbg.basictype", &M);
534   GV->setSection("llvm.metadata");
535   return DIBasicType(GV);
536 }
537
538 /// CreateDerivedType - Create a derived type like const qualified type,
539 /// pointer, typedef, etc.
540 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
541                                            DIDescriptor Context,
542                                            const std::string &Name,
543                                            DICompileUnit CompileUnit,
544                                            unsigned LineNumber,
545                                            uint64_t SizeInBits,
546                                            uint64_t AlignInBits,
547                                            uint64_t OffsetInBits,
548                                            unsigned Flags,
549                                            DIType DerivedFrom) {
550   Constant *Elts[] = {
551     GetTagConstant(Tag),
552     getCastToEmpty(Context),
553     GetStringConstant(Name),
554     getCastToEmpty(CompileUnit),
555     ConstantInt::get(Type::Int32Ty, LineNumber),
556     ConstantInt::get(Type::Int64Ty, SizeInBits),
557     ConstantInt::get(Type::Int64Ty, AlignInBits),
558     ConstantInt::get(Type::Int64Ty, OffsetInBits),
559     ConstantInt::get(Type::Int32Ty, Flags),
560     getCastToEmpty(DerivedFrom)
561   };
562   
563   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
564   
565   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
566   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
567                                           GlobalValue::InternalLinkage,
568                                           Init, "llvm.dbg.derivedtype", &M);
569   GV->setSection("llvm.metadata");
570   return DIDerivedType(GV);
571 }
572
573 /// CreateCompositeType - Create a composite type like array, struct, etc.
574 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
575                                                DIDescriptor Context,
576                                                const std::string &Name,
577                                                DICompileUnit CompileUnit,
578                                                unsigned LineNumber,
579                                                uint64_t SizeInBits,
580                                                uint64_t AlignInBits,
581                                                uint64_t OffsetInBits,
582                                                unsigned Flags,
583                                                DIType DerivedFrom,
584                                                DIArray Elements,
585                                                unsigned RuntimeLang) {
586
587   Constant *Elts[] = {
588     GetTagConstant(Tag),
589     getCastToEmpty(Context),
590     GetStringConstant(Name),
591     getCastToEmpty(CompileUnit),
592     ConstantInt::get(Type::Int32Ty, LineNumber),
593     ConstantInt::get(Type::Int64Ty, SizeInBits),
594     ConstantInt::get(Type::Int64Ty, AlignInBits),
595     ConstantInt::get(Type::Int64Ty, OffsetInBits),
596     ConstantInt::get(Type::Int32Ty, Flags),
597     getCastToEmpty(DerivedFrom),
598     getCastToEmpty(Elements),
599     ConstantInt::get(Type::Int32Ty, RuntimeLang)
600   };
601   
602   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
603   
604   M.addTypeName("llvm.dbg.composite.type", Init->getType());
605   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
606                                           GlobalValue::InternalLinkage,
607                                           Init, "llvm.dbg.composite", &M);
608   GV->setSection("llvm.metadata");
609   return DICompositeType(GV);
610 }
611
612
613 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
614 /// See comments in DISubprogram for descriptions of these fields.  This
615 /// method does not unique the generated descriptors.
616 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
617                                          const std::string &Name,
618                                          const std::string &DisplayName,
619                                          const std::string &LinkageName,
620                                          DICompileUnit CompileUnit,
621                                          unsigned LineNo, DIType Type,
622                                          bool isLocalToUnit,
623                                          bool isDefinition) {
624
625   Constant *Elts[] = {
626     GetTagConstant(dwarf::DW_TAG_subprogram),
627     getCastToEmpty(GetOrCreateSubprogramAnchor()),
628     getCastToEmpty(Context),
629     GetStringConstant(Name),
630     GetStringConstant(DisplayName),
631     GetStringConstant(LinkageName),
632     getCastToEmpty(CompileUnit),
633     ConstantInt::get(Type::Int32Ty, LineNo),
634     getCastToEmpty(Type),
635     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
636     ConstantInt::get(Type::Int1Ty, isDefinition)
637   };
638   
639   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
640   
641   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
642   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
643                                           GlobalValue::InternalLinkage,
644                                           Init, "llvm.dbg.subprogram", &M);
645   GV->setSection("llvm.metadata");
646   return DISubprogram(GV);
647 }
648
649 /// CreateGlobalVariable - Create a new descriptor for the specified global.
650 DIGlobalVariable
651 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
652                                 const std::string &DisplayName,
653                                 const std::string &LinkageName,
654                                 DICompileUnit CompileUnit,
655                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
656                                 bool isDefinition, llvm::GlobalVariable *Val) {
657   Constant *Elts[] = {
658     GetTagConstant(dwarf::DW_TAG_variable),
659     getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
660     getCastToEmpty(Context),
661     GetStringConstant(Name),
662     GetStringConstant(DisplayName),
663     GetStringConstant(LinkageName),
664     getCastToEmpty(CompileUnit),
665     ConstantInt::get(Type::Int32Ty, LineNo),
666     getCastToEmpty(Type),
667     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
668     ConstantInt::get(Type::Int1Ty, isDefinition),
669     ConstantExpr::getBitCast(Val, EmptyStructPtr)
670   };
671   
672   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
673   
674   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
675   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
676                                           GlobalValue::InternalLinkage,
677                                           Init, "llvm.dbg.global_variable", &M);
678   GV->setSection("llvm.metadata");
679   return DIGlobalVariable(GV);
680 }
681
682
683 /// CreateVariable - Create a new descriptor for the specified variable.
684 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
685                                      const std::string &Name,
686                                      DICompileUnit CompileUnit, unsigned LineNo,
687                                      DIType Type) {
688   Constant *Elts[] = {
689     GetTagConstant(Tag),
690     getCastToEmpty(Context),
691     GetStringConstant(Name),
692     getCastToEmpty(CompileUnit),
693     ConstantInt::get(Type::Int32Ty, LineNo),
694     getCastToEmpty(Type)
695   };
696   
697   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
698   
699   M.addTypeName("llvm.dbg.variable.type", Init->getType());
700   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
701                                           GlobalValue::InternalLinkage,
702                                           Init, "llvm.dbg.variable", &M);
703   GV->setSection("llvm.metadata");
704   return DIVariable(GV);
705 }
706
707
708 /// CreateBlock - This creates a descriptor for a lexical block with the
709 /// specified parent context.
710 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
711   Constant *Elts[] = {
712     GetTagConstant(dwarf::DW_TAG_lexical_block),
713     getCastToEmpty(Context)
714   };
715   
716   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
717   
718   M.addTypeName("llvm.dbg.block.type", Init->getType());
719   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
720                                           GlobalValue::InternalLinkage,
721                                           Init, "llvm.dbg.block", &M);
722   GV->setSection("llvm.metadata");
723   return DIBlock(GV);
724 }
725
726
727 //===----------------------------------------------------------------------===//
728 // DIFactory: Routines for inserting code into a function
729 //===----------------------------------------------------------------------===//
730
731 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
732 /// inserting it at the end of the specified basic block.
733 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
734                                 unsigned ColNo, BasicBlock *BB) {
735   
736   // Lazily construct llvm.dbg.stoppoint function.
737   if (!StopPointFn)
738     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
739                                               llvm::Intrinsic::dbg_stoppoint);
740   
741   // Invoke llvm.dbg.stoppoint
742   Value *Args[] = {
743     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
744     llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
745     getCastToEmpty(CU)
746   };
747   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
748 }
749
750 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
751 /// mark the start of the specified subprogram.
752 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
753   // Lazily construct llvm.dbg.func.start.
754   if (!FuncStartFn)
755     FuncStartFn = llvm::Intrinsic::getDeclaration(&M, 
756                                               llvm::Intrinsic::dbg_func_start);
757   
758   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
759   CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
760 }
761
762 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
763 /// mark the start of a region for the specified scoping descriptor.
764 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
765   // Lazily construct llvm.dbg.region.start function.
766   if (!RegionStartFn)
767     RegionStartFn = llvm::Intrinsic::getDeclaration(&M, 
768                                             llvm::Intrinsic::dbg_region_start);
769   // Call llvm.dbg.func.start.
770   CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
771 }
772
773
774 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
775 /// mark the end of a region for the specified scoping descriptor.
776 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
777   // Lazily construct llvm.dbg.region.end function.
778   if (!RegionEndFn)
779     RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
780                                                llvm::Intrinsic::dbg_region_end);
781   
782   CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
783 }
784
785 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
786 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
787                               BasicBlock *BB) {
788   // Cast the storage to a {}* for the call to llvm.dbg.declare.
789   Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
790   
791   if (!DeclareFn)
792     DeclareFn = llvm::Intrinsic::getDeclaration(&M,
793                                                 llvm::Intrinsic::dbg_declare);
794   Value *Args[] = { Storage, getCastToEmpty(D) };
795   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
796 }
797
798 namespace llvm {
799   /// Finds the stoppoint coressponding to this instruction, that is the
800   /// stoppoint that dominates this instruction 
801   const DbgStopPointInst *findStopPoint(const Instruction *Inst)
802   {
803     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
804       return DSI;
805
806     const BasicBlock *BB = Inst->getParent();
807     BasicBlock::const_iterator I = Inst, B;
808     do {
809       B = BB->begin();
810       // A BB consisting only of a terminator can't have a stoppoint.
811       if (I != B) {
812         do {
813           --I;
814           if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
815             return DSI;
816         } while (I != B);
817       }
818       // This BB didn't have a stoppoint: if there is only one
819       // predecessor, look for a stoppoint there.
820       // We could use getIDom(), but that would require dominator info.
821       BB = I->getParent()->getUniquePredecessor();
822       if (BB)
823         I = BB->getTerminator();
824     } while (BB != 0);
825     return 0;
826   }
827
828   /// Finds the stoppoint corresponding to first real (non-debug intrinsic) 
829   /// instruction in this Basic Block, and returns the stoppoint for it.
830   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
831   {
832     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
833       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
834         return DSI;
835     }
836     // Fallback to looking for stoppoint of unique predecessor.
837     // Useful if this BB contains no stoppoints, but unique predecessor does.
838     BB = BB->getUniquePredecessor();
839     if (BB)
840       return findStopPoint(BB->getTerminator());
841     return 0;
842   }
843
844   Value *findDbgGlobalDeclare(GlobalVariable *V)
845   {
846     const Module *M = V->getParent();
847     const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
848     if (!Ty)
849       return 0;
850     Ty = PointerType::get(Ty, 0);
851
852     Value *Val = V->stripPointerCasts();
853     for (Value::use_iterator I = Val->use_begin(), E =Val->use_end();
854          I != E; ++I) {
855       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
856         if (CE->getOpcode() == Instruction::BitCast) {
857           Value *VV = CE;
858           while (VV->hasOneUse()) {
859             VV = *VV->use_begin();
860           }
861           if (VV->getType() == Ty)
862             return VV;
863         }
864       }
865     }
866     
867     if (Val->getType() == Ty)
868       return Val;
869     return 0;
870   }
871
872   /// Finds the dbg.declare intrinsic corresponding to this value if any.
873   /// It looks through pointer casts too.
874   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
875   {
876     if (stripCasts) {
877       V = V->stripPointerCasts();
878       // Look for the bitcast.
879       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
880             I != E; ++I) {
881         if (isa<BitCastInst>(I))
882           return findDbgDeclare(*I, false);
883       }
884       return 0;
885     }
886
887     // Find dbg.declare among uses of the instruction.
888     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
889           I != E; ++I) {
890       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
891         return DDI;
892     }
893     return 0;
894   }
895
896   bool getLocationInfo(const Value *V, std::string &DisplayName, std::string &Type,
897                        unsigned &LineNo, std::string &File, std::string &Dir)
898   {
899     DICompileUnit Unit;
900     DIType TypeD;
901     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
902       Value *DIGV = findDbgGlobalDeclare(GV);
903       if (!DIGV)
904         return false;
905       DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
906       Var.getDisplayName(DisplayName);
907       LineNo = Var.getLineNumber();
908       Unit = Var.getCompileUnit();
909       TypeD = Var.getType();
910     } else {
911       const DbgDeclareInst *DDI = findDbgDeclare(V);
912       if (!DDI)
913         return false;
914       DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
915       Var.getName(DisplayName);
916       LineNo = Var.getLineNumber();
917       Unit = Var.getCompileUnit();
918       TypeD = Var.getType();
919     }
920     TypeD.getName(Type);
921     Unit.getFilename(File);
922     Unit.getDirectory(Dir);
923     return true;
924   }
925 }
926
927 /// dump - print compile unit.
928 void DICompileUnit::dump() const {
929   if (getLanguage())
930     cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
931
932   std::string Res1, Res2;
933   cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
934 }
935
936 /// dump - print type.
937 void DIType::dump() const {
938   if (isNull()) return;
939
940   std::string Res;
941   if (!getName(Res).empty())
942     cerr << " [" << Res << "] ";
943
944   unsigned Tag = getTag();
945   cerr << " [" << dwarf::TagString(Tag) << "] ";
946
947   // TODO : Print context
948   getCompileUnit().dump();
949   cerr << " [" 
950        << getLineNumber() << ", " 
951        << getSizeInBits() << ", "
952        << getAlignInBits() << ", "
953        << getOffsetInBits() 
954        << "] ";
955
956   if (isPrivate()) 
957     cerr << " [private] ";
958   else if (isProtected())
959     cerr << " [protected] ";
960
961   if (isForwardDecl())
962     cerr << " [fwd] ";
963
964   if (isBasicType(Tag))
965     DIBasicType(GV).dump();
966   else if (isDerivedType(Tag))
967     DIDerivedType(GV).dump();
968   else if (isCompositeType(Tag))
969     DICompositeType(GV).dump();
970   else {
971     cerr << "Invalid DIType\n";
972     return;
973   }
974
975   cerr << "\n";
976 }
977
978 /// dump - print basic type.
979 void DIBasicType::dump() const {
980   cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
981
982 }
983
984 /// dump - print derived type.
985 void DIDerivedType::dump() const {
986   cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
987 }
988
989 /// dump - print composite type.
990 void DICompositeType::dump() const {
991   DIArray A = getTypeArray();
992   if (A.isNull())
993     return;
994   cerr << " [" << A.getNumElements() << " elements]";
995 }
996
997 /// dump - print global.
998 void DIGlobal::dump() const {
999   std::string Res;
1000   if (!getName(Res).empty())
1001     cerr << " [" << Res << "] ";
1002
1003   unsigned Tag = getTag();
1004   cerr << " [" << dwarf::TagString(Tag) << "] ";
1005
1006   // TODO : Print context
1007   getCompileUnit().dump();
1008   cerr << " [" << getLineNumber() << "] ";
1009
1010   if (isLocalToUnit())
1011     cerr << " [local] ";
1012
1013   if (isDefinition())
1014     cerr << " [def] ";
1015
1016   if (isGlobalVariable(Tag))
1017     DIGlobalVariable(GV).dump();
1018
1019   cerr << "\n";
1020 }
1021
1022 /// dump - print subprogram.
1023 void DISubprogram::dump() const {
1024   DIGlobal::dump();
1025 }
1026
1027 /// dump - print global variable.
1028 void DIGlobalVariable::dump() const {
1029   cerr << " ["; getGlobal()->dump(); cerr << "] ";
1030 }
1031
1032 /// dump - print variable.
1033 void DIVariable::dump() const {
1034   std::string Res;
1035   if (!getName(Res).empty())
1036     cerr << " [" << Res << "] ";
1037
1038   getCompileUnit().dump();
1039   cerr << " [" << getLineNumber() << "] ";
1040   getType().dump();
1041   cerr << "\n";
1042 }