Verify debug info.
[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 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 // DIDescriptor
27 //===----------------------------------------------------------------------===//
28
29 DIDescriptor::DIDescriptor(GlobalVariable *gv, unsigned RequiredTag) {
30   GV = gv;
31   
32   // If this is non-null, check to see if the Tag matches.  If not, set to null.
33   if (GV && getTag() != RequiredTag)
34     GV = 0;
35 }
36
37
38 std::string DIDescriptor::getStringField(unsigned Elt) const {
39   if (GV == 0) return "";
40   Constant *C = GV->getInitializer();
41   if (C == 0 || Elt >= C->getNumOperands())
42     return "";
43   
44   std::string Result;
45   // Fills in the string if it succeeds
46   if (!GetConstantStringInfo(C->getOperand(Elt), Result))
47     Result.clear();
48   return Result;
49 }
50
51 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
52   if (GV == 0) return 0;
53   Constant *C = GV->getInitializer();
54   if (C == 0 || Elt >= C->getNumOperands())
55     return 0;
56   if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
57     return CI->getZExtValue();
58   return 0;
59 }
60
61
62 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
63   if (GV == 0) return DIDescriptor();
64   Constant *C = GV->getInitializer();
65   if (C == 0 || Elt >= C->getNumOperands())
66     return DIDescriptor();
67   C = C->getOperand(Elt);
68   return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
69 }
70
71 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
72   if (GV == 0) return 0;
73   Constant *C = GV->getInitializer();
74   if (C == 0 || Elt >= C->getNumOperands())
75     return 0;
76   C = C->getOperand(Elt);
77   
78   return dyn_cast<GlobalVariable>(C->stripPointerCasts());
79 }
80
81
82
83 //===----------------------------------------------------------------------===//
84 // Simple Descriptor Constructors and other Methods
85 //===----------------------------------------------------------------------===//
86
87 DIAnchor::DIAnchor(GlobalVariable *GV)
88   : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
89 DIEnumerator::DIEnumerator(GlobalVariable *GV)
90   : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
91 DISubrange::DISubrange(GlobalVariable *GV)
92   : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
93 DICompileUnit::DICompileUnit(GlobalVariable *GV)
94   : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
95 DIBasicType::DIBasicType(GlobalVariable *GV)
96   : DIType(GV, dwarf::DW_TAG_base_type) {}
97 DISubprogram::DISubprogram(GlobalVariable *GV)
98   : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
99 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
100   : DIGlobal(GV, dwarf::DW_TAG_variable) {}
101 DIBlock::DIBlock(GlobalVariable *GV)
102   : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
103 // needed by DIVariable::getType()
104 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
105   if (!gv) return;
106   unsigned tag = getTag();
107   if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
108       !DICompositeType::isCompositeType(tag))
109     GV = 0;
110 }
111
112 /// isDerivedType - Return true if the specified tag is legal for
113 /// DIDerivedType.
114 bool DIType::isDerivedType(unsigned Tag) {
115   switch (Tag) {
116   case dwarf::DW_TAG_typedef:
117   case dwarf::DW_TAG_pointer_type:
118   case dwarf::DW_TAG_reference_type:
119   case dwarf::DW_TAG_const_type:
120   case dwarf::DW_TAG_volatile_type:
121   case dwarf::DW_TAG_restrict_type:
122   case dwarf::DW_TAG_member:
123   case dwarf::DW_TAG_inheritance:
124     return true;
125   default:
126     // FIXME: Even though it doesn't make sense, CompositeTypes are current
127     // modelled as DerivedTypes, this should return true for them as well.
128     return false;
129   }
130 }
131
132 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
133   if (GV && !isDerivedType(getTag()))
134     GV = 0;
135 }
136
137 /// isCompositeType - Return true if the specified tag is legal for
138 /// DICompositeType.
139 bool DIType::isCompositeType(unsigned TAG) {
140   switch (TAG) {
141   case dwarf::DW_TAG_array_type:
142   case dwarf::DW_TAG_structure_type:
143   case dwarf::DW_TAG_union_type:
144   case dwarf::DW_TAG_enumeration_type:
145   case dwarf::DW_TAG_vector_type:
146   case dwarf::DW_TAG_subroutine_type:
147     return true;
148   default:
149     return false;
150   }
151 }
152
153 DICompositeType::DICompositeType(GlobalVariable *GV)
154   : DIDerivedType(GV, true, true) {
155   if (GV && !isCompositeType(getTag()))
156     GV = 0;
157 }
158
159 /// isVariable - Return true if the specified tag is legal for DIVariable.
160 bool DIVariable::isVariable(unsigned Tag) {
161   switch (Tag) {
162   case dwarf::DW_TAG_auto_variable:
163   case dwarf::DW_TAG_arg_variable:
164   case dwarf::DW_TAG_return_variable:
165     return true;
166   default:
167     return false;
168   }
169 }
170
171 DIVariable::DIVariable(GlobalVariable *GV) : DIDescriptor(GV) {
172   if (GV && !isVariable(getTag()))
173     GV = 0;
174 }
175
176 unsigned DIArray::getNumElements() const {
177   assert (GV && "Invalid DIArray");
178   Constant *C = GV->getInitializer();
179   assert (C && "Invalid DIArray initializer");
180   return C->getNumOperands();
181 }
182
183 /// Verify - Verify that a compile unit is well formed.
184 bool DICompileUnit::Verify() const {
185   if (isNull()) 
186     return false;
187   if (getFilename().empty()) 
188     return false;
189   // It is possible that directory and produce string is empty.
190   return true;
191 }
192
193 /// Verify - Verify that a type descriptor is well formed.
194 bool DIType::Verify() const {
195   if (isNull()) 
196     return false;
197   if (getContext().isNull()) 
198     return false;
199
200   DICompileUnit CU = getCompileUnit();
201   if (!CU.isNull() && !CU.Verify()) 
202     return false;
203   return true;
204 }
205
206 /// Verify - Verify that a composite type descriptor is well formed.
207 bool DICompositeType::Verify() const {
208   if (isNull()) 
209     return false;
210   if (getContext().isNull()) 
211     return false;
212
213   DICompileUnit CU = getCompileUnit();
214   if (!CU.isNull() && !CU.Verify()) 
215     return false;
216   return true;
217 }
218
219 /// Verify - Verify that a subprogram descriptor is well formed.
220 bool DISubprogram::Verify() const {
221   if (isNull())
222     return false;
223   
224   if (getContext().isNull())
225     return false;
226
227   DICompileUnit CU = getCompileUnit();
228   if (!CU.Verify()) 
229     return false;
230
231   DICompositeType Ty = getType();
232   if (!Ty.isNull() && !Ty.Verify())
233     return false;
234   return true;
235 }
236
237 /// Verify - Verify that a global variable descriptor is well formed.
238 bool DIGlobalVariable::Verify() const {
239   if (isNull())
240     return false;
241   
242   if (getContext().isNull())
243     return false;
244
245   DICompileUnit CU = getCompileUnit();
246   if (!CU.Verify()) 
247     return false;
248
249   DIType Ty = getType();
250   if (!Ty.Verify())
251     return false;
252
253   if (!getGlobal())
254     return false;
255
256   return true;
257 }
258
259 /// Verify - Verify that a variable descriptor is well formed.
260 bool DIVariable::Verify() const {
261   if (isNull())
262     return false;
263   
264   if (getContext().isNull())
265     return false;
266
267   DIType Ty = getType();
268   if (!Ty.Verify())
269     return false;
270
271
272   return true;
273 }
274
275
276
277 //===----------------------------------------------------------------------===//
278 // DIFactory: Basic Helpers
279 //===----------------------------------------------------------------------===//
280
281 DIFactory::DIFactory(Module &m) : M(m) {
282   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
283   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
284 }
285
286 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
287 /// This is only valid when the descriptor is non-null.
288 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
289   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
290   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
291 }
292
293 Constant *DIFactory::GetTagConstant(unsigned TAG) {
294   assert((TAG & DIDescriptor::VersionMask) == 0 &&
295          "Tag too large for debug encoding!");
296   return ConstantInt::get(Type::Int32Ty, TAG | DIDescriptor::Version7);
297 }
298
299 Constant *DIFactory::GetStringConstant(const std::string &String) {
300   // Check string cache for previous edition.
301   Constant *&Slot = StringCache[String];
302   
303   // Return Constant if previously defined.
304   if (Slot) return Slot;
305   
306   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
307   
308   // If empty string then use a sbyte* null instead.
309   if (String.empty())
310     return Slot = ConstantPointerNull::get(DestTy);
311
312   // Construct string as an llvm constant.
313   Constant *ConstStr = ConstantArray::get(String);
314     
315   // Otherwise create and return a new string global.
316   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
317                                              GlobalVariable::InternalLinkage,
318                                              ConstStr, ".str", &M);
319   StrGV->setSection("llvm.metadata");
320   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
321 }
322
323 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
324 /// already exists, return it.  If not, create a new one and return it.
325 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
326   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
327   
328   // Otherwise, create the global or return it if already in the module.
329   Constant *C = M.getOrInsertGlobal(Name, EltTy);
330   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
331   GlobalVariable *GV = cast<GlobalVariable>(C);
332   
333   // If it has an initializer, it is already in the module.
334   if (GV->hasInitializer()) 
335     return SubProgramAnchor = DIAnchor(GV);
336   
337   GV->setLinkage(GlobalValue::LinkOnceLinkage);
338   GV->setSection("llvm.metadata");
339   GV->setConstant(true);
340   M.addTypeName("llvm.dbg.anchor.type", EltTy);
341   
342   // Otherwise, set the initializer.
343   Constant *Elts[] = {
344     GetTagConstant(dwarf::DW_TAG_anchor),
345     ConstantInt::get(Type::Int32Ty, TAG)
346   };
347   
348   GV->setInitializer(ConstantStruct::get(Elts, 2));
349   return DIAnchor(GV);
350 }
351
352
353
354 //===----------------------------------------------------------------------===//
355 // DIFactory: Primary Constructors
356 //===----------------------------------------------------------------------===//
357
358 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
359 /// creating a new one if there isn't already one in the module.
360 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
361   // If we already created one, just return it.
362   if (!CompileUnitAnchor.isNull())
363     return CompileUnitAnchor;
364   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
365                                                "llvm.dbg.compile_units");
366 }
367
368 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
369 /// creating a new one if there isn't already one in the module.
370 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
371   // If we already created one, just return it.
372   if (!SubProgramAnchor.isNull())
373     return SubProgramAnchor;
374   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
375                                               "llvm.dbg.subprograms");
376 }
377
378 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
379 /// creating a new one if there isn't already one in the module.
380 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
381   // If we already created one, just return it.
382   if (!GlobalVariableAnchor.isNull())
383     return GlobalVariableAnchor;
384   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
385                                                   "llvm.dbg.global_variables");
386 }
387
388 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
389 /// This implicitly uniques the arrays created.
390 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
391   SmallVector<Constant*, 16> Elts;
392   
393   for (unsigned i = 0; i != NumTys; ++i)
394     Elts.push_back(getCastToEmpty(Tys[i]));
395   
396   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
397                                                      Elts.size()),
398                                       &Elts[0], Elts.size());
399   // If we already have this array, just return the uniqued version.
400   DIDescriptor &Entry = SimpleConstantCache[Init];
401   if (!Entry.isNull()) return DIArray(Entry.getGV());
402   
403   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
404                                           GlobalValue::InternalLinkage,
405                                           Init, "llvm.dbg.array", &M);
406   GV->setSection("llvm.metadata");
407   Entry = DIDescriptor(GV);
408   return DIArray(GV);
409 }
410
411 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
412 /// implicitly uniques the values returned.
413 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
414   Constant *Elts[] = {
415     GetTagConstant(dwarf::DW_TAG_subrange_type),
416     ConstantInt::get(Type::Int64Ty, Lo),
417     ConstantInt::get(Type::Int64Ty, Hi)
418   };
419   
420   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
421
422   // If we already have this range, just return the uniqued version.
423   DIDescriptor &Entry = SimpleConstantCache[Init];
424   if (!Entry.isNull()) return DISubrange(Entry.getGV());
425   
426   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
427
428   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
429                                           GlobalValue::InternalLinkage,
430                                           Init, "llvm.dbg.subrange", &M);
431   GV->setSection("llvm.metadata");
432   Entry = DIDescriptor(GV);
433   return DISubrange(GV);
434 }
435
436
437
438 /// CreateCompileUnit - Create a new descriptor for the specified compile
439 /// unit.  Note that this does not unique compile units within the module.
440 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
441                                            const std::string &Filename,
442                                            const std::string &Directory,
443                                            const std::string &Producer) {
444   Constant *Elts[] = {
445     GetTagConstant(dwarf::DW_TAG_compile_unit),
446     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
447     ConstantInt::get(Type::Int32Ty, LangID),
448     GetStringConstant(Filename),
449     GetStringConstant(Directory),
450     GetStringConstant(Producer)
451   };
452   
453   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
454   
455   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
456   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
457                                           GlobalValue::InternalLinkage,
458                                           Init, "llvm.dbg.compile_unit", &M);
459   GV->setSection("llvm.metadata");
460   return DICompileUnit(GV);
461 }
462
463 /// CreateEnumerator - Create a single enumerator value.
464 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
465   Constant *Elts[] = {
466     GetTagConstant(dwarf::DW_TAG_enumerator),
467     GetStringConstant(Name),
468     ConstantInt::get(Type::Int64Ty, Val)
469   };
470   
471   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
472   
473   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
474   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
475                                           GlobalValue::InternalLinkage,
476                                           Init, "llvm.dbg.enumerator", &M);
477   GV->setSection("llvm.metadata");
478   return DIEnumerator(GV);
479 }
480
481
482 /// CreateBasicType - Create a basic type like int, float, etc.
483 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
484                                       const std::string &Name,
485                                        DICompileUnit CompileUnit,
486                                        unsigned LineNumber,
487                                        uint64_t SizeInBits,
488                                        uint64_t AlignInBits,
489                                        uint64_t OffsetInBits, unsigned Flags,
490                                        unsigned Encoding,
491                                        const std::string *FileName,
492                                        const std::string *Directory) {
493   Constant *Elts[] = {
494     GetTagConstant(dwarf::DW_TAG_base_type),
495     getCastToEmpty(Context),
496     GetStringConstant(Name),
497     getCastToEmpty(CompileUnit),
498     ConstantInt::get(Type::Int32Ty, LineNumber),
499     ConstantInt::get(Type::Int64Ty, SizeInBits),
500     ConstantInt::get(Type::Int64Ty, AlignInBits),
501     ConstantInt::get(Type::Int64Ty, OffsetInBits),
502     ConstantInt::get(Type::Int32Ty, Flags),
503     ConstantInt::get(Type::Int32Ty, Encoding),
504     GetStringConstant(FileName ? FileName->c_str() : ""),
505     GetStringConstant(Directory ? Directory->c_str() : "")
506   };
507   
508   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
509   
510   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
511   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
512                                           GlobalValue::InternalLinkage,
513                                           Init, "llvm.dbg.basictype", &M);
514   GV->setSection("llvm.metadata");
515   return DIBasicType(GV);
516 }
517
518 /// CreateDerivedType - Create a derived type like const qualified type,
519 /// pointer, typedef, etc.
520 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
521                                            DIDescriptor Context,
522                                            const std::string &Name,
523                                            DICompileUnit CompileUnit,
524                                            unsigned LineNumber,
525                                            uint64_t SizeInBits,
526                                            uint64_t AlignInBits,
527                                            uint64_t OffsetInBits,
528                                            unsigned Flags,
529                                            DIType DerivedFrom,
530                                            const std::string *FileName,
531                                            const std::string *Directory) {
532   Constant *Elts[] = {
533     GetTagConstant(Tag),
534     getCastToEmpty(Context),
535     GetStringConstant(Name),
536     getCastToEmpty(CompileUnit),
537     ConstantInt::get(Type::Int32Ty, LineNumber),
538     ConstantInt::get(Type::Int64Ty, SizeInBits),
539     ConstantInt::get(Type::Int64Ty, AlignInBits),
540     ConstantInt::get(Type::Int64Ty, OffsetInBits),
541     ConstantInt::get(Type::Int32Ty, Flags),
542     getCastToEmpty(DerivedFrom),
543     GetStringConstant(FileName ? FileName->c_str() : ""),
544     GetStringConstant(Directory ? Directory->c_str() : "")
545   };
546   
547   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
548   
549   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
550   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
551                                           GlobalValue::InternalLinkage,
552                                           Init, "llvm.dbg.derivedtype", &M);
553   GV->setSection("llvm.metadata");
554   return DIDerivedType(GV);
555 }
556
557 /// CreateCompositeType - Create a composite type like array, struct, etc.
558 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
559                                                DIDescriptor Context,
560                                                const std::string &Name,
561                                                DICompileUnit CompileUnit,
562                                                unsigned LineNumber,
563                                                uint64_t SizeInBits,
564                                                uint64_t AlignInBits,
565                                                uint64_t OffsetInBits,
566                                                unsigned Flags,
567                                                DIType DerivedFrom,
568                                                DIArray Elements,
569                                                const std::string *FileName,
570                                                const std::string *Directory) {
571
572   Constant *Elts[] = {
573     GetTagConstant(Tag),
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     getCastToEmpty(DerivedFrom),
583     getCastToEmpty(Elements),
584     GetStringConstant(FileName ? FileName->c_str() : ""),
585     GetStringConstant(Directory ? Directory->c_str() : "")
586   };
587   
588   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
589   
590   M.addTypeName("llvm.dbg.composite.type", Init->getType());
591   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
592                                           GlobalValue::InternalLinkage,
593                                           Init, "llvm.dbg.composite", &M);
594   GV->setSection("llvm.metadata");
595   return DICompositeType(GV);
596 }
597
598
599 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
600 /// See comments in DISubprogram for descriptions of these fields.  This
601 /// method does not unique the generated descriptors.
602 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
603                                          const std::string &Name,
604                                          const std::string &DisplayName,
605                                          const std::string &LinkageName,
606                                          DICompileUnit CompileUnit,
607                                          unsigned LineNo, DIType Type,
608                                          bool isLocalToUnit,
609                                          bool isDefinition,
610                                          const std::string *FileName,
611                                          const std::string *Directory) {
612
613   Constant *Elts[] = {
614     GetTagConstant(dwarf::DW_TAG_subprogram),
615     getCastToEmpty(GetOrCreateSubprogramAnchor()),
616     getCastToEmpty(Context),
617     GetStringConstant(Name),
618     GetStringConstant(DisplayName),
619     GetStringConstant(LinkageName),
620     getCastToEmpty(CompileUnit),
621     ConstantInt::get(Type::Int32Ty, LineNo),
622     getCastToEmpty(Type),
623     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
624     ConstantInt::get(Type::Int1Ty, isDefinition),
625     GetStringConstant(FileName ? FileName->c_str() : ""),
626     GetStringConstant(Directory ? Directory->c_str() : "")
627   };
628   
629   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
630   
631   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
632   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
633                                           GlobalValue::InternalLinkage,
634                                           Init, "llvm.dbg.subprogram", &M);
635   GV->setSection("llvm.metadata");
636   return DISubprogram(GV);
637 }
638
639 /// CreateGlobalVariable - Create a new descriptor for the specified global.
640 DIGlobalVariable
641 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
642                                 const std::string &DisplayName,
643                                 const std::string &LinkageName,
644                                 DICompileUnit CompileUnit,
645                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
646                                 bool isDefinition, llvm::GlobalVariable *Val,
647                                 const std::string *FileName,
648                                 const std::string *Directory) {
649   Constant *Elts[] = {
650     GetTagConstant(dwarf::DW_TAG_variable),
651     getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
652     getCastToEmpty(Context),
653     GetStringConstant(Name),
654     GetStringConstant(DisplayName),
655     GetStringConstant(LinkageName),
656     getCastToEmpty(CompileUnit),
657     ConstantInt::get(Type::Int32Ty, LineNo),
658     getCastToEmpty(Type),
659     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
660     ConstantInt::get(Type::Int1Ty, isDefinition),
661     ConstantExpr::getBitCast(Val, EmptyStructPtr),
662     GetStringConstant(FileName ? FileName->c_str() : ""),
663     GetStringConstant(Directory ? Directory->c_str() : "")
664   };
665   
666   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
667   
668   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
669   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
670                                           GlobalValue::InternalLinkage,
671                                           Init, "llvm.dbg.global_variable", &M);
672   GV->setSection("llvm.metadata");
673   return DIGlobalVariable(GV);
674 }
675
676
677 /// CreateVariable - Create a new descriptor for the specified variable.
678 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
679                                      const std::string &Name,
680                                      DICompileUnit CompileUnit, unsigned LineNo,
681                                      DIType Type,
682                                      const std::string *FileName,
683                                      const std::string *Directory) {
684
685   
686   Constant *Elts[] = {
687     GetTagConstant(Tag),
688     getCastToEmpty(Context),
689     GetStringConstant(Name),
690     getCastToEmpty(CompileUnit),
691     ConstantInt::get(Type::Int32Ty, LineNo),
692     getCastToEmpty(Type),
693     GetStringConstant(FileName ? FileName->c_str() : ""),
694     GetStringConstant(Directory ? Directory->c_str() : "")
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   /// Finds the dbg.declare intrinsic corresponding to this value if any.
845   /// It looks through pointer casts too.
846   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
847   {
848     if (stripCasts) {
849       V = V->stripPointerCasts();
850       // Look for the bitcast.
851       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
852             I != E; ++I) {
853         if (isa<BitCastInst>(I))
854           return findDbgDeclare(*I, false);
855       }
856       return 0;
857     }
858
859     // Find dbg.declare among uses of the instruction.
860     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
861           I != E; ++I) {
862       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
863         return DDI;
864     }
865     return 0;
866   }
867 }
868