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/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/DebugLoc.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 /// FIXME : Add DIDescriptor.isValid()
37 bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) {
43 // Check current version. Allow Version6 for now.
44 unsigned Version = DI.getVersion();
45 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
48 unsigned Tag = DI.getTag();
51 assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
53 case DW_TAG_compile_unit:
54 assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
56 case DW_TAG_subprogram:
57 assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_lexical_block:
60 // FIXME: This interfers with the quality of generated code during
62 if (OptLevel != CodeGenOpt::None)
72 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
75 // If this is non-null, check to see if the Tag matches. If not, set to null.
76 if (N && getTag() != RequiredTag) {
82 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
87 if (Elt < DbgNode->getNumElements())
88 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt))) {
89 Result.assign(MDS->begin(), MDS->begin() + MDS->length());
96 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
100 if (Elt < DbgNode->getNumElements())
101 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
102 return CI->getZExtValue();
107 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
109 return DIDescriptor();
111 if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
112 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
114 return DIDescriptor();
117 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
121 if (Elt < DbgNode->getNumElements())
122 return dyn_cast<GlobalVariable>(DbgNode->getElement(Elt));
126 //===----------------------------------------------------------------------===//
128 //===----------------------------------------------------------------------===//
130 /// isBasicType - Return true if the specified tag is legal for
132 bool DIDescriptor::isBasicType() const {
133 assert (!isNull() && "Invalid descriptor!");
134 unsigned Tag = getTag();
136 return Tag == dwarf::DW_TAG_base_type;
139 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
140 bool DIDescriptor::isDerivedType() const {
141 assert (!isNull() && "Invalid descriptor!");
142 unsigned Tag = getTag();
145 case dwarf::DW_TAG_typedef:
146 case dwarf::DW_TAG_pointer_type:
147 case dwarf::DW_TAG_reference_type:
148 case dwarf::DW_TAG_const_type:
149 case dwarf::DW_TAG_volatile_type:
150 case dwarf::DW_TAG_restrict_type:
151 case dwarf::DW_TAG_member:
152 case dwarf::DW_TAG_inheritance:
155 // CompositeTypes are currently modelled as DerivedTypes.
156 return isCompositeType();
160 /// isCompositeType - Return true if the specified tag is legal for
162 bool DIDescriptor::isCompositeType() const {
163 assert (!isNull() && "Invalid descriptor!");
164 unsigned Tag = getTag();
167 case dwarf::DW_TAG_array_type:
168 case dwarf::DW_TAG_structure_type:
169 case dwarf::DW_TAG_union_type:
170 case dwarf::DW_TAG_enumeration_type:
171 case dwarf::DW_TAG_vector_type:
172 case dwarf::DW_TAG_subroutine_type:
173 case dwarf::DW_TAG_class_type:
180 /// isVariable - Return true if the specified tag is legal for DIVariable.
181 bool DIDescriptor::isVariable() const {
182 assert (!isNull() && "Invalid descriptor!");
183 unsigned Tag = getTag();
186 case dwarf::DW_TAG_auto_variable:
187 case dwarf::DW_TAG_arg_variable:
188 case dwarf::DW_TAG_return_variable:
195 /// isSubprogram - Return true if the specified tag is legal for
197 bool DIDescriptor::isSubprogram() const {
198 assert (!isNull() && "Invalid descriptor!");
199 unsigned Tag = getTag();
201 return Tag == dwarf::DW_TAG_subprogram;
204 /// isGlobalVariable - Return true if the specified tag is legal for
205 /// DIGlobalVariable.
206 bool DIDescriptor::isGlobalVariable() const {
207 assert (!isNull() && "Invalid descriptor!");
208 unsigned Tag = getTag();
210 return Tag == dwarf::DW_TAG_variable;
213 /// isScope - Return true if the specified tag is one of the scope
215 bool DIDescriptor::isScope() const {
216 assert (!isNull() && "Invalid descriptor!");
217 unsigned Tag = getTag();
220 case dwarf::DW_TAG_compile_unit:
221 case dwarf::DW_TAG_lexical_block:
222 case dwarf::DW_TAG_subprogram:
230 //===----------------------------------------------------------------------===//
231 // Simple Descriptor Constructors and other Methods
232 //===----------------------------------------------------------------------===//
234 DIType::DIType(MDNode *N) : DIDescriptor(N) {
236 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
241 unsigned DIArray::getNumElements() const {
242 assert (DbgNode && "Invalid DIArray");
243 return DbgNode->getNumElements();
246 /// replaceAllUsesWith - Replace all uses of debug info referenced by
247 /// this descriptor. After this completes, the current debug info value
249 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
253 assert (!D.isNull() && "Can not replace with null");
254 DbgNode->replaceAllUsesWith(D.getNode());
258 /// Verify - Verify that a compile unit is well formed.
259 bool DICompileUnit::Verify() const {
263 if (getFilename(Res).empty())
265 // It is possible that directory and produce string is empty.
269 /// Verify - Verify that a type descriptor is well formed.
270 bool DIType::Verify() const {
273 if (getContext().isNull())
276 DICompileUnit CU = getCompileUnit();
277 if (!CU.isNull() && !CU.Verify())
282 /// Verify - Verify that a composite type descriptor is well formed.
283 bool DICompositeType::Verify() const {
286 if (getContext().isNull())
289 DICompileUnit CU = getCompileUnit();
290 if (!CU.isNull() && !CU.Verify())
295 /// Verify - Verify that a subprogram descriptor is well formed.
296 bool DISubprogram::Verify() const {
300 if (getContext().isNull())
303 DICompileUnit CU = getCompileUnit();
307 DICompositeType Ty = getType();
308 if (!Ty.isNull() && !Ty.Verify())
313 /// Verify - Verify that a global variable descriptor is well formed.
314 bool DIGlobalVariable::Verify() const {
318 if (getContext().isNull())
321 DICompileUnit CU = getCompileUnit();
322 if (!CU.isNull() && !CU.Verify())
325 DIType Ty = getType();
335 /// Verify - Verify that a variable descriptor is well formed.
336 bool DIVariable::Verify() const {
340 if (getContext().isNull())
343 DIType Ty = getType();
350 /// getOriginalTypeSize - If this type is derived from a base type then
351 /// return base type size.
352 uint64_t DIDerivedType::getOriginalTypeSize() const {
353 if (getTag() != dwarf::DW_TAG_member)
354 return getSizeInBits();
355 DIType BT = getTypeDerivedFrom();
356 if (BT.getTag() != dwarf::DW_TAG_base_type)
357 return getSizeInBits();
358 return BT.getSizeInBits();
361 /// describes - Return true if this subprogram provides debugging
362 /// information for the function F.
363 bool DISubprogram::describes(const Function *F) {
364 assert (F && "Invalid function");
366 getLinkageName(Name);
369 if (F->getName() == Name)
374 //===----------------------------------------------------------------------===//
375 // DIDescriptor: dump routines for all descriptors.
376 //===----------------------------------------------------------------------===//
379 /// dump - Print descriptor.
380 void DIDescriptor::dump() const {
381 errs() << "[" << dwarf::TagString(getTag()) << "] ";
382 errs().write_hex((intptr_t)DbgNode) << ']';
385 /// dump - Print compile unit.
386 void DICompileUnit::dump() const {
388 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
390 std::string Res1, Res2;
391 errs() << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
394 /// dump - Print type.
395 void DIType::dump() const {
396 if (isNull()) return;
399 if (!getName(Res).empty())
400 errs() << " [" << Res << "] ";
402 unsigned Tag = getTag();
403 errs() << " [" << dwarf::TagString(Tag) << "] ";
405 // TODO : Print context
406 getCompileUnit().dump();
408 << getLineNumber() << ", "
409 << getSizeInBits() << ", "
410 << getAlignInBits() << ", "
415 errs() << " [private] ";
416 else if (isProtected())
417 errs() << " [protected] ";
423 DIBasicType(DbgNode).dump();
424 else if (isDerivedType())
425 DIDerivedType(DbgNode).dump();
426 else if (isCompositeType())
427 DICompositeType(DbgNode).dump();
429 errs() << "Invalid DIType\n";
436 /// dump - Print basic type.
437 void DIBasicType::dump() const {
438 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
441 /// dump - Print derived type.
442 void DIDerivedType::dump() const {
443 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
446 /// dump - Print composite type.
447 void DICompositeType::dump() const {
448 DIArray A = getTypeArray();
451 errs() << " [" << A.getNumElements() << " elements]";
454 /// dump - Print global.
455 void DIGlobal::dump() const {
457 if (!getName(Res).empty())
458 errs() << " [" << Res << "] ";
460 unsigned Tag = getTag();
461 errs() << " [" << dwarf::TagString(Tag) << "] ";
463 // TODO : Print context
464 getCompileUnit().dump();
465 errs() << " [" << getLineNumber() << "] ";
468 errs() << " [local] ";
473 if (isGlobalVariable())
474 DIGlobalVariable(DbgNode).dump();
479 /// dump - Print subprogram.
480 void DISubprogram::dump() const {
484 /// dump - Print global variable.
485 void DIGlobalVariable::dump() const {
491 /// dump - Print variable.
492 void DIVariable::dump() const {
494 if (!getName(Res).empty())
495 errs() << " [" << Res << "] ";
497 getCompileUnit().dump();
498 errs() << " [" << getLineNumber() << "] ";
503 //===----------------------------------------------------------------------===//
504 // DIFactory: Basic Helpers
505 //===----------------------------------------------------------------------===//
507 DIFactory::DIFactory(Module &m)
508 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
509 RegionStartFn(0), RegionEndFn(0),
511 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
514 Constant *DIFactory::GetTagConstant(unsigned TAG) {
515 assert((TAG & LLVMDebugVersionMask) == 0 &&
516 "Tag too large for debug encoding!");
517 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
520 //===----------------------------------------------------------------------===//
521 // DIFactory: Primary Constructors
522 //===----------------------------------------------------------------------===//
524 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
525 /// This implicitly uniques the arrays created.
526 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
527 SmallVector<Value*, 16> Elts;
530 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
532 for (unsigned i = 0; i != NumTys; ++i)
533 Elts.push_back(Tys[i].getNode());
535 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
538 /// GetOrCreateSubrange - Create a descriptor for a value range. This
539 /// implicitly uniques the values returned.
540 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
542 GetTagConstant(dwarf::DW_TAG_subrange_type),
543 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
544 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
547 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
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 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
565 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
566 MDString::get(VMContext, Filename),
567 MDString::get(VMContext, Directory),
568 MDString::get(VMContext, Producer),
569 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
570 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
571 MDString::get(VMContext, Flags),
572 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
575 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
578 /// CreateEnumerator - Create a single enumerator value.
579 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
581 GetTagConstant(dwarf::DW_TAG_enumerator),
582 MDString::get(VMContext, Name),
583 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
585 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
589 /// CreateBasicType - Create a basic type like int, float, etc.
590 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
591 const std::string &Name,
592 DICompileUnit CompileUnit,
595 uint64_t AlignInBits,
596 uint64_t OffsetInBits, unsigned Flags,
599 GetTagConstant(dwarf::DW_TAG_base_type),
601 MDString::get(VMContext, Name),
602 CompileUnit.getNode(),
603 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
604 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
605 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
606 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
607 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
608 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
610 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
613 /// CreateDerivedType - Create a derived type like const qualified type,
614 /// pointer, typedef, etc.
615 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
616 DIDescriptor Context,
617 const std::string &Name,
618 DICompileUnit CompileUnit,
621 uint64_t AlignInBits,
622 uint64_t OffsetInBits,
624 DIType DerivedFrom) {
628 MDString::get(VMContext, Name),
629 CompileUnit.getNode(),
630 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
631 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
632 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
633 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
634 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
635 DerivedFrom.getNode(),
637 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
640 /// CreateCompositeType - Create a composite type like array, struct, etc.
641 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
642 DIDescriptor Context,
643 const std::string &Name,
644 DICompileUnit CompileUnit,
647 uint64_t AlignInBits,
648 uint64_t OffsetInBits,
652 unsigned RuntimeLang) {
657 MDString::get(VMContext, Name),
658 CompileUnit.getNode(),
659 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
660 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
661 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
662 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
663 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
664 DerivedFrom.getNode(),
666 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
668 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
672 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
673 /// See comments in DISubprogram for descriptions of these fields. This
674 /// method does not unique the generated descriptors.
675 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
676 const std::string &Name,
677 const std::string &DisplayName,
678 const std::string &LinkageName,
679 DICompileUnit CompileUnit,
680 unsigned LineNo, DIType Type,
685 GetTagConstant(dwarf::DW_TAG_subprogram),
686 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
688 MDString::get(VMContext, Name),
689 MDString::get(VMContext, DisplayName),
690 MDString::get(VMContext, LinkageName),
691 CompileUnit.getNode(),
692 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
694 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
695 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
697 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
700 /// CreateGlobalVariable - Create a new descriptor for the specified global.
702 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
703 const std::string &DisplayName,
704 const std::string &LinkageName,
705 DICompileUnit CompileUnit,
706 unsigned LineNo, DIType Type,bool isLocalToUnit,
707 bool isDefinition, llvm::GlobalVariable *Val) {
709 GetTagConstant(dwarf::DW_TAG_variable),
710 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
712 MDString::get(VMContext, Name),
713 MDString::get(VMContext, DisplayName),
714 MDString::get(VMContext, LinkageName),
715 CompileUnit.getNode(),
716 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
718 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
719 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
723 Value *const *Vs = &Elts[0];
724 MDNode *Node = MDNode::get(VMContext,Vs, 12);
726 // Create a named metadata so that we do not lose this mdnode.
727 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
728 NMD->addElement(Node);
730 return DIGlobalVariable(Node);
734 /// CreateVariable - Create a new descriptor for the specified variable.
735 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
736 const std::string &Name,
737 DICompileUnit CompileUnit, unsigned LineNo,
742 MDString::get(VMContext, Name),
743 CompileUnit.getNode(),
744 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
747 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
751 /// CreateBlock - This creates a descriptor for a lexical block with the
752 /// specified parent VMContext.
753 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
755 GetTagConstant(dwarf::DW_TAG_lexical_block),
758 return DIBlock(MDNode::get(VMContext, &Elts[0], 2));
762 //===----------------------------------------------------------------------===//
763 // DIFactory: Routines for inserting code into a function
764 //===----------------------------------------------------------------------===//
766 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
767 /// inserting it at the end of the specified basic block.
768 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
769 unsigned ColNo, BasicBlock *BB) {
771 // Lazily construct llvm.dbg.stoppoint function.
773 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
774 llvm::Intrinsic::dbg_stoppoint);
776 // Invoke llvm.dbg.stoppoint
778 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
779 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
782 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
785 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
786 /// mark the start of the specified subprogram.
787 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
788 // Lazily construct llvm.dbg.func.start.
790 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
792 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
793 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
796 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
797 /// mark the start of a region for the specified scoping descriptor.
798 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
799 // Lazily construct llvm.dbg.region.start function.
801 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
803 // Call llvm.dbg.func.start.
804 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
807 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
808 /// mark the end of a region for the specified scoping descriptor.
809 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
810 // Lazily construct llvm.dbg.region.end function.
812 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
814 // Call llvm.dbg.region.end.
815 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
818 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
819 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
820 // Cast the storage to a {}* for the call to llvm.dbg.declare.
821 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
824 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
826 Value *Args[] = { Storage, D.getNode() };
827 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
831 //===----------------------------------------------------------------------===//
832 // DebugInfoFinder implementations.
833 //===----------------------------------------------------------------------===//
835 /// processModule - Process entire module and collect debug info.
836 void DebugInfoFinder::processModule(Module &M) {
839 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
840 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
841 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
843 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
844 processStopPoint(SPI);
845 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
846 processFuncStart(FSI);
847 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
848 processRegionStart(DRS);
849 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
850 processRegionEnd(DRE);
851 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
855 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
859 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
860 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
861 if (addGlobalVariable(DIG)) {
862 addCompileUnit(DIG.getCompileUnit());
863 processType(DIG.getType());
868 /// processType - Process DIType.
869 void DebugInfoFinder::processType(DIType DT) {
873 addCompileUnit(DT.getCompileUnit());
874 if (DT.isCompositeType()) {
875 DICompositeType DCT(DT.getNode());
876 processType(DCT.getTypeDerivedFrom());
877 DIArray DA = DCT.getTypeArray();
879 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
880 DIDescriptor D = DA.getElement(i);
881 DIType TypeE = DIType(D.getNode());
885 processSubprogram(DISubprogram(D.getNode()));
887 } else if (DT.isDerivedType()) {
888 DIDerivedType DDT(DT.getNode());
890 processType(DDT.getTypeDerivedFrom());
894 /// processSubprogram - Process DISubprogram.
895 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
898 if (!addSubprogram(SP))
900 addCompileUnit(SP.getCompileUnit());
901 processType(SP.getType());
904 /// processStopPoint - Process DbgStopPointInst.
905 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
906 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
907 addCompileUnit(DICompileUnit(Context));
910 /// processFuncStart - Process DbgFuncStartInst.
911 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
912 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
913 processSubprogram(DISubprogram(SP));
916 /// processRegionStart - Process DbgRegionStart.
917 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
918 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
919 processSubprogram(DISubprogram(SP));
922 /// processRegionEnd - Process DbgRegionEnd.
923 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
924 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
925 processSubprogram(DISubprogram(SP));
928 /// processDeclare - Process DbgDeclareInst.
929 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
930 DIVariable DV(cast<MDNode>(DDI->getVariable()));
934 if (!NodesSeen.insert(DV.getNode()))
937 addCompileUnit(DV.getCompileUnit());
938 processType(DV.getType());
941 /// addType - Add type into Tys.
942 bool DebugInfoFinder::addType(DIType DT) {
946 if (!NodesSeen.insert(DT.getNode()))
949 TYs.push_back(DT.getNode());
953 /// addCompileUnit - Add compile unit into CUs.
954 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
958 if (!NodesSeen.insert(CU.getNode()))
961 CUs.push_back(CU.getNode());
965 /// addGlobalVariable - Add global variable into GVs.
966 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
970 if (!NodesSeen.insert(DIG.getNode()))
973 GVs.push_back(DIG.getNode());
977 // addSubprogram - Add subprgoram into SPs.
978 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
982 if (!NodesSeen.insert(SP.getNode()))
985 SPs.push_back(SP.getNode());
990 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
991 /// is the stoppoint that dominates this instruction.
992 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
993 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
996 const BasicBlock *BB = Inst->getParent();
997 BasicBlock::const_iterator I = Inst, B;
1001 // A BB consisting only of a terminator can't have a stoppoint.
1004 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1008 // This BB didn't have a stoppoint: if there is only one predecessor, look
1009 // for a stoppoint there. We could use getIDom(), but that would require
1011 BB = I->getParent()->getUniquePredecessor();
1013 I = BB->getTerminator();
1019 /// findBBStopPoint - Find the stoppoint corresponding to first real
1020 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1021 /// stoppoint for it.
1022 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1023 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1024 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1027 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1028 // BB contains no stoppoints, but unique predecessor does.
1029 BB = BB->getUniquePredecessor();
1031 return findStopPoint(BB->getTerminator());
1036 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1037 const Module *M = V->getParent();
1038 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1042 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1043 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1046 if (DIG.getGlobal() == V)
1047 return DIG.getNode();
1052 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1053 /// It looks through pointer casts too.
1054 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1056 V = V->stripPointerCasts();
1058 // Look for the bitcast.
1059 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1061 if (isa<BitCastInst>(I))
1062 return findDbgDeclare(*I, false);
1067 // Find llvm.dbg.declare among uses of the instruction.
1068 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1070 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1076 bool getLocationInfo(const Value *V, std::string &DisplayName,
1077 std::string &Type, unsigned &LineNo, std::string &File,
1082 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1083 Value *DIGV = findDbgGlobalDeclare(GV);
1084 if (!DIGV) return false;
1085 DIGlobalVariable Var(cast<MDNode>(DIGV));
1087 Var.getDisplayName(DisplayName);
1088 LineNo = Var.getLineNumber();
1089 Unit = Var.getCompileUnit();
1090 TypeD = Var.getType();
1092 const DbgDeclareInst *DDI = findDbgDeclare(V);
1093 if (!DDI) return false;
1094 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1096 Var.getName(DisplayName);
1097 LineNo = Var.getLineNumber();
1098 Unit = Var.getCompileUnit();
1099 TypeD = Var.getType();
1102 TypeD.getName(Type);
1103 Unit.getFilename(File);
1104 Unit.getDirectory(Dir);
1108 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1110 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1111 CodeGenOpt::Level OptLev) {
1112 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1115 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1117 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1118 CodeGenOpt::Level OptLev) {
1119 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1122 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1124 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1125 CodeGenOpt::Level OptLev) {
1126 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1129 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1131 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1132 CodeGenOpt::Level OptLev) {
1133 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1137 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1139 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1140 CodeGenOpt::Level OptLev) {
1141 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1144 /// ExtractDebugLocation - Extract debug location information
1145 /// from llvm.dbg.stoppoint intrinsic.
1146 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1147 DebugLocTracker &DebugLocInfo) {
1149 Value *Context = SPI.getContext();
1151 // If this location is already tracked then use it.
1152 DebugLocTuple Tuple(cast<MDNode>(Context), SPI.getLine(),
1154 DenseMap<DebugLocTuple, unsigned>::iterator II
1155 = DebugLocInfo.DebugIdMap.find(Tuple);
1156 if (II != DebugLocInfo.DebugIdMap.end())
1157 return DebugLoc::get(II->second);
1159 // Add a new location entry.
1160 unsigned Id = DebugLocInfo.DebugLocations.size();
1161 DebugLocInfo.DebugLocations.push_back(Tuple);
1162 DebugLocInfo.DebugIdMap[Tuple] = Id;
1164 return DebugLoc::get(Id);
1167 /// ExtractDebugLocation - Extract debug location information
1168 /// from llvm.dbg.func_start intrinsic.
1169 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1170 DebugLocTracker &DebugLocInfo) {
1172 Value *SP = FSI.getSubprogram();
1174 DISubprogram Subprogram(cast<MDNode>(SP));
1175 unsigned Line = Subprogram.getLineNumber();
1176 DICompileUnit CU(Subprogram.getCompileUnit());
1178 // If this location is already tracked then use it.
1179 DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0);
1180 DenseMap<DebugLocTuple, unsigned>::iterator II
1181 = DebugLocInfo.DebugIdMap.find(Tuple);
1182 if (II != DebugLocInfo.DebugIdMap.end())
1183 return DebugLoc::get(II->second);
1185 // Add a new location entry.
1186 unsigned Id = DebugLocInfo.DebugLocations.size();
1187 DebugLocInfo.DebugLocations.push_back(Tuple);
1188 DebugLocInfo.DebugIdMap[Tuple] = Id;
1190 return DebugLoc::get(Id);
1193 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1194 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1195 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1196 if (Subprogram.describes(CurrentFn))
1202 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1203 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1204 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1205 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))