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