1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/DebugLoc.h"
25 #include "llvm/Support/Streams.h"
28 using namespace llvm::dwarf;
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 /// ValidDebugInfo - Return true if V represents valid debug info value.
35 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
39 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
43 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
48 // Check current version. Allow Version6 for now.
49 unsigned Version = DI.getVersion();
50 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
53 unsigned Tag = DI.getTag();
56 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
58 case DW_TAG_compile_unit:
59 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
61 case DW_TAG_subprogram:
62 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
64 case DW_TAG_lexical_block:
65 // FIXME: This interfers with the quality of generated code during
67 if (OptLevel != CodeGenOpt::None)
77 DIDescriptor::DIDescriptor(GlobalVariable *GV, unsigned RequiredTag) {
80 // If this is non-null, check to see if the Tag matches. If not, set to null.
81 if (GV && getTag() != RequiredTag)
86 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
92 Constant *C = DbgGV->getInitializer();
93 if (C == 0 || Elt >= C->getNumOperands()) {
98 // Fills in the string if it succeeds
99 if (!GetConstantStringInfo(C->getOperand(Elt), Result))
105 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
106 if (DbgGV == 0) return 0;
108 Constant *C = DbgGV->getInitializer();
109 if (C == 0 || Elt >= C->getNumOperands())
112 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
113 return CI->getZExtValue();
117 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
118 if (DbgGV == 0) return DIDescriptor();
120 Constant *C = DbgGV->getInitializer();
121 if (C == 0 || Elt >= C->getNumOperands())
122 return DIDescriptor();
124 C = C->getOperand(Elt);
125 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
128 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
129 if (DbgGV == 0) return 0;
131 Constant *C = DbgGV->getInitializer();
132 if (C == 0 || Elt >= C->getNumOperands())
135 C = C->getOperand(Elt);
136 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
139 //===----------------------------------------------------------------------===//
140 // Simple Descriptor Constructors and other Methods
141 //===----------------------------------------------------------------------===//
143 // Needed by DIVariable::getType().
144 DIType::DIType(GlobalVariable *GV) : DIDescriptor(GV) {
146 unsigned tag = getTag();
147 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
148 !DICompositeType::isCompositeType(tag))
152 /// isDerivedType - Return true if the specified tag is legal for
154 bool DIType::isDerivedType(unsigned Tag) {
156 case dwarf::DW_TAG_typedef:
157 case dwarf::DW_TAG_pointer_type:
158 case dwarf::DW_TAG_reference_type:
159 case dwarf::DW_TAG_const_type:
160 case dwarf::DW_TAG_volatile_type:
161 case dwarf::DW_TAG_restrict_type:
162 case dwarf::DW_TAG_member:
163 case dwarf::DW_TAG_inheritance:
166 // FIXME: Even though it doesn't make sense, CompositeTypes are current
167 // modelled as DerivedTypes, this should return true for them as well.
172 /// isCompositeType - Return true if the specified tag is legal for
174 bool DIType::isCompositeType(unsigned TAG) {
176 case dwarf::DW_TAG_array_type:
177 case dwarf::DW_TAG_structure_type:
178 case dwarf::DW_TAG_union_type:
179 case dwarf::DW_TAG_enumeration_type:
180 case dwarf::DW_TAG_vector_type:
181 case dwarf::DW_TAG_subroutine_type:
182 case dwarf::DW_TAG_class_type:
189 /// isVariable - Return true if the specified tag is legal for DIVariable.
190 bool DIVariable::isVariable(unsigned Tag) {
192 case dwarf::DW_TAG_auto_variable:
193 case dwarf::DW_TAG_arg_variable:
194 case dwarf::DW_TAG_return_variable:
201 unsigned DIArray::getNumElements() const {
202 assert (DbgGV && "Invalid DIArray");
203 Constant *C = DbgGV->getInitializer();
204 assert (C && "Invalid DIArray initializer");
205 return C->getNumOperands();
208 /// Verify - Verify that a compile unit is well formed.
209 bool DICompileUnit::Verify() const {
213 if (getFilename(Res).empty())
215 // It is possible that directory and produce string is empty.
219 /// Verify - Verify that a type descriptor is well formed.
220 bool DIType::Verify() const {
223 if (getContext().isNull())
226 DICompileUnit CU = getCompileUnit();
227 if (!CU.isNull() && !CU.Verify())
232 /// Verify - Verify that a composite type descriptor is well formed.
233 bool DICompositeType::Verify() const {
236 if (getContext().isNull())
239 DICompileUnit CU = getCompileUnit();
240 if (!CU.isNull() && !CU.Verify())
245 /// Verify - Verify that a subprogram descriptor is well formed.
246 bool DISubprogram::Verify() const {
250 if (getContext().isNull())
253 DICompileUnit CU = getCompileUnit();
257 DICompositeType Ty = getType();
258 if (!Ty.isNull() && !Ty.Verify())
263 /// Verify - Verify that a global variable descriptor is well formed.
264 bool DIGlobalVariable::Verify() const {
268 if (getContext().isNull())
271 DICompileUnit CU = getCompileUnit();
272 if (!CU.isNull() && !CU.Verify())
275 DIType Ty = getType();
285 /// Verify - Verify that a variable descriptor is well formed.
286 bool DIVariable::Verify() const {
290 if (getContext().isNull())
293 DIType Ty = getType();
300 /// getOriginalTypeSize - If this type is derived from a base type then
301 /// return base type size.
302 uint64_t DIDerivedType::getOriginalTypeSize() const {
303 if (getTag() != dwarf::DW_TAG_member)
304 return getSizeInBits();
305 DIType BT = getTypeDerivedFrom();
306 if (BT.getTag() != dwarf::DW_TAG_base_type)
307 return getSizeInBits();
308 return BT.getSizeInBits();
311 /// describes - Return true if this subprogram provides debugging
312 /// information for the function F.
313 bool DISubprogram::describes(const Function *F) {
314 assert (F && "Invalid function");
316 getLinkageName(Name);
319 if (!Name.empty() && (strcmp(Name.c_str(), F->getNameStart()) == false))
324 //===----------------------------------------------------------------------===//
325 // DIDescriptor: dump routines for all descriptors.
326 //===----------------------------------------------------------------------===//
329 /// dump - Print descriptor.
330 void DIDescriptor::dump() const {
331 cerr << "[" << dwarf::TagString(getTag()) << "] ";
332 cerr << std::hex << "[GV:" << DbgGV << "]" << std::dec;
335 /// dump - Print compile unit.
336 void DICompileUnit::dump() const {
338 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
340 std::string Res1, Res2;
341 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
344 /// dump - Print type.
345 void DIType::dump() const {
346 if (isNull()) return;
349 if (!getName(Res).empty())
350 cerr << " [" << Res << "] ";
352 unsigned Tag = getTag();
353 cerr << " [" << dwarf::TagString(Tag) << "] ";
355 // TODO : Print context
356 getCompileUnit().dump();
358 << getLineNumber() << ", "
359 << getSizeInBits() << ", "
360 << getAlignInBits() << ", "
365 cerr << " [private] ";
366 else if (isProtected())
367 cerr << " [protected] ";
372 if (isBasicType(Tag))
373 DIBasicType(DbgGV).dump();
374 else if (isDerivedType(Tag))
375 DIDerivedType(DbgGV).dump();
376 else if (isCompositeType(Tag))
377 DICompositeType(DbgGV).dump();
379 cerr << "Invalid DIType\n";
386 /// dump - Print basic type.
387 void DIBasicType::dump() const {
388 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
391 /// dump - Print derived type.
392 void DIDerivedType::dump() const {
393 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
396 /// dump - Print composite type.
397 void DICompositeType::dump() const {
398 DIArray A = getTypeArray();
401 cerr << " [" << A.getNumElements() << " elements]";
404 /// dump - Print global.
405 void DIGlobal::dump() const {
407 if (!getName(Res).empty())
408 cerr << " [" << Res << "] ";
410 unsigned Tag = getTag();
411 cerr << " [" << dwarf::TagString(Tag) << "] ";
413 // TODO : Print context
414 getCompileUnit().dump();
415 cerr << " [" << getLineNumber() << "] ";
423 if (isGlobalVariable(Tag))
424 DIGlobalVariable(DbgGV).dump();
429 /// dump - Print subprogram.
430 void DISubprogram::dump() const {
434 /// dump - Print global variable.
435 void DIGlobalVariable::dump() const {
436 cerr << " ["; getGlobal()->dump(); cerr << "] ";
439 /// dump - Print variable.
440 void DIVariable::dump() const {
442 if (!getName(Res).empty())
443 cerr << " [" << Res << "] ";
445 getCompileUnit().dump();
446 cerr << " [" << getLineNumber() << "] ";
451 //===----------------------------------------------------------------------===//
452 // DIFactory: Basic Helpers
453 //===----------------------------------------------------------------------===//
455 DIFactory::DIFactory(Module &m)
456 : M(m), StopPointFn(0), FuncStartFn(0), RegionStartFn(0), RegionEndFn(0),
458 EmptyStructPtr = PointerType::getUnqual(StructType::get());
461 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
462 /// This is only valid when the descriptor is non-null.
463 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
464 if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
465 return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
468 Constant *DIFactory::GetTagConstant(unsigned TAG) {
469 assert((TAG & LLVMDebugVersionMask) == 0 &&
470 "Tag too large for debug encoding!");
471 return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
474 Constant *DIFactory::GetStringConstant(const std::string &String) {
475 // Check string cache for previous edition.
476 Constant *&Slot = StringCache[String];
478 // Return Constant if previously defined.
479 if (Slot) return Slot;
481 const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
483 // If empty string then use a i8* null instead.
485 return Slot = ConstantPointerNull::get(DestTy);
487 // Construct string as an llvm constant.
488 Constant *ConstStr = ConstantArray::get(String);
490 // Otherwise create and return a new string global.
491 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
492 GlobalVariable::InternalLinkage,
493 ConstStr, ".str", &M);
494 StrGV->setSection("llvm.metadata");
495 return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
498 //===----------------------------------------------------------------------===//
499 // DIFactory: Primary Constructors
500 //===----------------------------------------------------------------------===//
502 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
503 /// This implicitly uniques the arrays created.
504 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
505 SmallVector<Constant*, 16> Elts;
507 for (unsigned i = 0; i != NumTys; ++i)
508 Elts.push_back(getCastToEmpty(Tys[i]));
510 Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
512 Elts.data(), Elts.size());
513 // If we already have this array, just return the uniqued version.
514 DIDescriptor &Entry = SimpleConstantCache[Init];
515 if (!Entry.isNull()) return DIArray(Entry.getGV());
517 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
518 GlobalValue::InternalLinkage,
519 Init, "llvm.dbg.array", &M);
520 GV->setSection("llvm.metadata");
521 Entry = DIDescriptor(GV);
525 /// GetOrCreateSubrange - Create a descriptor for a value range. This
526 /// implicitly uniques the values returned.
527 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
529 GetTagConstant(dwarf::DW_TAG_subrange_type),
530 ConstantInt::get(Type::Int64Ty, Lo),
531 ConstantInt::get(Type::Int64Ty, Hi)
534 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
536 // If we already have this range, just return the uniqued version.
537 DIDescriptor &Entry = SimpleConstantCache[Init];
538 if (!Entry.isNull()) return DISubrange(Entry.getGV());
540 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
542 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
543 GlobalValue::InternalLinkage,
544 Init, "llvm.dbg.subrange", &M);
545 GV->setSection("llvm.metadata");
546 Entry = DIDescriptor(GV);
547 return DISubrange(GV);
552 /// CreateCompileUnit - Create a new descriptor for the specified compile
553 /// unit. Note that this does not unique compile units within the module.
554 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
555 const std::string &Filename,
556 const std::string &Directory,
557 const std::string &Producer,
561 unsigned RunTimeVer) {
563 GetTagConstant(dwarf::DW_TAG_compile_unit),
564 Constant::getNullValue(EmptyStructPtr),
565 ConstantInt::get(Type::Int32Ty, LangID),
566 GetStringConstant(Filename),
567 GetStringConstant(Directory),
568 GetStringConstant(Producer),
569 ConstantInt::get(Type::Int1Ty, isMain),
570 ConstantInt::get(Type::Int1Ty, isOptimized),
571 GetStringConstant(Flags),
572 ConstantInt::get(Type::Int32Ty, RunTimeVer)
575 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
577 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
578 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
579 GlobalValue::LinkOnceAnyLinkage,
580 Init, "llvm.dbg.compile_unit", &M);
581 GV->setSection("llvm.metadata");
582 return DICompileUnit(GV);
585 /// CreateEnumerator - Create a single enumerator value.
586 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
588 GetTagConstant(dwarf::DW_TAG_enumerator),
589 GetStringConstant(Name),
590 ConstantInt::get(Type::Int64Ty, Val)
593 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
595 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
596 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
597 GlobalValue::InternalLinkage,
598 Init, "llvm.dbg.enumerator", &M);
599 GV->setSection("llvm.metadata");
600 return DIEnumerator(GV);
604 /// CreateBasicType - Create a basic type like int, float, etc.
605 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
606 const std::string &Name,
607 DICompileUnit CompileUnit,
610 uint64_t AlignInBits,
611 uint64_t OffsetInBits, unsigned Flags,
614 GetTagConstant(dwarf::DW_TAG_base_type),
615 getCastToEmpty(Context),
616 GetStringConstant(Name),
617 getCastToEmpty(CompileUnit),
618 ConstantInt::get(Type::Int32Ty, LineNumber),
619 ConstantInt::get(Type::Int64Ty, SizeInBits),
620 ConstantInt::get(Type::Int64Ty, AlignInBits),
621 ConstantInt::get(Type::Int64Ty, OffsetInBits),
622 ConstantInt::get(Type::Int32Ty, Flags),
623 ConstantInt::get(Type::Int32Ty, Encoding)
626 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
628 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
629 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
630 GlobalValue::InternalLinkage,
631 Init, "llvm.dbg.basictype", &M);
632 GV->setSection("llvm.metadata");
633 return DIBasicType(GV);
636 /// CreateDerivedType - Create a derived type like const qualified type,
637 /// pointer, typedef, etc.
638 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
639 DIDescriptor Context,
640 const std::string &Name,
641 DICompileUnit CompileUnit,
644 uint64_t AlignInBits,
645 uint64_t OffsetInBits,
647 DIType DerivedFrom) {
650 getCastToEmpty(Context),
651 GetStringConstant(Name),
652 getCastToEmpty(CompileUnit),
653 ConstantInt::get(Type::Int32Ty, LineNumber),
654 ConstantInt::get(Type::Int64Ty, SizeInBits),
655 ConstantInt::get(Type::Int64Ty, AlignInBits),
656 ConstantInt::get(Type::Int64Ty, OffsetInBits),
657 ConstantInt::get(Type::Int32Ty, Flags),
658 getCastToEmpty(DerivedFrom)
661 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
663 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
664 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
665 GlobalValue::InternalLinkage,
666 Init, "llvm.dbg.derivedtype", &M);
667 GV->setSection("llvm.metadata");
668 return DIDerivedType(GV);
671 /// CreateCompositeType - Create a composite type like array, struct, etc.
672 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
673 DIDescriptor Context,
674 const std::string &Name,
675 DICompileUnit CompileUnit,
678 uint64_t AlignInBits,
679 uint64_t OffsetInBits,
683 unsigned RuntimeLang) {
687 getCastToEmpty(Context),
688 GetStringConstant(Name),
689 getCastToEmpty(CompileUnit),
690 ConstantInt::get(Type::Int32Ty, LineNumber),
691 ConstantInt::get(Type::Int64Ty, SizeInBits),
692 ConstantInt::get(Type::Int64Ty, AlignInBits),
693 ConstantInt::get(Type::Int64Ty, OffsetInBits),
694 ConstantInt::get(Type::Int32Ty, Flags),
695 getCastToEmpty(DerivedFrom),
696 getCastToEmpty(Elements),
697 ConstantInt::get(Type::Int32Ty, RuntimeLang)
700 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
702 M.addTypeName("llvm.dbg.composite.type", Init->getType());
703 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
704 GlobalValue::InternalLinkage,
705 Init, "llvm.dbg.composite", &M);
706 GV->setSection("llvm.metadata");
707 return DICompositeType(GV);
711 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
712 /// See comments in DISubprogram for descriptions of these fields. This
713 /// method does not unique the generated descriptors.
714 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
715 const std::string &Name,
716 const std::string &DisplayName,
717 const std::string &LinkageName,
718 DICompileUnit CompileUnit,
719 unsigned LineNo, DIType Type,
724 GetTagConstant(dwarf::DW_TAG_subprogram),
725 Constant::getNullValue(EmptyStructPtr),
726 getCastToEmpty(Context),
727 GetStringConstant(Name),
728 GetStringConstant(DisplayName),
729 GetStringConstant(LinkageName),
730 getCastToEmpty(CompileUnit),
731 ConstantInt::get(Type::Int32Ty, LineNo),
732 getCastToEmpty(Type),
733 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
734 ConstantInt::get(Type::Int1Ty, isDefinition)
737 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
739 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
740 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
741 GlobalValue::LinkOnceAnyLinkage,
742 Init, "llvm.dbg.subprogram", &M);
743 GV->setSection("llvm.metadata");
744 return DISubprogram(GV);
747 /// CreateGlobalVariable - Create a new descriptor for the specified global.
749 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
750 const std::string &DisplayName,
751 const std::string &LinkageName,
752 DICompileUnit CompileUnit,
753 unsigned LineNo, DIType Type,bool isLocalToUnit,
754 bool isDefinition, llvm::GlobalVariable *Val) {
756 GetTagConstant(dwarf::DW_TAG_variable),
757 Constant::getNullValue(EmptyStructPtr),
758 getCastToEmpty(Context),
759 GetStringConstant(Name),
760 GetStringConstant(DisplayName),
761 GetStringConstant(LinkageName),
762 getCastToEmpty(CompileUnit),
763 ConstantInt::get(Type::Int32Ty, LineNo),
764 getCastToEmpty(Type),
765 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
766 ConstantInt::get(Type::Int1Ty, isDefinition),
767 ConstantExpr::getBitCast(Val, EmptyStructPtr)
770 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
772 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
773 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
774 GlobalValue::LinkOnceAnyLinkage,
775 Init, "llvm.dbg.global_variable", &M);
776 GV->setSection("llvm.metadata");
777 return DIGlobalVariable(GV);
781 /// CreateVariable - Create a new descriptor for the specified variable.
782 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
783 const std::string &Name,
784 DICompileUnit CompileUnit, unsigned LineNo,
788 getCastToEmpty(Context),
789 GetStringConstant(Name),
790 getCastToEmpty(CompileUnit),
791 ConstantInt::get(Type::Int32Ty, LineNo),
795 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
797 M.addTypeName("llvm.dbg.variable.type", Init->getType());
798 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
799 GlobalValue::InternalLinkage,
800 Init, "llvm.dbg.variable", &M);
801 GV->setSection("llvm.metadata");
802 return DIVariable(GV);
806 /// CreateBlock - This creates a descriptor for a lexical block with the
807 /// specified parent context.
808 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
810 GetTagConstant(dwarf::DW_TAG_lexical_block),
811 getCastToEmpty(Context)
814 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
816 M.addTypeName("llvm.dbg.block.type", Init->getType());
817 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
818 GlobalValue::InternalLinkage,
819 Init, "llvm.dbg.block", &M);
820 GV->setSection("llvm.metadata");
825 //===----------------------------------------------------------------------===//
826 // DIFactory: Routines for inserting code into a function
827 //===----------------------------------------------------------------------===//
829 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
830 /// inserting it at the end of the specified basic block.
831 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
832 unsigned ColNo, BasicBlock *BB) {
834 // Lazily construct llvm.dbg.stoppoint function.
836 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
837 llvm::Intrinsic::dbg_stoppoint);
839 // Invoke llvm.dbg.stoppoint
841 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
842 llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
845 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
848 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
849 /// mark the start of the specified subprogram.
850 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
851 // Lazily construct llvm.dbg.func.start.
853 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
855 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
856 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
859 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
860 /// mark the start of a region for the specified scoping descriptor.
861 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
862 // Lazily construct llvm.dbg.region.start function.
864 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
866 // Call llvm.dbg.func.start.
867 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
870 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
871 /// mark the end of a region for the specified scoping descriptor.
872 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
873 // Lazily construct llvm.dbg.region.end function.
875 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
877 // Call llvm.dbg.region.end.
878 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
881 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
882 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
883 // Cast the storage to a {}* for the call to llvm.dbg.declare.
884 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
887 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
889 Value *Args[] = { Storage, getCastToEmpty(D) };
890 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
894 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
895 /// is the stoppoint that dominates this instruction.
896 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
897 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
900 const BasicBlock *BB = Inst->getParent();
901 BasicBlock::const_iterator I = Inst, B;
905 // A BB consisting only of a terminator can't have a stoppoint.
908 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
912 // This BB didn't have a stoppoint: if there is only one predecessor, look
913 // for a stoppoint there. We could use getIDom(), but that would require
915 BB = I->getParent()->getUniquePredecessor();
917 I = BB->getTerminator();
923 /// findBBStopPoint - Find the stoppoint corresponding to first real
924 /// (non-debug intrinsic) instruction in this Basic Block, and return the
925 /// stoppoint for it.
926 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
927 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
928 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
931 // Fallback to looking for stoppoint of unique predecessor. Useful if this
932 // BB contains no stoppoints, but unique predecessor does.
933 BB = BB->getUniquePredecessor();
935 return findStopPoint(BB->getTerminator());
940 Value *findDbgGlobalDeclare(GlobalVariable *V) {
941 const Module *M = V->getParent();
942 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
945 Ty = PointerType::get(Ty, 0);
947 Value *Val = V->stripPointerCasts();
948 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
950 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
951 if (CE->getOpcode() == Instruction::BitCast) {
954 while (VV->hasOneUse())
955 VV = *VV->use_begin();
957 if (VV->getType() == Ty)
963 if (Val->getType() == Ty)
969 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
970 /// It looks through pointer casts too.
971 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
973 V = V->stripPointerCasts();
975 // Look for the bitcast.
976 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
978 if (isa<BitCastInst>(I))
979 return findDbgDeclare(*I, false);
984 // Find llvm.dbg.declare among uses of the instruction.
985 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
987 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
993 bool getLocationInfo(const Value *V, std::string &DisplayName,
994 std::string &Type, unsigned &LineNo, std::string &File,
999 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1000 Value *DIGV = findDbgGlobalDeclare(GV);
1001 if (!DIGV) return false;
1002 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1004 Var.getDisplayName(DisplayName);
1005 LineNo = Var.getLineNumber();
1006 Unit = Var.getCompileUnit();
1007 TypeD = Var.getType();
1009 const DbgDeclareInst *DDI = findDbgDeclare(V);
1010 if (!DDI) return false;
1011 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1013 Var.getName(DisplayName);
1014 LineNo = Var.getLineNumber();
1015 Unit = Var.getCompileUnit();
1016 TypeD = Var.getType();
1019 TypeD.getName(Type);
1020 Unit.getFilename(File);
1021 Unit.getDirectory(Dir);
1025 /// CollectDebugInfoAnchors - Collect debugging information anchors.
1026 void CollectDebugInfoAnchors(Module &M,
1027 SmallVector<GlobalVariable *, 2> &CUs,
1028 SmallVector<GlobalVariable *, 4> &GVs,
1029 SmallVector<GlobalVariable *, 4> &SPs) {
1031 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1033 GlobalVariable *GV = GVI;
1034 if (GV->hasName() && strncmp(GV->getNameStart(), "llvm.dbg", 8) == 0
1035 && GV->isConstant() && GV->hasInitializer()) {
1036 DICompileUnit C(GV);
1037 if (C.isNull() == false) {
1041 DIGlobalVariable G(GV);
1042 if (G.isNull() == false) {
1047 if (S.isNull() == false) {
1055 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1057 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1058 CodeGenOpt::Level OptLev) {
1059 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1062 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1064 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1065 CodeGenOpt::Level OptLev) {
1066 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1069 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1071 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1072 CodeGenOpt::Level OptLev) {
1073 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1076 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1078 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1079 CodeGenOpt::Level OptLev) {
1080 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1084 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1086 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1087 CodeGenOpt::Level OptLev) {
1088 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1091 /// ExtractDebugLocation - Extract debug location information
1092 /// from llvm.dbg.stoppoint intrinsic.
1093 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1094 DebugLocTracker &DebugLocInfo) {
1096 Value *Context = SPI.getContext();
1098 // If this location is already tracked then use it.
1099 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
1101 DenseMap<DebugLocTuple, unsigned>::iterator II
1102 = DebugLocInfo.DebugIdMap.find(Tuple);
1103 if (II != DebugLocInfo.DebugIdMap.end())
1104 return DebugLoc::get(II->second);
1106 // Add a new location entry.
1107 unsigned Id = DebugLocInfo.DebugLocations.size();
1108 DebugLocInfo.DebugLocations.push_back(Tuple);
1109 DebugLocInfo.DebugIdMap[Tuple] = Id;
1111 return DebugLoc::get(Id);
1114 /// ExtractDebugLocation - Extract debug location information
1115 /// from llvm.dbg.func_start intrinsic.
1116 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1117 DebugLocTracker &DebugLocInfo) {
1119 Value *SP = FSI.getSubprogram();
1121 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1122 unsigned Line = Subprogram.getLineNumber();
1123 DICompileUnit CU(Subprogram.getCompileUnit());
1125 // If this location is already tracked then use it.
1126 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1127 DenseMap<DebugLocTuple, unsigned>::iterator II
1128 = DebugLocInfo.DebugIdMap.find(Tuple);
1129 if (II != DebugLocInfo.DebugIdMap.end())
1130 return DebugLoc::get(II->second);
1132 // Add a new location entry.
1133 unsigned Id = DebugLocInfo.DebugLocations.size();
1134 DebugLocInfo.DebugLocations.push_back(Tuple);
1135 DebugLocInfo.DebugIdMap[Tuple] = Id;
1137 return DebugLoc::get(Id);
1140 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1141 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1142 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1143 if (Subprogram.describes(CurrentFn))
1149 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1150 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1151 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1152 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))