Move ConstantExpr to 2.5 API.
[llvm/avr.git] / lib / Analysis / DebugInfo.cpp
blob3db7ff964c200d3904304ebe67b0ae56e4f8aac6
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.
13 //===----------------------------------------------------------------------===//
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"
28 using namespace llvm;
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
32 // DIDescriptor
33 //===----------------------------------------------------------------------===//
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;
40 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
41 if (!GV)
42 return false;
44 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
45 return false;
47 DIDescriptor DI(GV);
49 // Check current version. Allow Version6 for now.
50 unsigned Version = DI.getVersion();
51 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
52 return false;
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;
75 return true;
78 DIDescriptor::DIDescriptor(GlobalVariable *GV, unsigned RequiredTag) {
79 DbgGV = GV;
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;
86 const std::string &
87 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
88 if (DbgGV == 0) {
89 Result.clear();
90 return Result;
93 Constant *C = DbgGV->getInitializer();
94 if (C == 0 || Elt >= C->getNumOperands()) {
95 Result.clear();
96 return Result;
99 // Fills in the string if it succeeds
100 if (!GetConstantStringInfo(C->getOperand(Elt), Result))
101 Result.clear();
103 return Result;
106 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
107 if (DbgGV == 0) return 0;
108 if (!DbgGV->hasInitializer()) return 0;
110 Constant *C = DbgGV->getInitializer();
111 if (C == 0 || Elt >= C->getNumOperands())
112 return 0;
114 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
115 return CI->getZExtValue();
116 return 0;
119 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
120 if (DbgGV == 0) return DIDescriptor();
122 Constant *C = DbgGV->getInitializer();
123 if (C == 0 || Elt >= C->getNumOperands())
124 return DIDescriptor();
126 C = C->getOperand(Elt);
127 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
130 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
131 if (DbgGV == 0) return 0;
133 Constant *C = DbgGV->getInitializer();
134 if (C == 0 || Elt >= C->getNumOperands())
135 return 0;
137 C = C->getOperand(Elt);
138 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
141 //===----------------------------------------------------------------------===//
142 // Simple Descriptor Constructors and other Methods
143 //===----------------------------------------------------------------------===//
145 // Needed by DIVariable::getType().
146 DIType::DIType(GlobalVariable *GV) : DIDescriptor(GV) {
147 if (!GV) return;
148 unsigned tag = getTag();
149 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
150 !DICompositeType::isCompositeType(tag))
151 DbgGV = 0;
154 /// isDerivedType - Return true if the specified tag is legal for
155 /// DIDerivedType.
156 bool DIType::isDerivedType(unsigned Tag) {
157 switch (Tag) {
158 case dwarf::DW_TAG_typedef:
159 case dwarf::DW_TAG_pointer_type:
160 case dwarf::DW_TAG_reference_type:
161 case dwarf::DW_TAG_const_type:
162 case dwarf::DW_TAG_volatile_type:
163 case dwarf::DW_TAG_restrict_type:
164 case dwarf::DW_TAG_member:
165 case dwarf::DW_TAG_inheritance:
166 return true;
167 default:
168 // FIXME: Even though it doesn't make sense, CompositeTypes are current
169 // modelled as DerivedTypes, this should return true for them as well.
170 return false;
174 /// isCompositeType - Return true if the specified tag is legal for
175 /// DICompositeType.
176 bool DIType::isCompositeType(unsigned TAG) {
177 switch (TAG) {
178 case dwarf::DW_TAG_array_type:
179 case dwarf::DW_TAG_structure_type:
180 case dwarf::DW_TAG_union_type:
181 case dwarf::DW_TAG_enumeration_type:
182 case dwarf::DW_TAG_vector_type:
183 case dwarf::DW_TAG_subroutine_type:
184 case dwarf::DW_TAG_class_type:
185 return true;
186 default:
187 return false;
191 /// isVariable - Return true if the specified tag is legal for DIVariable.
192 bool DIVariable::isVariable(unsigned Tag) {
193 switch (Tag) {
194 case dwarf::DW_TAG_auto_variable:
195 case dwarf::DW_TAG_arg_variable:
196 case dwarf::DW_TAG_return_variable:
197 return true;
198 default:
199 return false;
203 unsigned DIArray::getNumElements() const {
204 assert (DbgGV && "Invalid DIArray");
205 Constant *C = DbgGV->getInitializer();
206 assert (C && "Invalid DIArray initializer");
207 return C->getNumOperands();
210 /// replaceAllUsesWith - Replace all uses of debug info referenced by
211 /// this descriptor. After this completes, the current debug info value
212 /// is erased.
213 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
214 if (isNull())
215 return;
217 assert (!D.isNull() && "Can not replace with null");
218 getGV()->replaceAllUsesWith(D.getGV());
219 getGV()->eraseFromParent();
222 /// Verify - Verify that a compile unit is well formed.
223 bool DICompileUnit::Verify() const {
224 if (isNull())
225 return false;
226 std::string Res;
227 if (getFilename(Res).empty())
228 return false;
229 // It is possible that directory and produce string is empty.
230 return true;
233 /// Verify - Verify that a type descriptor is well formed.
234 bool DIType::Verify() const {
235 if (isNull())
236 return false;
237 if (getContext().isNull())
238 return false;
240 DICompileUnit CU = getCompileUnit();
241 if (!CU.isNull() && !CU.Verify())
242 return false;
243 return true;
246 /// Verify - Verify that a composite type descriptor is well formed.
247 bool DICompositeType::Verify() const {
248 if (isNull())
249 return false;
250 if (getContext().isNull())
251 return false;
253 DICompileUnit CU = getCompileUnit();
254 if (!CU.isNull() && !CU.Verify())
255 return false;
256 return true;
259 /// Verify - Verify that a subprogram descriptor is well formed.
260 bool DISubprogram::Verify() const {
261 if (isNull())
262 return false;
264 if (getContext().isNull())
265 return false;
267 DICompileUnit CU = getCompileUnit();
268 if (!CU.Verify())
269 return false;
271 DICompositeType Ty = getType();
272 if (!Ty.isNull() && !Ty.Verify())
273 return false;
274 return true;
277 /// Verify - Verify that a global variable descriptor is well formed.
278 bool DIGlobalVariable::Verify() const {
279 if (isNull())
280 return false;
282 if (getContext().isNull())
283 return false;
285 DICompileUnit CU = getCompileUnit();
286 if (!CU.isNull() && !CU.Verify())
287 return false;
289 DIType Ty = getType();
290 if (!Ty.Verify())
291 return false;
293 if (!getGlobal())
294 return false;
296 return true;
299 /// Verify - Verify that a variable descriptor is well formed.
300 bool DIVariable::Verify() const {
301 if (isNull())
302 return false;
304 if (getContext().isNull())
305 return false;
307 DIType Ty = getType();
308 if (!Ty.Verify())
309 return false;
311 return true;
314 /// getOriginalTypeSize - If this type is derived from a base type then
315 /// return base type size.
316 uint64_t DIDerivedType::getOriginalTypeSize() const {
317 if (getTag() != dwarf::DW_TAG_member)
318 return getSizeInBits();
319 DIType BT = getTypeDerivedFrom();
320 if (BT.getTag() != dwarf::DW_TAG_base_type)
321 return getSizeInBits();
322 return BT.getSizeInBits();
325 /// describes - Return true if this subprogram provides debugging
326 /// information for the function F.
327 bool DISubprogram::describes(const Function *F) {
328 assert (F && "Invalid function");
329 std::string Name;
330 getLinkageName(Name);
331 if (Name.empty())
332 getName(Name);
333 if (F->getName() == Name)
334 return true;
335 return false;
338 //===----------------------------------------------------------------------===//
339 // DIDescriptor: dump routines for all descriptors.
340 //===----------------------------------------------------------------------===//
343 /// dump - Print descriptor.
344 void DIDescriptor::dump() const {
345 cerr << "[" << dwarf::TagString(getTag()) << "] ";
346 cerr << std::hex << "[GV:" << DbgGV << "]" << std::dec;
349 /// dump - Print compile unit.
350 void DICompileUnit::dump() const {
351 if (getLanguage())
352 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
354 std::string Res1, Res2;
355 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
358 /// dump - Print type.
359 void DIType::dump() const {
360 if (isNull()) return;
362 std::string Res;
363 if (!getName(Res).empty())
364 cerr << " [" << Res << "] ";
366 unsigned Tag = getTag();
367 cerr << " [" << dwarf::TagString(Tag) << "] ";
369 // TODO : Print context
370 getCompileUnit().dump();
371 cerr << " ["
372 << getLineNumber() << ", "
373 << getSizeInBits() << ", "
374 << getAlignInBits() << ", "
375 << getOffsetInBits()
376 << "] ";
378 if (isPrivate())
379 cerr << " [private] ";
380 else if (isProtected())
381 cerr << " [protected] ";
383 if (isForwardDecl())
384 cerr << " [fwd] ";
386 if (isBasicType(Tag))
387 DIBasicType(DbgGV).dump();
388 else if (isDerivedType(Tag))
389 DIDerivedType(DbgGV).dump();
390 else if (isCompositeType(Tag))
391 DICompositeType(DbgGV).dump();
392 else {
393 cerr << "Invalid DIType\n";
394 return;
397 cerr << "\n";
400 /// dump - Print basic type.
401 void DIBasicType::dump() const {
402 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
405 /// dump - Print derived type.
406 void DIDerivedType::dump() const {
407 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
410 /// dump - Print composite type.
411 void DICompositeType::dump() const {
412 DIArray A = getTypeArray();
413 if (A.isNull())
414 return;
415 cerr << " [" << A.getNumElements() << " elements]";
418 /// dump - Print global.
419 void DIGlobal::dump() const {
420 std::string Res;
421 if (!getName(Res).empty())
422 cerr << " [" << Res << "] ";
424 unsigned Tag = getTag();
425 cerr << " [" << dwarf::TagString(Tag) << "] ";
427 // TODO : Print context
428 getCompileUnit().dump();
429 cerr << " [" << getLineNumber() << "] ";
431 if (isLocalToUnit())
432 cerr << " [local] ";
434 if (isDefinition())
435 cerr << " [def] ";
437 if (isGlobalVariable(Tag))
438 DIGlobalVariable(DbgGV).dump();
440 cerr << "\n";
443 /// dump - Print subprogram.
444 void DISubprogram::dump() const {
445 DIGlobal::dump();
448 /// dump - Print global variable.
449 void DIGlobalVariable::dump() const {
450 cerr << " ["; getGlobal()->dump(); cerr << "] ";
453 /// dump - Print variable.
454 void DIVariable::dump() const {
455 std::string Res;
456 if (!getName(Res).empty())
457 cerr << " [" << Res << "] ";
459 getCompileUnit().dump();
460 cerr << " [" << getLineNumber() << "] ";
461 getType().dump();
462 cerr << "\n";
465 //===----------------------------------------------------------------------===//
466 // DIFactory: Basic Helpers
467 //===----------------------------------------------------------------------===//
469 DIFactory::DIFactory(Module &m)
470 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
471 RegionStartFn(0), RegionEndFn(0),
472 DeclareFn(0) {
473 EmptyStructPtr = VMContext.getPointerTypeUnqual(VMContext.getStructType());
476 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
477 /// This is only valid when the descriptor is non-null.
478 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
479 if (D.isNull()) return VMContext.getNullValue(EmptyStructPtr);
480 return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
483 Constant *DIFactory::GetTagConstant(unsigned TAG) {
484 assert((TAG & LLVMDebugVersionMask) == 0 &&
485 "Tag too large for debug encoding!");
486 return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
489 Constant *DIFactory::GetStringConstant(const std::string &String) {
490 // Check string cache for previous edition.
491 Constant *&Slot = StringCache[String];
493 // Return Constant if previously defined.
494 if (Slot) return Slot;
496 const PointerType *DestTy = VMContext.getPointerTypeUnqual(Type::Int8Ty);
498 // If empty string then use a i8* null instead.
499 if (String.empty())
500 return Slot = VMContext.getConstantPointerNull(DestTy);
502 // Construct string as an llvm constant.
503 Constant *ConstStr = ConstantArray::get(String);
505 // Otherwise create and return a new string global.
506 GlobalVariable *StrGV = new GlobalVariable(M, ConstStr->getType(), true,
507 GlobalVariable::InternalLinkage,
508 ConstStr, ".str");
509 StrGV->setSection("llvm.metadata");
510 return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
513 //===----------------------------------------------------------------------===//
514 // DIFactory: Primary Constructors
515 //===----------------------------------------------------------------------===//
517 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
518 /// This implicitly uniques the arrays created.
519 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
520 SmallVector<Constant*, 16> Elts;
522 for (unsigned i = 0; i != NumTys; ++i)
523 Elts.push_back(getCastToEmpty(Tys[i]));
525 Constant *Init = ConstantArray::get(VMContext.getArrayType(EmptyStructPtr,
526 Elts.size()),
527 Elts.data(), Elts.size());
528 // If we already have this array, just return the uniqued version.
529 DIDescriptor &Entry = SimpleConstantCache[Init];
530 if (!Entry.isNull()) return DIArray(Entry.getGV());
532 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
533 GlobalValue::InternalLinkage,
534 Init, "llvm.dbg.array");
535 GV->setSection("llvm.metadata");
536 Entry = DIDescriptor(GV);
537 return DIArray(GV);
540 /// GetOrCreateSubrange - Create a descriptor for a value range. This
541 /// implicitly uniques the values returned.
542 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
543 Constant *Elts[] = {
544 GetTagConstant(dwarf::DW_TAG_subrange_type),
545 ConstantInt::get(Type::Int64Ty, Lo),
546 ConstantInt::get(Type::Int64Ty, Hi)
549 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
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());
555 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
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);
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 ConstantInt::get(Type::Int32Ty, LangID),
581 GetStringConstant(Filename),
582 GetStringConstant(Directory),
583 GetStringConstant(Producer),
584 ConstantInt::get(Type::Int1Ty, isMain),
585 ConstantInt::get(Type::Int1Ty, isOptimized),
586 GetStringConstant(Flags),
587 ConstantInt::get(Type::Int32Ty, RunTimeVer)
590 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
592 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
593 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
594 GlobalValue::LinkOnceAnyLinkage,
595 Init, "llvm.dbg.compile_unit");
596 GV->setSection("llvm.metadata");
597 return DICompileUnit(GV);
600 /// CreateEnumerator - Create a single enumerator value.
601 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
602 Constant *Elts[] = {
603 GetTagConstant(dwarf::DW_TAG_enumerator),
604 GetStringConstant(Name),
605 ConstantInt::get(Type::Int64Ty, Val)
608 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
610 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
611 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
612 GlobalValue::InternalLinkage,
613 Init, "llvm.dbg.enumerator");
614 GV->setSection("llvm.metadata");
615 return DIEnumerator(GV);
619 /// CreateBasicType - Create a basic type like int, float, etc.
620 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
621 const std::string &Name,
622 DICompileUnit CompileUnit,
623 unsigned LineNumber,
624 uint64_t SizeInBits,
625 uint64_t AlignInBits,
626 uint64_t OffsetInBits, unsigned Flags,
627 unsigned Encoding) {
628 Constant *Elts[] = {
629 GetTagConstant(dwarf::DW_TAG_base_type),
630 getCastToEmpty(Context),
631 GetStringConstant(Name),
632 getCastToEmpty(CompileUnit),
633 ConstantInt::get(Type::Int32Ty, LineNumber),
634 ConstantInt::get(Type::Int64Ty, SizeInBits),
635 ConstantInt::get(Type::Int64Ty, AlignInBits),
636 ConstantInt::get(Type::Int64Ty, OffsetInBits),
637 ConstantInt::get(Type::Int32Ty, Flags),
638 ConstantInt::get(Type::Int32Ty, Encoding)
641 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
643 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
644 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
645 GlobalValue::InternalLinkage,
646 Init, "llvm.dbg.basictype");
647 GV->setSection("llvm.metadata");
648 return DIBasicType(GV);
651 /// CreateDerivedType - Create a derived type like const qualified type,
652 /// pointer, typedef, etc.
653 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
654 DIDescriptor Context,
655 const std::string &Name,
656 DICompileUnit CompileUnit,
657 unsigned LineNumber,
658 uint64_t SizeInBits,
659 uint64_t AlignInBits,
660 uint64_t OffsetInBits,
661 unsigned Flags,
662 DIType DerivedFrom) {
663 Constant *Elts[] = {
664 GetTagConstant(Tag),
665 getCastToEmpty(Context),
666 GetStringConstant(Name),
667 getCastToEmpty(CompileUnit),
668 ConstantInt::get(Type::Int32Ty, LineNumber),
669 ConstantInt::get(Type::Int64Ty, SizeInBits),
670 ConstantInt::get(Type::Int64Ty, AlignInBits),
671 ConstantInt::get(Type::Int64Ty, OffsetInBits),
672 ConstantInt::get(Type::Int32Ty, Flags),
673 getCastToEmpty(DerivedFrom)
676 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
678 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
679 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
680 GlobalValue::InternalLinkage,
681 Init, "llvm.dbg.derivedtype");
682 GV->setSection("llvm.metadata");
683 return DIDerivedType(GV);
686 /// CreateCompositeType - Create a composite type like array, struct, etc.
687 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
688 DIDescriptor Context,
689 const std::string &Name,
690 DICompileUnit CompileUnit,
691 unsigned LineNumber,
692 uint64_t SizeInBits,
693 uint64_t AlignInBits,
694 uint64_t OffsetInBits,
695 unsigned Flags,
696 DIType DerivedFrom,
697 DIArray Elements,
698 unsigned RuntimeLang) {
700 Constant *Elts[] = {
701 GetTagConstant(Tag),
702 getCastToEmpty(Context),
703 GetStringConstant(Name),
704 getCastToEmpty(CompileUnit),
705 ConstantInt::get(Type::Int32Ty, LineNumber),
706 ConstantInt::get(Type::Int64Ty, SizeInBits),
707 ConstantInt::get(Type::Int64Ty, AlignInBits),
708 ConstantInt::get(Type::Int64Ty, OffsetInBits),
709 ConstantInt::get(Type::Int32Ty, Flags),
710 getCastToEmpty(DerivedFrom),
711 getCastToEmpty(Elements),
712 ConstantInt::get(Type::Int32Ty, RuntimeLang)
715 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
717 M.addTypeName("llvm.dbg.composite.type", Init->getType());
718 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
719 GlobalValue::InternalLinkage,
720 Init, "llvm.dbg.composite");
721 GV->setSection("llvm.metadata");
722 return DICompositeType(GV);
726 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
727 /// See comments in DISubprogram for descriptions of these fields. This
728 /// method does not unique the generated descriptors.
729 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
730 const std::string &Name,
731 const std::string &DisplayName,
732 const std::string &LinkageName,
733 DICompileUnit CompileUnit,
734 unsigned LineNo, DIType Type,
735 bool isLocalToUnit,
736 bool isDefinition) {
738 Constant *Elts[] = {
739 GetTagConstant(dwarf::DW_TAG_subprogram),
740 VMContext.getNullValue(EmptyStructPtr),
741 getCastToEmpty(Context),
742 GetStringConstant(Name),
743 GetStringConstant(DisplayName),
744 GetStringConstant(LinkageName),
745 getCastToEmpty(CompileUnit),
746 ConstantInt::get(Type::Int32Ty, LineNo),
747 getCastToEmpty(Type),
748 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
749 ConstantInt::get(Type::Int1Ty, isDefinition)
752 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
754 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
755 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
756 GlobalValue::LinkOnceAnyLinkage,
757 Init, "llvm.dbg.subprogram");
758 GV->setSection("llvm.metadata");
759 return DISubprogram(GV);
762 /// CreateGlobalVariable - Create a new descriptor for the specified global.
763 DIGlobalVariable
764 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
765 const std::string &DisplayName,
766 const std::string &LinkageName,
767 DICompileUnit CompileUnit,
768 unsigned LineNo, DIType Type,bool isLocalToUnit,
769 bool isDefinition, llvm::GlobalVariable *Val) {
770 Constant *Elts[] = {
771 GetTagConstant(dwarf::DW_TAG_variable),
772 VMContext.getNullValue(EmptyStructPtr),
773 getCastToEmpty(Context),
774 GetStringConstant(Name),
775 GetStringConstant(DisplayName),
776 GetStringConstant(LinkageName),
777 getCastToEmpty(CompileUnit),
778 ConstantInt::get(Type::Int32Ty, LineNo),
779 getCastToEmpty(Type),
780 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
781 ConstantInt::get(Type::Int1Ty, isDefinition),
782 ConstantExpr::getBitCast(Val, EmptyStructPtr)
785 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
787 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
788 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
789 GlobalValue::LinkOnceAnyLinkage,
790 Init, "llvm.dbg.global_variable");
791 GV->setSection("llvm.metadata");
792 return DIGlobalVariable(GV);
796 /// CreateVariable - Create a new descriptor for the specified variable.
797 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
798 const std::string &Name,
799 DICompileUnit CompileUnit, unsigned LineNo,
800 DIType Type) {
801 Constant *Elts[] = {
802 GetTagConstant(Tag),
803 getCastToEmpty(Context),
804 GetStringConstant(Name),
805 getCastToEmpty(CompileUnit),
806 ConstantInt::get(Type::Int32Ty, LineNo),
807 getCastToEmpty(Type)
810 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
812 M.addTypeName("llvm.dbg.variable.type", Init->getType());
813 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
814 GlobalValue::InternalLinkage,
815 Init, "llvm.dbg.variable");
816 GV->setSection("llvm.metadata");
817 return DIVariable(GV);
821 /// CreateBlock - This creates a descriptor for a lexical block with the
822 /// specified parent VMContext.
823 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
824 Constant *Elts[] = {
825 GetTagConstant(dwarf::DW_TAG_lexical_block),
826 getCastToEmpty(Context)
829 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
831 M.addTypeName("llvm.dbg.block.type", Init->getType());
832 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
833 GlobalValue::InternalLinkage,
834 Init, "llvm.dbg.block");
835 GV->setSection("llvm.metadata");
836 return DIBlock(GV);
840 //===----------------------------------------------------------------------===//
841 // DIFactory: Routines for inserting code into a function
842 //===----------------------------------------------------------------------===//
844 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
845 /// inserting it at the end of the specified basic block.
846 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
847 unsigned ColNo, BasicBlock *BB) {
849 // Lazily construct llvm.dbg.stoppoint function.
850 if (!StopPointFn)
851 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
852 llvm::Intrinsic::dbg_stoppoint);
854 // Invoke llvm.dbg.stoppoint
855 Value *Args[] = {
856 ConstantInt::get(llvm::Type::Int32Ty, LineNo),
857 ConstantInt::get(llvm::Type::Int32Ty, ColNo),
858 getCastToEmpty(CU)
860 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
863 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
864 /// mark the start of the specified subprogram.
865 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
866 // Lazily construct llvm.dbg.func.start.
867 if (!FuncStartFn)
868 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
870 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
871 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
874 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
875 /// mark the start of a region for the specified scoping descriptor.
876 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
877 // Lazily construct llvm.dbg.region.start function.
878 if (!RegionStartFn)
879 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
881 // Call llvm.dbg.func.start.
882 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
885 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
886 /// mark the end of a region for the specified scoping descriptor.
887 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
888 // Lazily construct llvm.dbg.region.end function.
889 if (!RegionEndFn)
890 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
892 // Call llvm.dbg.region.end.
893 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
896 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
897 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
898 // Cast the storage to a {}* for the call to llvm.dbg.declare.
899 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
901 if (!DeclareFn)
902 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
904 Value *Args[] = { Storage, getCastToEmpty(D) };
905 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
908 //===----------------------------------------------------------------------===//
909 // DebugInfoEnumerator implementations.
910 //===----------------------------------------------------------------------===//
912 /// enumerateModule - Enumerate entire module and collect debug info.
913 void DebugInfoEnumerator::enumerateModule(Module &M) {
915 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
916 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
917 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
918 ++BI) {
919 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
920 enumerateStopPoint(SPI);
921 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
922 enumerateFuncStart(FSI);
925 for (Module::global_iterator GVI = M.global_begin(), GVE = M.global_end();
926 GVI != GVE; ++GVI) {
927 GlobalVariable *GV = GVI;
928 if (!GV->hasName() || !GV->isConstant()
929 || strcmp(GV->getName().data(), "llvm.dbg.global_variable")
930 || !GV->hasInitializer())
931 continue;
932 DIGlobalVariable DIG(GV);
933 if (addGlobalVariable(DIG)) {
934 addCompileUnit(DIG.getCompileUnit());
935 enumerateType(DIG.getType());
940 /// enumerateType - Enumerate DIType.
941 void DebugInfoEnumerator::enumerateType(DIType DT) {
942 if (DT.isNull())
943 return;
944 if (!NodesSeen.insert(DT.getGV()))
945 return;
947 addCompileUnit(DT.getCompileUnit());
948 if (DT.isCompositeType(DT.getTag())) {
949 DICompositeType DCT(DT.getGV());
950 enumerateType(DCT.getTypeDerivedFrom());
951 DIArray DA = DCT.getTypeArray();
952 if (!DA.isNull())
953 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
954 DIDescriptor D = DA.getElement(i);
955 DIType TypeE = DIType(D.getGV());
956 if (!TypeE.isNull())
957 enumerateType(TypeE);
958 else
959 enumerateSubprogram(DISubprogram(D.getGV()));
961 } else if (DT.isDerivedType(DT.getTag())) {
962 DIDerivedType DDT(DT.getGV());
963 if (!DDT.isNull())
964 enumerateType(DDT.getTypeDerivedFrom());
968 /// enumerateSubprogram - Enumberate DISubprogram.
969 void DebugInfoEnumerator::enumerateSubprogram(DISubprogram SP) {
970 if (!addSubprogram(SP))
971 return;
972 addCompileUnit(SP.getCompileUnit());
973 enumerateType(SP.getType());
976 /// enumerateStopPoint - Enumerate DbgStopPointInst.
977 void DebugInfoEnumerator::enumerateStopPoint(DbgStopPointInst *SPI) {
978 GlobalVariable *Context = dyn_cast<GlobalVariable>(SPI->getContext());
979 addCompileUnit(DICompileUnit(Context));
982 /// enumerateFuncStart - Enumberate DbgFuncStartInst.
983 void DebugInfoEnumerator::enumerateFuncStart(DbgFuncStartInst *FSI) {
984 GlobalVariable *SP = dyn_cast<GlobalVariable>(FSI->getSubprogram());
985 enumerateSubprogram(DISubprogram(SP));
988 /// addCompileUnit - Add compile unit into CUs.
989 bool DebugInfoEnumerator::addCompileUnit(DICompileUnit CU) {
990 if (CU.isNull())
991 return false;
993 if (!NodesSeen.insert(CU.getGV()))
994 return false;
996 CUs.push_back(CU.getGV());
997 return true;
1000 /// addGlobalVariable - Add global variable into GVs.
1001 bool DebugInfoEnumerator::addGlobalVariable(DIGlobalVariable DIG) {
1002 if (DIG.isNull())
1003 return false;
1005 if (!NodesSeen.insert(DIG.getGV()))
1006 return false;
1008 GVs.push_back(DIG.getGV());
1009 return true;
1012 // addSubprogram - Add subprgoram into SPs.
1013 bool DebugInfoEnumerator::addSubprogram(DISubprogram SP) {
1014 if (SP.isNull())
1015 return false;
1017 if (!NodesSeen.insert(SP.getGV()))
1018 return false;
1020 SPs.push_back(SP.getGV());
1021 return true;
1024 namespace llvm {
1025 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1026 /// is the stoppoint that dominates this instruction.
1027 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1028 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1029 return DSI;
1031 const BasicBlock *BB = Inst->getParent();
1032 BasicBlock::const_iterator I = Inst, B;
1033 while (BB) {
1034 B = BB->begin();
1036 // A BB consisting only of a terminator can't have a stoppoint.
1037 while (I != B) {
1038 --I;
1039 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1040 return DSI;
1043 // This BB didn't have a stoppoint: if there is only one predecessor, look
1044 // for a stoppoint there. We could use getIDom(), but that would require
1045 // dominator info.
1046 BB = I->getParent()->getUniquePredecessor();
1047 if (BB)
1048 I = BB->getTerminator();
1051 return 0;
1054 /// findBBStopPoint - Find the stoppoint corresponding to first real
1055 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1056 /// stoppoint for it.
1057 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1058 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1059 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1060 return DSI;
1062 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1063 // BB contains no stoppoints, but unique predecessor does.
1064 BB = BB->getUniquePredecessor();
1065 if (BB)
1066 return findStopPoint(BB->getTerminator());
1068 return 0;
1071 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1072 const Module *M = V->getParent();
1073 LLVMContext& Context = M->getContext();
1075 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
1076 if (!Ty) return 0;
1078 Ty = Context.getPointerType(Ty, 0);
1080 Value *Val = V->stripPointerCasts();
1081 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
1082 I != E; ++I) {
1083 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
1084 if (CE->getOpcode() == Instruction::BitCast) {
1085 Value *VV = CE;
1087 while (VV->hasOneUse())
1088 VV = *VV->use_begin();
1090 if (VV->getType() == Ty)
1091 return VV;
1096 if (Val->getType() == Ty)
1097 return Val;
1099 return 0;
1102 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1103 /// It looks through pointer casts too.
1104 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1105 if (stripCasts) {
1106 V = V->stripPointerCasts();
1108 // Look for the bitcast.
1109 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1110 I != E; ++I)
1111 if (isa<BitCastInst>(I))
1112 return findDbgDeclare(*I, false);
1114 return 0;
1117 // Find llvm.dbg.declare among uses of the instruction.
1118 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1119 I != E; ++I)
1120 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1121 return DDI;
1123 return 0;
1126 bool getLocationInfo(const Value *V, std::string &DisplayName,
1127 std::string &Type, unsigned &LineNo, std::string &File,
1128 std::string &Dir) {
1129 DICompileUnit Unit;
1130 DIType TypeD;
1132 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1133 Value *DIGV = findDbgGlobalDeclare(GV);
1134 if (!DIGV) return false;
1135 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1137 Var.getDisplayName(DisplayName);
1138 LineNo = Var.getLineNumber();
1139 Unit = Var.getCompileUnit();
1140 TypeD = Var.getType();
1141 } else {
1142 const DbgDeclareInst *DDI = findDbgDeclare(V);
1143 if (!DDI) return false;
1144 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1146 Var.getName(DisplayName);
1147 LineNo = Var.getLineNumber();
1148 Unit = Var.getCompileUnit();
1149 TypeD = Var.getType();
1152 TypeD.getName(Type);
1153 Unit.getFilename(File);
1154 Unit.getDirectory(Dir);
1155 return true;
1158 /// CollectDebugInfoAnchors - Collect debugging information anchors.
1159 void CollectDebugInfoAnchors(Module &M,
1160 SmallVector<GlobalVariable *, 2> &CUs,
1161 SmallVector<GlobalVariable *, 4> &GVs,
1162 SmallVector<GlobalVariable *, 4> &SPs) {
1164 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1165 GVI != E; GVI++) {
1166 GlobalVariable *GV = GVI;
1167 if (GV->hasName() && GV->getName().startswith("llvm.dbg")
1168 && GV->isConstant() && GV->hasInitializer()) {
1169 DICompileUnit C(GV);
1170 if (C.isNull() == false) {
1171 CUs.push_back(GV);
1172 continue;
1174 DIGlobalVariable G(GV);
1175 if (G.isNull() == false) {
1176 GVs.push_back(GV);
1177 continue;
1179 DISubprogram S(GV);
1180 if (S.isNull() == false) {
1181 SPs.push_back(GV);
1182 continue;
1188 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1189 /// info intrinsic.
1190 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1191 CodeGenOpt::Level OptLev) {
1192 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1195 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1196 /// info intrinsic.
1197 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1198 CodeGenOpt::Level OptLev) {
1199 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1202 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1203 /// info intrinsic.
1204 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1205 CodeGenOpt::Level OptLev) {
1206 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1209 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1210 /// info intrinsic.
1211 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1212 CodeGenOpt::Level OptLev) {
1213 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1217 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1218 /// info intrinsic.
1219 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1220 CodeGenOpt::Level OptLev) {
1221 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1224 /// ExtractDebugLocation - Extract debug location information
1225 /// from llvm.dbg.stoppoint intrinsic.
1226 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1227 DebugLocTracker &DebugLocInfo) {
1228 DebugLoc DL;
1229 Value *Context = SPI.getContext();
1231 // If this location is already tracked then use it.
1232 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
1233 SPI.getColumn());
1234 DenseMap<DebugLocTuple, unsigned>::iterator II
1235 = DebugLocInfo.DebugIdMap.find(Tuple);
1236 if (II != DebugLocInfo.DebugIdMap.end())
1237 return DebugLoc::get(II->second);
1239 // Add a new location entry.
1240 unsigned Id = DebugLocInfo.DebugLocations.size();
1241 DebugLocInfo.DebugLocations.push_back(Tuple);
1242 DebugLocInfo.DebugIdMap[Tuple] = Id;
1244 return DebugLoc::get(Id);
1247 /// ExtractDebugLocation - Extract debug location information
1248 /// from llvm.dbg.func_start intrinsic.
1249 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1250 DebugLocTracker &DebugLocInfo) {
1251 DebugLoc DL;
1252 Value *SP = FSI.getSubprogram();
1254 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1255 unsigned Line = Subprogram.getLineNumber();
1256 DICompileUnit CU(Subprogram.getCompileUnit());
1258 // If this location is already tracked then use it.
1259 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1260 DenseMap<DebugLocTuple, unsigned>::iterator II
1261 = DebugLocInfo.DebugIdMap.find(Tuple);
1262 if (II != DebugLocInfo.DebugIdMap.end())
1263 return DebugLoc::get(II->second);
1265 // Add a new location entry.
1266 unsigned Id = DebugLocInfo.DebugLocations.size();
1267 DebugLocInfo.DebugLocations.push_back(Tuple);
1268 DebugLocInfo.DebugIdMap[Tuple] = Id;
1270 return DebugLoc::get(Id);
1273 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1274 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1275 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1276 if (Subprogram.describes(CurrentFn))
1277 return false;
1279 return true;
1282 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1283 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1284 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1285 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))
1286 return false;
1288 return true;