1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
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 DIBuilder.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/DIBuilder.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfo.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Dwarf.h"
24 using namespace llvm::dwarf;
28 /// \brief Whether there are any fields yet.
30 /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
31 /// may have been called already with an empty string.
33 SmallVector<char, 256> Chars;
36 HeaderBuilder() : IsEmpty(true) {}
37 HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
38 HeaderBuilder(HeaderBuilder &&X)
39 : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
41 template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
46 Twine(X).toVector(Chars);
50 MDString *get(LLVMContext &Context) const {
51 return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
54 static HeaderBuilder get(unsigned Tag) {
55 return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
60 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
61 : M(m), VMContext(M.getContext()), CUNode(nullptr),
62 DeclareFn(nullptr), ValueFn(nullptr),
63 AllowUnresolvedNodes(AllowUnresolvedNodes) {}
65 void DIBuilder::trackIfUnresolved(MDNode *N) {
71 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
72 UnresolvedNodes.emplace_back(N);
75 void DIBuilder::finalize() {
77 assert(!AllowUnresolvedNodes &&
78 "creating type nodes without a CU is not supported");
82 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
84 SmallVector<Metadata *, 16> RetainValues;
85 // Declarations and definitions of the same type may be retained. Some
86 // clients RAUW these pairs, leaving duplicates in the retained types
87 // list. Use a set to remove the duplicates while we transform the
88 // TrackingVHs back into Values.
89 SmallPtrSet<Metadata *, 16> RetainSet;
90 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
91 if (RetainSet.insert(AllRetainTypes[I]).second)
92 RetainValues.push_back(AllRetainTypes[I]);
93 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
95 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
96 CUNode->replaceSubprograms(SPs.get());
97 for (auto *SP : SPs) {
98 if (MDTuple *Temp = SP->getVariables().get()) {
99 const auto &PV = PreservedVariables.lookup(SP);
100 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
101 DINodeArray AV = getOrCreateArray(Variables);
102 TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
106 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
108 CUNode->replaceImportedEntities(MDTuple::get(
109 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
110 AllImportedModules.end())));
112 // Now that all temp nodes have been replaced or deleted, resolve remaining
114 for (const auto &N : UnresolvedNodes)
115 if (N && !N->isResolved())
117 UnresolvedNodes.clear();
119 // Can't handle unresolved nodes anymore.
120 AllowUnresolvedNodes = false;
123 /// If N is compile unit return NULL otherwise return N.
124 static DIScope *getNonCompileUnitScope(DIScope *N) {
125 if (!N || isa<DICompileUnit>(N))
127 return cast<DIScope>(N);
130 DICompileUnit *DIBuilder::createCompileUnit(
131 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
132 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
133 DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
135 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
136 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
137 "Invalid Language tag");
138 assert(!Filename.empty() &&
139 "Unable to create compile unit without filename");
141 assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
142 CUNode = DICompileUnit::getDistinct(
143 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
144 isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
145 nullptr, nullptr, nullptr, nullptr, DWOId);
147 // Create a named metadata so that it is easier to find cu in a module.
148 // Note that we only generate this when the caller wants to actually
149 // emit debug information. When we are only interested in tracking
150 // source line locations throughout the backend, we prevent codegen from
151 // emitting debug info in the final output by not generating llvm.dbg.cu.
153 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
154 NMD->addOperand(CUNode);
157 trackIfUnresolved(CUNode);
161 static DIImportedEntity *
162 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
163 Metadata *NS, unsigned Line, StringRef Name,
164 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
165 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
166 AllImportedModules.emplace_back(M);
170 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
173 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
174 Context, NS, Line, StringRef(), AllImportedModules);
177 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
178 DIImportedEntity *NS,
180 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
181 Context, NS, Line, StringRef(), AllImportedModules);
184 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
186 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
187 Context, M, Line, StringRef(), AllImportedModules);
190 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
194 // Make sure to use the unique identifier based metadata reference for
195 // types that have one.
196 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
197 Context, DINodeRef::get(Decl), Line, Name,
201 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
202 return DIFile::get(VMContext, Filename, Directory);
205 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
206 assert(!Name.empty() && "Unable to create enumerator without name");
207 return DIEnumerator::get(VMContext, Val, Name);
210 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
211 assert(!Name.empty() && "Unable to create type without name");
212 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
215 DIBasicType *DIBuilder::createNullPtrType() {
216 return createUnspecifiedType("decltype(nullptr)");
219 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
220 uint64_t AlignInBits,
222 assert(!Name.empty() && "Unable to create type without name");
223 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
224 AlignInBits, Encoding);
227 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
228 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
229 DITypeRef::get(FromTy), 0, 0, 0, 0);
232 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
234 uint64_t AlignInBits,
236 // FIXME: Why is there a name here?
237 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
238 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
239 SizeInBits, AlignInBits, 0, 0);
242 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
245 uint64_t AlignInBits) {
246 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
247 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
248 SizeInBits, AlignInBits, 0, 0,
249 DITypeRef::get(Base));
252 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
253 assert(RTy && "Unable to create reference type");
254 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
255 DITypeRef::get(RTy), 0, 0, 0, 0);
258 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
259 DIFile *File, unsigned LineNo,
261 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
263 DIScopeRef::get(getNonCompileUnitScope(Context)),
264 DITypeRef::get(Ty), 0, 0, 0, 0);
267 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
268 assert(Ty && "Invalid type!");
269 assert(FriendTy && "Invalid friend type!");
270 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
271 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
275 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
278 assert(Ty && "Unable to create inheritance");
279 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
280 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
284 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
285 DIFile *File, unsigned LineNumber,
287 uint64_t AlignInBits,
288 uint64_t OffsetInBits,
289 unsigned Flags, DIType *Ty) {
290 return DIDerivedType::get(
291 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
292 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
293 SizeInBits, AlignInBits, OffsetInBits, Flags);
296 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
298 return ConstantAsMetadata::get(C);
302 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
305 DIType *Ty, unsigned Flags,
306 llvm::Constant *Val) {
307 Flags |= DINode::FlagStaticMember;
308 return DIDerivedType::get(
309 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
310 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
311 0, Flags, getConstantOrNull(Val));
314 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
317 uint64_t AlignInBits,
318 uint64_t OffsetInBits, unsigned Flags,
319 DIType *Ty, MDNode *PropertyNode) {
320 return DIDerivedType::get(
321 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
322 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
323 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
327 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
328 StringRef GetterName, StringRef SetterName,
329 unsigned PropertyAttributes, DIType *Ty) {
330 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
331 SetterName, PropertyAttributes,
335 DITemplateTypeParameter *
336 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
338 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
339 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
342 static DITemplateValueParameter *
343 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
344 DIScope *Context, StringRef Name, DIType *Ty,
346 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
347 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
351 DITemplateValueParameter *
352 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
353 DIType *Ty, Constant *Val) {
354 return createTemplateValueParameterHelper(
355 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
356 getConstantOrNull(Val));
359 DITemplateValueParameter *
360 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
361 DIType *Ty, StringRef Val) {
362 return createTemplateValueParameterHelper(
363 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
364 MDString::get(VMContext, Val));
367 DITemplateValueParameter *
368 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
369 DIType *Ty, DINodeArray Val) {
370 return createTemplateValueParameterHelper(
371 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
375 DICompositeType *DIBuilder::createClassType(
376 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
377 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
378 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
379 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
380 assert((!Context || isa<DIScope>(Context)) &&
381 "createClassType should be called with a valid Context");
383 auto *R = DICompositeType::get(
384 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
385 DIScopeRef::get(getNonCompileUnitScope(Context)),
386 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
387 Elements, 0, DITypeRef::get(VTableHolder),
388 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
389 if (!UniqueIdentifier.empty())
391 trackIfUnresolved(R);
395 DICompositeType *DIBuilder::createStructType(
396 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
397 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
398 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
399 DIType *VTableHolder, StringRef UniqueIdentifier) {
400 auto *R = DICompositeType::get(
401 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
402 DIScopeRef::get(getNonCompileUnitScope(Context)),
403 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
404 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
405 if (!UniqueIdentifier.empty())
407 trackIfUnresolved(R);
411 DICompositeType *DIBuilder::createUnionType(
412 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
413 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
414 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
415 auto *R = DICompositeType::get(
416 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
417 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
418 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
420 if (!UniqueIdentifier.empty())
422 trackIfUnresolved(R);
426 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
427 DITypeRefArray ParameterTypes,
429 return DISubroutineType::get(VMContext, Flags, ParameterTypes);
432 DICompositeType *DIBuilder::createEnumerationType(
433 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
434 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
435 DIType *UnderlyingType, StringRef UniqueIdentifier) {
436 auto *CTy = DICompositeType::get(
437 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
438 DIScopeRef::get(getNonCompileUnitScope(Scope)),
439 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
440 0, nullptr, nullptr, UniqueIdentifier);
441 AllEnumTypes.push_back(CTy);
442 if (!UniqueIdentifier.empty())
444 trackIfUnresolved(CTy);
448 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
450 DINodeArray Subscripts) {
451 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
452 nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
453 AlignInBits, 0, 0, Subscripts, 0, nullptr);
454 trackIfUnresolved(R);
458 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
459 uint64_t AlignInBits, DIType *Ty,
460 DINodeArray Subscripts) {
462 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
463 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
464 DINode::FlagVector, Subscripts, 0, nullptr);
465 trackIfUnresolved(R);
469 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
470 unsigned FlagsToSet) {
471 auto NewTy = Ty->clone();
472 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
473 return MDNode::replaceWithUniqued(std::move(NewTy));
476 DIType *DIBuilder::createArtificialType(DIType *Ty) {
477 // FIXME: Restrict this to the nodes where it's valid.
478 if (Ty->isArtificial())
480 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
483 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
484 // FIXME: Restrict this to the nodes where it's valid.
485 if (Ty->isObjectPointer())
487 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
488 return createTypeWithFlags(VMContext, Ty, Flags);
491 void DIBuilder::retainType(DIType *T) {
492 assert(T && "Expected non-null type");
493 AllRetainTypes.emplace_back(T);
496 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
499 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
500 DIFile *F, unsigned Line, unsigned RuntimeLang,
501 uint64_t SizeInBits, uint64_t AlignInBits,
502 StringRef UniqueIdentifier) {
503 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
504 // replaceWithUniqued().
505 auto *RetTy = DICompositeType::get(
506 VMContext, Tag, Name, F, Line,
507 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
508 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
509 nullptr, UniqueIdentifier);
510 if (!UniqueIdentifier.empty())
512 trackIfUnresolved(RetTy);
516 DICompositeType *DIBuilder::createReplaceableCompositeType(
517 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
518 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
519 unsigned Flags, StringRef UniqueIdentifier) {
520 auto *RetTy = DICompositeType::getTemporary(
521 VMContext, Tag, Name, F, Line,
522 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
523 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
524 nullptr, nullptr, UniqueIdentifier)
526 if (!UniqueIdentifier.empty())
528 trackIfUnresolved(RetTy);
532 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
533 return MDTuple::get(VMContext, Elements);
536 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
537 SmallVector<llvm::Metadata *, 16> Elts;
538 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
539 if (Elements[i] && isa<MDNode>(Elements[i]))
540 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
542 Elts.push_back(Elements[i]);
544 return DITypeRefArray(MDNode::get(VMContext, Elts));
547 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
548 return DISubrange::get(VMContext, Count, Lo);
551 static void checkGlobalVariableScope(DIScope *Context) {
554 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
555 assert(CT->getIdentifier().empty() &&
556 "Context of a global variable should not be a type with identifier");
560 DIGlobalVariable *DIBuilder::createGlobalVariable(
561 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
562 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
564 checkGlobalVariableScope(Context);
566 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
567 Name, LinkageName, F, LineNumber,
568 DITypeRef::get(Ty), isLocalToUnit, true, Val,
569 cast_or_null<DIDerivedType>(Decl));
574 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
575 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
576 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
578 checkGlobalVariableScope(Context);
580 return DIGlobalVariable::getTemporary(
581 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
582 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
583 cast_or_null<DIDerivedType>(Decl))
587 DILocalVariable *DIBuilder::createLocalVariable(
588 unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
589 DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
590 // FIXME: Why getNonCompileUnitScope()?
591 // FIXME: Why is "!Context" okay here?
592 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
593 // the only valid scopes)?
594 DIScope *Context = getNonCompileUnitScope(Scope);
596 auto *Node = DILocalVariable::get(
597 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
598 DITypeRef::get(Ty), ArgNo, Flags);
599 if (AlwaysPreserve) {
600 // The optimizer may remove local variable. If there is an interest
601 // to preserve variable info in such situation then stash it in a
603 DISubprogram *Fn = getDISubprogram(Scope);
604 assert(Fn && "Missing subprogram for local variable");
605 PreservedVariables[Fn].emplace_back(Node);
610 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
611 return DIExpression::get(VMContext, Addr);
614 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
615 // TODO: Remove the callers of this signed version and delete.
616 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
617 return createExpression(Addr);
620 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
621 unsigned SizeInBytes) {
622 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
623 return DIExpression::get(VMContext, Addr);
626 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
627 StringRef LinkageName, DIFile *File,
628 unsigned LineNo, DISubroutineType *Ty,
629 bool isLocalToUnit, bool isDefinition,
630 unsigned ScopeLine, unsigned Flags,
631 bool isOptimized, Function *Fn,
632 MDNode *TParams, MDNode *Decl) {
633 // dragonegg does not generate identifier for types, so using an empty map
634 // to resolve the context should be fine.
635 DITypeIdentifierMap EmptyMap;
636 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
637 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
638 Flags, isOptimized, Fn, TParams, Decl);
641 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
642 StringRef LinkageName, DIFile *File,
643 unsigned LineNo, DISubroutineType *Ty,
644 bool isLocalToUnit, bool isDefinition,
645 unsigned ScopeLine, unsigned Flags,
646 bool isOptimized, Function *Fn,
647 MDNode *TParams, MDNode *Decl) {
648 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
649 "function types should be subroutines");
650 auto *Node = DISubprogram::get(
651 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
652 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
653 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
654 cast_or_null<DISubprogram>(Decl),
655 MDTuple::getTemporary(VMContext, None).release());
658 AllSubprograms.push_back(Node);
659 trackIfUnresolved(Node);
663 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
664 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
665 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
666 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
667 Function *Fn, MDNode *TParams, MDNode *Decl) {
668 return DISubprogram::getTemporary(
669 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
670 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
671 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
672 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
678 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
679 DIFile *F, unsigned LineNo, DISubroutineType *Ty,
680 bool isLocalToUnit, bool isDefinition, unsigned VK,
681 unsigned VIndex, DIType *VTableHolder, unsigned Flags,
682 bool isOptimized, Function *Fn, MDNode *TParam) {
683 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
684 "function types should be subroutines");
685 assert(getNonCompileUnitScope(Context) &&
686 "Methods should have both a Context and a context that isn't "
687 "the compile unit.");
688 // FIXME: Do we want to use different scope/lines?
689 auto *SP = DISubprogram::get(
690 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
691 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
692 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
693 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
696 AllSubprograms.push_back(SP);
697 trackIfUnresolved(SP);
701 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
702 DIFile *File, unsigned LineNo) {
703 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
707 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
708 StringRef ConfigurationMacros,
709 StringRef IncludePath,
710 StringRef ISysRoot) {
711 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
712 ConfigurationMacros, IncludePath, ISysRoot);
715 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
717 unsigned Discriminator) {
718 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
721 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
722 unsigned Line, unsigned Col) {
723 // Make these distinct, to avoid merging two lexical blocks on the same
725 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
729 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
730 assert(V && "no value passed to dbg intrinsic");
731 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
734 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
735 I->setDebugLoc(const_cast<DILocation *>(DL));
739 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
740 DIExpression *Expr, const DILocation *DL,
741 Instruction *InsertBefore) {
742 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
743 assert(DL && "Expected debug loc");
744 assert(DL->getScope()->getSubprogram() ==
745 VarInfo->getScope()->getSubprogram() &&
746 "Expected matching subprograms");
748 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
750 trackIfUnresolved(VarInfo);
751 trackIfUnresolved(Expr);
752 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
753 MetadataAsValue::get(VMContext, VarInfo),
754 MetadataAsValue::get(VMContext, Expr)};
755 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
758 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
759 DIExpression *Expr, const DILocation *DL,
760 BasicBlock *InsertAtEnd) {
761 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
762 assert(DL && "Expected debug loc");
763 assert(DL->getScope()->getSubprogram() ==
764 VarInfo->getScope()->getSubprogram() &&
765 "Expected matching subprograms");
767 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
769 trackIfUnresolved(VarInfo);
770 trackIfUnresolved(Expr);
771 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
772 MetadataAsValue::get(VMContext, VarInfo),
773 MetadataAsValue::get(VMContext, Expr)};
775 // If this block already has a terminator then insert this intrinsic
776 // before the terminator.
777 if (TerminatorInst *T = InsertAtEnd->getTerminator())
778 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
779 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
782 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
783 DILocalVariable *VarInfo,
785 const DILocation *DL,
786 Instruction *InsertBefore) {
787 assert(V && "no value passed to dbg.value");
788 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
789 assert(DL && "Expected debug loc");
790 assert(DL->getScope()->getSubprogram() ==
791 VarInfo->getScope()->getSubprogram() &&
792 "Expected matching subprograms");
794 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
796 trackIfUnresolved(VarInfo);
797 trackIfUnresolved(Expr);
798 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
799 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
800 MetadataAsValue::get(VMContext, VarInfo),
801 MetadataAsValue::get(VMContext, Expr)};
802 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
805 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
806 DILocalVariable *VarInfo,
808 const DILocation *DL,
809 BasicBlock *InsertAtEnd) {
810 assert(V && "no value passed to dbg.value");
811 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
812 assert(DL && "Expected debug loc");
813 assert(DL->getScope()->getSubprogram() ==
814 VarInfo->getScope()->getSubprogram() &&
815 "Expected matching subprograms");
817 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
819 trackIfUnresolved(VarInfo);
820 trackIfUnresolved(Expr);
821 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
822 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
823 MetadataAsValue::get(VMContext, VarInfo),
824 MetadataAsValue::get(VMContext, Expr)};
826 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
829 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
830 DICompositeType *VTableHolder) {
832 TypedTrackingMDRef<DICompositeType> N(T);
833 N->replaceVTableHolder(DITypeRef::get(VTableHolder));
837 // If this didn't create a self-reference, just return.
838 if (T != VTableHolder)
841 // Look for unresolved operands. T will drop RAUW support, orphaning any
842 // cycles underneath it.
844 for (const MDOperand &O : T->operands())
845 if (auto *N = dyn_cast_or_null<MDNode>(O))
846 trackIfUnresolved(N);
849 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
850 DINodeArray TParams) {
852 TypedTrackingMDRef<DICompositeType> N(T);
854 N->replaceElements(Elements);
856 N->replaceTemplateParams(DITemplateParameterArray(TParams));
860 // If T isn't resolved, there's no problem.
861 if (!T->isResolved())
864 // If "T" is resolved, it may be due to a self-reference cycle. Track the
865 // arrays explicitly if they're unresolved, or else the cycles will be
868 trackIfUnresolved(Elements.get());
870 trackIfUnresolved(TParams.get());