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 // TODO: Switch to getDistinct(). We never want to merge compile units based
146 DICompileUnit *CUNode = DICompileUnit::get(
147 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
148 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
149 TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
150 TempImportedModules.get(), DWOId);
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 DIImportedEntity *
167 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
168 Metadata *NS, unsigned Line, StringRef Name,
169 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
170 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
171 AllImportedModules.emplace_back(M);
175 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
178 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
179 Context, NS, Line, StringRef(), AllImportedModules);
182 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
183 DIImportedEntity *NS,
185 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
186 Context, NS, Line, StringRef(), AllImportedModules);
189 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
191 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
192 Context, M, Line, StringRef(), AllImportedModules);
195 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
199 // Make sure to use the unique identifier based metadata reference for
200 // types that have one.
201 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
202 Context, DINodeRef::get(Decl), Line, Name,
206 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
207 return DIFile::get(VMContext, Filename, Directory);
210 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
211 assert(!Name.empty() && "Unable to create enumerator without name");
212 return DIEnumerator::get(VMContext, Val, Name);
215 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
216 assert(!Name.empty() && "Unable to create type without name");
217 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
220 DIBasicType *DIBuilder::createNullPtrType() {
221 return createUnspecifiedType("decltype(nullptr)");
224 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
225 uint64_t AlignInBits,
227 assert(!Name.empty() && "Unable to create type without name");
228 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
229 AlignInBits, Encoding);
232 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
233 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
234 DITypeRef::get(FromTy), 0, 0, 0, 0);
237 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
239 uint64_t AlignInBits,
241 // FIXME: Why is there a name here?
242 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
243 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
244 SizeInBits, AlignInBits, 0, 0);
247 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
250 uint64_t AlignInBits) {
251 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
252 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
253 SizeInBits, AlignInBits, 0, 0,
254 DITypeRef::get(Base));
257 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
258 assert(RTy && "Unable to create reference type");
259 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
260 DITypeRef::get(RTy), 0, 0, 0, 0);
263 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
264 DIFile *File, unsigned LineNo,
266 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
268 DIScopeRef::get(getNonCompileUnitScope(Context)),
269 DITypeRef::get(Ty), 0, 0, 0, 0);
272 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
273 assert(Ty && "Invalid type!");
274 assert(FriendTy && "Invalid friend type!");
275 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
276 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
280 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
283 assert(Ty && "Unable to create inheritance");
284 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
285 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
289 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
290 DIFile *File, unsigned LineNumber,
292 uint64_t AlignInBits,
293 uint64_t OffsetInBits,
294 unsigned Flags, DIType *Ty) {
295 return DIDerivedType::get(
296 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
297 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
298 SizeInBits, AlignInBits, OffsetInBits, Flags);
301 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
303 return ConstantAsMetadata::get(C);
307 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
310 DIType *Ty, unsigned Flags,
311 llvm::Constant *Val) {
312 Flags |= DINode::FlagStaticMember;
313 return DIDerivedType::get(
314 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
315 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
316 0, Flags, getConstantOrNull(Val));
319 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
322 uint64_t AlignInBits,
323 uint64_t OffsetInBits, unsigned Flags,
324 DIType *Ty, MDNode *PropertyNode) {
325 return DIDerivedType::get(
326 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
327 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
328 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
332 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
333 StringRef GetterName, StringRef SetterName,
334 unsigned PropertyAttributes, DIType *Ty) {
335 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
336 SetterName, PropertyAttributes,
340 DITemplateTypeParameter *
341 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
343 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
344 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
347 static DITemplateValueParameter *
348 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
349 DIScope *Context, StringRef Name, DIType *Ty,
351 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
352 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
356 DITemplateValueParameter *
357 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
358 DIType *Ty, Constant *Val) {
359 return createTemplateValueParameterHelper(
360 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
361 getConstantOrNull(Val));
364 DITemplateValueParameter *
365 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
366 DIType *Ty, StringRef Val) {
367 return createTemplateValueParameterHelper(
368 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
369 MDString::get(VMContext, Val));
372 DITemplateValueParameter *
373 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
374 DIType *Ty, DINodeArray Val) {
375 return createTemplateValueParameterHelper(
376 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
380 DICompositeType *DIBuilder::createClassType(
381 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
382 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
383 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
384 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
385 assert((!Context || isa<DIScope>(Context)) &&
386 "createClassType should be called with a valid Context");
388 auto *R = DICompositeType::get(
389 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
390 DIScopeRef::get(getNonCompileUnitScope(Context)),
391 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
392 Elements, 0, DITypeRef::get(VTableHolder),
393 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
394 if (!UniqueIdentifier.empty())
396 trackIfUnresolved(R);
400 DICompositeType *DIBuilder::createStructType(
401 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
402 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
403 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
404 DIType *VTableHolder, StringRef UniqueIdentifier) {
405 auto *R = DICompositeType::get(
406 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
407 DIScopeRef::get(getNonCompileUnitScope(Context)),
408 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
409 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
410 if (!UniqueIdentifier.empty())
412 trackIfUnresolved(R);
416 DICompositeType *DIBuilder::createUnionType(
417 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
418 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
419 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
420 auto *R = DICompositeType::get(
421 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
422 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
423 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
425 if (!UniqueIdentifier.empty())
427 trackIfUnresolved(R);
431 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
432 DITypeRefArray ParameterTypes,
434 return DISubroutineType::get(VMContext, Flags, ParameterTypes);
437 DICompositeType *DIBuilder::createEnumerationType(
438 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
439 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
440 DIType *UnderlyingType, StringRef UniqueIdentifier) {
441 auto *CTy = DICompositeType::get(
442 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
443 DIScopeRef::get(getNonCompileUnitScope(Scope)),
444 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
445 0, nullptr, nullptr, UniqueIdentifier);
446 AllEnumTypes.push_back(CTy);
447 if (!UniqueIdentifier.empty())
449 trackIfUnresolved(CTy);
453 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
455 DINodeArray Subscripts) {
456 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
457 nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
458 AlignInBits, 0, 0, Subscripts, 0, nullptr);
459 trackIfUnresolved(R);
463 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
464 uint64_t AlignInBits, DIType *Ty,
465 DINodeArray Subscripts) {
467 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
468 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
469 DINode::FlagVector, Subscripts, 0, nullptr);
470 trackIfUnresolved(R);
474 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
475 unsigned FlagsToSet) {
476 auto NewTy = Ty->clone();
477 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
478 return MDNode::replaceWithUniqued(std::move(NewTy));
481 DIType *DIBuilder::createArtificialType(DIType *Ty) {
482 // FIXME: Restrict this to the nodes where it's valid.
483 if (Ty->isArtificial())
485 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
488 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
489 // FIXME: Restrict this to the nodes where it's valid.
490 if (Ty->isObjectPointer())
492 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
493 return createTypeWithFlags(VMContext, Ty, Flags);
496 void DIBuilder::retainType(DIType *T) {
497 assert(T && "Expected non-null type");
498 AllRetainTypes.emplace_back(T);
501 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
504 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
505 DIFile *F, unsigned Line, unsigned RuntimeLang,
506 uint64_t SizeInBits, uint64_t AlignInBits,
507 StringRef UniqueIdentifier) {
508 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
509 // replaceWithUniqued().
510 auto *RetTy = DICompositeType::get(
511 VMContext, Tag, Name, F, Line,
512 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
513 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
514 nullptr, UniqueIdentifier);
515 if (!UniqueIdentifier.empty())
517 trackIfUnresolved(RetTy);
521 DICompositeType *DIBuilder::createReplaceableCompositeType(
522 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
523 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
524 unsigned Flags, StringRef UniqueIdentifier) {
525 auto *RetTy = DICompositeType::getTemporary(
526 VMContext, Tag, Name, F, Line,
527 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
528 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
529 nullptr, nullptr, UniqueIdentifier)
531 if (!UniqueIdentifier.empty())
533 trackIfUnresolved(RetTy);
537 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
538 return MDTuple::get(VMContext, Elements);
541 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
542 SmallVector<llvm::Metadata *, 16> Elts;
543 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
544 if (Elements[i] && isa<MDNode>(Elements[i]))
545 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
547 Elts.push_back(Elements[i]);
549 return DITypeRefArray(MDNode::get(VMContext, Elts));
552 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
553 return DISubrange::get(VMContext, Count, Lo);
556 static void checkGlobalVariableScope(DIScope *Context) {
559 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
560 assert(CT->getIdentifier().empty() &&
561 "Context of a global variable should not be a type with identifier");
565 DIGlobalVariable *DIBuilder::createGlobalVariable(
566 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
567 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
569 checkGlobalVariableScope(Context);
571 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
572 Name, LinkageName, F, LineNumber,
573 DITypeRef::get(Ty), isLocalToUnit, true, Val,
574 cast_or_null<DIDerivedType>(Decl));
579 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
580 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
581 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
583 checkGlobalVariableScope(Context);
585 return DIGlobalVariable::getTemporary(
586 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
587 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
588 cast_or_null<DIDerivedType>(Decl))
592 DILocalVariable *DIBuilder::createLocalVariable(
593 unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
594 DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
595 // FIXME: Why getNonCompileUnitScope()?
596 // FIXME: Why is "!Context" okay here?
597 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
598 // the only valid scopes)?
599 DIScope *Context = getNonCompileUnitScope(Scope);
601 auto *Node = DILocalVariable::get(
602 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
603 DITypeRef::get(Ty), ArgNo, Flags);
604 if (AlwaysPreserve) {
605 // The optimizer may remove local variable. If there is an interest
606 // to preserve variable info in such situation then stash it in a
608 DISubprogram *Fn = getDISubprogram(Scope);
609 assert(Fn && "Missing subprogram for local variable");
610 PreservedVariables[Fn].emplace_back(Node);
615 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
616 return DIExpression::get(VMContext, Addr);
619 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
620 // TODO: Remove the callers of this signed version and delete.
621 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
622 return createExpression(Addr);
625 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
626 unsigned SizeInBytes) {
627 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
628 return DIExpression::get(VMContext, Addr);
631 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
632 StringRef LinkageName, DIFile *File,
633 unsigned LineNo, DISubroutineType *Ty,
634 bool isLocalToUnit, bool isDefinition,
635 unsigned ScopeLine, unsigned Flags,
636 bool isOptimized, Function *Fn,
637 MDNode *TParams, MDNode *Decl) {
638 // dragonegg does not generate identifier for types, so using an empty map
639 // to resolve the context should be fine.
640 DITypeIdentifierMap EmptyMap;
641 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
642 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
643 Flags, isOptimized, Fn, TParams, Decl);
646 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
647 StringRef LinkageName, DIFile *File,
648 unsigned LineNo, DISubroutineType *Ty,
649 bool isLocalToUnit, bool isDefinition,
650 unsigned ScopeLine, unsigned Flags,
651 bool isOptimized, Function *Fn,
652 MDNode *TParams, MDNode *Decl) {
653 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
654 "function types should be subroutines");
655 auto *Node = DISubprogram::get(
656 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
657 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
658 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
659 cast_or_null<DISubprogram>(Decl),
660 MDTuple::getTemporary(VMContext, None).release());
663 AllSubprograms.push_back(Node);
664 trackIfUnresolved(Node);
668 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
669 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
670 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
671 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
672 Function *Fn, MDNode *TParams, MDNode *Decl) {
673 return DISubprogram::getTemporary(
674 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
675 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
676 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
677 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
683 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
684 DIFile *F, unsigned LineNo, DISubroutineType *Ty,
685 bool isLocalToUnit, bool isDefinition, unsigned VK,
686 unsigned VIndex, DIType *VTableHolder, unsigned Flags,
687 bool isOptimized, Function *Fn, MDNode *TParam) {
688 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
689 "function types should be subroutines");
690 assert(getNonCompileUnitScope(Context) &&
691 "Methods should have both a Context and a context that isn't "
692 "the compile unit.");
693 // FIXME: Do we want to use different scope/lines?
694 auto *SP = DISubprogram::get(
695 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
696 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
697 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
698 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
701 AllSubprograms.push_back(SP);
702 trackIfUnresolved(SP);
706 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
707 DIFile *File, unsigned LineNo) {
708 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
712 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
713 StringRef ConfigurationMacros,
714 StringRef IncludePath,
715 StringRef ISysRoot) {
716 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
717 ConfigurationMacros, IncludePath, ISysRoot);
720 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
722 unsigned Discriminator) {
723 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
726 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
727 unsigned Line, unsigned Col) {
728 // Make these distinct, to avoid merging two lexical blocks on the same
730 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
734 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
735 assert(V && "no value passed to dbg intrinsic");
736 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
739 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
740 I->setDebugLoc(const_cast<DILocation *>(DL));
744 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
745 DIExpression *Expr, const DILocation *DL,
746 Instruction *InsertBefore) {
747 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
748 assert(DL && "Expected debug loc");
749 assert(DL->getScope()->getSubprogram() ==
750 VarInfo->getScope()->getSubprogram() &&
751 "Expected matching subprograms");
753 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
755 trackIfUnresolved(VarInfo);
756 trackIfUnresolved(Expr);
757 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
758 MetadataAsValue::get(VMContext, VarInfo),
759 MetadataAsValue::get(VMContext, Expr)};
760 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
763 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
764 DIExpression *Expr, const DILocation *DL,
765 BasicBlock *InsertAtEnd) {
766 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
767 assert(DL && "Expected debug loc");
768 assert(DL->getScope()->getSubprogram() ==
769 VarInfo->getScope()->getSubprogram() &&
770 "Expected matching subprograms");
772 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
774 trackIfUnresolved(VarInfo);
775 trackIfUnresolved(Expr);
776 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
777 MetadataAsValue::get(VMContext, VarInfo),
778 MetadataAsValue::get(VMContext, Expr)};
780 // If this block already has a terminator then insert this intrinsic
781 // before the terminator.
782 if (TerminatorInst *T = InsertAtEnd->getTerminator())
783 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
784 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
787 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
788 DILocalVariable *VarInfo,
790 const DILocation *DL,
791 Instruction *InsertBefore) {
792 assert(V && "no value passed to dbg.value");
793 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
794 assert(DL && "Expected debug loc");
795 assert(DL->getScope()->getSubprogram() ==
796 VarInfo->getScope()->getSubprogram() &&
797 "Expected matching subprograms");
799 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
801 trackIfUnresolved(VarInfo);
802 trackIfUnresolved(Expr);
803 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
804 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
805 MetadataAsValue::get(VMContext, VarInfo),
806 MetadataAsValue::get(VMContext, Expr)};
807 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
810 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
811 DILocalVariable *VarInfo,
813 const DILocation *DL,
814 BasicBlock *InsertAtEnd) {
815 assert(V && "no value passed to dbg.value");
816 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
817 assert(DL && "Expected debug loc");
818 assert(DL->getScope()->getSubprogram() ==
819 VarInfo->getScope()->getSubprogram() &&
820 "Expected matching subprograms");
822 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
824 trackIfUnresolved(VarInfo);
825 trackIfUnresolved(Expr);
826 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
827 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
828 MetadataAsValue::get(VMContext, VarInfo),
829 MetadataAsValue::get(VMContext, Expr)};
831 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
834 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
835 DICompositeType *VTableHolder) {
837 TypedTrackingMDRef<DICompositeType> N(T);
838 N->replaceVTableHolder(DITypeRef::get(VTableHolder));
842 // If this didn't create a self-reference, just return.
843 if (T != VTableHolder)
846 // Look for unresolved operands. T will drop RAUW support, orphaning any
847 // cycles underneath it.
849 for (const MDOperand &O : T->operands())
850 if (auto *N = dyn_cast_or_null<MDNode>(O))
851 trackIfUnresolved(N);
854 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
855 DINodeArray TParams) {
857 TypedTrackingMDRef<DICompositeType> N(T);
859 N->replaceElements(Elements);
861 N->replaceTemplateParams(DITemplateParameterArray(TParams));
865 // If T isn't resolved, there's no problem.
866 if (!T->isResolved())
869 // If "T" is resolved, it may be due to a self-reference cycle. Track the
870 // arrays explicitly if they're unresolved, or else the cycles will be
873 trackIfUnresolved(Elements.get());
875 trackIfUnresolved(TParams.get());