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