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()), TempEnumTypes(nullptr),
62 TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
63 DeclareFn(nullptr), ValueFn(nullptr),
64 AllowUnresolvedNodes(AllowUnresolvedNodes) {}
66 void DIBuilder::trackIfUnresolved(MDNode *N) {
72 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
73 UnresolvedNodes.emplace_back(N);
76 void DIBuilder::finalize() {
77 DIArray Enums = getOrCreateArray(AllEnumTypes);
78 TempEnumTypes->replaceAllUsesWith(Enums.get());
80 SmallVector<Metadata *, 16> RetainValues;
81 // Declarations and definitions of the same type may be retained. Some
82 // clients RAUW these pairs, leaving duplicates in the retained types
83 // list. Use a set to remove the duplicates while we transform the
84 // TrackingVHs back into Values.
85 SmallPtrSet<Metadata *, 16> RetainSet;
86 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
87 if (RetainSet.insert(AllRetainTypes[I]).second)
88 RetainValues.push_back(AllRetainTypes[I]);
89 DIArray RetainTypes = getOrCreateArray(RetainValues);
90 TempRetainTypes->replaceAllUsesWith(RetainTypes.get());
92 DIArray SPs = getOrCreateArray(AllSubprograms);
93 TempSubprograms->replaceAllUsesWith(SPs.get());
94 for (unsigned i = 0, e = SPs.size(); i != e; ++i) {
95 DISubprogram SP = cast<MDSubprogram>(SPs[i]);
96 if (MDTuple *Temp = SP->getVariables().get()) {
97 const auto &PV = PreservedVariables.lookup(SP);
98 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
99 DIArray AV = getOrCreateArray(Variables);
100 TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
104 DIArray GVs = getOrCreateArray(AllGVs);
105 TempGVs->replaceAllUsesWith(GVs.get());
107 SmallVector<Metadata *, 16> RetainValuesI(AllImportedModules.begin(),
108 AllImportedModules.end());
109 DIArray IMs = getOrCreateArray(RetainValuesI);
110 TempImportedModules->replaceAllUsesWith(IMs.get());
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 MDScope *getNonCompileUnitScope(MDNode *N) {
125 if (!N || isa<MDCompileUnit>(N))
127 return cast<MDScope>(N);
130 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
132 StringRef Producer, bool isOptimized,
133 StringRef Flags, unsigned RunTimeVer,
135 DebugEmissionKind Kind,
136 bool EmitDebugInfo) {
138 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
139 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
140 "Invalid Language tag");
141 assert(!Filename.empty() &&
142 "Unable to create compile unit without filename");
144 // TODO: Once we make MDCompileUnit distinct, stop using temporaries here
145 // (just start with operands assigned to nullptr).
146 TempEnumTypes = MDTuple::getTemporary(VMContext, None);
147 TempRetainTypes = MDTuple::getTemporary(VMContext, None);
148 TempSubprograms = MDTuple::getTemporary(VMContext, None);
149 TempGVs = MDTuple::getTemporary(VMContext, None);
150 TempImportedModules = MDTuple::getTemporary(VMContext, None);
152 // TODO: Switch to getDistinct(). We never want to merge compile units based
154 MDCompileUnit *CUNode = MDCompileUnit::get(
155 VMContext, Lang, MDFile::get(VMContext, Filename, Directory), Producer,
156 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
157 TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
158 TempImportedModules.get());
160 // Create a named metadata so that it is easier to find cu in a module.
161 // Note that we only generate this when the caller wants to actually
162 // emit debug information. When we are only interested in tracking
163 // source line locations throughout the backend, we prevent codegen from
164 // emitting debug info in the final output by not generating llvm.dbg.cu.
166 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
167 NMD->addOperand(CUNode);
170 trackIfUnresolved(CUNode);
174 static DIImportedEntity
175 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
176 Metadata *NS, unsigned Line, StringRef Name,
177 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
179 MDImportedEntity::get(C, Tag, Context, DebugNodeRef(NS), Line, Name);
180 AllImportedModules.emplace_back(M);
184 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
187 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
188 Context, NS, Line, StringRef(), AllImportedModules);
191 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
194 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
195 Context, NS, Line, StringRef(), AllImportedModules);
198 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
202 // Make sure to use the unique identifier based metadata reference for
203 // types that have one.
204 return ::createImportedModule(
205 VMContext, dwarf::DW_TAG_imported_declaration, Context,
206 DebugNodeRef::get(cast_or_null<DebugNode>(Decl.get())), Line, Name,
210 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
211 DIImportedEntity Imp,
212 unsigned Line, StringRef Name) {
213 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
214 Context, Imp, Line, Name, AllImportedModules);
217 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
218 return MDFile::get(VMContext, Filename, Directory);
221 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
222 assert(!Name.empty() && "Unable to create enumerator without name");
223 return MDEnumerator::get(VMContext, Val, Name);
226 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
227 assert(!Name.empty() && "Unable to create type without name");
228 return MDBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
231 DIBasicType DIBuilder::createNullPtrType() {
232 return createUnspecifiedType("decltype(nullptr)");
236 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
237 uint64_t AlignInBits, unsigned Encoding) {
238 assert(!Name.empty() && "Unable to create type without name");
239 return MDBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
240 AlignInBits, Encoding);
243 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
244 return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
245 MDTypeRef::get(FromTy), 0, 0, 0, 0);
249 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
250 uint64_t AlignInBits, StringRef Name) {
251 // FIXME: Why is there a name here?
252 return MDDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
253 nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
254 SizeInBits, AlignInBits, 0, 0);
258 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
259 uint64_t SizeInBits, uint64_t AlignInBits) {
260 return MDDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
261 nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
262 SizeInBits, AlignInBits, 0, 0, MDTypeRef::get(Base));
265 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
266 assert(RTy && "Unable to create reference type");
267 return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
268 MDTypeRef::get(RTy), 0, 0, 0, 0);
271 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
272 unsigned LineNo, DIDescriptor Context) {
273 return MDDerivedType::get(
274 VMContext, dwarf::DW_TAG_typedef, Name, File, LineNo,
275 MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
276 MDTypeRef::get(Ty), 0, 0, 0, 0);
279 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
280 // typedefs are encoded in DIDerivedType format.
281 assert(Ty && "Invalid type!");
282 assert(FriendTy && "Invalid friend type!");
283 return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
284 MDTypeRef::get(Ty), MDTypeRef::get(FriendTy), 0, 0,
288 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
291 assert(Ty && "Unable to create inheritance");
292 return MDDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
293 0, MDTypeRef::get(Ty), MDTypeRef::get(BaseTy), 0, 0,
297 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
298 DIFile File, unsigned LineNumber,
300 uint64_t AlignInBits,
301 uint64_t OffsetInBits, unsigned Flags,
303 return MDDerivedType::get(
304 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
305 MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))),
306 MDTypeRef::get(Ty), SizeInBits, AlignInBits, OffsetInBits, Flags);
309 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
311 return ConstantAsMetadata::get(C);
315 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
316 StringRef Name, DIFile File,
317 unsigned LineNumber, DIType Ty,
319 llvm::Constant *Val) {
320 // TAG_member is encoded in DIDerivedType format.
321 Flags |= DIDescriptor::FlagStaticMember;
322 return MDDerivedType::get(
323 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
324 MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))),
325 MDTypeRef::get(Ty), 0, 0, 0, Flags, getConstantOrNull(Val));
328 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
331 uint64_t AlignInBits,
332 uint64_t OffsetInBits, unsigned Flags,
333 DIType Ty, MDNode *PropertyNode) {
334 return MDDerivedType::get(
335 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
336 MDScopeRef::get(getNonCompileUnitScope(File)), MDTypeRef::get(Ty),
337 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
341 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
342 StringRef GetterName, StringRef SetterName,
343 unsigned PropertyAttributes, DIType Ty) {
344 return MDObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
345 SetterName, PropertyAttributes, Ty);
348 DITemplateTypeParameter
349 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
351 assert((!Context || isa<MDCompileUnit>(Context.get())) &&
352 "Expected compile unit");
353 return MDTemplateTypeParameter::get(VMContext, Name, MDTypeRef::get(Ty));
356 static DITemplateValueParameter
357 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
358 DIDescriptor Context, StringRef Name,
359 DIType Ty, Metadata *MD) {
360 assert((!Context || isa<MDCompileUnit>(Context.get())) &&
361 "Expected compile unit");
362 return MDTemplateValueParameter::get(VMContext, Tag, Name, MDTypeRef::get(Ty),
366 DITemplateValueParameter
367 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
368 DIType Ty, Constant *Val) {
369 return createTemplateValueParameterHelper(
370 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
371 getConstantOrNull(Val));
374 DITemplateValueParameter
375 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
376 DIType Ty, StringRef Val) {
377 return createTemplateValueParameterHelper(
378 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
379 MDString::get(VMContext, Val));
382 DITemplateValueParameter
383 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
384 DIType Ty, DIArray Val) {
385 return createTemplateValueParameterHelper(
386 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
390 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
391 DIFile File, unsigned LineNumber,
393 uint64_t AlignInBits,
394 uint64_t OffsetInBits,
395 unsigned Flags, DIType DerivedFrom,
398 MDNode *TemplateParams,
399 StringRef UniqueIdentifier) {
400 assert((!Context || isa<MDScope>(Context)) &&
401 "createClassType should be called with a valid Context");
402 // TAG_class_type is encoded in DICompositeType format.
403 DICompositeType R = MDCompositeType::get(
404 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
405 MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
406 MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
407 Elements, 0, MDTypeRef::get(VTableHolder),
408 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
409 if (!UniqueIdentifier.empty())
411 trackIfUnresolved(R);
415 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
416 StringRef Name, DIFile File,
419 uint64_t AlignInBits,
420 unsigned Flags, DIType DerivedFrom,
422 unsigned RunTimeLang,
424 StringRef UniqueIdentifier) {
425 DICompositeType R = MDCompositeType::get(
426 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
427 MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
428 MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
429 RunTimeLang, MDTypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
430 if (!UniqueIdentifier.empty())
432 trackIfUnresolved(R);
436 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
437 DIFile File, unsigned LineNumber,
439 uint64_t AlignInBits, unsigned Flags,
441 unsigned RunTimeLang,
442 StringRef UniqueIdentifier) {
443 DICompositeType R = MDCompositeType::get(
444 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
445 MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))), nullptr,
446 SizeInBits, AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr,
447 nullptr, UniqueIdentifier);
448 if (!UniqueIdentifier.empty())
450 trackIfUnresolved(R);
454 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
455 DITypeArray ParameterTypes,
457 return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
460 DICompositeType DIBuilder::createEnumerationType(
461 DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
462 uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
463 DIType UnderlyingType, StringRef UniqueIdentifier) {
464 DICompositeType CTy = MDCompositeType::get(
465 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
466 MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))),
467 MDTypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
468 0, nullptr, nullptr, UniqueIdentifier);
469 AllEnumTypes.push_back(CTy);
470 if (!UniqueIdentifier.empty())
472 trackIfUnresolved(CTy);
476 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
477 DIType Ty, DIArray Subscripts) {
478 auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
479 nullptr, 0, nullptr, MDTypeRef::get(Ty), Size,
480 AlignInBits, 0, 0, Subscripts, 0, nullptr);
481 trackIfUnresolved(R);
485 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
486 DIType Ty, DIArray Subscripts) {
488 MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
489 nullptr, MDTypeRef::get(Ty), Size, AlignInBits, 0,
490 DebugNode::FlagVector, Subscripts, 0, nullptr);
491 trackIfUnresolved(R);
495 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
496 unsigned FlagsToSet) {
497 TempMDType NewTy = cast<MDType>(static_cast<MDNode *>(Ty))->clone();
498 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
499 return MDNode::replaceWithUniqued(std::move(NewTy));
502 DIType DIBuilder::createArtificialType(DIType Ty) {
503 // FIXME: Restrict this to the nodes where it's valid.
504 if (Ty->isArtificial())
506 return createTypeWithFlags(VMContext, Ty, DebugNode::FlagArtificial);
509 DIType DIBuilder::createObjectPointerType(DIType Ty) {
510 // FIXME: Restrict this to the nodes where it's valid.
511 if (Ty->isObjectPointer())
513 unsigned Flags = DebugNode::FlagObjectPointer | DebugNode::FlagArtificial;
514 return createTypeWithFlags(VMContext, Ty, Flags);
517 void DIBuilder::retainType(DIType T) {
518 assert(T && "Expected non-null type");
519 AllRetainTypes.emplace_back(T);
522 DIBasicType DIBuilder::createUnspecifiedParameter() { return nullptr; }
525 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
526 DIFile F, unsigned Line, unsigned RuntimeLang,
527 uint64_t SizeInBits, uint64_t AlignInBits,
528 StringRef UniqueIdentifier) {
529 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
530 // replaceWithUniqued().
531 DICompositeType RetTy = MDCompositeType::get(
532 VMContext, Tag, Name, F, Line,
533 MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))), nullptr,
534 SizeInBits, AlignInBits, 0, DIDescriptor::FlagFwdDecl, nullptr,
535 RuntimeLang, nullptr, nullptr, UniqueIdentifier);
536 if (!UniqueIdentifier.empty())
538 trackIfUnresolved(RetTy);
542 DICompositeType DIBuilder::createReplaceableCompositeType(
543 unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
544 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
545 unsigned Flags, StringRef UniqueIdentifier) {
546 DICompositeType RetTy =
547 MDCompositeType::getTemporary(
548 VMContext, Tag, Name, F, Line,
549 MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))), nullptr,
550 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
551 nullptr, UniqueIdentifier)
553 if (!UniqueIdentifier.empty())
555 trackIfUnresolved(RetTy);
559 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
560 return DIArray(MDNode::get(VMContext, Elements));
563 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
564 SmallVector<llvm::Metadata *, 16> Elts;
565 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
566 if (Elements[i] && isa<MDNode>(Elements[i]))
567 Elts.push_back(MDTypeRef::get(cast<MDType>(Elements[i])));
569 Elts.push_back(Elements[i]);
571 return DITypeArray(MDNode::get(VMContext, Elts));
574 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
575 return MDSubrange::get(VMContext, Count, Lo);
578 static void checkGlobalVariableScope(DIDescriptor Context) {
581 dyn_cast_or_null<MDCompositeType>(getNonCompileUnitScope(Context)))
582 assert(CT->getIdentifier().empty() &&
583 "Context of a global variable should not be a type with identifier");
587 DIGlobalVariable DIBuilder::createGlobalVariable(
588 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
589 unsigned LineNumber, DIType Ty, bool isLocalToUnit, Constant *Val,
591 checkGlobalVariableScope(Context);
593 auto *N = MDGlobalVariable::get(
594 VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName, F,
595 LineNumber, MDTypeRef::get(Ty), isLocalToUnit, true, Val,
596 cast_or_null<MDDerivedType>(Decl));
601 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
602 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
603 unsigned LineNumber, DIType Ty, bool isLocalToUnit, Constant *Val,
605 checkGlobalVariableScope(Context);
607 return MDGlobalVariable::getTemporary(
608 VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName,
609 F, LineNumber, MDTypeRef::get(Ty), isLocalToUnit, false, Val,
610 cast_or_null<MDDerivedType>(Decl)).release();
613 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
614 StringRef Name, DIFile File,
615 unsigned LineNo, DIType Ty,
616 bool AlwaysPreserve, unsigned Flags,
618 // FIXME: Why getNonCompileUnitScope()?
619 // FIXME: Why is "!Context" okay here?
620 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
621 // the only valid scopes)?
622 DIScope Context = getNonCompileUnitScope(Scope);
624 auto *Node = MDLocalVariable::get(
625 VMContext, Tag, cast_or_null<MDLocalScope>(Context.get()), Name, File,
626 LineNo, MDTypeRef::get(Ty), ArgNo, Flags);
627 if (AlwaysPreserve) {
628 // The optimizer may remove local variable. If there is an interest
629 // to preserve variable info in such situation then stash it in a
631 DISubprogram Fn(getDISubprogram(Scope));
632 assert(Fn && "Missing subprogram for local variable");
633 PreservedVariables[Fn].emplace_back(Node);
638 DIExpression DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
639 return MDExpression::get(VMContext, Addr);
642 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
643 // TODO: Remove the callers of this signed version and delete.
644 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
645 return createExpression(Addr);
648 DIExpression DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
649 unsigned SizeInBytes) {
650 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
651 return MDExpression::get(VMContext, Addr);
654 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
655 StringRef LinkageName, DIFile File,
656 unsigned LineNo, DICompositeType Ty,
657 bool isLocalToUnit, bool isDefinition,
658 unsigned ScopeLine, unsigned Flags,
659 bool isOptimized, Function *Fn,
660 MDNode *TParams, MDNode *Decl) {
661 // dragonegg does not generate identifier for types, so using an empty map
662 // to resolve the context should be fine.
663 DITypeIdentifierMap EmptyMap;
664 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
665 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
666 Flags, isOptimized, Fn, TParams, Decl);
669 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
670 StringRef LinkageName, DIFile File,
671 unsigned LineNo, DICompositeType Ty,
672 bool isLocalToUnit, bool isDefinition,
673 unsigned ScopeLine, unsigned Flags,
674 bool isOptimized, Function *Fn,
675 MDNode *TParams, MDNode *Decl) {
676 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
677 "function types should be subroutines");
678 auto *Node = MDSubprogram::get(
679 VMContext, MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
680 Name, LinkageName, File, LineNo, cast_or_null<MDSubroutineType>(Ty),
681 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
682 Fn, cast_or_null<MDTuple>(TParams), cast_or_null<MDSubprogram>(Decl),
683 MDTuple::getTemporary(VMContext, None).release());
686 AllSubprograms.push_back(Node);
687 trackIfUnresolved(Node);
692 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
693 StringRef LinkageName, DIFile File,
694 unsigned LineNo, DICompositeType Ty,
695 bool isLocalToUnit, bool isDefinition,
696 unsigned ScopeLine, unsigned Flags,
697 bool isOptimized, Function *Fn,
698 MDNode *TParams, MDNode *Decl) {
699 return MDSubprogram::getTemporary(
701 MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))), Name,
702 LinkageName, File, LineNo, cast_or_null<MDSubroutineType>(Ty),
703 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags,
704 isOptimized, Fn, cast_or_null<MDTuple>(TParams),
705 cast_or_null<MDSubprogram>(Decl), nullptr)
709 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
710 StringRef LinkageName, DIFile F,
711 unsigned LineNo, DICompositeType Ty,
712 bool isLocalToUnit, bool isDefinition,
713 unsigned VK, unsigned VIndex,
714 DIType VTableHolder, unsigned Flags,
715 bool isOptimized, Function *Fn,
717 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
718 "function types should be subroutines");
719 assert(getNonCompileUnitScope(Context) &&
720 "Methods should have both a Context and a context that isn't "
721 "the compile unit.");
722 // FIXME: Do we want to use different scope/lines?
723 auto *SP = MDSubprogram::get(
724 VMContext, MDScopeRef::get(cast<MDScope>(Context)), Name, LinkageName, F,
725 LineNo, cast_or_null<MDSubroutineType>(Ty), isLocalToUnit, isDefinition,
726 LineNo, MDTypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
727 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
730 AllSubprograms.push_back(SP);
731 trackIfUnresolved(SP);
735 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
736 DIFile File, unsigned LineNo) {
737 return MDNamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
741 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
743 unsigned Discriminator) {
744 return MDLexicalBlockFile::get(VMContext, Scope, File, Discriminator);
747 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
748 unsigned Line, unsigned Col) {
749 // Make these distinct, to avoid merging two lexical blocks on the same
751 return MDLexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
755 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
756 assert(V && "no value passed to dbg intrinsic");
757 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
760 static Instruction *withDebugLoc(Instruction *I, const MDLocation *DL) {
761 I->setDebugLoc(const_cast<MDLocation *>(DL));
765 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
766 DIExpression Expr, const MDLocation *DL,
767 Instruction *InsertBefore) {
768 assert(VarInfo && "empty or invalid DIVariable passed to dbg.declare");
769 assert(DL && "Expected debug loc");
770 assert(DL->getScope()->getSubprogram() ==
771 VarInfo->getScope()->getSubprogram() &&
772 "Expected matching subprograms");
774 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
776 trackIfUnresolved(VarInfo);
777 trackIfUnresolved(Expr);
778 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
779 MetadataAsValue::get(VMContext, VarInfo),
780 MetadataAsValue::get(VMContext, Expr)};
781 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
784 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
785 DIExpression Expr, const MDLocation *DL,
786 BasicBlock *InsertAtEnd) {
787 assert(VarInfo && "empty or invalid DIVariable passed to dbg.declare");
788 assert(DL && "Expected debug loc");
789 assert(DL->getScope()->getSubprogram() ==
790 VarInfo->getScope()->getSubprogram() &&
791 "Expected matching subprograms");
793 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
795 trackIfUnresolved(VarInfo);
796 trackIfUnresolved(Expr);
797 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
798 MetadataAsValue::get(VMContext, VarInfo),
799 MetadataAsValue::get(VMContext, Expr)};
801 // If this block already has a terminator then insert this intrinsic
802 // before the terminator.
803 if (TerminatorInst *T = InsertAtEnd->getTerminator())
804 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
805 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
808 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
811 const MDLocation *DL,
812 Instruction *InsertBefore) {
813 assert(V && "no value passed to dbg.value");
814 assert(VarInfo && "empty or invalid DIVariable passed to dbg.value");
815 assert(DL && "Expected debug loc");
816 assert(DL->getScope()->getSubprogram() ==
817 VarInfo->getScope()->getSubprogram() &&
818 "Expected matching subprograms");
820 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
822 trackIfUnresolved(VarInfo);
823 trackIfUnresolved(Expr);
824 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
825 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
826 MetadataAsValue::get(VMContext, VarInfo),
827 MetadataAsValue::get(VMContext, Expr)};
828 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
831 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
834 const MDLocation *DL,
835 BasicBlock *InsertAtEnd) {
836 assert(V && "no value passed to dbg.value");
837 assert(VarInfo && "empty or invalid DIVariable passed to dbg.value");
838 assert(DL && "Expected debug loc");
839 assert(DL->getScope()->getSubprogram() ==
840 VarInfo->getScope()->getSubprogram() &&
841 "Expected matching subprograms");
843 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
845 trackIfUnresolved(VarInfo);
846 trackIfUnresolved(Expr);
847 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
848 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
849 MetadataAsValue::get(VMContext, VarInfo),
850 MetadataAsValue::get(VMContext, Expr)};
852 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
855 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
857 TypedTrackingMDRef<MDCompositeTypeBase> N(T);
858 N->replaceVTableHolder(MDTypeRef::get(VTableHolder));
862 // If this didn't create a self-reference, just return.
863 if (T != VTableHolder)
866 // Look for unresolved operands. T will drop RAUW support, orphaning any
867 // cycles underneath it.
869 for (const MDOperand &O : T->operands())
870 if (auto *N = dyn_cast_or_null<MDNode>(O))
871 trackIfUnresolved(N);
874 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
877 TypedTrackingMDRef<MDCompositeTypeBase> N(T);
879 N->replaceElements(Elements);
881 N->replaceTemplateParams(MDTemplateParameterArray(TParams));
885 // If T isn't resolved, there's no problem.
886 if (!T->isResolved())
889 // If "T" is resolved, it may be due to a self-reference cycle. Track the
890 // arrays explicitly if they're unresolved, or else the cycles will be
893 trackIfUnresolved(Elements.get());
895 trackIfUnresolved(TParams.get());