1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/Streams.h"
26 using namespace llvm::dwarf;
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 /// ValidDebugInfo - Return true if V represents valid debug info value.
33 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
37 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
41 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
46 // Check current version. Allow Version6 for now.
47 unsigned Version = DI.getVersion();
48 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
51 unsigned Tag = DI.getTag();
54 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
56 case DW_TAG_compile_unit:
57 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_subprogram:
60 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
62 case DW_TAG_lexical_block:
63 /// FIXME. This interfers with the quality of generated code when
64 /// during optimization.
65 if (OptLevel != CodeGenOpt::None)
74 DIDescriptor::DIDescriptor(GlobalVariable *gv, unsigned RequiredTag) {
77 // If this is non-null, check to see if the Tag matches. If not, set to null.
78 if (GV && getTag() != RequiredTag)
83 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
89 Constant *C = GV->getInitializer();
90 if (C == 0 || Elt >= C->getNumOperands()) {
95 // Fills in the string if it succeeds
96 if (!GetConstantStringInfo(C->getOperand(Elt), Result))
102 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
103 if (GV == 0) return 0;
104 Constant *C = GV->getInitializer();
105 if (C == 0 || Elt >= C->getNumOperands())
107 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
108 return CI->getZExtValue();
112 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
113 if (GV == 0) return DIDescriptor();
114 Constant *C = GV->getInitializer();
115 if (C == 0 || Elt >= C->getNumOperands())
116 return DIDescriptor();
117 C = C->getOperand(Elt);
118 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
121 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
122 if (GV == 0) return 0;
123 Constant *C = GV->getInitializer();
124 if (C == 0 || Elt >= C->getNumOperands())
126 C = C->getOperand(Elt);
128 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
133 //===----------------------------------------------------------------------===//
134 // Simple Descriptor Constructors and other Methods
135 //===----------------------------------------------------------------------===//
137 DIAnchor::DIAnchor(GlobalVariable *GV)
138 : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
139 DIEnumerator::DIEnumerator(GlobalVariable *GV)
140 : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
141 DISubrange::DISubrange(GlobalVariable *GV)
142 : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
143 DICompileUnit::DICompileUnit(GlobalVariable *GV)
144 : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
145 DIBasicType::DIBasicType(GlobalVariable *GV)
146 : DIType(GV, dwarf::DW_TAG_base_type) {}
147 DISubprogram::DISubprogram(GlobalVariable *GV)
148 : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
149 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
150 : DIGlobal(GV, dwarf::DW_TAG_variable) {}
151 DIBlock::DIBlock(GlobalVariable *GV)
152 : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
153 // needed by DIVariable::getType()
154 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
156 unsigned tag = getTag();
157 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
158 !DICompositeType::isCompositeType(tag))
162 /// isDerivedType - Return true if the specified tag is legal for
164 bool DIType::isDerivedType(unsigned Tag) {
166 case dwarf::DW_TAG_typedef:
167 case dwarf::DW_TAG_pointer_type:
168 case dwarf::DW_TAG_reference_type:
169 case dwarf::DW_TAG_const_type:
170 case dwarf::DW_TAG_volatile_type:
171 case dwarf::DW_TAG_restrict_type:
172 case dwarf::DW_TAG_member:
173 case dwarf::DW_TAG_inheritance:
176 // FIXME: Even though it doesn't make sense, CompositeTypes are current
177 // modelled as DerivedTypes, this should return true for them as well.
182 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
183 if (GV && !isDerivedType(getTag()))
187 /// isCompositeType - Return true if the specified tag is legal for
189 bool DIType::isCompositeType(unsigned TAG) {
191 case dwarf::DW_TAG_array_type:
192 case dwarf::DW_TAG_structure_type:
193 case dwarf::DW_TAG_union_type:
194 case dwarf::DW_TAG_enumeration_type:
195 case dwarf::DW_TAG_vector_type:
196 case dwarf::DW_TAG_subroutine_type:
197 case dwarf::DW_TAG_class_type:
204 DICompositeType::DICompositeType(GlobalVariable *GV)
205 : DIDerivedType(GV, true, true) {
206 if (GV && !isCompositeType(getTag()))
210 /// isVariable - Return true if the specified tag is legal for DIVariable.
211 bool DIVariable::isVariable(unsigned Tag) {
213 case dwarf::DW_TAG_auto_variable:
214 case dwarf::DW_TAG_arg_variable:
215 case dwarf::DW_TAG_return_variable:
222 DIVariable::DIVariable(GlobalVariable *gv) : DIDescriptor(gv) {
223 if (gv && !isVariable(getTag()))
227 unsigned DIArray::getNumElements() const {
228 assert (GV && "Invalid DIArray");
229 Constant *C = GV->getInitializer();
230 assert (C && "Invalid DIArray initializer");
231 return C->getNumOperands();
234 /// Verify - Verify that a compile unit is well formed.
235 bool DICompileUnit::Verify() const {
239 if (getFilename(Res).empty())
241 // It is possible that directory and produce string is empty.
245 /// Verify - Verify that a type descriptor is well formed.
246 bool DIType::Verify() const {
249 if (getContext().isNull())
252 DICompileUnit CU = getCompileUnit();
253 if (!CU.isNull() && !CU.Verify())
258 /// Verify - Verify that a composite type descriptor is well formed.
259 bool DICompositeType::Verify() const {
262 if (getContext().isNull())
265 DICompileUnit CU = getCompileUnit();
266 if (!CU.isNull() && !CU.Verify())
271 /// Verify - Verify that a subprogram descriptor is well formed.
272 bool DISubprogram::Verify() const {
276 if (getContext().isNull())
279 DICompileUnit CU = getCompileUnit();
283 DICompositeType Ty = getType();
284 if (!Ty.isNull() && !Ty.Verify())
289 /// Verify - Verify that a global variable descriptor is well formed.
290 bool DIGlobalVariable::Verify() const {
294 if (getContext().isNull())
297 DICompileUnit CU = getCompileUnit();
298 if (!CU.isNull() && !CU.Verify())
301 DIType Ty = getType();
311 /// Verify - Verify that a variable descriptor is well formed.
312 bool DIVariable::Verify() const {
316 if (getContext().isNull())
319 DIType Ty = getType();
326 /// getOriginalTypeSize - If this type is derived from a base type then
327 /// return base type size.
328 uint64_t DIDerivedType::getOriginalTypeSize() const {
329 if (getTag() != dwarf::DW_TAG_member)
330 return getSizeInBits();
331 DIType BT = getTypeDerivedFrom();
332 if (BT.getTag() != dwarf::DW_TAG_base_type)
333 return getSizeInBits();
334 return BT.getSizeInBits();
337 /// describes - Return true if this subprogram provides debugging
338 /// information for the function F.
339 bool DISubprogram::describes(const Function *F) {
340 assert (F && "Invalid function");
342 getLinkageName(Name);
345 if (!Name.empty() && (strcmp(Name.c_str(), F->getNameStart()) == false))
350 //===----------------------------------------------------------------------===//
351 // DIFactory: Basic Helpers
352 //===----------------------------------------------------------------------===//
354 DIFactory::DIFactory(Module &m) : M(m) {
355 StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
356 EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
359 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
360 /// This is only valid when the descriptor is non-null.
361 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
362 if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
363 return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
366 Constant *DIFactory::GetTagConstant(unsigned TAG) {
367 assert((TAG & LLVMDebugVersionMask) == 0 &&
368 "Tag too large for debug encoding!");
369 return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
372 Constant *DIFactory::GetStringConstant(const std::string &String) {
373 // Check string cache for previous edition.
374 Constant *&Slot = StringCache[String];
376 // Return Constant if previously defined.
377 if (Slot) return Slot;
379 const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
381 // If empty string then use a sbyte* null instead.
383 return Slot = ConstantPointerNull::get(DestTy);
385 // Construct string as an llvm constant.
386 Constant *ConstStr = ConstantArray::get(String);
388 // Otherwise create and return a new string global.
389 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
390 GlobalVariable::InternalLinkage,
391 ConstStr, ".str", &M);
392 StrGV->setSection("llvm.metadata");
393 return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
396 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name. If it
397 /// already exists, return it. If not, create a new one and return it.
398 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
399 const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
401 // Otherwise, create the global or return it if already in the module.
402 Constant *C = M.getOrInsertGlobal(Name, EltTy);
403 assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
404 GlobalVariable *GV = cast<GlobalVariable>(C);
406 // If it has an initializer, it is already in the module.
407 if (GV->hasInitializer())
408 return SubProgramAnchor = DIAnchor(GV);
410 GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
411 GV->setSection("llvm.metadata");
412 GV->setConstant(true);
413 M.addTypeName("llvm.dbg.anchor.type", EltTy);
415 // Otherwise, set the initializer.
417 GetTagConstant(dwarf::DW_TAG_anchor),
418 ConstantInt::get(Type::Int32Ty, TAG)
421 GV->setInitializer(ConstantStruct::get(Elts, 2));
427 //===----------------------------------------------------------------------===//
428 // DIFactory: Primary Constructors
429 //===----------------------------------------------------------------------===//
431 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
432 /// creating a new one if there isn't already one in the module.
433 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
434 // If we already created one, just return it.
435 if (!CompileUnitAnchor.isNull())
436 return CompileUnitAnchor;
437 return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
438 "llvm.dbg.compile_units");
441 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
442 /// creating a new one if there isn't already one in the module.
443 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
444 // If we already created one, just return it.
445 if (!SubProgramAnchor.isNull())
446 return SubProgramAnchor;
447 return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
448 "llvm.dbg.subprograms");
451 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
452 /// creating a new one if there isn't already one in the module.
453 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
454 // If we already created one, just return it.
455 if (!GlobalVariableAnchor.isNull())
456 return GlobalVariableAnchor;
457 return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
458 "llvm.dbg.global_variables");
461 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
462 /// This implicitly uniques the arrays created.
463 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
464 SmallVector<Constant*, 16> Elts;
466 for (unsigned i = 0; i != NumTys; ++i)
467 Elts.push_back(getCastToEmpty(Tys[i]));
469 Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
471 &Elts[0], Elts.size());
472 // If we already have this array, just return the uniqued version.
473 DIDescriptor &Entry = SimpleConstantCache[Init];
474 if (!Entry.isNull()) return DIArray(Entry.getGV());
476 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
477 GlobalValue::InternalLinkage,
478 Init, "llvm.dbg.array", &M);
479 GV->setSection("llvm.metadata");
480 Entry = DIDescriptor(GV);
484 /// GetOrCreateSubrange - Create a descriptor for a value range. This
485 /// implicitly uniques the values returned.
486 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
488 GetTagConstant(dwarf::DW_TAG_subrange_type),
489 ConstantInt::get(Type::Int64Ty, Lo),
490 ConstantInt::get(Type::Int64Ty, Hi)
493 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
495 // If we already have this range, just return the uniqued version.
496 DIDescriptor &Entry = SimpleConstantCache[Init];
497 if (!Entry.isNull()) return DISubrange(Entry.getGV());
499 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
501 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
502 GlobalValue::InternalLinkage,
503 Init, "llvm.dbg.subrange", &M);
504 GV->setSection("llvm.metadata");
505 Entry = DIDescriptor(GV);
506 return DISubrange(GV);
511 /// CreateCompileUnit - Create a new descriptor for the specified compile
512 /// unit. Note that this does not unique compile units within the module.
513 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
514 const std::string &Filename,
515 const std::string &Directory,
516 const std::string &Producer,
520 unsigned RunTimeVer) {
522 GetTagConstant(dwarf::DW_TAG_compile_unit),
523 getCastToEmpty(GetOrCreateCompileUnitAnchor()),
524 ConstantInt::get(Type::Int32Ty, LangID),
525 GetStringConstant(Filename),
526 GetStringConstant(Directory),
527 GetStringConstant(Producer),
528 ConstantInt::get(Type::Int1Ty, isMain),
529 ConstantInt::get(Type::Int1Ty, isOptimized),
530 GetStringConstant(Flags),
531 ConstantInt::get(Type::Int32Ty, RunTimeVer)
534 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
536 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
537 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
538 GlobalValue::InternalLinkage,
539 Init, "llvm.dbg.compile_unit", &M);
540 GV->setSection("llvm.metadata");
541 return DICompileUnit(GV);
544 /// CreateEnumerator - Create a single enumerator value.
545 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
547 GetTagConstant(dwarf::DW_TAG_enumerator),
548 GetStringConstant(Name),
549 ConstantInt::get(Type::Int64Ty, Val)
552 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
554 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
555 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
556 GlobalValue::InternalLinkage,
557 Init, "llvm.dbg.enumerator", &M);
558 GV->setSection("llvm.metadata");
559 return DIEnumerator(GV);
563 /// CreateBasicType - Create a basic type like int, float, etc.
564 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
565 const std::string &Name,
566 DICompileUnit CompileUnit,
569 uint64_t AlignInBits,
570 uint64_t OffsetInBits, unsigned Flags,
573 GetTagConstant(dwarf::DW_TAG_base_type),
574 getCastToEmpty(Context),
575 GetStringConstant(Name),
576 getCastToEmpty(CompileUnit),
577 ConstantInt::get(Type::Int32Ty, LineNumber),
578 ConstantInt::get(Type::Int64Ty, SizeInBits),
579 ConstantInt::get(Type::Int64Ty, AlignInBits),
580 ConstantInt::get(Type::Int64Ty, OffsetInBits),
581 ConstantInt::get(Type::Int32Ty, Flags),
582 ConstantInt::get(Type::Int32Ty, Encoding)
585 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
587 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
588 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
589 GlobalValue::InternalLinkage,
590 Init, "llvm.dbg.basictype", &M);
591 GV->setSection("llvm.metadata");
592 return DIBasicType(GV);
595 /// CreateDerivedType - Create a derived type like const qualified type,
596 /// pointer, typedef, etc.
597 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
598 DIDescriptor Context,
599 const std::string &Name,
600 DICompileUnit CompileUnit,
603 uint64_t AlignInBits,
604 uint64_t OffsetInBits,
606 DIType DerivedFrom) {
609 getCastToEmpty(Context),
610 GetStringConstant(Name),
611 getCastToEmpty(CompileUnit),
612 ConstantInt::get(Type::Int32Ty, LineNumber),
613 ConstantInt::get(Type::Int64Ty, SizeInBits),
614 ConstantInt::get(Type::Int64Ty, AlignInBits),
615 ConstantInt::get(Type::Int64Ty, OffsetInBits),
616 ConstantInt::get(Type::Int32Ty, Flags),
617 getCastToEmpty(DerivedFrom)
620 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
622 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
623 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
624 GlobalValue::InternalLinkage,
625 Init, "llvm.dbg.derivedtype", &M);
626 GV->setSection("llvm.metadata");
627 return DIDerivedType(GV);
630 /// CreateCompositeType - Create a composite type like array, struct, etc.
631 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
632 DIDescriptor Context,
633 const std::string &Name,
634 DICompileUnit CompileUnit,
637 uint64_t AlignInBits,
638 uint64_t OffsetInBits,
642 unsigned RuntimeLang) {
646 getCastToEmpty(Context),
647 GetStringConstant(Name),
648 getCastToEmpty(CompileUnit),
649 ConstantInt::get(Type::Int32Ty, LineNumber),
650 ConstantInt::get(Type::Int64Ty, SizeInBits),
651 ConstantInt::get(Type::Int64Ty, AlignInBits),
652 ConstantInt::get(Type::Int64Ty, OffsetInBits),
653 ConstantInt::get(Type::Int32Ty, Flags),
654 getCastToEmpty(DerivedFrom),
655 getCastToEmpty(Elements),
656 ConstantInt::get(Type::Int32Ty, RuntimeLang)
659 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
661 M.addTypeName("llvm.dbg.composite.type", Init->getType());
662 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
663 GlobalValue::InternalLinkage,
664 Init, "llvm.dbg.composite", &M);
665 GV->setSection("llvm.metadata");
666 return DICompositeType(GV);
670 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
671 /// See comments in DISubprogram for descriptions of these fields. This
672 /// method does not unique the generated descriptors.
673 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
674 const std::string &Name,
675 const std::string &DisplayName,
676 const std::string &LinkageName,
677 DICompileUnit CompileUnit,
678 unsigned LineNo, DIType Type,
683 GetTagConstant(dwarf::DW_TAG_subprogram),
684 getCastToEmpty(GetOrCreateSubprogramAnchor()),
685 getCastToEmpty(Context),
686 GetStringConstant(Name),
687 GetStringConstant(DisplayName),
688 GetStringConstant(LinkageName),
689 getCastToEmpty(CompileUnit),
690 ConstantInt::get(Type::Int32Ty, LineNo),
691 getCastToEmpty(Type),
692 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
693 ConstantInt::get(Type::Int1Ty, isDefinition)
696 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
698 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
699 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
700 GlobalValue::InternalLinkage,
701 Init, "llvm.dbg.subprogram", &M);
702 GV->setSection("llvm.metadata");
703 return DISubprogram(GV);
706 /// CreateGlobalVariable - Create a new descriptor for the specified global.
708 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
709 const std::string &DisplayName,
710 const std::string &LinkageName,
711 DICompileUnit CompileUnit,
712 unsigned LineNo, DIType Type,bool isLocalToUnit,
713 bool isDefinition, llvm::GlobalVariable *Val) {
715 GetTagConstant(dwarf::DW_TAG_variable),
716 getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
717 getCastToEmpty(Context),
718 GetStringConstant(Name),
719 GetStringConstant(DisplayName),
720 GetStringConstant(LinkageName),
721 getCastToEmpty(CompileUnit),
722 ConstantInt::get(Type::Int32Ty, LineNo),
723 getCastToEmpty(Type),
724 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
725 ConstantInt::get(Type::Int1Ty, isDefinition),
726 ConstantExpr::getBitCast(Val, EmptyStructPtr)
729 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
731 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
732 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
733 GlobalValue::InternalLinkage,
734 Init, "llvm.dbg.global_variable", &M);
735 GV->setSection("llvm.metadata");
736 return DIGlobalVariable(GV);
740 /// CreateVariable - Create a new descriptor for the specified variable.
741 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
742 const std::string &Name,
743 DICompileUnit CompileUnit, unsigned LineNo,
747 getCastToEmpty(Context),
748 GetStringConstant(Name),
749 getCastToEmpty(CompileUnit),
750 ConstantInt::get(Type::Int32Ty, LineNo),
754 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
756 M.addTypeName("llvm.dbg.variable.type", Init->getType());
757 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
758 GlobalValue::InternalLinkage,
759 Init, "llvm.dbg.variable", &M);
760 GV->setSection("llvm.metadata");
761 return DIVariable(GV);
765 /// CreateBlock - This creates a descriptor for a lexical block with the
766 /// specified parent context.
767 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
769 GetTagConstant(dwarf::DW_TAG_lexical_block),
770 getCastToEmpty(Context)
773 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
775 M.addTypeName("llvm.dbg.block.type", Init->getType());
776 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
777 GlobalValue::InternalLinkage,
778 Init, "llvm.dbg.block", &M);
779 GV->setSection("llvm.metadata");
784 //===----------------------------------------------------------------------===//
785 // DIFactory: Routines for inserting code into a function
786 //===----------------------------------------------------------------------===//
788 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
789 /// inserting it at the end of the specified basic block.
790 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
791 unsigned ColNo, BasicBlock *BB) {
793 // Lazily construct llvm.dbg.stoppoint function.
795 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
796 llvm::Intrinsic::dbg_stoppoint);
798 // Invoke llvm.dbg.stoppoint
800 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
801 llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
804 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
807 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
808 /// mark the start of the specified subprogram.
809 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
810 // Lazily construct llvm.dbg.func.start.
812 FuncStartFn = llvm::Intrinsic::getDeclaration(&M,
813 llvm::Intrinsic::dbg_func_start);
815 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
816 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
819 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
820 /// mark the start of a region for the specified scoping descriptor.
821 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
822 // Lazily construct llvm.dbg.region.start function.
824 RegionStartFn = llvm::Intrinsic::getDeclaration(&M,
825 llvm::Intrinsic::dbg_region_start);
826 // Call llvm.dbg.func.start.
827 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
831 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
832 /// mark the end of a region for the specified scoping descriptor.
833 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
834 // Lazily construct llvm.dbg.region.end function.
836 RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
837 llvm::Intrinsic::dbg_region_end);
839 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
842 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
843 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
845 // Cast the storage to a {}* for the call to llvm.dbg.declare.
846 Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
849 DeclareFn = llvm::Intrinsic::getDeclaration(&M,
850 llvm::Intrinsic::dbg_declare);
851 Value *Args[] = { Storage, getCastToEmpty(D) };
852 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
856 /// Finds the stoppoint coressponding to this instruction, that is the
857 /// stoppoint that dominates this instruction
858 const DbgStopPointInst *findStopPoint(const Instruction *Inst)
860 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
863 const BasicBlock *BB = Inst->getParent();
864 BasicBlock::const_iterator I = Inst, B;
867 // A BB consisting only of a terminator can't have a stoppoint.
871 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
875 // This BB didn't have a stoppoint: if there is only one
876 // predecessor, look for a stoppoint there.
877 // We could use getIDom(), but that would require dominator info.
878 BB = I->getParent()->getUniquePredecessor();
880 I = BB->getTerminator();
885 /// Finds the stoppoint corresponding to first real (non-debug intrinsic)
886 /// instruction in this Basic Block, and returns the stoppoint for it.
887 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
889 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
890 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
893 // Fallback to looking for stoppoint of unique predecessor.
894 // Useful if this BB contains no stoppoints, but unique predecessor does.
895 BB = BB->getUniquePredecessor();
897 return findStopPoint(BB->getTerminator());
901 Value *findDbgGlobalDeclare(GlobalVariable *V)
903 const Module *M = V->getParent();
904 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
907 Ty = PointerType::get(Ty, 0);
909 Value *Val = V->stripPointerCasts();
910 for (Value::use_iterator I = Val->use_begin(), E =Val->use_end();
912 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
913 if (CE->getOpcode() == Instruction::BitCast) {
915 while (VV->hasOneUse()) {
916 VV = *VV->use_begin();
918 if (VV->getType() == Ty)
924 if (Val->getType() == Ty)
929 /// Finds the dbg.declare intrinsic corresponding to this value if any.
930 /// It looks through pointer casts too.
931 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
934 V = V->stripPointerCasts();
935 // Look for the bitcast.
936 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
938 if (isa<BitCastInst>(I))
939 return findDbgDeclare(*I, false);
944 // Find dbg.declare among uses of the instruction.
945 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
947 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
953 bool getLocationInfo(const Value *V, std::string &DisplayName, std::string &Type,
954 unsigned &LineNo, std::string &File, std::string &Dir)
958 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
959 Value *DIGV = findDbgGlobalDeclare(GV);
962 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
963 Var.getDisplayName(DisplayName);
964 LineNo = Var.getLineNumber();
965 Unit = Var.getCompileUnit();
966 TypeD = Var.getType();
968 const DbgDeclareInst *DDI = findDbgDeclare(V);
971 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
972 Var.getName(DisplayName);
973 LineNo = Var.getLineNumber();
974 Unit = Var.getCompileUnit();
975 TypeD = Var.getType();
978 Unit.getFilename(File);
979 Unit.getDirectory(Dir);
984 /// dump - print descriptor.
985 void DIDescriptor::dump() const {
986 cerr << " [" << dwarf::TagString(getTag()) << "]\n";
989 /// dump - print compile unit.
990 void DICompileUnit::dump() const {
992 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
994 std::string Res1, Res2;
995 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
998 /// dump - print type.
999 void DIType::dump() const {
1000 if (isNull()) return;
1003 if (!getName(Res).empty())
1004 cerr << " [" << Res << "] ";
1006 unsigned Tag = getTag();
1007 cerr << " [" << dwarf::TagString(Tag) << "] ";
1009 // TODO : Print context
1010 getCompileUnit().dump();
1012 << getLineNumber() << ", "
1013 << getSizeInBits() << ", "
1014 << getAlignInBits() << ", "
1015 << getOffsetInBits()
1019 cerr << " [private] ";
1020 else if (isProtected())
1021 cerr << " [protected] ";
1023 if (isForwardDecl())
1026 if (isBasicType(Tag))
1027 DIBasicType(GV).dump();
1028 else if (isDerivedType(Tag))
1029 DIDerivedType(GV).dump();
1030 else if (isCompositeType(Tag))
1031 DICompositeType(GV).dump();
1033 cerr << "Invalid DIType\n";
1040 /// dump - print basic type.
1041 void DIBasicType::dump() const {
1042 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
1045 /// dump - print derived type.
1046 void DIDerivedType::dump() const {
1047 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
1050 /// dump - print composite type.
1051 void DICompositeType::dump() const {
1052 DIArray A = getTypeArray();
1055 cerr << " [" << A.getNumElements() << " elements]";
1058 /// dump - print global.
1059 void DIGlobal::dump() const {
1061 if (!getName(Res).empty())
1062 cerr << " [" << Res << "] ";
1064 unsigned Tag = getTag();
1065 cerr << " [" << dwarf::TagString(Tag) << "] ";
1067 // TODO : Print context
1068 getCompileUnit().dump();
1069 cerr << " [" << getLineNumber() << "] ";
1071 if (isLocalToUnit())
1072 cerr << " [local] ";
1077 if (isGlobalVariable(Tag))
1078 DIGlobalVariable(GV).dump();
1083 /// dump - print subprogram.
1084 void DISubprogram::dump() const {
1088 /// dump - print global variable.
1089 void DIGlobalVariable::dump() const {
1090 cerr << " ["; getGlobal()->dump(); cerr << "] ";
1093 /// dump - print variable.
1094 void DIVariable::dump() const {
1096 if (!getName(Res).empty())
1097 cerr << " [" << Res << "] ";
1099 getCompileUnit().dump();
1100 cerr << " [" << getLineNumber() << "] ";