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