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/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"
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
40 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
44 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
49 // Check current version. Allow Version6 for now.
50 unsigned Version = DI.getVersion();
51 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
54 unsigned Tag = DI.getTag();
57 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_compile_unit:
60 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
62 case DW_TAG_subprogram:
63 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
65 case DW_TAG_lexical_block:
66 // FIXME: This interfers with the quality of generated code during
68 if (OptLevel != CodeGenOpt::None)
78 DIDescriptor::DIDescriptor(GlobalVariable *GV, unsigned RequiredTag) {
81 // If this is non-null, check to see if the Tag matches. If not, set to null.
82 if (GV && getTag() != RequiredTag)
87 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
93 Constant *C = DbgGV->getInitializer();
94 if (C == 0 || Elt >= C->getNumOperands()) {
99 // Fills in the string if it succeeds
100 if (!GetConstantStringInfo(C->getOperand(Elt), Result))
106 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
107 if (DbgGV == 0) return 0;
109 Constant *C = DbgGV->getInitializer();
110 if (C == 0 || Elt >= C->getNumOperands())
113 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
114 return CI->getZExtValue();
118 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
119 if (DbgGV == 0) return DIDescriptor();
121 Constant *C = DbgGV->getInitializer();
122 if (C == 0 || Elt >= C->getNumOperands())
123 return DIDescriptor();
125 C = C->getOperand(Elt);
126 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
129 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
130 if (DbgGV == 0) return 0;
132 Constant *C = DbgGV->getInitializer();
133 if (C == 0 || Elt >= C->getNumOperands())
136 C = C->getOperand(Elt);
137 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
140 //===----------------------------------------------------------------------===//
141 // Simple Descriptor Constructors and other Methods
142 //===----------------------------------------------------------------------===//
144 // Needed by DIVariable::getType().
145 DIType::DIType(GlobalVariable *GV) : DIDescriptor(GV) {
147 unsigned tag = getTag();
148 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
149 !DICompositeType::isCompositeType(tag))
153 /// isDerivedType - Return true if the specified tag is legal for
155 bool DIType::isDerivedType(unsigned 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:
167 // FIXME: Even though it doesn't make sense, CompositeTypes are current
168 // modelled as DerivedTypes, this should return true for them as well.
173 /// isCompositeType - Return true if the specified tag is legal for
175 bool DIType::isCompositeType(unsigned 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:
190 /// isVariable - Return true if the specified tag is legal for DIVariable.
191 bool DIVariable::isVariable(unsigned Tag) {
193 case dwarf::DW_TAG_auto_variable:
194 case dwarf::DW_TAG_arg_variable:
195 case dwarf::DW_TAG_return_variable:
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();
209 /// replaceAllUsesWith - Replace all uses of debug info referenced by
210 /// this descriptor. After this completes, the current debug info value
212 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
216 assert (D.isNull() && "Can not replace with null");
217 getGV()->replaceAllUsesWith(D.getGV());
218 getGV()->eraseFromParent();
221 /// Verify - Verify that a compile unit is well formed.
222 bool DICompileUnit::Verify() const {
226 if (getFilename(Res).empty())
228 // It is possible that directory and produce string is empty.
232 /// Verify - Verify that a type descriptor is well formed.
233 bool DIType::Verify() const {
236 if (getContext().isNull())
239 DICompileUnit CU = getCompileUnit();
240 if (!CU.isNull() && !CU.Verify())
245 /// Verify - Verify that a composite type descriptor is well formed.
246 bool DICompositeType::Verify() const {
249 if (getContext().isNull())
252 DICompileUnit CU = getCompileUnit();
253 if (!CU.isNull() && !CU.Verify())
258 /// Verify - Verify that a subprogram descriptor is well formed.
259 bool DISubprogram::Verify() const {
263 if (getContext().isNull())
266 DICompileUnit CU = getCompileUnit();
270 DICompositeType Ty = getType();
271 if (!Ty.isNull() && !Ty.Verify())
276 /// Verify - Verify that a global variable descriptor is well formed.
277 bool DIGlobalVariable::Verify() const {
281 if (getContext().isNull())
284 DICompileUnit CU = getCompileUnit();
285 if (!CU.isNull() && !CU.Verify())
288 DIType Ty = getType();
298 /// Verify - Verify that a variable descriptor is well formed.
299 bool DIVariable::Verify() const {
303 if (getContext().isNull())
306 DIType Ty = getType();
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();
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");
329 getLinkageName(Name);
332 if (!Name.empty() && (strcmp(Name.c_str(), F->getNameStart()) == false))
337 //===----------------------------------------------------------------------===//
338 // DIDescriptor: dump routines for all descriptors.
339 //===----------------------------------------------------------------------===//
342 /// dump - Print descriptor.
343 void DIDescriptor::dump() const {
344 cerr << "[" << dwarf::TagString(getTag()) << "] ";
345 cerr << std::hex << "[GV:" << DbgGV << "]" << std::dec;
348 /// dump - Print compile unit.
349 void DICompileUnit::dump() const {
351 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
353 std::string Res1, Res2;
354 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
357 /// dump - Print type.
358 void DIType::dump() const {
359 if (isNull()) return;
362 if (!getName(Res).empty())
363 cerr << " [" << Res << "] ";
365 unsigned Tag = getTag();
366 cerr << " [" << dwarf::TagString(Tag) << "] ";
368 // TODO : Print context
369 getCompileUnit().dump();
371 << getLineNumber() << ", "
372 << getSizeInBits() << ", "
373 << getAlignInBits() << ", "
378 cerr << " [private] ";
379 else if (isProtected())
380 cerr << " [protected] ";
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();
392 cerr << "Invalid DIType\n";
399 /// dump - Print basic type.
400 void DIBasicType::dump() const {
401 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
404 /// dump - Print derived type.
405 void DIDerivedType::dump() const {
406 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
409 /// dump - Print composite type.
410 void DICompositeType::dump() const {
411 DIArray A = getTypeArray();
414 cerr << " [" << A.getNumElements() << " elements]";
417 /// dump - Print global.
418 void DIGlobal::dump() const {
420 if (!getName(Res).empty())
421 cerr << " [" << Res << "] ";
423 unsigned Tag = getTag();
424 cerr << " [" << dwarf::TagString(Tag) << "] ";
426 // TODO : Print context
427 getCompileUnit().dump();
428 cerr << " [" << getLineNumber() << "] ";
436 if (isGlobalVariable(Tag))
437 DIGlobalVariable(DbgGV).dump();
442 /// dump - Print subprogram.
443 void DISubprogram::dump() const {
447 /// dump - Print global variable.
448 void DIGlobalVariable::dump() const {
449 cerr << " ["; getGlobal()->dump(); cerr << "] ";
452 /// dump - Print variable.
453 void DIVariable::dump() const {
455 if (!getName(Res).empty())
456 cerr << " [" << Res << "] ";
458 getCompileUnit().dump();
459 cerr << " [" << getLineNumber() << "] ";
464 //===----------------------------------------------------------------------===//
465 // DIFactory: Basic Helpers
466 //===----------------------------------------------------------------------===//
468 DIFactory::DIFactory(Module &m)
469 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
470 RegionStartFn(0), RegionEndFn(0),
472 EmptyStructPtr = VMContext.getPointerTypeUnqual(VMContext.getStructType());
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);
482 Constant *DIFactory::GetTagConstant(unsigned TAG) {
483 assert((TAG & LLVMDebugVersionMask) == 0 &&
484 "Tag too large for debug encoding!");
485 return VMContext.getConstantInt(Type::Int32Ty, TAG | LLVMDebugVersion);
488 Constant *DIFactory::GetStringConstant(const std::string &String) {
489 // Check string cache for previous edition.
490 Constant *&Slot = StringCache[String];
492 // Return Constant if previously defined.
493 if (Slot) return Slot;
495 const PointerType *DestTy = VMContext.getPointerTypeUnqual(Type::Int8Ty);
497 // If empty string then use a i8* null instead.
499 return Slot = VMContext.getConstantPointerNull(DestTy);
501 // Construct string as an llvm constant.
502 Constant *ConstStr = VMContext.getConstantArray(String);
504 // Otherwise create and return a new string global.
505 GlobalVariable *StrGV = new GlobalVariable(M, ConstStr->getType(), true,
506 GlobalVariable::InternalLinkage,
508 StrGV->setSection("llvm.metadata");
509 return Slot = VMContext.getConstantExprBitCast(StrGV, DestTy);
512 //===----------------------------------------------------------------------===//
513 // DIFactory: Primary Constructors
514 //===----------------------------------------------------------------------===//
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;
521 for (unsigned i = 0; i != NumTys; ++i)
522 Elts.push_back(getCastToEmpty(Tys[i]));
524 Constant *Init = VMContext.getConstantArray(VMContext.getArrayType(EmptyStructPtr,
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());
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);
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) {
543 GetTagConstant(dwarf::DW_TAG_subrange_type),
544 VMContext.getConstantInt(Type::Int64Ty, Lo),
545 VMContext.getConstantInt(Type::Int64Ty, Hi)
548 Constant *Init = VMContext.getConstantStruct(Elts,
549 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,
576 unsigned RunTimeVer) {
578 GetTagConstant(dwarf::DW_TAG_compile_unit),
579 VMContext.getNullValue(EmptyStructPtr),
580 VMContext.getConstantInt(Type::Int32Ty, LangID),
581 GetStringConstant(Filename),
582 GetStringConstant(Directory),
583 GetStringConstant(Producer),
584 VMContext.getConstantInt(Type::Int1Ty, isMain),
585 VMContext.getConstantInt(Type::Int1Ty, isOptimized),
586 GetStringConstant(Flags),
587 VMContext.getConstantInt(Type::Int32Ty, RunTimeVer)
590 Constant *Init = VMContext.getConstantStruct(Elts,
591 sizeof(Elts)/sizeof(Elts[0]));
593 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
594 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
595 GlobalValue::LinkOnceAnyLinkage,
596 Init, "llvm.dbg.compile_unit");
597 GV->setSection("llvm.metadata");
598 return DICompileUnit(GV);
601 /// CreateEnumerator - Create a single enumerator value.
602 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
604 GetTagConstant(dwarf::DW_TAG_enumerator),
605 GetStringConstant(Name),
606 VMContext.getConstantInt(Type::Int64Ty, Val)
609 Constant *Init = VMContext.getConstantStruct(Elts,
610 sizeof(Elts)/sizeof(Elts[0]));
612 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
613 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
614 GlobalValue::InternalLinkage,
615 Init, "llvm.dbg.enumerator");
616 GV->setSection("llvm.metadata");
617 return DIEnumerator(GV);
621 /// CreateBasicType - Create a basic type like int, float, etc.
622 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
623 const std::string &Name,
624 DICompileUnit CompileUnit,
627 uint64_t AlignInBits,
628 uint64_t OffsetInBits, unsigned Flags,
631 GetTagConstant(dwarf::DW_TAG_base_type),
632 getCastToEmpty(Context),
633 GetStringConstant(Name),
634 getCastToEmpty(CompileUnit),
635 VMContext.getConstantInt(Type::Int32Ty, LineNumber),
636 VMContext.getConstantInt(Type::Int64Ty, SizeInBits),
637 VMContext.getConstantInt(Type::Int64Ty, AlignInBits),
638 VMContext.getConstantInt(Type::Int64Ty, OffsetInBits),
639 VMContext.getConstantInt(Type::Int32Ty, Flags),
640 VMContext.getConstantInt(Type::Int32Ty, Encoding)
643 Constant *Init = VMContext.getConstantStruct(Elts,
644 sizeof(Elts)/sizeof(Elts[0]));
646 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
647 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
648 GlobalValue::InternalLinkage,
649 Init, "llvm.dbg.basictype");
650 GV->setSection("llvm.metadata");
651 return DIBasicType(GV);
654 /// CreateDerivedType - Create a derived type like const qualified type,
655 /// pointer, typedef, etc.
656 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
657 DIDescriptor Context,
658 const std::string &Name,
659 DICompileUnit CompileUnit,
662 uint64_t AlignInBits,
663 uint64_t OffsetInBits,
665 DIType DerivedFrom) {
668 getCastToEmpty(Context),
669 GetStringConstant(Name),
670 getCastToEmpty(CompileUnit),
671 VMContext.getConstantInt(Type::Int32Ty, LineNumber),
672 VMContext.getConstantInt(Type::Int64Ty, SizeInBits),
673 VMContext.getConstantInt(Type::Int64Ty, AlignInBits),
674 VMContext.getConstantInt(Type::Int64Ty, OffsetInBits),
675 VMContext.getConstantInt(Type::Int32Ty, Flags),
676 getCastToEmpty(DerivedFrom)
679 Constant *Init = VMContext.getConstantStruct(Elts,
680 sizeof(Elts)/sizeof(Elts[0]));
682 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
683 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
684 GlobalValue::InternalLinkage,
685 Init, "llvm.dbg.derivedtype");
686 GV->setSection("llvm.metadata");
687 return DIDerivedType(GV);
690 /// CreateCompositeType - Create a composite type like array, struct, etc.
691 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
692 DIDescriptor Context,
693 const std::string &Name,
694 DICompileUnit CompileUnit,
697 uint64_t AlignInBits,
698 uint64_t OffsetInBits,
702 unsigned RuntimeLang) {
706 getCastToEmpty(Context),
707 GetStringConstant(Name),
708 getCastToEmpty(CompileUnit),
709 VMContext.getConstantInt(Type::Int32Ty, LineNumber),
710 VMContext.getConstantInt(Type::Int64Ty, SizeInBits),
711 VMContext.getConstantInt(Type::Int64Ty, AlignInBits),
712 VMContext.getConstantInt(Type::Int64Ty, OffsetInBits),
713 VMContext.getConstantInt(Type::Int32Ty, Flags),
714 getCastToEmpty(DerivedFrom),
715 getCastToEmpty(Elements),
716 VMContext.getConstantInt(Type::Int32Ty, RuntimeLang)
719 Constant *Init = VMContext.getConstantStruct(Elts,
720 sizeof(Elts)/sizeof(Elts[0]));
722 M.addTypeName("llvm.dbg.composite.type", Init->getType());
723 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
724 GlobalValue::InternalLinkage,
725 Init, "llvm.dbg.composite");
726 GV->setSection("llvm.metadata");
727 return DICompositeType(GV);
731 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
732 /// See comments in DISubprogram for descriptions of these fields. This
733 /// method does not unique the generated descriptors.
734 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
735 const std::string &Name,
736 const std::string &DisplayName,
737 const std::string &LinkageName,
738 DICompileUnit CompileUnit,
739 unsigned LineNo, DIType Type,
744 GetTagConstant(dwarf::DW_TAG_subprogram),
745 VMContext.getNullValue(EmptyStructPtr),
746 getCastToEmpty(Context),
747 GetStringConstant(Name),
748 GetStringConstant(DisplayName),
749 GetStringConstant(LinkageName),
750 getCastToEmpty(CompileUnit),
751 VMContext.getConstantInt(Type::Int32Ty, LineNo),
752 getCastToEmpty(Type),
753 VMContext.getConstantInt(Type::Int1Ty, isLocalToUnit),
754 VMContext.getConstantInt(Type::Int1Ty, isDefinition)
757 Constant *Init = VMContext.getConstantStruct(Elts,
758 sizeof(Elts)/sizeof(Elts[0]));
760 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
761 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
762 GlobalValue::LinkOnceAnyLinkage,
763 Init, "llvm.dbg.subprogram");
764 GV->setSection("llvm.metadata");
765 return DISubprogram(GV);
768 /// CreateGlobalVariable - Create a new descriptor for the specified global.
770 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
771 const std::string &DisplayName,
772 const std::string &LinkageName,
773 DICompileUnit CompileUnit,
774 unsigned LineNo, DIType Type,bool isLocalToUnit,
775 bool isDefinition, llvm::GlobalVariable *Val) {
777 GetTagConstant(dwarf::DW_TAG_variable),
778 VMContext.getNullValue(EmptyStructPtr),
779 getCastToEmpty(Context),
780 GetStringConstant(Name),
781 GetStringConstant(DisplayName),
782 GetStringConstant(LinkageName),
783 getCastToEmpty(CompileUnit),
784 VMContext.getConstantInt(Type::Int32Ty, LineNo),
785 getCastToEmpty(Type),
786 VMContext.getConstantInt(Type::Int1Ty, isLocalToUnit),
787 VMContext.getConstantInt(Type::Int1Ty, isDefinition),
788 VMContext.getConstantExprBitCast(Val, EmptyStructPtr)
791 Constant *Init = VMContext.getConstantStruct(Elts,
792 sizeof(Elts)/sizeof(Elts[0]));
794 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
795 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
796 GlobalValue::LinkOnceAnyLinkage,
797 Init, "llvm.dbg.global_variable");
798 GV->setSection("llvm.metadata");
799 return DIGlobalVariable(GV);
803 /// CreateVariable - Create a new descriptor for the specified variable.
804 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
805 const std::string &Name,
806 DICompileUnit CompileUnit, unsigned LineNo,
810 getCastToEmpty(Context),
811 GetStringConstant(Name),
812 getCastToEmpty(CompileUnit),
813 VMContext.getConstantInt(Type::Int32Ty, LineNo),
817 Constant *Init = VMContext.getConstantStruct(Elts,
818 sizeof(Elts)/sizeof(Elts[0]));
820 M.addTypeName("llvm.dbg.variable.type", Init->getType());
821 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
822 GlobalValue::InternalLinkage,
823 Init, "llvm.dbg.variable");
824 GV->setSection("llvm.metadata");
825 return DIVariable(GV);
829 /// CreateBlock - This creates a descriptor for a lexical block with the
830 /// specified parent VMContext.
831 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
833 GetTagConstant(dwarf::DW_TAG_lexical_block),
834 getCastToEmpty(Context)
837 Constant *Init = VMContext.getConstantStruct(Elts,
838 sizeof(Elts)/sizeof(Elts[0]));
840 M.addTypeName("llvm.dbg.block.type", Init->getType());
841 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
842 GlobalValue::InternalLinkage,
843 Init, "llvm.dbg.block");
844 GV->setSection("llvm.metadata");
849 //===----------------------------------------------------------------------===//
850 // DIFactory: Routines for inserting code into a function
851 //===----------------------------------------------------------------------===//
853 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
854 /// inserting it at the end of the specified basic block.
855 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
856 unsigned ColNo, BasicBlock *BB) {
858 // Lazily construct llvm.dbg.stoppoint function.
860 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
861 llvm::Intrinsic::dbg_stoppoint);
863 // Invoke llvm.dbg.stoppoint
865 VMContext.getConstantInt(llvm::Type::Int32Ty, LineNo),
866 VMContext.getConstantInt(llvm::Type::Int32Ty, ColNo),
869 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
872 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
873 /// mark the start of the specified subprogram.
874 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
875 // Lazily construct llvm.dbg.func.start.
877 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
879 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
880 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
883 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
884 /// mark the start of a region for the specified scoping descriptor.
885 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
886 // Lazily construct llvm.dbg.region.start function.
888 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
890 // Call llvm.dbg.func.start.
891 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
894 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
895 /// mark the end of a region for the specified scoping descriptor.
896 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
897 // Lazily construct llvm.dbg.region.end function.
899 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
901 // Call llvm.dbg.region.end.
902 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
905 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
906 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
907 // Cast the storage to a {}* for the call to llvm.dbg.declare.
908 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
911 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
913 Value *Args[] = { Storage, getCastToEmpty(D) };
914 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
918 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
919 /// is the stoppoint that dominates this instruction.
920 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
921 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
924 const BasicBlock *BB = Inst->getParent();
925 BasicBlock::const_iterator I = Inst, B;
929 // A BB consisting only of a terminator can't have a stoppoint.
932 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
936 // This BB didn't have a stoppoint: if there is only one predecessor, look
937 // for a stoppoint there. We could use getIDom(), but that would require
939 BB = I->getParent()->getUniquePredecessor();
941 I = BB->getTerminator();
947 /// findBBStopPoint - Find the stoppoint corresponding to first real
948 /// (non-debug intrinsic) instruction in this Basic Block, and return the
949 /// stoppoint for it.
950 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
951 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
952 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
955 // Fallback to looking for stoppoint of unique predecessor. Useful if this
956 // BB contains no stoppoints, but unique predecessor does.
957 BB = BB->getUniquePredecessor();
959 return findStopPoint(BB->getTerminator());
964 Value *findDbgGlobalDeclare(GlobalVariable *V) {
965 const Module *M = V->getParent();
966 LLVMContext& Context = M->getContext();
968 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
971 Ty = Context.getPointerType(Ty, 0);
973 Value *Val = V->stripPointerCasts();
974 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
976 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
977 if (CE->getOpcode() == Instruction::BitCast) {
980 while (VV->hasOneUse())
981 VV = *VV->use_begin();
983 if (VV->getType() == Ty)
989 if (Val->getType() == Ty)
995 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
996 /// It looks through pointer casts too.
997 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
999 V = V->stripPointerCasts();
1001 // Look for the bitcast.
1002 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1004 if (isa<BitCastInst>(I))
1005 return findDbgDeclare(*I, false);
1010 // Find llvm.dbg.declare among uses of the instruction.
1011 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1013 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1019 bool getLocationInfo(const Value *V, std::string &DisplayName,
1020 std::string &Type, unsigned &LineNo, std::string &File,
1025 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1026 Value *DIGV = findDbgGlobalDeclare(GV);
1027 if (!DIGV) return false;
1028 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1030 Var.getDisplayName(DisplayName);
1031 LineNo = Var.getLineNumber();
1032 Unit = Var.getCompileUnit();
1033 TypeD = Var.getType();
1035 const DbgDeclareInst *DDI = findDbgDeclare(V);
1036 if (!DDI) return false;
1037 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1039 Var.getName(DisplayName);
1040 LineNo = Var.getLineNumber();
1041 Unit = Var.getCompileUnit();
1042 TypeD = Var.getType();
1045 TypeD.getName(Type);
1046 Unit.getFilename(File);
1047 Unit.getDirectory(Dir);
1051 /// CollectDebugInfoAnchors - Collect debugging information anchors.
1052 void CollectDebugInfoAnchors(Module &M,
1053 SmallVector<GlobalVariable *, 2> &CUs,
1054 SmallVector<GlobalVariable *, 4> &GVs,
1055 SmallVector<GlobalVariable *, 4> &SPs) {
1057 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1059 GlobalVariable *GV = GVI;
1060 if (GV->hasName() && strncmp(GV->getNameStart(), "llvm.dbg", 8) == 0
1061 && GV->isConstant() && GV->hasInitializer()) {
1062 DICompileUnit C(GV);
1063 if (C.isNull() == false) {
1067 DIGlobalVariable G(GV);
1068 if (G.isNull() == false) {
1073 if (S.isNull() == false) {
1081 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1083 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1084 CodeGenOpt::Level OptLev) {
1085 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1088 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1090 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1091 CodeGenOpt::Level OptLev) {
1092 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1095 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1097 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1098 CodeGenOpt::Level OptLev) {
1099 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1102 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1104 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1105 CodeGenOpt::Level OptLev) {
1106 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1110 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1112 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1113 CodeGenOpt::Level OptLev) {
1114 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1117 /// ExtractDebugLocation - Extract debug location information
1118 /// from llvm.dbg.stoppoint intrinsic.
1119 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1120 DebugLocTracker &DebugLocInfo) {
1122 Value *Context = SPI.getContext();
1124 // If this location is already tracked then use it.
1125 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
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 /// ExtractDebugLocation - Extract debug location information
1141 /// from llvm.dbg.func_start intrinsic.
1142 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1143 DebugLocTracker &DebugLocInfo) {
1145 Value *SP = FSI.getSubprogram();
1147 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1148 unsigned Line = Subprogram.getLineNumber();
1149 DICompileUnit CU(Subprogram.getCompileUnit());
1151 // If this location is already tracked then use it.
1152 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1153 DenseMap<DebugLocTuple, unsigned>::iterator II
1154 = DebugLocInfo.DebugIdMap.find(Tuple);
1155 if (II != DebugLocInfo.DebugIdMap.end())
1156 return DebugLoc::get(II->second);
1158 // Add a new location entry.
1159 unsigned Id = DebugLocInfo.DebugLocations.size();
1160 DebugLocInfo.DebugLocations.push_back(Tuple);
1161 DebugLocInfo.DebugIdMap[Tuple] = Id;
1163 return DebugLoc::get(Id);
1166 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1167 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1168 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1169 if (Subprogram.describes(CurrentFn))
1175 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1176 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1177 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1178 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))