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 MDSubprogramArray 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 DIArray 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 MDScope *getNonCompileUnitScope(MDScope *N) {
120 if (!N || isa<MDCompileUnit>(N))
122 return cast<MDScope>(N);
125 MDCompileUnit *DIBuilder::createCompileUnit(
126 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
127 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
128 DebugEmissionKind Kind, 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 MDCompileUnit 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 // TODO: Switch to getDistinct(). We never want to merge compile units based
146 MDCompileUnit *CUNode = MDCompileUnit::get(
147 VMContext, Lang, MDFile::get(VMContext, Filename, Directory), Producer,
148 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
149 TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
150 TempImportedModules.get());
152 // Create a named metadata so that it is easier to find cu in a module.
153 // Note that we only generate this when the caller wants to actually
154 // emit debug information. When we are only interested in tracking
155 // source line locations throughout the backend, we prevent codegen from
156 // emitting debug info in the final output by not generating llvm.dbg.cu.
158 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
159 NMD->addOperand(CUNode);
162 trackIfUnresolved(CUNode);
166 static MDImportedEntity*
167 createImportedModule(LLVMContext &C, dwarf::Tag Tag, MDScope* Context,
168 Metadata *NS, unsigned Line, StringRef Name,
169 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
171 MDImportedEntity::get(C, Tag, Context, DebugNodeRef(NS), Line, Name);
172 AllImportedModules.emplace_back(M);
176 MDImportedEntity* DIBuilder::createImportedModule(MDScope* Context,
179 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
180 Context, NS, Line, StringRef(), AllImportedModules);
183 MDImportedEntity* DIBuilder::createImportedModule(MDScope* Context,
184 MDImportedEntity* NS,
186 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
187 Context, NS, Line, StringRef(), AllImportedModules);
190 MDImportedEntity *DIBuilder::createImportedDeclaration(MDScope *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, DebugNodeRef::get(Decl), Line, Name,
201 MDFile* DIBuilder::createFile(StringRef Filename, StringRef Directory) {
202 return MDFile::get(VMContext, Filename, Directory);
205 MDEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
206 assert(!Name.empty() && "Unable to create enumerator without name");
207 return MDEnumerator::get(VMContext, Val, Name);
210 MDBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
211 assert(!Name.empty() && "Unable to create type without name");
212 return MDBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
215 MDBasicType *DIBuilder::createNullPtrType() {
216 return createUnspecifiedType("decltype(nullptr)");
219 MDBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
220 uint64_t AlignInBits,
222 assert(!Name.empty() && "Unable to create type without name");
223 return MDBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
224 AlignInBits, Encoding);
227 MDDerivedType *DIBuilder::createQualifiedType(unsigned Tag, MDType *FromTy) {
228 return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
229 MDTypeRef::get(FromTy), 0, 0, 0, 0);
232 MDDerivedType *DIBuilder::createPointerType(MDType *PointeeTy,
234 uint64_t AlignInBits,
236 // FIXME: Why is there a name here?
237 return MDDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
238 nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
239 SizeInBits, AlignInBits, 0, 0);
242 MDDerivedType *DIBuilder::createMemberPointerType(MDType *PointeeTy,
245 uint64_t AlignInBits) {
246 return MDDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
247 nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
248 SizeInBits, AlignInBits, 0, 0, MDTypeRef::get(Base));
251 MDDerivedType *DIBuilder::createReferenceType(unsigned Tag, MDType *RTy) {
252 assert(RTy && "Unable to create reference type");
253 return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
254 MDTypeRef::get(RTy), 0, 0, 0, 0);
257 MDDerivedType *DIBuilder::createTypedef(MDType *Ty, StringRef Name,
258 MDFile *File, unsigned LineNo,
260 return MDDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
262 MDScopeRef::get(getNonCompileUnitScope(Context)),
263 MDTypeRef::get(Ty), 0, 0, 0, 0);
266 MDDerivedType *DIBuilder::createFriend(MDType *Ty, MDType *FriendTy) {
267 assert(Ty && "Invalid type!");
268 assert(FriendTy && "Invalid friend type!");
269 return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
270 MDTypeRef::get(Ty), MDTypeRef::get(FriendTy), 0, 0,
274 MDDerivedType *DIBuilder::createInheritance(MDType *Ty, MDType *BaseTy,
277 assert(Ty && "Unable to create inheritance");
278 return MDDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
279 0, MDTypeRef::get(Ty), MDTypeRef::get(BaseTy), 0, 0,
283 MDDerivedType *DIBuilder::createMemberType(MDScope *Scope, StringRef Name,
284 MDFile *File, unsigned LineNumber,
286 uint64_t AlignInBits,
287 uint64_t OffsetInBits,
288 unsigned Flags, MDType *Ty) {
289 return MDDerivedType::get(
290 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
291 MDScopeRef::get(getNonCompileUnitScope(Scope)), MDTypeRef::get(Ty),
292 SizeInBits, AlignInBits, OffsetInBits, Flags);
295 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
297 return ConstantAsMetadata::get(C);
301 MDDerivedType *DIBuilder::createStaticMemberType(MDScope *Scope, StringRef Name,
304 MDType *Ty, unsigned Flags,
305 llvm::Constant *Val) {
306 Flags |= DebugNode::FlagStaticMember;
307 return MDDerivedType::get(
308 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
309 MDScopeRef::get(getNonCompileUnitScope(Scope)), MDTypeRef::get(Ty), 0, 0,
310 0, Flags, getConstantOrNull(Val));
313 MDDerivedType *DIBuilder::createObjCIVar(StringRef Name, MDFile *File,
316 uint64_t AlignInBits,
317 uint64_t OffsetInBits, unsigned Flags,
318 MDType *Ty, MDNode *PropertyNode) {
319 return MDDerivedType::get(
320 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
321 MDScopeRef::get(getNonCompileUnitScope(File)), MDTypeRef::get(Ty),
322 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
326 DIBuilder::createObjCProperty(StringRef Name, MDFile *File, unsigned LineNumber,
327 StringRef GetterName, StringRef SetterName,
328 unsigned PropertyAttributes, MDType *Ty) {
329 return MDObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
330 SetterName, PropertyAttributes, Ty);
333 MDTemplateTypeParameter *
334 DIBuilder::createTemplateTypeParameter(MDScope *Context, StringRef Name,
336 assert((!Context || isa<MDCompileUnit>(Context)) && "Expected compile unit");
337 return MDTemplateTypeParameter::get(VMContext, Name, MDTypeRef::get(Ty));
340 static MDTemplateValueParameter *
341 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
342 MDScope *Context, StringRef Name, MDType *Ty,
344 assert((!Context || isa<MDCompileUnit>(Context)) && "Expected compile unit");
345 return MDTemplateValueParameter::get(VMContext, Tag, Name, MDTypeRef::get(Ty),
349 MDTemplateValueParameter *
350 DIBuilder::createTemplateValueParameter(MDScope *Context, StringRef Name,
351 MDType *Ty, Constant *Val) {
352 return createTemplateValueParameterHelper(
353 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
354 getConstantOrNull(Val));
357 MDTemplateValueParameter *
358 DIBuilder::createTemplateTemplateParameter(MDScope *Context, StringRef Name,
359 MDType *Ty, StringRef Val) {
360 return createTemplateValueParameterHelper(
361 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
362 MDString::get(VMContext, Val));
365 MDTemplateValueParameter *
366 DIBuilder::createTemplateParameterPack(MDScope *Context, StringRef Name,
367 MDType *Ty, DIArray Val) {
368 return createTemplateValueParameterHelper(
369 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
373 MDCompositeType *DIBuilder::createClassType(
374 MDScope *Context, StringRef Name, MDFile *File, unsigned LineNumber,
375 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
376 unsigned Flags, MDType *DerivedFrom, DIArray Elements, MDType *VTableHolder,
377 MDNode *TemplateParams, StringRef UniqueIdentifier) {
378 assert((!Context || isa<MDScope>(Context)) &&
379 "createClassType should be called with a valid Context");
381 auto *R = MDCompositeType::get(
382 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
383 MDScopeRef::get(getNonCompileUnitScope(Context)),
384 MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
385 Elements, 0, MDTypeRef::get(VTableHolder),
386 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
387 if (!UniqueIdentifier.empty())
389 trackIfUnresolved(R);
393 MDCompositeType *DIBuilder::createStructType(
394 MDScope *Context, StringRef Name, MDFile *File, unsigned LineNumber,
395 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
396 MDType *DerivedFrom, DIArray Elements, unsigned RunTimeLang,
397 MDType *VTableHolder, StringRef UniqueIdentifier) {
398 auto *R = MDCompositeType::get(
399 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
400 MDScopeRef::get(getNonCompileUnitScope(Context)),
401 MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
402 RunTimeLang, MDTypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
403 if (!UniqueIdentifier.empty())
405 trackIfUnresolved(R);
409 MDCompositeType* DIBuilder::createUnionType(MDScope * Scope, StringRef Name,
410 MDFile* File, unsigned LineNumber,
412 uint64_t AlignInBits, unsigned Flags,
414 unsigned RunTimeLang,
415 StringRef UniqueIdentifier) {
416 auto *R = MDCompositeType::get(
417 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
418 MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
419 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
421 if (!UniqueIdentifier.empty())
423 trackIfUnresolved(R);
427 MDSubroutineType *DIBuilder::createSubroutineType(MDFile *File,
428 DITypeArray ParameterTypes,
430 return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
433 MDCompositeType *DIBuilder::createEnumerationType(
434 MDScope *Scope, StringRef Name, MDFile *File, unsigned LineNumber,
435 uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
436 MDType *UnderlyingType, StringRef UniqueIdentifier) {
437 auto *CTy = MDCompositeType::get(
438 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
439 MDScopeRef::get(getNonCompileUnitScope(Scope)),
440 MDTypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
441 0, nullptr, nullptr, UniqueIdentifier);
442 AllEnumTypes.push_back(CTy);
443 if (!UniqueIdentifier.empty())
445 trackIfUnresolved(CTy);
449 MDCompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
450 MDType *Ty, DIArray Subscripts) {
451 auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
452 nullptr, 0, nullptr, MDTypeRef::get(Ty), Size,
453 AlignInBits, 0, 0, Subscripts, 0, nullptr);
454 trackIfUnresolved(R);
458 MDCompositeType *DIBuilder::createVectorType(uint64_t Size,
459 uint64_t AlignInBits, MDType *Ty,
460 DIArray Subscripts) {
462 MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
463 nullptr, MDTypeRef::get(Ty), Size, AlignInBits, 0,
464 DebugNode::FlagVector, Subscripts, 0, nullptr);
465 trackIfUnresolved(R);
469 static MDType *createTypeWithFlags(LLVMContext &Context, MDType *Ty,
470 unsigned FlagsToSet) {
471 auto NewTy = Ty->clone();
472 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
473 return MDNode::replaceWithUniqued(std::move(NewTy));
476 MDType *DIBuilder::createArtificialType(MDType *Ty) {
477 // FIXME: Restrict this to the nodes where it's valid.
478 if (Ty->isArtificial())
480 return createTypeWithFlags(VMContext, Ty, DebugNode::FlagArtificial);
483 MDType *DIBuilder::createObjectPointerType(MDType *Ty) {
484 // FIXME: Restrict this to the nodes where it's valid.
485 if (Ty->isObjectPointer())
487 unsigned Flags = DebugNode::FlagObjectPointer | DebugNode::FlagArtificial;
488 return createTypeWithFlags(VMContext, Ty, Flags);
491 void DIBuilder::retainType(MDType *T) {
492 assert(T && "Expected non-null type");
493 AllRetainTypes.emplace_back(T);
496 MDBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
499 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, MDScope * Scope,
500 MDFile* 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 = MDCompositeType::get(
506 VMContext, Tag, Name, F, Line,
507 MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
508 AlignInBits, 0, DebugNode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
509 nullptr, UniqueIdentifier);
510 if (!UniqueIdentifier.empty())
512 trackIfUnresolved(RetTy);
516 MDCompositeType* DIBuilder::createReplaceableCompositeType(
517 unsigned Tag, StringRef Name, MDScope * Scope, MDFile* F, unsigned Line,
518 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
519 unsigned Flags, StringRef UniqueIdentifier) {
520 auto *RetTy = MDCompositeType::getTemporary(
521 VMContext, Tag, Name, F, Line,
522 MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
523 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
524 nullptr, nullptr, UniqueIdentifier).release();
525 if (!UniqueIdentifier.empty())
527 trackIfUnresolved(RetTy);
531 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
532 return MDTuple::get(VMContext, Elements);
535 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
536 SmallVector<llvm::Metadata *, 16> Elts;
537 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
538 if (Elements[i] && isa<MDNode>(Elements[i]))
539 Elts.push_back(MDTypeRef::get(cast<MDType>(Elements[i])));
541 Elts.push_back(Elements[i]);
543 return DITypeArray(MDNode::get(VMContext, Elts));
546 MDSubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
547 return MDSubrange::get(VMContext, Count, Lo);
550 static void checkGlobalVariableScope(MDScope * Context) {
553 dyn_cast_or_null<MDCompositeType>(getNonCompileUnitScope(Context)))
554 assert(CT->getIdentifier().empty() &&
555 "Context of a global variable should not be a type with identifier");
559 MDGlobalVariable *DIBuilder::createGlobalVariable(
560 MDScope *Context, StringRef Name, StringRef LinkageName, MDFile *F,
561 unsigned LineNumber, MDType *Ty, bool isLocalToUnit, Constant *Val,
563 checkGlobalVariableScope(Context);
565 auto *N = MDGlobalVariable::get(VMContext, cast_or_null<MDScope>(Context),
566 Name, LinkageName, F, LineNumber,
567 MDTypeRef::get(Ty), isLocalToUnit, true, Val,
568 cast_or_null<MDDerivedType>(Decl));
573 MDGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
574 MDScope *Context, StringRef Name, StringRef LinkageName, MDFile *F,
575 unsigned LineNumber, MDType *Ty, bool isLocalToUnit, Constant *Val,
577 checkGlobalVariableScope(Context);
579 return MDGlobalVariable::getTemporary(
580 VMContext, cast_or_null<MDScope>(Context), Name, LinkageName, F,
581 LineNumber, MDTypeRef::get(Ty), isLocalToUnit, false, Val,
582 cast_or_null<MDDerivedType>(Decl))
586 MDLocalVariable *DIBuilder::createLocalVariable(
587 unsigned Tag, MDScope *Scope, StringRef Name, MDFile *File, unsigned LineNo,
588 MDType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
589 // FIXME: Why getNonCompileUnitScope()?
590 // FIXME: Why is "!Context" okay here?
591 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
592 // the only valid scopes)?
593 MDScope* Context = getNonCompileUnitScope(Scope);
595 auto *Node = MDLocalVariable::get(
596 VMContext, Tag, cast_or_null<MDLocalScope>(Context), Name, File, LineNo,
597 MDTypeRef::get(Ty), ArgNo, Flags);
598 if (AlwaysPreserve) {
599 // The optimizer may remove local variable. If there is an interest
600 // to preserve variable info in such situation then stash it in a
602 MDSubprogram *Fn = getDISubprogram(Scope);
603 assert(Fn && "Missing subprogram for local variable");
604 PreservedVariables[Fn].emplace_back(Node);
609 MDExpression* DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
610 return MDExpression::get(VMContext, Addr);
613 MDExpression* DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
614 // TODO: Remove the callers of this signed version and delete.
615 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
616 return createExpression(Addr);
619 MDExpression* DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
620 unsigned SizeInBytes) {
621 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
622 return MDExpression::get(VMContext, Addr);
625 MDSubprogram *DIBuilder::createFunction(MDScopeRef Context, StringRef Name,
626 StringRef LinkageName, MDFile *File,
627 unsigned LineNo, MDSubroutineType *Ty,
628 bool isLocalToUnit, bool isDefinition,
629 unsigned ScopeLine, unsigned Flags,
630 bool isOptimized, Function *Fn,
631 MDNode *TParams, MDNode *Decl) {
632 // dragonegg does not generate identifier for types, so using an empty map
633 // to resolve the context should be fine.
634 DITypeIdentifierMap EmptyMap;
635 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
636 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
637 Flags, isOptimized, Fn, TParams, Decl);
640 MDSubprogram* DIBuilder::createFunction(MDScope * Context, StringRef Name,
641 StringRef LinkageName, MDFile* File,
642 unsigned LineNo, MDSubroutineType* Ty,
643 bool isLocalToUnit, bool isDefinition,
644 unsigned ScopeLine, unsigned Flags,
645 bool isOptimized, Function *Fn,
646 MDNode *TParams, MDNode *Decl) {
647 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
648 "function types should be subroutines");
649 auto *Node = MDSubprogram::get(
650 VMContext, MDScopeRef::get(getNonCompileUnitScope(Context)), Name,
651 LinkageName, File, LineNo, Ty,
652 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
653 Fn, cast_or_null<MDTuple>(TParams), cast_or_null<MDSubprogram>(Decl),
654 MDTuple::getTemporary(VMContext, None).release());
657 AllSubprograms.push_back(Node);
658 trackIfUnresolved(Node);
663 DIBuilder::createTempFunctionFwdDecl(MDScope * Context, StringRef Name,
664 StringRef LinkageName, MDFile* File,
665 unsigned LineNo, MDSubroutineType* Ty,
666 bool isLocalToUnit, bool isDefinition,
667 unsigned ScopeLine, unsigned Flags,
668 bool isOptimized, Function *Fn,
669 MDNode *TParams, MDNode *Decl) {
670 return MDSubprogram::getTemporary(
671 VMContext, MDScopeRef::get(getNonCompileUnitScope(Context)), Name,
672 LinkageName, File, LineNo, Ty,
673 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags,
674 isOptimized, Fn, cast_or_null<MDTuple>(TParams),
675 cast_or_null<MDSubprogram>(Decl), nullptr).release();
679 DIBuilder::createMethod(MDScope *Context, StringRef Name, StringRef LinkageName,
680 MDFile *F, unsigned LineNo, MDSubroutineType *Ty,
681 bool isLocalToUnit, bool isDefinition, unsigned VK,
682 unsigned VIndex, MDType *VTableHolder, unsigned Flags,
683 bool isOptimized, Function *Fn, MDNode *TParam) {
684 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
685 "function types should be subroutines");
686 assert(getNonCompileUnitScope(Context) &&
687 "Methods should have both a Context and a context that isn't "
688 "the compile unit.");
689 // FIXME: Do we want to use different scope/lines?
690 auto *SP = MDSubprogram::get(
691 VMContext, MDScopeRef::get(cast<MDScope>(Context)), Name, LinkageName, F,
692 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
693 MDTypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
694 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
697 AllSubprograms.push_back(SP);
698 trackIfUnresolved(SP);
702 MDNamespace* DIBuilder::createNameSpace(MDScope * Scope, StringRef Name,
703 MDFile* File, unsigned LineNo) {
704 return MDNamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
708 MDLexicalBlockFile* DIBuilder::createLexicalBlockFile(MDScope * Scope,
710 unsigned Discriminator) {
711 return MDLexicalBlockFile::get(VMContext, Scope, File, Discriminator);
714 MDLexicalBlock* DIBuilder::createLexicalBlock(MDScope * Scope, MDFile* File,
715 unsigned Line, unsigned Col) {
716 // Make these distinct, to avoid merging two lexical blocks on the same
718 return MDLexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
722 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
723 assert(V && "no value passed to dbg intrinsic");
724 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
727 static Instruction *withDebugLoc(Instruction *I, const MDLocation *DL) {
728 I->setDebugLoc(const_cast<MDLocation *>(DL));
732 Instruction *DIBuilder::insertDeclare(Value *Storage, MDLocalVariable* VarInfo,
733 MDExpression* Expr, const MDLocation *DL,
734 Instruction *InsertBefore) {
735 assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.declare");
736 assert(DL && "Expected debug loc");
737 assert(DL->getScope()->getSubprogram() ==
738 VarInfo->getScope()->getSubprogram() &&
739 "Expected matching subprograms");
741 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
743 trackIfUnresolved(VarInfo);
744 trackIfUnresolved(Expr);
745 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
746 MetadataAsValue::get(VMContext, VarInfo),
747 MetadataAsValue::get(VMContext, Expr)};
748 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
751 Instruction *DIBuilder::insertDeclare(Value *Storage, MDLocalVariable* VarInfo,
752 MDExpression* Expr, const MDLocation *DL,
753 BasicBlock *InsertAtEnd) {
754 assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.declare");
755 assert(DL && "Expected debug loc");
756 assert(DL->getScope()->getSubprogram() ==
757 VarInfo->getScope()->getSubprogram() &&
758 "Expected matching subprograms");
760 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
762 trackIfUnresolved(VarInfo);
763 trackIfUnresolved(Expr);
764 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
765 MetadataAsValue::get(VMContext, VarInfo),
766 MetadataAsValue::get(VMContext, Expr)};
768 // If this block already has a terminator then insert this intrinsic
769 // before the terminator.
770 if (TerminatorInst *T = InsertAtEnd->getTerminator())
771 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
772 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
775 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
776 MDLocalVariable* VarInfo,
778 const MDLocation *DL,
779 Instruction *InsertBefore) {
780 assert(V && "no value passed to dbg.value");
781 assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.value");
782 assert(DL && "Expected debug loc");
783 assert(DL->getScope()->getSubprogram() ==
784 VarInfo->getScope()->getSubprogram() &&
785 "Expected matching subprograms");
787 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
789 trackIfUnresolved(VarInfo);
790 trackIfUnresolved(Expr);
791 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
792 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
793 MetadataAsValue::get(VMContext, VarInfo),
794 MetadataAsValue::get(VMContext, Expr)};
795 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
798 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
799 MDLocalVariable* VarInfo,
801 const MDLocation *DL,
802 BasicBlock *InsertAtEnd) {
803 assert(V && "no value passed to dbg.value");
804 assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.value");
805 assert(DL && "Expected debug loc");
806 assert(DL->getScope()->getSubprogram() ==
807 VarInfo->getScope()->getSubprogram() &&
808 "Expected matching subprograms");
810 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
812 trackIfUnresolved(VarInfo);
813 trackIfUnresolved(Expr);
814 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
815 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
816 MetadataAsValue::get(VMContext, VarInfo),
817 MetadataAsValue::get(VMContext, Expr)};
819 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
822 void DIBuilder::replaceVTableHolder(MDCompositeType* &T, MDCompositeType* VTableHolder) {
824 TypedTrackingMDRef<MDCompositeType> N(T);
825 N->replaceVTableHolder(MDTypeRef::get(VTableHolder));
829 // If this didn't create a self-reference, just return.
830 if (T != VTableHolder)
833 // Look for unresolved operands. T will drop RAUW support, orphaning any
834 // cycles underneath it.
836 for (const MDOperand &O : T->operands())
837 if (auto *N = dyn_cast_or_null<MDNode>(O))
838 trackIfUnresolved(N);
841 void DIBuilder::replaceArrays(MDCompositeType* &T, DIArray Elements,
844 TypedTrackingMDRef<MDCompositeType> N(T);
846 N->replaceElements(Elements);
848 N->replaceTemplateParams(MDTemplateParameterArray(TParams));
852 // If T isn't resolved, there's no problem.
853 if (!T->isResolved())
856 // If "T" is resolved, it may be due to a self-reference cycle. Track the
857 // arrays explicitly if they're unresolved, or else the cycles will be
860 trackIfUnresolved(Elements.get());
862 trackIfUnresolved(TParams.get());