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 TempEnumTypes->replaceAllUsesWith(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 TempRetainTypes->replaceAllUsesWith(MDTuple::get(VMContext, RetainValues));
90 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
91 TempSubprograms->replaceAllUsesWith(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 TempGVs->replaceAllUsesWith(MDTuple::get(VMContext, AllGVs));
103 TempImportedModules->replaceAllUsesWith(MDTuple::get(
104 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
105 AllImportedModules.end())));
107 // Now that all temp nodes have been replaced or deleted, resolve remaining
109 for (const auto &N : UnresolvedNodes)
110 if (N && !N->isResolved())
112 UnresolvedNodes.clear();
114 // Can't handle unresolved nodes anymore.
115 AllowUnresolvedNodes = false;
118 /// If N is compile unit return NULL otherwise return N.
119 static DIScope *getNonCompileUnitScope(DIScope *N) {
120 if (!N || isa<DICompileUnit>(N))
122 return cast<DIScope>(N);
125 DICompileUnit *DIBuilder::createCompileUnit(
126 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
127 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
128 DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
130 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
131 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
132 "Invalid Language tag");
133 assert(!Filename.empty() &&
134 "Unable to create compile unit without filename");
136 // TODO: Once we make DICompileUnit distinct, stop using temporaries here
137 // (just start with operands assigned to nullptr).
138 TempEnumTypes = MDTuple::getTemporary(VMContext, None);
139 TempRetainTypes = MDTuple::getTemporary(VMContext, None);
140 TempSubprograms = MDTuple::getTemporary(VMContext, None);
141 TempGVs = MDTuple::getTemporary(VMContext, None);
142 TempImportedModules = MDTuple::getTemporary(VMContext, None);
144 DICompileUnit *CUNode = DICompileUnit::getDistinct(
145 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
146 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
147 TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
148 TempImportedModules.get(), DWOId);
150 // Create a named metadata so that it is easier to find cu in a module.
151 // Note that we only generate this when the caller wants to actually
152 // emit debug information. When we are only interested in tracking
153 // source line locations throughout the backend, we prevent codegen from
154 // emitting debug info in the final output by not generating llvm.dbg.cu.
156 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
157 NMD->addOperand(CUNode);
160 trackIfUnresolved(CUNode);
164 static DIImportedEntity *
165 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
166 Metadata *NS, unsigned Line, StringRef Name,
167 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
168 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
169 AllImportedModules.emplace_back(M);
173 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
176 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
177 Context, NS, Line, StringRef(), AllImportedModules);
180 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
181 DIImportedEntity *NS,
183 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
184 Context, NS, Line, StringRef(), AllImportedModules);
187 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
189 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
190 Context, M, Line, StringRef(), AllImportedModules);
193 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
197 // Make sure to use the unique identifier based metadata reference for
198 // types that have one.
199 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
200 Context, DINodeRef::get(Decl), Line, Name,
204 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
205 return DIFile::get(VMContext, Filename, Directory);
208 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
209 assert(!Name.empty() && "Unable to create enumerator without name");
210 return DIEnumerator::get(VMContext, Val, Name);
213 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
214 assert(!Name.empty() && "Unable to create type without name");
215 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
218 DIBasicType *DIBuilder::createNullPtrType() {
219 return createUnspecifiedType("decltype(nullptr)");
222 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
223 uint64_t AlignInBits,
225 assert(!Name.empty() && "Unable to create type without name");
226 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
227 AlignInBits, Encoding);
230 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
231 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
232 DITypeRef::get(FromTy), 0, 0, 0, 0);
235 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
237 uint64_t AlignInBits,
239 // FIXME: Why is there a name here?
240 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
241 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
242 SizeInBits, AlignInBits, 0, 0);
245 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
248 uint64_t AlignInBits) {
249 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
250 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
251 SizeInBits, AlignInBits, 0, 0,
252 DITypeRef::get(Base));
255 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
256 assert(RTy && "Unable to create reference type");
257 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
258 DITypeRef::get(RTy), 0, 0, 0, 0);
261 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
262 DIFile *File, unsigned LineNo,
264 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
266 DIScopeRef::get(getNonCompileUnitScope(Context)),
267 DITypeRef::get(Ty), 0, 0, 0, 0);
270 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
271 assert(Ty && "Invalid type!");
272 assert(FriendTy && "Invalid friend type!");
273 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
274 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
278 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
281 assert(Ty && "Unable to create inheritance");
282 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
283 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
287 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
288 DIFile *File, unsigned LineNumber,
290 uint64_t AlignInBits,
291 uint64_t OffsetInBits,
292 unsigned Flags, DIType *Ty) {
293 return DIDerivedType::get(
294 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
295 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
296 SizeInBits, AlignInBits, OffsetInBits, Flags);
299 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
301 return ConstantAsMetadata::get(C);
305 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
308 DIType *Ty, unsigned Flags,
309 llvm::Constant *Val) {
310 Flags |= DINode::FlagStaticMember;
311 return DIDerivedType::get(
312 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
313 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
314 0, Flags, getConstantOrNull(Val));
317 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
320 uint64_t AlignInBits,
321 uint64_t OffsetInBits, unsigned Flags,
322 DIType *Ty, MDNode *PropertyNode) {
323 return DIDerivedType::get(
324 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
325 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
326 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
330 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
331 StringRef GetterName, StringRef SetterName,
332 unsigned PropertyAttributes, DIType *Ty) {
333 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
334 SetterName, PropertyAttributes,
338 DITemplateTypeParameter *
339 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
341 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
342 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
345 static DITemplateValueParameter *
346 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
347 DIScope *Context, StringRef Name, DIType *Ty,
349 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
350 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
354 DITemplateValueParameter *
355 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
356 DIType *Ty, Constant *Val) {
357 return createTemplateValueParameterHelper(
358 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
359 getConstantOrNull(Val));
362 DITemplateValueParameter *
363 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
364 DIType *Ty, StringRef Val) {
365 return createTemplateValueParameterHelper(
366 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
367 MDString::get(VMContext, Val));
370 DITemplateValueParameter *
371 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
372 DIType *Ty, DINodeArray Val) {
373 return createTemplateValueParameterHelper(
374 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
378 DICompositeType *DIBuilder::createClassType(
379 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
380 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
381 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
382 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
383 assert((!Context || isa<DIScope>(Context)) &&
384 "createClassType should be called with a valid Context");
386 auto *R = DICompositeType::get(
387 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
388 DIScopeRef::get(getNonCompileUnitScope(Context)),
389 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
390 Elements, 0, DITypeRef::get(VTableHolder),
391 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
392 if (!UniqueIdentifier.empty())
394 trackIfUnresolved(R);
398 DICompositeType *DIBuilder::createStructType(
399 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
400 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
401 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
402 DIType *VTableHolder, StringRef UniqueIdentifier) {
403 auto *R = DICompositeType::get(
404 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
405 DIScopeRef::get(getNonCompileUnitScope(Context)),
406 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
407 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
408 if (!UniqueIdentifier.empty())
410 trackIfUnresolved(R);
414 DICompositeType *DIBuilder::createUnionType(
415 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
416 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
417 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
418 auto *R = DICompositeType::get(
419 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
420 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
421 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
423 if (!UniqueIdentifier.empty())
425 trackIfUnresolved(R);
429 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
430 DITypeRefArray ParameterTypes,
432 return DISubroutineType::get(VMContext, Flags, ParameterTypes);
435 DICompositeType *DIBuilder::createEnumerationType(
436 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
437 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
438 DIType *UnderlyingType, StringRef UniqueIdentifier) {
439 auto *CTy = DICompositeType::get(
440 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
441 DIScopeRef::get(getNonCompileUnitScope(Scope)),
442 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
443 0, nullptr, nullptr, UniqueIdentifier);
444 AllEnumTypes.push_back(CTy);
445 if (!UniqueIdentifier.empty())
447 trackIfUnresolved(CTy);
451 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
453 DINodeArray Subscripts) {
454 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
455 nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
456 AlignInBits, 0, 0, Subscripts, 0, nullptr);
457 trackIfUnresolved(R);
461 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
462 uint64_t AlignInBits, DIType *Ty,
463 DINodeArray Subscripts) {
465 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
466 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
467 DINode::FlagVector, Subscripts, 0, nullptr);
468 trackIfUnresolved(R);
472 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
473 unsigned FlagsToSet) {
474 auto NewTy = Ty->clone();
475 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
476 return MDNode::replaceWithUniqued(std::move(NewTy));
479 DIType *DIBuilder::createArtificialType(DIType *Ty) {
480 // FIXME: Restrict this to the nodes where it's valid.
481 if (Ty->isArtificial())
483 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
486 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
487 // FIXME: Restrict this to the nodes where it's valid.
488 if (Ty->isObjectPointer())
490 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
491 return createTypeWithFlags(VMContext, Ty, Flags);
494 void DIBuilder::retainType(DIType *T) {
495 assert(T && "Expected non-null type");
496 AllRetainTypes.emplace_back(T);
499 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
502 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
503 DIFile *F, unsigned Line, unsigned RuntimeLang,
504 uint64_t SizeInBits, uint64_t AlignInBits,
505 StringRef UniqueIdentifier) {
506 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
507 // replaceWithUniqued().
508 auto *RetTy = DICompositeType::get(
509 VMContext, Tag, Name, F, Line,
510 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
511 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
512 nullptr, UniqueIdentifier);
513 if (!UniqueIdentifier.empty())
515 trackIfUnresolved(RetTy);
519 DICompositeType *DIBuilder::createReplaceableCompositeType(
520 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
521 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
522 unsigned Flags, StringRef UniqueIdentifier) {
523 auto *RetTy = DICompositeType::getTemporary(
524 VMContext, Tag, Name, F, Line,
525 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
526 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
527 nullptr, nullptr, UniqueIdentifier)
529 if (!UniqueIdentifier.empty())
531 trackIfUnresolved(RetTy);
535 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
536 return MDTuple::get(VMContext, Elements);
539 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
540 SmallVector<llvm::Metadata *, 16> Elts;
541 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
542 if (Elements[i] && isa<MDNode>(Elements[i]))
543 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
545 Elts.push_back(Elements[i]);
547 return DITypeRefArray(MDNode::get(VMContext, Elts));
550 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
551 return DISubrange::get(VMContext, Count, Lo);
554 static void checkGlobalVariableScope(DIScope *Context) {
557 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
558 assert(CT->getIdentifier().empty() &&
559 "Context of a global variable should not be a type with identifier");
563 DIGlobalVariable *DIBuilder::createGlobalVariable(
564 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
565 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
567 checkGlobalVariableScope(Context);
569 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
570 Name, LinkageName, F, LineNumber,
571 DITypeRef::get(Ty), isLocalToUnit, true, Val,
572 cast_or_null<DIDerivedType>(Decl));
577 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
578 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
579 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
581 checkGlobalVariableScope(Context);
583 return DIGlobalVariable::getTemporary(
584 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
585 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
586 cast_or_null<DIDerivedType>(Decl))
590 DILocalVariable *DIBuilder::createLocalVariable(
591 unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
592 DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
593 // FIXME: Why getNonCompileUnitScope()?
594 // FIXME: Why is "!Context" okay here?
595 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
596 // the only valid scopes)?
597 DIScope *Context = getNonCompileUnitScope(Scope);
599 auto *Node = DILocalVariable::get(
600 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
601 DITypeRef::get(Ty), ArgNo, Flags);
602 if (AlwaysPreserve) {
603 // The optimizer may remove local variable. If there is an interest
604 // to preserve variable info in such situation then stash it in a
606 DISubprogram *Fn = getDISubprogram(Scope);
607 assert(Fn && "Missing subprogram for local variable");
608 PreservedVariables[Fn].emplace_back(Node);
613 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
614 return DIExpression::get(VMContext, Addr);
617 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
618 // TODO: Remove the callers of this signed version and delete.
619 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
620 return createExpression(Addr);
623 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
624 unsigned SizeInBytes) {
625 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
626 return DIExpression::get(VMContext, Addr);
629 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
630 StringRef LinkageName, DIFile *File,
631 unsigned LineNo, DISubroutineType *Ty,
632 bool isLocalToUnit, bool isDefinition,
633 unsigned ScopeLine, unsigned Flags,
634 bool isOptimized, Function *Fn,
635 MDNode *TParams, MDNode *Decl) {
636 // dragonegg does not generate identifier for types, so using an empty map
637 // to resolve the context should be fine.
638 DITypeIdentifierMap EmptyMap;
639 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
640 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
641 Flags, isOptimized, Fn, TParams, Decl);
644 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
645 StringRef LinkageName, DIFile *File,
646 unsigned LineNo, DISubroutineType *Ty,
647 bool isLocalToUnit, bool isDefinition,
648 unsigned ScopeLine, unsigned Flags,
649 bool isOptimized, Function *Fn,
650 MDNode *TParams, MDNode *Decl) {
651 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
652 "function types should be subroutines");
653 auto *Node = DISubprogram::get(
654 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
655 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
656 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
657 cast_or_null<DISubprogram>(Decl),
658 MDTuple::getTemporary(VMContext, None).release());
661 AllSubprograms.push_back(Node);
662 trackIfUnresolved(Node);
666 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
667 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
668 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
669 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
670 Function *Fn, MDNode *TParams, MDNode *Decl) {
671 return DISubprogram::getTemporary(
672 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
673 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
674 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
675 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
681 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
682 DIFile *F, unsigned LineNo, DISubroutineType *Ty,
683 bool isLocalToUnit, bool isDefinition, unsigned VK,
684 unsigned VIndex, DIType *VTableHolder, unsigned Flags,
685 bool isOptimized, Function *Fn, MDNode *TParam) {
686 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
687 "function types should be subroutines");
688 assert(getNonCompileUnitScope(Context) &&
689 "Methods should have both a Context and a context that isn't "
690 "the compile unit.");
691 // FIXME: Do we want to use different scope/lines?
692 auto *SP = DISubprogram::get(
693 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
694 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
695 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
696 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
699 AllSubprograms.push_back(SP);
700 trackIfUnresolved(SP);
704 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
705 DIFile *File, unsigned LineNo) {
706 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
710 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
711 StringRef ConfigurationMacros,
712 StringRef IncludePath,
713 StringRef ISysRoot) {
714 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
715 ConfigurationMacros, IncludePath, ISysRoot);
718 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
720 unsigned Discriminator) {
721 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
724 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
725 unsigned Line, unsigned Col) {
726 // Make these distinct, to avoid merging two lexical blocks on the same
728 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
732 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
733 assert(V && "no value passed to dbg intrinsic");
734 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
737 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
738 I->setDebugLoc(const_cast<DILocation *>(DL));
742 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
743 DIExpression *Expr, const DILocation *DL,
744 Instruction *InsertBefore) {
745 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
746 assert(DL && "Expected debug loc");
747 assert(DL->getScope()->getSubprogram() ==
748 VarInfo->getScope()->getSubprogram() &&
749 "Expected matching subprograms");
751 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
753 trackIfUnresolved(VarInfo);
754 trackIfUnresolved(Expr);
755 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
756 MetadataAsValue::get(VMContext, VarInfo),
757 MetadataAsValue::get(VMContext, Expr)};
758 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
761 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
762 DIExpression *Expr, const DILocation *DL,
763 BasicBlock *InsertAtEnd) {
764 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
765 assert(DL && "Expected debug loc");
766 assert(DL->getScope()->getSubprogram() ==
767 VarInfo->getScope()->getSubprogram() &&
768 "Expected matching subprograms");
770 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
772 trackIfUnresolved(VarInfo);
773 trackIfUnresolved(Expr);
774 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
775 MetadataAsValue::get(VMContext, VarInfo),
776 MetadataAsValue::get(VMContext, Expr)};
778 // If this block already has a terminator then insert this intrinsic
779 // before the terminator.
780 if (TerminatorInst *T = InsertAtEnd->getTerminator())
781 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
782 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
785 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
786 DILocalVariable *VarInfo,
788 const DILocation *DL,
789 Instruction *InsertBefore) {
790 assert(V && "no value passed to dbg.value");
791 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
792 assert(DL && "Expected debug loc");
793 assert(DL->getScope()->getSubprogram() ==
794 VarInfo->getScope()->getSubprogram() &&
795 "Expected matching subprograms");
797 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
799 trackIfUnresolved(VarInfo);
800 trackIfUnresolved(Expr);
801 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
802 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
803 MetadataAsValue::get(VMContext, VarInfo),
804 MetadataAsValue::get(VMContext, Expr)};
805 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
808 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
809 DILocalVariable *VarInfo,
811 const DILocation *DL,
812 BasicBlock *InsertAtEnd) {
813 assert(V && "no value passed to dbg.value");
814 assert(VarInfo && "empty or invalid DILocalVariable* 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)};
829 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
832 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
833 DICompositeType *VTableHolder) {
835 TypedTrackingMDRef<DICompositeType> N(T);
836 N->replaceVTableHolder(DITypeRef::get(VTableHolder));
840 // If this didn't create a self-reference, just return.
841 if (T != VTableHolder)
844 // Look for unresolved operands. T will drop RAUW support, orphaning any
845 // cycles underneath it.
847 for (const MDOperand &O : T->operands())
848 if (auto *N = dyn_cast_or_null<MDNode>(O))
849 trackIfUnresolved(N);
852 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
853 DINodeArray TParams) {
855 TypedTrackingMDRef<DICompositeType> N(T);
857 N->replaceElements(Elements);
859 N->replaceTemplateParams(DITemplateParameterArray(TParams));
863 // If T isn't resolved, there's no problem.
864 if (!T->isResolved())
867 // If "T" is resolved, it may be due to a self-reference cycle. Track the
868 // arrays explicitly if they're unresolved, or else the cycles will be
871 trackIfUnresolved(Elements.get());
873 trackIfUnresolved(TParams.get());