Move ConstantStruct back to 2.5 API.
[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 (F->getName() == Name)
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 ConstantInt::get(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     ConstantInt::get(Type::Int64Ty, Lo),
545     ConstantInt::get(Type::Int64Ty, Hi)
546   };
547   
548   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
549
550   // If we already have this range, just return the uniqued version.
551   DIDescriptor &Entry = SimpleConstantCache[Init];
552   if (!Entry.isNull()) return DISubrange(Entry.getGV());
553   
554   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
555
556   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
557                                           GlobalValue::InternalLinkage,
558                                           Init, "llvm.dbg.subrange");
559   GV->setSection("llvm.metadata");
560   Entry = DIDescriptor(GV);
561   return DISubrange(GV);
562 }
563
564
565
566 /// CreateCompileUnit - Create a new descriptor for the specified compile
567 /// unit.  Note that this does not unique compile units within the module.
568 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
569                                            const std::string &Filename,
570                                            const std::string &Directory,
571                                            const std::string &Producer,
572                                            bool isMain,
573                                            bool isOptimized,
574                                            const char *Flags,
575                                            unsigned RunTimeVer) {
576   Constant *Elts[] = {
577     GetTagConstant(dwarf::DW_TAG_compile_unit),
578     VMContext.getNullValue(EmptyStructPtr),
579     ConstantInt::get(Type::Int32Ty, LangID),
580     GetStringConstant(Filename),
581     GetStringConstant(Directory),
582     GetStringConstant(Producer),
583     ConstantInt::get(Type::Int1Ty, isMain),
584     ConstantInt::get(Type::Int1Ty, isOptimized),
585     GetStringConstant(Flags),
586     ConstantInt::get(Type::Int32Ty, RunTimeVer)
587   };
588   
589   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
590   
591   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
592   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
593                                           GlobalValue::LinkOnceAnyLinkage,
594                                           Init, "llvm.dbg.compile_unit");
595   GV->setSection("llvm.metadata");
596   return DICompileUnit(GV);
597 }
598
599 /// CreateEnumerator - Create a single enumerator value.
600 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
601   Constant *Elts[] = {
602     GetTagConstant(dwarf::DW_TAG_enumerator),
603     GetStringConstant(Name),
604     ConstantInt::get(Type::Int64Ty, Val)
605   };
606   
607   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
608   
609   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
610   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
611                                           GlobalValue::InternalLinkage,
612                                           Init, "llvm.dbg.enumerator");
613   GV->setSection("llvm.metadata");
614   return DIEnumerator(GV);
615 }
616
617
618 /// CreateBasicType - Create a basic type like int, float, etc.
619 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
620                                       const std::string &Name,
621                                        DICompileUnit CompileUnit,
622                                        unsigned LineNumber,
623                                        uint64_t SizeInBits,
624                                        uint64_t AlignInBits,
625                                        uint64_t OffsetInBits, unsigned Flags,
626                                        unsigned Encoding) {
627   Constant *Elts[] = {
628     GetTagConstant(dwarf::DW_TAG_base_type),
629     getCastToEmpty(Context),
630     GetStringConstant(Name),
631     getCastToEmpty(CompileUnit),
632     ConstantInt::get(Type::Int32Ty, LineNumber),
633     ConstantInt::get(Type::Int64Ty, SizeInBits),
634     ConstantInt::get(Type::Int64Ty, AlignInBits),
635     ConstantInt::get(Type::Int64Ty, OffsetInBits),
636     ConstantInt::get(Type::Int32Ty, Flags),
637     ConstantInt::get(Type::Int32Ty, Encoding)
638   };
639   
640   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
641   
642   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
643   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
644                                           GlobalValue::InternalLinkage,
645                                           Init, "llvm.dbg.basictype");
646   GV->setSection("llvm.metadata");
647   return DIBasicType(GV);
648 }
649
650 /// CreateDerivedType - Create a derived type like const qualified type,
651 /// pointer, typedef, etc.
652 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
653                                            DIDescriptor Context,
654                                            const std::string &Name,
655                                            DICompileUnit CompileUnit,
656                                            unsigned LineNumber,
657                                            uint64_t SizeInBits,
658                                            uint64_t AlignInBits,
659                                            uint64_t OffsetInBits,
660                                            unsigned Flags,
661                                            DIType DerivedFrom) {
662   Constant *Elts[] = {
663     GetTagConstant(Tag),
664     getCastToEmpty(Context),
665     GetStringConstant(Name),
666     getCastToEmpty(CompileUnit),
667     ConstantInt::get(Type::Int32Ty, LineNumber),
668     ConstantInt::get(Type::Int64Ty, SizeInBits),
669     ConstantInt::get(Type::Int64Ty, AlignInBits),
670     ConstantInt::get(Type::Int64Ty, OffsetInBits),
671     ConstantInt::get(Type::Int32Ty, Flags),
672     getCastToEmpty(DerivedFrom)
673   };
674   
675   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
676   
677   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
678   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
679                                           GlobalValue::InternalLinkage,
680                                           Init, "llvm.dbg.derivedtype");
681   GV->setSection("llvm.metadata");
682   return DIDerivedType(GV);
683 }
684
685 /// CreateCompositeType - Create a composite type like array, struct, etc.
686 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
687                                                DIDescriptor Context,
688                                                const std::string &Name,
689                                                DICompileUnit CompileUnit,
690                                                unsigned LineNumber,
691                                                uint64_t SizeInBits,
692                                                uint64_t AlignInBits,
693                                                uint64_t OffsetInBits,
694                                                unsigned Flags,
695                                                DIType DerivedFrom,
696                                                DIArray Elements,
697                                                unsigned RuntimeLang) {
698
699   Constant *Elts[] = {
700     GetTagConstant(Tag),
701     getCastToEmpty(Context),
702     GetStringConstant(Name),
703     getCastToEmpty(CompileUnit),
704     ConstantInt::get(Type::Int32Ty, LineNumber),
705     ConstantInt::get(Type::Int64Ty, SizeInBits),
706     ConstantInt::get(Type::Int64Ty, AlignInBits),
707     ConstantInt::get(Type::Int64Ty, OffsetInBits),
708     ConstantInt::get(Type::Int32Ty, Flags),
709     getCastToEmpty(DerivedFrom),
710     getCastToEmpty(Elements),
711     ConstantInt::get(Type::Int32Ty, RuntimeLang)
712   };
713   
714   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
715   
716   M.addTypeName("llvm.dbg.composite.type", Init->getType());
717   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
718                                           GlobalValue::InternalLinkage,
719                                           Init, "llvm.dbg.composite");
720   GV->setSection("llvm.metadata");
721   return DICompositeType(GV);
722 }
723
724
725 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
726 /// See comments in DISubprogram for descriptions of these fields.  This
727 /// method does not unique the generated descriptors.
728 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
729                                          const std::string &Name,
730                                          const std::string &DisplayName,
731                                          const std::string &LinkageName,
732                                          DICompileUnit CompileUnit,
733                                          unsigned LineNo, DIType Type,
734                                          bool isLocalToUnit,
735                                          bool isDefinition) {
736
737   Constant *Elts[] = {
738     GetTagConstant(dwarf::DW_TAG_subprogram),
739     VMContext.getNullValue(EmptyStructPtr),
740     getCastToEmpty(Context),
741     GetStringConstant(Name),
742     GetStringConstant(DisplayName),
743     GetStringConstant(LinkageName),
744     getCastToEmpty(CompileUnit),
745     ConstantInt::get(Type::Int32Ty, LineNo),
746     getCastToEmpty(Type),
747     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
748     ConstantInt::get(Type::Int1Ty, isDefinition)
749   };
750   
751   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
752   
753   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
754   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
755                                           GlobalValue::LinkOnceAnyLinkage,
756                                           Init, "llvm.dbg.subprogram");
757   GV->setSection("llvm.metadata");
758   return DISubprogram(GV);
759 }
760
761 /// CreateGlobalVariable - Create a new descriptor for the specified global.
762 DIGlobalVariable
763 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
764                                 const std::string &DisplayName,
765                                 const std::string &LinkageName,
766                                 DICompileUnit CompileUnit,
767                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
768                                 bool isDefinition, llvm::GlobalVariable *Val) {
769   Constant *Elts[] = {
770     GetTagConstant(dwarf::DW_TAG_variable),
771     VMContext.getNullValue(EmptyStructPtr),
772     getCastToEmpty(Context),
773     GetStringConstant(Name),
774     GetStringConstant(DisplayName),
775     GetStringConstant(LinkageName),
776     getCastToEmpty(CompileUnit),
777     ConstantInt::get(Type::Int32Ty, LineNo),
778     getCastToEmpty(Type),
779     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
780     ConstantInt::get(Type::Int1Ty, isDefinition),
781     VMContext.getConstantExprBitCast(Val, EmptyStructPtr)
782   };
783   
784   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
785   
786   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
787   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
788                                           GlobalValue::LinkOnceAnyLinkage,
789                                           Init, "llvm.dbg.global_variable");
790   GV->setSection("llvm.metadata");
791   return DIGlobalVariable(GV);
792 }
793
794
795 /// CreateVariable - Create a new descriptor for the specified variable.
796 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
797                                      const std::string &Name,
798                                      DICompileUnit CompileUnit, unsigned LineNo,
799                                      DIType Type) {
800   Constant *Elts[] = {
801     GetTagConstant(Tag),
802     getCastToEmpty(Context),
803     GetStringConstant(Name),
804     getCastToEmpty(CompileUnit),
805     ConstantInt::get(Type::Int32Ty, LineNo),
806     getCastToEmpty(Type)
807   };
808   
809   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
810   
811   M.addTypeName("llvm.dbg.variable.type", Init->getType());
812   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
813                                           GlobalValue::InternalLinkage,
814                                           Init, "llvm.dbg.variable");
815   GV->setSection("llvm.metadata");
816   return DIVariable(GV);
817 }
818
819
820 /// CreateBlock - This creates a descriptor for a lexical block with the
821 /// specified parent VMContext.
822 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
823   Constant *Elts[] = {
824     GetTagConstant(dwarf::DW_TAG_lexical_block),
825     getCastToEmpty(Context)
826   };
827   
828   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
829   
830   M.addTypeName("llvm.dbg.block.type", Init->getType());
831   GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
832                                           GlobalValue::InternalLinkage,
833                                           Init, "llvm.dbg.block");
834   GV->setSection("llvm.metadata");
835   return DIBlock(GV);
836 }
837
838
839 //===----------------------------------------------------------------------===//
840 // DIFactory: Routines for inserting code into a function
841 //===----------------------------------------------------------------------===//
842
843 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
844 /// inserting it at the end of the specified basic block.
845 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
846                                 unsigned ColNo, BasicBlock *BB) {
847   
848   // Lazily construct llvm.dbg.stoppoint function.
849   if (!StopPointFn)
850     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
851                                               llvm::Intrinsic::dbg_stoppoint);
852   
853   // Invoke llvm.dbg.stoppoint
854   Value *Args[] = {
855     ConstantInt::get(llvm::Type::Int32Ty, LineNo),
856     ConstantInt::get(llvm::Type::Int32Ty, ColNo),
857     getCastToEmpty(CU)
858   };
859   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
860 }
861
862 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
863 /// mark the start of the specified subprogram.
864 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
865   // Lazily construct llvm.dbg.func.start.
866   if (!FuncStartFn)
867     FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
868   
869   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
870   CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
871 }
872
873 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
874 /// mark the start of a region for the specified scoping descriptor.
875 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
876   // Lazily construct llvm.dbg.region.start function.
877   if (!RegionStartFn)
878     RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
879
880   // Call llvm.dbg.func.start.
881   CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
882 }
883
884 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
885 /// mark the end of a region for the specified scoping descriptor.
886 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
887   // Lazily construct llvm.dbg.region.end function.
888   if (!RegionEndFn)
889     RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
890
891   // Call llvm.dbg.region.end.
892   CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
893 }
894
895 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
896 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
897   // Cast the storage to a {}* for the call to llvm.dbg.declare.
898   Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
899   
900   if (!DeclareFn)
901     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
902
903   Value *Args[] = { Storage, getCastToEmpty(D) };
904   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
905 }
906
907 namespace llvm {
908   /// findStopPoint - Find the stoppoint coressponding to this instruction, that
909   /// is the stoppoint that dominates this instruction.
910   const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
911     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
912       return DSI;
913
914     const BasicBlock *BB = Inst->getParent();
915     BasicBlock::const_iterator I = Inst, B;
916     while (BB) {
917       B = BB->begin();
918
919       // A BB consisting only of a terminator can't have a stoppoint.
920       while (I != B) {
921         --I;
922         if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
923           return DSI;
924       }
925
926       // This BB didn't have a stoppoint: if there is only one predecessor, look
927       // for a stoppoint there. We could use getIDom(), but that would require
928       // dominator info.
929       BB = I->getParent()->getUniquePredecessor();
930       if (BB)
931         I = BB->getTerminator();
932     }
933
934     return 0;
935   }
936
937   /// findBBStopPoint - Find the stoppoint corresponding to first real
938   /// (non-debug intrinsic) instruction in this Basic Block, and return the
939   /// stoppoint for it.
940   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
941     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
942       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
943         return DSI;
944
945     // Fallback to looking for stoppoint of unique predecessor. Useful if this
946     // BB contains no stoppoints, but unique predecessor does.
947     BB = BB->getUniquePredecessor();
948     if (BB)
949       return findStopPoint(BB->getTerminator());
950
951     return 0;
952   }
953
954   Value *findDbgGlobalDeclare(GlobalVariable *V) {
955     const Module *M = V->getParent();
956     LLVMContext& Context = M->getContext();
957     
958     const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
959     if (!Ty) return 0;
960
961     Ty = Context.getPointerType(Ty, 0);
962
963     Value *Val = V->stripPointerCasts();
964     for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
965          I != E; ++I) {
966       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
967         if (CE->getOpcode() == Instruction::BitCast) {
968           Value *VV = CE;
969
970           while (VV->hasOneUse())
971             VV = *VV->use_begin();
972
973           if (VV->getType() == Ty)
974             return VV;
975         }
976       }
977     }
978     
979     if (Val->getType() == Ty)
980       return Val;
981
982     return 0;
983   }
984
985   /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
986   /// It looks through pointer casts too.
987   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
988     if (stripCasts) {
989       V = V->stripPointerCasts();
990
991       // Look for the bitcast.
992       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
993             I != E; ++I)
994         if (isa<BitCastInst>(I))
995           return findDbgDeclare(*I, false);
996
997       return 0;
998     }
999
1000     // Find llvm.dbg.declare among uses of the instruction.
1001     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1002           I != E; ++I)
1003       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1004         return DDI;
1005
1006     return 0;
1007   }
1008
1009   bool getLocationInfo(const Value *V, std::string &DisplayName,
1010                        std::string &Type, unsigned &LineNo, std::string &File,
1011                        std::string &Dir) {
1012     DICompileUnit Unit;
1013     DIType TypeD;
1014
1015     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1016       Value *DIGV = findDbgGlobalDeclare(GV);
1017       if (!DIGV) return false;
1018       DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1019
1020       Var.getDisplayName(DisplayName);
1021       LineNo = Var.getLineNumber();
1022       Unit = Var.getCompileUnit();
1023       TypeD = Var.getType();
1024     } else {
1025       const DbgDeclareInst *DDI = findDbgDeclare(V);
1026       if (!DDI) return false;
1027       DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1028
1029       Var.getName(DisplayName);
1030       LineNo = Var.getLineNumber();
1031       Unit = Var.getCompileUnit();
1032       TypeD = Var.getType();
1033     }
1034
1035     TypeD.getName(Type);
1036     Unit.getFilename(File);
1037     Unit.getDirectory(Dir);
1038     return true;
1039   }
1040
1041   /// CollectDebugInfoAnchors - Collect debugging information anchors.
1042   void CollectDebugInfoAnchors(Module &M,
1043                                SmallVector<GlobalVariable *, 2> &CUs,
1044                                SmallVector<GlobalVariable *, 4> &GVs,
1045                                SmallVector<GlobalVariable *, 4> &SPs) {
1046
1047     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1048        GVI != E; GVI++) {
1049       GlobalVariable *GV = GVI;
1050       if (GV->hasName() && GV->getName().startswith("llvm.dbg")
1051           && GV->isConstant() && GV->hasInitializer()) {
1052         DICompileUnit C(GV);
1053         if (C.isNull() == false) {
1054           CUs.push_back(GV);
1055           continue;
1056         }
1057         DIGlobalVariable G(GV);
1058         if (G.isNull() == false) {
1059           GVs.push_back(GV);
1060           continue;
1061         }
1062         DISubprogram S(GV);
1063         if (S.isNull() == false) {
1064           SPs.push_back(GV);
1065           continue;
1066         }
1067       }
1068     }
1069   }
1070
1071   /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug 
1072   /// info intrinsic.
1073   bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, 
1074                                  CodeGenOpt::Level OptLev) {
1075     return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1076   }
1077
1078   /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug 
1079   /// info intrinsic.
1080   bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1081                                  CodeGenOpt::Level OptLev) {
1082     return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1083   }
1084
1085   /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug 
1086   /// info intrinsic.
1087   bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1088                                  CodeGenOpt::Level OptLev) {
1089     return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1090   }
1091
1092   /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug 
1093   /// info intrinsic.
1094   bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1095                                  CodeGenOpt::Level OptLev) {
1096     return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1097   }
1098
1099
1100   /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug 
1101   /// info intrinsic.
1102   bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1103                                  CodeGenOpt::Level OptLev) {
1104     return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1105   }
1106
1107   /// ExtractDebugLocation - Extract debug location information 
1108   /// from llvm.dbg.stoppoint intrinsic.
1109   DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1110                                 DebugLocTracker &DebugLocInfo) {
1111     DebugLoc DL;
1112     Value *Context = SPI.getContext();
1113
1114     // If this location is already tracked then use it.
1115     DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(), 
1116                         SPI.getColumn());
1117     DenseMap<DebugLocTuple, unsigned>::iterator II
1118       = DebugLocInfo.DebugIdMap.find(Tuple);
1119     if (II != DebugLocInfo.DebugIdMap.end())
1120       return DebugLoc::get(II->second);
1121
1122     // Add a new location entry.
1123     unsigned Id = DebugLocInfo.DebugLocations.size();
1124     DebugLocInfo.DebugLocations.push_back(Tuple);
1125     DebugLocInfo.DebugIdMap[Tuple] = Id;
1126     
1127     return DebugLoc::get(Id);
1128   }
1129
1130   /// ExtractDebugLocation - Extract debug location information 
1131   /// from llvm.dbg.func_start intrinsic.
1132   DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1133                                 DebugLocTracker &DebugLocInfo) {
1134     DebugLoc DL;
1135     Value *SP = FSI.getSubprogram();
1136
1137     DISubprogram Subprogram(cast<GlobalVariable>(SP));
1138     unsigned Line = Subprogram.getLineNumber();
1139     DICompileUnit CU(Subprogram.getCompileUnit());
1140
1141     // If this location is already tracked then use it.
1142     DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1143     DenseMap<DebugLocTuple, unsigned>::iterator II
1144       = DebugLocInfo.DebugIdMap.find(Tuple);
1145     if (II != DebugLocInfo.DebugIdMap.end())
1146       return DebugLoc::get(II->second);
1147
1148     // Add a new location entry.
1149     unsigned Id = DebugLocInfo.DebugLocations.size();
1150     DebugLocInfo.DebugLocations.push_back(Tuple);
1151     DebugLocInfo.DebugIdMap[Tuple] = Id;
1152     
1153     return DebugLoc::get(Id);
1154   }
1155
1156   /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1157   bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1158     DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1159     if (Subprogram.describes(CurrentFn))
1160       return false;
1161
1162     return true;
1163   }
1164
1165   /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1166   bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1167     DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1168     if (Subprogram.isNull() || Subprogram.describes(CurrentFn))
1169       return false;
1170
1171     return true;
1172   }
1173
1174 }