Add a new set of helper classes for creating and reading debug
[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/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Support/Dwarf.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 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
84 /// This is only valid when the descriptor is non-null.
85 Constant *DIDescriptor::getCastToEmpty() const {
86   const Type *DestTy = PointerType::getUnqual(StructType::get(NULL, NULL));
87   if (isNull()) return Constant::getNullValue(DestTy);
88   return ConstantExpr::getBitCast(GV, DestTy);
89 }
90
91 //===----------------------------------------------------------------------===//
92 // Simple Descriptor Constructors and other Methods
93 //===----------------------------------------------------------------------===//
94
95 DIAnchor::DIAnchor(GlobalVariable *GV)
96   : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
97 DIEnumerator::DIEnumerator(GlobalVariable *GV)
98   : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
99 DISubrange::DISubrange(GlobalVariable *GV)
100   : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
101 DICompileUnit::DICompileUnit(GlobalVariable *GV)
102   : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
103 DIBasicType::DIBasicType(GlobalVariable *GV)
104   : DIType(GV, dwarf::DW_TAG_base_type) {}
105 DISubprogram::DISubprogram(GlobalVariable *GV)
106   : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
107 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
108   : DIGlobal(GV, dwarf::DW_TAG_variable) {}
109 DIBlock::DIBlock(GlobalVariable *GV)
110   : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
111
112 /// isDerivedType - Return true if the specified tag is legal for
113 /// DIDerivedType.
114 bool DIDerivedType::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 DICompositeType::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
177
178 //===----------------------------------------------------------------------===//
179 // DIFactory: Basic Helpers
180 //===----------------------------------------------------------------------===//
181
182 Constant *DIFactory::GetTagConstant(unsigned TAG) {
183   assert((TAG & DIDescriptor::VersionMask) == 0 &&
184          "Tag too large for debug encoding!");
185   return ConstantInt::get(Type::Int32Ty, TAG | DIDescriptor::Version6);
186 }
187
188 Constant *DIFactory::GetStringConstant(const std::string &String) {
189   // Check string cache for previous edition.
190   Constant *&Slot = StringCache[String];
191   
192   // Return Constant if previously defined.
193   if (Slot) return Slot;
194   
195   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
196   
197   // If empty string then use a sbyte* null instead.
198   if (String.empty())
199     return Slot = ConstantPointerNull::get(DestTy);
200
201   // Construct string as an llvm constant.
202   Constant *ConstStr = ConstantArray::get(String);
203     
204   // Otherwise create and return a new string global.
205   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
206                                              GlobalVariable::InternalLinkage,
207                                              ConstStr, ".str", &M);
208   StrGV->setSection("llvm.metadata");
209   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
210 }
211
212 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
213 /// already exists, return it.  If not, create a new one and return it.
214 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
215   const Type *EltTy = StructType::get(Type::Int32Ty,  Type::Int32Ty, NULL);
216   
217   // Otherwise, create the global or return it if already in the module.
218   Constant *C = M.getOrInsertGlobal(Name, EltTy);
219   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
220   GlobalVariable *GV = cast<GlobalVariable>(C);
221   
222   // If it has an initializer, it is already in the module.
223   if (GV->hasInitializer()) 
224     return SubProgramAnchor = DIAnchor(GV);
225   
226   GV->setLinkage(GlobalValue::LinkOnceLinkage);
227   GV->setSection("llvm.metadata");
228   GV->setConstant(true);
229   M.addTypeName("llvm.dbg.anchor.type", EltTy);
230   
231   // Otherwise, set the initializer.
232   Constant *Elts[] = {
233     GetTagConstant(dwarf::DW_TAG_anchor),
234     ConstantInt::get(Type::Int32Ty, TAG)
235   };
236   
237   GV->setInitializer(ConstantStruct::get(Elts, 2));
238   return DIAnchor(GV);
239 }
240
241
242
243 //===----------------------------------------------------------------------===//
244 // DIFactory: Primary Constructors
245 //===----------------------------------------------------------------------===//
246
247 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
248 /// creating a new one if there isn't already one in the module.
249 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
250   // If we already created one, just return it.
251   if (!CompileUnitAnchor.isNull())
252     return CompileUnitAnchor;
253   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
254                                                "llvm.dbg.compile_units");
255 }
256
257 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
258 /// creating a new one if there isn't already one in the module.
259 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
260   // If we already created one, just return it.
261   if (!SubProgramAnchor.isNull())
262     return SubProgramAnchor;
263   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
264                                               "llvm.dbg.subprograms");
265 }
266
267 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
268 /// creating a new one if there isn't already one in the module.
269 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
270   // If we already created one, just return it.
271   if (!GlobalVariableAnchor.isNull())
272     return GlobalVariableAnchor;
273   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
274                                                   "llvm.dbg.global_variables");
275 }
276
277 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
278 /// This implicitly uniques the arrays created.
279 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
280   SmallVector<Constant*, 16> Elts;
281   
282   for (unsigned i = 0; i != NumTys; ++i)
283     Elts.push_back(Tys[i].getCastToEmpty());
284   
285   const Type *EltTy = PointerType::getUnqual(StructType::get(NULL,NULL));
286   
287   Constant *Init = ConstantArray::get(ArrayType::get(EltTy, Elts.size()),
288                                       &Elts[0], Elts.size());
289   // If we already have this array, just return the uniqued version.
290   DIDescriptor &Entry = SimpleConstantCache[Init];
291   if (!Entry.isNull()) return DIArray(Entry.getGV());
292   
293   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
294                                           GlobalValue::InternalLinkage,
295                                           Init, "llvm.dbg.array", &M);
296   GV->setSection("llvm.metadata");
297   Entry = DIDescriptor(GV);
298   return DIArray(GV);
299 }
300
301 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
302 /// implicitly uniques the values returned.
303 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
304   Constant *Elts[] = {
305     GetTagConstant(dwarf::DW_TAG_subrange_type),
306     ConstantInt::get(Type::Int64Ty, Lo),
307     ConstantInt::get(Type::Int64Ty, Hi)
308   };
309   
310   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
311
312   // If we already have this range, just return the uniqued version.
313   DIDescriptor &Entry = SimpleConstantCache[Init];
314   if (!Entry.isNull()) return DISubrange(Entry.getGV());
315   
316   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
317
318   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
319                                           GlobalValue::InternalLinkage,
320                                           Init, "llvm.dbg.subrange", &M);
321   GV->setSection("llvm.metadata");
322   Entry = DIDescriptor(GV);
323   return DISubrange(GV);
324 }
325
326
327
328 /// CreateCompileUnit - Create a new descriptor for the specified compile
329 /// unit.  Note that this does not unique compile units within the module.
330 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
331                                            const std::string &Filename,
332                                            const std::string &Directory,
333                                            const std::string &Producer) {
334   Constant *Elts[] = {
335     GetTagConstant(dwarf::DW_TAG_compile_unit),
336     GetOrCreateCompileUnitAnchor().getCastToEmpty(),
337     ConstantInt::get(Type::Int32Ty, LangID),
338     GetStringConstant(Filename),
339     GetStringConstant(Directory),
340     GetStringConstant(Producer)
341   };
342   
343   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
344   
345   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
346   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
347                                           GlobalValue::InternalLinkage,
348                                           Init, "llvm.dbg.compile_unit", &M);
349   GV->setSection("llvm.metadata");
350   return DICompileUnit(GV);
351 }
352
353 /// CreateEnumerator - Create a single enumerator value.
354 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
355   Constant *Elts[] = {
356     GetTagConstant(dwarf::DW_TAG_enumerator),
357     GetStringConstant(Name),
358     ConstantInt::get(Type::Int64Ty, Val)
359   };
360   
361   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
362   
363   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
364   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
365                                           GlobalValue::InternalLinkage,
366                                           Init, "llvm.dbg.enumerator", &M);
367   GV->setSection("llvm.metadata");
368   return DIEnumerator(GV);
369 }
370
371
372 /// CreateBasicType - Create a basic type like int, float, etc.
373 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
374                                       const std::string &Name,
375                                        DICompileUnit CompileUnit,
376                                        unsigned LineNumber,
377                                        uint64_t SizeInBits,
378                                        uint64_t AlignInBits,
379                                        uint64_t OffsetInBits, unsigned Flags,
380                                        unsigned Encoding) {
381   Constant *Elts[] = {
382     GetTagConstant(dwarf::DW_TAG_base_type),
383     Context.getCastToEmpty(),
384     GetStringConstant(Name),
385     CompileUnit.getCastToEmpty(),
386     ConstantInt::get(Type::Int32Ty, LineNumber),
387     ConstantInt::get(Type::Int64Ty, SizeInBits),
388     ConstantInt::get(Type::Int64Ty, AlignInBits),
389     ConstantInt::get(Type::Int64Ty, OffsetInBits),
390     ConstantInt::get(Type::Int32Ty, Flags),
391     ConstantInt::get(Type::Int32Ty, Encoding)
392   };
393   
394   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
395   
396   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
397   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
398                                           GlobalValue::InternalLinkage,
399                                           Init, "llvm.dbg.basictype", &M);
400   GV->setSection("llvm.metadata");
401   return DIBasicType(GV);
402 }
403
404 /// CreateDerivedType - Create a derived type like const qualified type,
405 /// pointer, typedef, etc.
406 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
407                                            DIDescriptor Context,
408                                            const std::string &Name,
409                                            DICompileUnit CompileUnit,
410                                            unsigned LineNumber,
411                                            uint64_t SizeInBits,
412                                            uint64_t AlignInBits,
413                                            uint64_t OffsetInBits,
414                                            unsigned Flags,
415                                            DIType DerivedFrom) {
416   Constant *Elts[] = {
417     GetTagConstant(Tag),
418     Context.getCastToEmpty(),
419     GetStringConstant(Name),
420     CompileUnit.getCastToEmpty(),
421     ConstantInt::get(Type::Int32Ty, LineNumber),
422     ConstantInt::get(Type::Int64Ty, SizeInBits),
423     ConstantInt::get(Type::Int64Ty, AlignInBits),
424     ConstantInt::get(Type::Int64Ty, OffsetInBits),
425     ConstantInt::get(Type::Int32Ty, Flags),
426     DerivedFrom.getCastToEmpty()
427   };
428   
429   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
430   
431   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
432   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
433                                           GlobalValue::InternalLinkage,
434                                           Init, "llvm.dbg.derivedtype", &M);
435   GV->setSection("llvm.metadata");
436   return DIDerivedType(GV);
437 }
438
439 /// CreateCompositeType - Create a composite type like array, struct, etc.
440 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
441                                                DIDescriptor Context,
442                                                const std::string &Name,
443                                                DICompileUnit CompileUnit,
444                                                unsigned LineNumber,
445                                                uint64_t SizeInBits,
446                                                uint64_t AlignInBits,
447                                                uint64_t OffsetInBits,
448                                                unsigned Flags,
449                                                DIType DerivedFrom,
450                                                DIArray Elements) {
451   Constant *Elts[] = {
452     GetTagConstant(Tag),
453     Context.getCastToEmpty(),
454     GetStringConstant(Name),
455     CompileUnit.getCastToEmpty(),
456     ConstantInt::get(Type::Int32Ty, LineNumber),
457     ConstantInt::get(Type::Int64Ty, SizeInBits),
458     ConstantInt::get(Type::Int64Ty, AlignInBits),
459     ConstantInt::get(Type::Int64Ty, OffsetInBits),
460     ConstantInt::get(Type::Int32Ty, Flags),
461     DerivedFrom.getCastToEmpty(),
462     Elements.getCastToEmpty()
463   };
464   
465   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
466   
467   M.addTypeName("llvm.dbg.composite.type", Init->getType());
468   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
469                                           GlobalValue::InternalLinkage,
470                                           Init, "llvm.dbg.composite", &M);
471   GV->setSection("llvm.metadata");
472   return DICompositeType(GV);
473 }
474
475
476 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
477 /// See comments in DISubprogram for descriptions of these fields.  This
478 /// method does not unique the generated descriptors.
479 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
480                                          const std::string &Name,
481                                          const std::string &DisplayName,
482                                          const std::string &LinkageName,
483                                          DICompileUnit CompileUnit,
484                                          unsigned LineNo, DIType Type,
485                                          bool isLocalToUnit,
486                                          bool isDefinition) {
487   Constant *Elts[] = {
488     GetTagConstant(dwarf::DW_TAG_subprogram),
489     GetOrCreateSubprogramAnchor().getCastToEmpty(),
490     Context.getCastToEmpty(),
491     GetStringConstant(Name),
492     GetStringConstant(DisplayName),
493     GetStringConstant(LinkageName),
494     CompileUnit.getCastToEmpty(),
495     ConstantInt::get(Type::Int32Ty, LineNo),
496     Type.getCastToEmpty(),
497     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
498     ConstantInt::get(Type::Int1Ty, isDefinition)
499   };
500   
501   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
502   
503   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
504   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
505                                           GlobalValue::InternalLinkage,
506                                           Init, "llvm.dbg.subprogram", &M);
507   GV->setSection("llvm.metadata");
508   return DISubprogram(GV);
509 }
510
511 /// CreateGlobalVariable - Create a new descriptor for the specified global.
512 DIGlobalVariable
513 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
514                                 const std::string &DisplayName,
515                                 const std::string &LinkageName,
516                                 DICompileUnit CompileUnit,
517                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
518                                 bool isDefinition, llvm::GlobalVariable *Val) {
519   
520   Constant *Elts[] = {
521     GetTagConstant(dwarf::DW_TAG_variable),
522     GetOrCreateGlobalVariableAnchor().getCastToEmpty(),
523     Context.getCastToEmpty(),
524     GetStringConstant(Name),
525     GetStringConstant(DisplayName),
526     GetStringConstant(LinkageName),
527     CompileUnit.getCastToEmpty(),
528     ConstantInt::get(Type::Int32Ty, LineNo),
529     Type.getCastToEmpty(),
530     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
531     ConstantInt::get(Type::Int1Ty, isDefinition),
532     ConstantExpr::getBitCast(Val, 
533                              PointerType::getUnqual(StructType::get(NULL,NULL)))
534   };
535   
536   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
537   
538   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
539   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
540                                           GlobalValue::InternalLinkage,
541                                           Init, "llvm.dbg.global_variable", &M);
542   GV->setSection("llvm.metadata");
543   return DIGlobalVariable(GV);
544 }
545
546
547 /// CreateVariable - Create a new descriptor for the specified variable.
548 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
549                                      const std::string &Name,
550                                      DICompileUnit CompileUnit, unsigned LineNo,
551                                      DIType Type) {
552   
553   Constant *Elts[] = {
554     GetTagConstant(Tag),
555     Context.getCastToEmpty(),
556     GetStringConstant(Name),
557     CompileUnit.getCastToEmpty(),
558     ConstantInt::get(Type::Int32Ty, LineNo),
559     Type.getCastToEmpty(),
560   };
561   
562   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
563   
564   M.addTypeName("llvm.dbg.variable.type", Init->getType());
565   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
566                                           GlobalValue::InternalLinkage,
567                                           Init, "llvm.dbg.variable", &M);
568   GV->setSection("llvm.metadata");
569   return DIVariable(GV);
570 }
571
572
573 /// CreateBlock - This creates a descriptor for a lexical block with the
574 /// specified parent context.
575 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
576   Constant *Elts[] = {
577     GetTagConstant(dwarf::DW_TAG_lexical_block),
578     Context.getCastToEmpty()
579   };
580   
581   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
582   
583   M.addTypeName("llvm.dbg.block.type", Init->getType());
584   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
585                                           GlobalValue::InternalLinkage,
586                                           Init, "llvm.dbg.block", &M);
587   GV->setSection("llvm.metadata");
588   return DIBlock(GV);
589 }
590
591
592 //===----------------------------------------------------------------------===//
593 // DIFactory: Routines for inserting code into a function
594 //===----------------------------------------------------------------------===//
595
596 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
597 /// inserting it at the end of the specified basic block.
598 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
599                                 unsigned ColNo, BasicBlock *BB) {
600   
601   // Lazily construct llvm.dbg.stoppoint function.
602   if (!StopPointFn)
603     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
604                                               llvm::Intrinsic::dbg_stoppoint);
605   
606   // Invoke llvm.dbg.stoppoint
607   Value *Args[] = {
608     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
609     llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
610     CU.getCastToEmpty()
611   };
612   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
613 }
614
615 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
616 /// mark the start of the specified subprogram.
617 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
618   // Lazily construct llvm.dbg.func.start.
619   if (!FuncStartFn)
620     FuncStartFn = llvm::Intrinsic::getDeclaration(&M, 
621                                               llvm::Intrinsic::dbg_func_start);
622   
623   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
624   CallInst::Create(FuncStartFn, SP.getCastToEmpty(), "", BB);
625 }
626
627 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
628 /// mark the start of a region for the specified scoping descriptor.
629 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
630   // Lazily construct llvm.dbg.region.start function.
631   if (!RegionStartFn)
632     RegionStartFn = llvm::Intrinsic::getDeclaration(&M, 
633                                             llvm::Intrinsic::dbg_region_start);
634   // Call llvm.dbg.func.start.
635   CallInst::Create(RegionStartFn, D.getCastToEmpty(), "", BB);
636 }
637
638
639 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
640 /// mark the end of a region for the specified scoping descriptor.
641 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
642   // Lazily construct llvm.dbg.region.end function.
643   if (!RegionEndFn)
644     RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
645                                                llvm::Intrinsic::dbg_region_end);
646   
647   CallInst::Create(RegionEndFn, D.getCastToEmpty(), "", BB);
648 }
649
650 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
651 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
652                               BasicBlock *BB) {
653   // Cast the storage to a {}* for the call to llvm.dbg.declare.
654   const Type *DestTy = PointerType::getUnqual(StructType::get(NULL, NULL));
655   Storage = new llvm::BitCastInst(Storage, DestTy, Storage->getName(), BB);
656   
657   if (!DeclareFn)
658     DeclareFn = llvm::Intrinsic::getDeclaration(&M,
659                                                 llvm::Intrinsic::dbg_declare);
660   Value *Args[] = { Storage, D.getCastToEmpty() };
661   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
662 }