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