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 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
79 SmallVector<Metadata *, 16> RetainValues;
80 // Declarations and definitions of the same type may be retained. Some
81 // clients RAUW these pairs, leaving duplicates in the retained types
82 // list. Use a set to remove the duplicates while we transform the
83 // TrackingVHs back into Values.
84 SmallPtrSet<Metadata *, 16> RetainSet;
85 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
86 if (RetainSet.insert(AllRetainTypes[I]).second)
87 RetainValues.push_back(AllRetainTypes[I]);
88 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
90 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
91 CUNode->replaceSubprograms(SPs.get());
92 for (auto *SP : SPs) {
93 if (MDTuple *Temp = SP->getVariables().get()) {
94 const auto &PV = PreservedVariables.lookup(SP);
95 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
96 DINodeArray AV = getOrCreateArray(Variables);
97 TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
101 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
103 CUNode->replaceImportedEntities(MDTuple::get(
104 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
105 AllImportedModules.end())));
108 // Now that all temp nodes have been replaced or deleted, resolve remaining
110 for (const auto &N : UnresolvedNodes)
111 if (N && !N->isResolved())
113 UnresolvedNodes.clear();
115 // Can't handle unresolved nodes anymore.
116 AllowUnresolvedNodes = false;
119 /// If N is compile unit return NULL otherwise return N.
120 static DIScope *getNonCompileUnitScope(DIScope *N) {
121 if (!N || isa<DICompileUnit>(N))
123 return cast<DIScope>(N);
126 DICompileUnit *DIBuilder::createCompileUnit(
127 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
128 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
129 DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
131 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
132 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
133 "Invalid Language tag");
134 assert(!Filename.empty() &&
135 "Unable to create compile unit without filename");
137 assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
138 CUNode = DICompileUnit::getDistinct(
139 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
140 isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
141 nullptr, nullptr, nullptr, nullptr, DWOId);
143 // Create a named metadata so that it is easier to find cu in a module.
144 // Note that we only generate this when the caller wants to actually
145 // emit debug information. When we are only interested in tracking
146 // source line locations throughout the backend, we prevent codegen from
147 // emitting debug info in the final output by not generating llvm.dbg.cu.
149 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
150 NMD->addOperand(CUNode);
153 trackIfUnresolved(CUNode);
157 static DIImportedEntity *
158 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
159 Metadata *NS, unsigned Line, StringRef Name,
160 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
161 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
162 AllImportedModules.emplace_back(M);
166 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
169 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
170 Context, NS, Line, StringRef(), AllImportedModules);
173 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
174 DIImportedEntity *NS,
176 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
177 Context, NS, Line, StringRef(), AllImportedModules);
180 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
182 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
183 Context, M, Line, StringRef(), AllImportedModules);
186 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
190 // Make sure to use the unique identifier based metadata reference for
191 // types that have one.
192 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
193 Context, DINodeRef::get(Decl), Line, Name,
197 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
198 return DIFile::get(VMContext, Filename, Directory);
201 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
202 assert(!Name.empty() && "Unable to create enumerator without name");
203 return DIEnumerator::get(VMContext, Val, Name);
206 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
207 assert(!Name.empty() && "Unable to create type without name");
208 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
211 DIBasicType *DIBuilder::createNullPtrType() {
212 return createUnspecifiedType("decltype(nullptr)");
215 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
216 uint64_t AlignInBits,
218 assert(!Name.empty() && "Unable to create type without name");
219 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
220 AlignInBits, Encoding);
223 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
224 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
225 DITypeRef::get(FromTy), 0, 0, 0, 0);
228 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
230 uint64_t AlignInBits,
232 // FIXME: Why is there a name here?
233 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
234 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
235 SizeInBits, AlignInBits, 0, 0);
238 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
241 uint64_t AlignInBits) {
242 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
243 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
244 SizeInBits, AlignInBits, 0, 0,
245 DITypeRef::get(Base));
248 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
249 assert(RTy && "Unable to create reference type");
250 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
251 DITypeRef::get(RTy), 0, 0, 0, 0);
254 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
255 DIFile *File, unsigned LineNo,
257 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
259 DIScopeRef::get(getNonCompileUnitScope(Context)),
260 DITypeRef::get(Ty), 0, 0, 0, 0);
263 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
264 assert(Ty && "Invalid type!");
265 assert(FriendTy && "Invalid friend type!");
266 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
267 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
271 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
274 assert(Ty && "Unable to create inheritance");
275 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
276 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
280 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
281 DIFile *File, unsigned LineNumber,
283 uint64_t AlignInBits,
284 uint64_t OffsetInBits,
285 unsigned Flags, DIType *Ty) {
286 return DIDerivedType::get(
287 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
288 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
289 SizeInBits, AlignInBits, OffsetInBits, Flags);
292 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
294 return ConstantAsMetadata::get(C);
298 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
301 DIType *Ty, unsigned Flags,
302 llvm::Constant *Val) {
303 Flags |= DINode::FlagStaticMember;
304 return DIDerivedType::get(
305 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
306 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
307 0, Flags, getConstantOrNull(Val));
310 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
313 uint64_t AlignInBits,
314 uint64_t OffsetInBits, unsigned Flags,
315 DIType *Ty, MDNode *PropertyNode) {
316 return DIDerivedType::get(
317 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
318 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
319 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
323 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
324 StringRef GetterName, StringRef SetterName,
325 unsigned PropertyAttributes, DIType *Ty) {
326 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
327 SetterName, PropertyAttributes,
331 DITemplateTypeParameter *
332 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
334 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
335 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
338 static DITemplateValueParameter *
339 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
340 DIScope *Context, StringRef Name, DIType *Ty,
342 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
343 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
347 DITemplateValueParameter *
348 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
349 DIType *Ty, Constant *Val) {
350 return createTemplateValueParameterHelper(
351 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
352 getConstantOrNull(Val));
355 DITemplateValueParameter *
356 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
357 DIType *Ty, StringRef Val) {
358 return createTemplateValueParameterHelper(
359 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
360 MDString::get(VMContext, Val));
363 DITemplateValueParameter *
364 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
365 DIType *Ty, DINodeArray Val) {
366 return createTemplateValueParameterHelper(
367 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
371 DICompositeType *DIBuilder::createClassType(
372 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
373 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
374 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
375 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
376 assert((!Context || isa<DIScope>(Context)) &&
377 "createClassType should be called with a valid Context");
379 auto *R = DICompositeType::get(
380 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
381 DIScopeRef::get(getNonCompileUnitScope(Context)),
382 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
383 Elements, 0, DITypeRef::get(VTableHolder),
384 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
385 if (!UniqueIdentifier.empty())
387 trackIfUnresolved(R);
391 DICompositeType *DIBuilder::createStructType(
392 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
393 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
394 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
395 DIType *VTableHolder, StringRef UniqueIdentifier) {
396 auto *R = DICompositeType::get(
397 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
398 DIScopeRef::get(getNonCompileUnitScope(Context)),
399 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
400 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
401 if (!UniqueIdentifier.empty())
403 trackIfUnresolved(R);
407 DICompositeType *DIBuilder::createUnionType(
408 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
409 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
410 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
411 auto *R = DICompositeType::get(
412 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
413 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
414 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
416 if (!UniqueIdentifier.empty())
418 trackIfUnresolved(R);
422 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
423 DITypeRefArray ParameterTypes,
425 return DISubroutineType::get(VMContext, Flags, ParameterTypes);
428 DICompositeType *DIBuilder::createEnumerationType(
429 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
430 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
431 DIType *UnderlyingType, StringRef UniqueIdentifier) {
432 auto *CTy = DICompositeType::get(
433 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
434 DIScopeRef::get(getNonCompileUnitScope(Scope)),
435 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
436 0, nullptr, nullptr, UniqueIdentifier);
437 AllEnumTypes.push_back(CTy);
438 if (!UniqueIdentifier.empty())
440 trackIfUnresolved(CTy);
444 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
446 DINodeArray Subscripts) {
447 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
448 nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
449 AlignInBits, 0, 0, Subscripts, 0, nullptr);
450 trackIfUnresolved(R);
454 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
455 uint64_t AlignInBits, DIType *Ty,
456 DINodeArray Subscripts) {
458 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
459 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
460 DINode::FlagVector, Subscripts, 0, nullptr);
461 trackIfUnresolved(R);
465 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
466 unsigned FlagsToSet) {
467 auto NewTy = Ty->clone();
468 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
469 return MDNode::replaceWithUniqued(std::move(NewTy));
472 DIType *DIBuilder::createArtificialType(DIType *Ty) {
473 // FIXME: Restrict this to the nodes where it's valid.
474 if (Ty->isArtificial())
476 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
479 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
480 // FIXME: Restrict this to the nodes where it's valid.
481 if (Ty->isObjectPointer())
483 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
484 return createTypeWithFlags(VMContext, Ty, Flags);
487 void DIBuilder::retainType(DIType *T) {
488 assert(T && "Expected non-null type");
489 AllRetainTypes.emplace_back(T);
492 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
495 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
496 DIFile *F, unsigned Line, unsigned RuntimeLang,
497 uint64_t SizeInBits, uint64_t AlignInBits,
498 StringRef UniqueIdentifier) {
499 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
500 // replaceWithUniqued().
501 auto *RetTy = DICompositeType::get(
502 VMContext, Tag, Name, F, Line,
503 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
504 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
505 nullptr, UniqueIdentifier);
506 if (!UniqueIdentifier.empty())
508 trackIfUnresolved(RetTy);
512 DICompositeType *DIBuilder::createReplaceableCompositeType(
513 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
514 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
515 unsigned Flags, StringRef UniqueIdentifier) {
516 auto *RetTy = DICompositeType::getTemporary(
517 VMContext, Tag, Name, F, Line,
518 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
519 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
520 nullptr, nullptr, UniqueIdentifier)
522 if (!UniqueIdentifier.empty())
524 trackIfUnresolved(RetTy);
528 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
529 return MDTuple::get(VMContext, Elements);
532 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
533 SmallVector<llvm::Metadata *, 16> Elts;
534 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
535 if (Elements[i] && isa<MDNode>(Elements[i]))
536 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
538 Elts.push_back(Elements[i]);
540 return DITypeRefArray(MDNode::get(VMContext, Elts));
543 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
544 return DISubrange::get(VMContext, Count, Lo);
547 static void checkGlobalVariableScope(DIScope *Context) {
550 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
551 assert(CT->getIdentifier().empty() &&
552 "Context of a global variable should not be a type with identifier");
556 DIGlobalVariable *DIBuilder::createGlobalVariable(
557 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
558 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
560 checkGlobalVariableScope(Context);
562 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
563 Name, LinkageName, F, LineNumber,
564 DITypeRef::get(Ty), isLocalToUnit, true, Val,
565 cast_or_null<DIDerivedType>(Decl));
570 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
571 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
572 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
574 checkGlobalVariableScope(Context);
576 return DIGlobalVariable::getTemporary(
577 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
578 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
579 cast_or_null<DIDerivedType>(Decl))
583 DILocalVariable *DIBuilder::createLocalVariable(
584 unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
585 DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
586 // FIXME: Why getNonCompileUnitScope()?
587 // FIXME: Why is "!Context" okay here?
588 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
589 // the only valid scopes)?
590 DIScope *Context = getNonCompileUnitScope(Scope);
592 auto *Node = DILocalVariable::get(
593 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
594 DITypeRef::get(Ty), ArgNo, Flags);
595 if (AlwaysPreserve) {
596 // The optimizer may remove local variable. If there is an interest
597 // to preserve variable info in such situation then stash it in a
599 DISubprogram *Fn = getDISubprogram(Scope);
600 assert(Fn && "Missing subprogram for local variable");
601 PreservedVariables[Fn].emplace_back(Node);
606 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
607 return DIExpression::get(VMContext, Addr);
610 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
611 // TODO: Remove the callers of this signed version and delete.
612 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
613 return createExpression(Addr);
616 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
617 unsigned SizeInBytes) {
618 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
619 return DIExpression::get(VMContext, Addr);
622 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
623 StringRef LinkageName, DIFile *File,
624 unsigned LineNo, DISubroutineType *Ty,
625 bool isLocalToUnit, bool isDefinition,
626 unsigned ScopeLine, unsigned Flags,
627 bool isOptimized, Function *Fn,
628 MDNode *TParams, MDNode *Decl) {
629 // dragonegg does not generate identifier for types, so using an empty map
630 // to resolve the context should be fine.
631 DITypeIdentifierMap EmptyMap;
632 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
633 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
634 Flags, isOptimized, Fn, TParams, Decl);
637 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
638 StringRef LinkageName, DIFile *File,
639 unsigned LineNo, DISubroutineType *Ty,
640 bool isLocalToUnit, bool isDefinition,
641 unsigned ScopeLine, unsigned Flags,
642 bool isOptimized, Function *Fn,
643 MDNode *TParams, MDNode *Decl) {
644 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
645 "function types should be subroutines");
646 auto *Node = DISubprogram::get(
647 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
648 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
649 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
650 cast_or_null<DISubprogram>(Decl),
651 MDTuple::getTemporary(VMContext, None).release());
654 AllSubprograms.push_back(Node);
655 trackIfUnresolved(Node);
659 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
660 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
661 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
662 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
663 Function *Fn, MDNode *TParams, MDNode *Decl) {
664 return DISubprogram::getTemporary(
665 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
666 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
667 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
668 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
674 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
675 DIFile *F, unsigned LineNo, DISubroutineType *Ty,
676 bool isLocalToUnit, bool isDefinition, unsigned VK,
677 unsigned VIndex, DIType *VTableHolder, unsigned Flags,
678 bool isOptimized, Function *Fn, MDNode *TParam) {
679 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
680 "function types should be subroutines");
681 assert(getNonCompileUnitScope(Context) &&
682 "Methods should have both a Context and a context that isn't "
683 "the compile unit.");
684 // FIXME: Do we want to use different scope/lines?
685 auto *SP = DISubprogram::get(
686 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
687 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
688 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
689 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
692 AllSubprograms.push_back(SP);
693 trackIfUnresolved(SP);
697 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
698 DIFile *File, unsigned LineNo) {
699 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
703 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
704 StringRef ConfigurationMacros,
705 StringRef IncludePath,
706 StringRef ISysRoot) {
707 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
708 ConfigurationMacros, IncludePath, ISysRoot);
711 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
713 unsigned Discriminator) {
714 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
717 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
718 unsigned Line, unsigned Col) {
719 // Make these distinct, to avoid merging two lexical blocks on the same
721 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
725 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
726 assert(V && "no value passed to dbg intrinsic");
727 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
730 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
731 I->setDebugLoc(const_cast<DILocation *>(DL));
735 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
736 DIExpression *Expr, const DILocation *DL,
737 Instruction *InsertBefore) {
738 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
739 assert(DL && "Expected debug loc");
740 assert(DL->getScope()->getSubprogram() ==
741 VarInfo->getScope()->getSubprogram() &&
742 "Expected matching subprograms");
744 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
746 trackIfUnresolved(VarInfo);
747 trackIfUnresolved(Expr);
748 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
749 MetadataAsValue::get(VMContext, VarInfo),
750 MetadataAsValue::get(VMContext, Expr)};
751 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
754 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
755 DIExpression *Expr, const DILocation *DL,
756 BasicBlock *InsertAtEnd) {
757 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
758 assert(DL && "Expected debug loc");
759 assert(DL->getScope()->getSubprogram() ==
760 VarInfo->getScope()->getSubprogram() &&
761 "Expected matching subprograms");
763 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
765 trackIfUnresolved(VarInfo);
766 trackIfUnresolved(Expr);
767 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
768 MetadataAsValue::get(VMContext, VarInfo),
769 MetadataAsValue::get(VMContext, Expr)};
771 // If this block already has a terminator then insert this intrinsic
772 // before the terminator.
773 if (TerminatorInst *T = InsertAtEnd->getTerminator())
774 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
775 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
778 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
779 DILocalVariable *VarInfo,
781 const DILocation *DL,
782 Instruction *InsertBefore) {
783 assert(V && "no value passed to dbg.value");
784 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
785 assert(DL && "Expected debug loc");
786 assert(DL->getScope()->getSubprogram() ==
787 VarInfo->getScope()->getSubprogram() &&
788 "Expected matching subprograms");
790 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
792 trackIfUnresolved(VarInfo);
793 trackIfUnresolved(Expr);
794 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
795 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
796 MetadataAsValue::get(VMContext, VarInfo),
797 MetadataAsValue::get(VMContext, Expr)};
798 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
801 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
802 DILocalVariable *VarInfo,
804 const DILocation *DL,
805 BasicBlock *InsertAtEnd) {
806 assert(V && "no value passed to dbg.value");
807 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
808 assert(DL && "Expected debug loc");
809 assert(DL->getScope()->getSubprogram() ==
810 VarInfo->getScope()->getSubprogram() &&
811 "Expected matching subprograms");
813 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
815 trackIfUnresolved(VarInfo);
816 trackIfUnresolved(Expr);
817 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
818 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
819 MetadataAsValue::get(VMContext, VarInfo),
820 MetadataAsValue::get(VMContext, Expr)};
822 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
825 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
826 DICompositeType *VTableHolder) {
828 TypedTrackingMDRef<DICompositeType> N(T);
829 N->replaceVTableHolder(DITypeRef::get(VTableHolder));
833 // If this didn't create a self-reference, just return.
834 if (T != VTableHolder)
837 // Look for unresolved operands. T will drop RAUW support, orphaning any
838 // cycles underneath it.
840 for (const MDOperand &O : T->operands())
841 if (auto *N = dyn_cast_or_null<MDNode>(O))
842 trackIfUnresolved(N);
845 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
846 DINodeArray TParams) {
848 TypedTrackingMDRef<DICompositeType> N(T);
850 N->replaceElements(Elements);
852 N->replaceTemplateParams(DITemplateParameterArray(TParams));
856 // If T isn't resolved, there's no problem.
857 if (!T->isResolved())
860 // If "T" is resolved, it may be due to a self-reference cycle. Track the
861 // arrays explicitly if they're unresolved, or else the cycles will be
864 trackIfUnresolved(Elements.get());
866 trackIfUnresolved(TParams.get());