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;
108 if (!DbgGV->hasInitializer()) return 0;
110 Constant *C = DbgGV->getInitializer();
111 if (C == 0 || Elt >= C->getNumOperands())
114 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
115 return CI->getZExtValue();
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())
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) {
148 unsigned tag = getTag();
149 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
150 !DICompositeType::isCompositeType(tag))
154 /// isDerivedType - Return true if the specified tag is legal for
156 bool DIType::isDerivedType(unsigned 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:
168 // FIXME: Even though it doesn't make sense, CompositeTypes are current
169 // modelled as DerivedTypes, this should return true for them as well.
174 /// isCompositeType - Return true if the specified tag is legal for
176 bool DIType::isCompositeType(unsigned 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:
191 /// isVariable - Return true if the specified tag is legal for DIVariable.
192 bool DIVariable::isVariable(unsigned Tag) {
194 case dwarf::DW_TAG_auto_variable:
195 case dwarf::DW_TAG_arg_variable:
196 case dwarf::DW_TAG_return_variable:
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
213 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
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 {
227 if (getFilename(Res).empty())
229 // It is possible that directory and produce string is empty.
233 /// Verify - Verify that a type descriptor is well formed.
234 bool DIType::Verify() const {
237 if (getContext().isNull())
240 DICompileUnit CU = getCompileUnit();
241 if (!CU.isNull() && !CU.Verify())
246 /// Verify - Verify that a composite type descriptor is well formed.
247 bool DICompositeType::Verify() const {
250 if (getContext().isNull())
253 DICompileUnit CU = getCompileUnit();
254 if (!CU.isNull() && !CU.Verify())
259 /// Verify - Verify that a subprogram descriptor is well formed.
260 bool DISubprogram::Verify() const {
264 if (getContext().isNull())
267 DICompileUnit CU = getCompileUnit();
271 DICompositeType Ty = getType();
272 if (!Ty.isNull() && !Ty.Verify())
277 /// Verify - Verify that a global variable descriptor is well formed.
278 bool DIGlobalVariable::Verify() const {
282 if (getContext().isNull())
285 DICompileUnit CU = getCompileUnit();
286 if (!CU.isNull() && !CU.Verify())
289 DIType Ty = getType();
299 /// Verify - Verify that a variable descriptor is well formed.
300 bool DIVariable::Verify() const {
304 if (getContext().isNull())
307 DIType Ty = getType();
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");
330 getLinkageName(Name);
333 if (F->getName() == Name)
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 {
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;
363 if (!getName(Res).empty())
364 cerr << " [" << Res << "] ";
366 unsigned Tag = getTag();
367 cerr << " [" << dwarf::TagString(Tag) << "] ";
369 // TODO : Print context
370 getCompileUnit().dump();
372 << getLineNumber() << ", "
373 << getSizeInBits() << ", "
374 << getAlignInBits() << ", "
379 cerr << " [private] ";
380 else if (isProtected())
381 cerr << " [protected] ";
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();
393 cerr << "Invalid DIType\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();
415 cerr << " [" << A.getNumElements() << " elements]";
418 /// dump - Print global.
419 void DIGlobal::dump() const {
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() << "] ";
437 if (isGlobalVariable(Tag))
438 DIGlobalVariable(DbgGV).dump();
443 /// dump - Print subprogram.
444 void DISubprogram::dump() const {
448 /// dump - Print global variable.
449 void DIGlobalVariable::dump() const {
450 cerr << " ["; getGlobal()->dump(); cerr << "] ";
453 /// dump - Print variable.
454 void DIVariable::dump() const {
456 if (!getName(Res).empty())
457 cerr << " [" << Res << "] ";
459 getCompileUnit().dump();
460 cerr << " [" << getLineNumber() << "] ";
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),
473 EmptyStructPtr = PointerType::getUnqual(StructType::get());
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 = PointerType::getUnqual(Type::Int8Ty);
498 // If empty string then use a i8* null instead.
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,
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(ArrayType::get(EmptyStructPtr,
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);
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) {
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,
576 unsigned RunTimeVer) {
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){
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,
625 uint64_t AlignInBits,
626 uint64_t OffsetInBits, unsigned Flags,
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,
659 uint64_t AlignInBits,
660 uint64_t OffsetInBits,
662 DIType DerivedFrom) {
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,
693 uint64_t AlignInBits,
694 uint64_t OffsetInBits,
698 unsigned RuntimeLang) {
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,
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.
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) {
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,
803 getCastToEmpty(Context),
804 GetStringConstant(Name),
805 getCastToEmpty(CompileUnit),
806 ConstantInt::get(Type::Int32Ty, LineNo),
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) {
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");
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.
851 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
852 llvm::Intrinsic::dbg_stoppoint);
854 // Invoke llvm.dbg.stoppoint
856 ConstantInt::get(llvm::Type::Int32Ty, LineNo),
857 ConstantInt::get(llvm::Type::Int32Ty, ColNo),
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.
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.
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.
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);
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;
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();
927 GlobalVariable *GV = GVI;
928 if (!GV->hasName() || !GV->isConstant()
929 || strcmp(GV->getName().data(), "llvm.dbg.global_variable")
930 || !GV->hasInitializer())
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) {
944 if (!NodesSeen.insert(DT.getGV()))
947 addCompileUnit(DT.getCompileUnit());
948 if (DT.isCompositeType(DT.getTag())) {
949 DICompositeType DCT(DT.getGV());
950 enumerateType(DCT.getTypeDerivedFrom());
951 DIArray DA = DCT.getTypeArray();
953 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
954 DIDescriptor D = DA.getElement(i);
955 DIType TypeE = DIType(D.getGV());
957 enumerateType(TypeE);
959 enumerateSubprogram(DISubprogram(D.getGV()));
961 } else if (DT.isDerivedType(DT.getTag())) {
962 DIDerivedType DDT(DT.getGV());
964 enumerateType(DDT.getTypeDerivedFrom());
968 /// enumerateSubprogram - Enumberate DISubprogram.
969 void DebugInfoEnumerator::enumerateSubprogram(DISubprogram SP) {
970 if (!addSubprogram(SP))
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) {
993 if (!NodesSeen.insert(CU.getGV()))
996 CUs.push_back(CU.getGV());
1000 /// addGlobalVariable - Add global variable into GVs.
1001 bool DebugInfoEnumerator::addGlobalVariable(DIGlobalVariable DIG) {
1005 if (!NodesSeen.insert(DIG.getGV()))
1008 GVs.push_back(DIG.getGV());
1012 // addSubprogram - Add subprgoram into SPs.
1013 bool DebugInfoEnumerator::addSubprogram(DISubprogram SP) {
1017 if (!NodesSeen.insert(SP.getGV()))
1020 SPs.push_back(SP.getGV());
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))
1031 const BasicBlock *BB = Inst->getParent();
1032 BasicBlock::const_iterator I = Inst, B;
1036 // A BB consisting only of a terminator can't have a stoppoint.
1039 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
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
1046 BB = I->getParent()->getUniquePredecessor();
1048 I = BB->getTerminator();
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))
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();
1066 return findStopPoint(BB->getTerminator());
1071 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1072 const Module *M = V->getParent();
1074 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
1077 Ty = PointerType::get(Ty, 0);
1079 Value *Val = V->stripPointerCasts();
1080 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
1082 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
1083 if (CE->getOpcode() == Instruction::BitCast) {
1086 while (VV->hasOneUse())
1087 VV = *VV->use_begin();
1089 if (VV->getType() == Ty)
1095 if (Val->getType() == Ty)
1101 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1102 /// It looks through pointer casts too.
1103 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1105 V = V->stripPointerCasts();
1107 // Look for the bitcast.
1108 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1110 if (isa<BitCastInst>(I))
1111 return findDbgDeclare(*I, false);
1116 // Find llvm.dbg.declare among uses of the instruction.
1117 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1119 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1125 bool getLocationInfo(const Value *V, std::string &DisplayName,
1126 std::string &Type, unsigned &LineNo, std::string &File,
1131 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1132 Value *DIGV = findDbgGlobalDeclare(GV);
1133 if (!DIGV) return false;
1134 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1136 Var.getDisplayName(DisplayName);
1137 LineNo = Var.getLineNumber();
1138 Unit = Var.getCompileUnit();
1139 TypeD = Var.getType();
1141 const DbgDeclareInst *DDI = findDbgDeclare(V);
1142 if (!DDI) return false;
1143 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1145 Var.getName(DisplayName);
1146 LineNo = Var.getLineNumber();
1147 Unit = Var.getCompileUnit();
1148 TypeD = Var.getType();
1151 TypeD.getName(Type);
1152 Unit.getFilename(File);
1153 Unit.getDirectory(Dir);
1157 /// CollectDebugInfoAnchors - Collect debugging information anchors.
1158 void CollectDebugInfoAnchors(Module &M,
1159 SmallVector<GlobalVariable *, 2> &CUs,
1160 SmallVector<GlobalVariable *, 4> &GVs,
1161 SmallVector<GlobalVariable *, 4> &SPs) {
1163 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1165 GlobalVariable *GV = GVI;
1166 if (GV->hasName() && GV->getName().startswith("llvm.dbg")
1167 && GV->isConstant() && GV->hasInitializer()) {
1168 DICompileUnit C(GV);
1169 if (C.isNull() == false) {
1173 DIGlobalVariable G(GV);
1174 if (G.isNull() == false) {
1179 if (S.isNull() == false) {
1187 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1189 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1190 CodeGenOpt::Level OptLev) {
1191 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1194 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1196 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1197 CodeGenOpt::Level OptLev) {
1198 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1201 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1203 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1204 CodeGenOpt::Level OptLev) {
1205 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1208 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1210 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1211 CodeGenOpt::Level OptLev) {
1212 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1216 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1218 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1219 CodeGenOpt::Level OptLev) {
1220 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1223 /// ExtractDebugLocation - Extract debug location information
1224 /// from llvm.dbg.stoppoint intrinsic.
1225 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1226 DebugLocTracker &DebugLocInfo) {
1228 Value *Context = SPI.getContext();
1230 // If this location is already tracked then use it.
1231 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
1233 DenseMap<DebugLocTuple, unsigned>::iterator II
1234 = DebugLocInfo.DebugIdMap.find(Tuple);
1235 if (II != DebugLocInfo.DebugIdMap.end())
1236 return DebugLoc::get(II->second);
1238 // Add a new location entry.
1239 unsigned Id = DebugLocInfo.DebugLocations.size();
1240 DebugLocInfo.DebugLocations.push_back(Tuple);
1241 DebugLocInfo.DebugIdMap[Tuple] = Id;
1243 return DebugLoc::get(Id);
1246 /// ExtractDebugLocation - Extract debug location information
1247 /// from llvm.dbg.func_start intrinsic.
1248 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1249 DebugLocTracker &DebugLocInfo) {
1251 Value *SP = FSI.getSubprogram();
1253 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1254 unsigned Line = Subprogram.getLineNumber();
1255 DICompileUnit CU(Subprogram.getCompileUnit());
1257 // If this location is already tracked then use it.
1258 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1259 DenseMap<DebugLocTuple, unsigned>::iterator II
1260 = DebugLocInfo.DebugIdMap.find(Tuple);
1261 if (II != DebugLocInfo.DebugIdMap.end())
1262 return DebugLoc::get(II->second);
1264 // Add a new location entry.
1265 unsigned Id = DebugLocInfo.DebugLocations.size();
1266 DebugLocInfo.DebugLocations.push_back(Tuple);
1267 DebugLocInfo.DebugIdMap[Tuple] = Id;
1269 return DebugLoc::get(Id);
1272 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1273 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1274 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1275 if (Subprogram.describes(CurrentFn))
1281 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1282 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1283 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1284 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))