1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the DIBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
22 
23 using namespace llvm;
24 using namespace llvm::dwarf;
25 
26 namespace {
27 class HeaderBuilder {
28   /// \brief Whether there are any fields yet.
29   ///
30   /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
31   /// may have been called already with an empty string.
32   bool IsEmpty;
33   SmallVector<char, 256> Chars;
34 
35 public:
HeaderBuilder()36   HeaderBuilder() : IsEmpty(true) {}
HeaderBuilder(const HeaderBuilder & X)37   HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
HeaderBuilder(HeaderBuilder && X)38   HeaderBuilder(HeaderBuilder &&X)
39       : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
40 
concat(Twineable && X)41   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
42     if (IsEmpty)
43       IsEmpty = false;
44     else
45       Chars.push_back(0);
46     Twine(X).toVector(Chars);
47     return *this;
48   }
49 
get(LLVMContext & Context) const50   MDString *get(LLVMContext &Context) const {
51     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
52   }
53 
get(unsigned Tag)54   static HeaderBuilder get(unsigned Tag) {
55     return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
56   }
57 };
58 }
59 
DIBuilder(Module & m,bool AllowUnresolvedNodes)60 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
61   : M(m), VMContext(M.getContext()), CUNode(nullptr),
62       DeclareFn(nullptr), ValueFn(nullptr),
63       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
64 
trackIfUnresolved(MDNode * N)65 void DIBuilder::trackIfUnresolved(MDNode *N) {
66   if (!N)
67     return;
68   if (N->isResolved())
69     return;
70 
71   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
72   UnresolvedNodes.emplace_back(N);
73 }
74 
finalize()75 void DIBuilder::finalize() {
76   if (!CUNode) {
77     assert(!AllowUnresolvedNodes &&
78            "creating type nodes without a CU is not supported");
79     return;
80   }
81 
82   CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
83 
84   SmallVector<Metadata *, 16> RetainValues;
85   // Declarations and definitions of the same type may be retained. Some
86   // clients RAUW these pairs, leaving duplicates in the retained types
87   // list. Use a set to remove the duplicates while we transform the
88   // TrackingVHs back into Values.
89   SmallPtrSet<Metadata *, 16> RetainSet;
90   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
91     if (RetainSet.insert(AllRetainTypes[I]).second)
92       RetainValues.push_back(AllRetainTypes[I]);
93 
94   if (!RetainValues.empty())
95     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
96 
97   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
98   if (!AllSubprograms.empty())
99     CUNode->replaceSubprograms(SPs.get());
100 
101   for (auto *SP : SPs) {
102     if (MDTuple *Temp = SP->getVariables().get()) {
103       const auto &PV = PreservedVariables.lookup(SP);
104       SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
105       DINodeArray AV = getOrCreateArray(Variables);
106       TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
107     }
108   }
109 
110   if (!AllGVs.empty())
111     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
112 
113   if (!AllImportedModules.empty())
114     CUNode->replaceImportedEntities(MDTuple::get(
115         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
116                                                AllImportedModules.end())));
117 
118   // Now that all temp nodes have been replaced or deleted, resolve remaining
119   // cycles.
120   for (const auto &N : UnresolvedNodes)
121     if (N && !N->isResolved())
122       N->resolveCycles();
123   UnresolvedNodes.clear();
124 
125   // Can't handle unresolved nodes anymore.
126   AllowUnresolvedNodes = false;
127 }
128 
129 /// If N is compile unit return NULL otherwise return N.
getNonCompileUnitScope(DIScope * N)130 static DIScope *getNonCompileUnitScope(DIScope *N) {
131   if (!N || isa<DICompileUnit>(N))
132     return nullptr;
133   return cast<DIScope>(N);
134 }
135 
createCompileUnit(unsigned Lang,StringRef Filename,StringRef Directory,StringRef Producer,bool isOptimized,StringRef Flags,unsigned RunTimeVer,StringRef SplitName,DebugEmissionKind Kind,uint64_t DWOId,bool EmitDebugInfo)136 DICompileUnit *DIBuilder::createCompileUnit(
137     unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
138     bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
139     DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
140 
141   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
142           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
143          "Invalid Language tag");
144   assert(!Filename.empty() &&
145          "Unable to create compile unit without filename");
146 
147   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
148   CUNode = DICompileUnit::getDistinct(
149       VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
150       isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
151       nullptr, nullptr, nullptr, nullptr, nullptr, DWOId);
152 
153   // Create a named metadata so that it is easier to find cu in a module.
154   // Note that we only generate this when the caller wants to actually
155   // emit debug information. When we are only interested in tracking
156   // source line locations throughout the backend, we prevent codegen from
157   // emitting debug info in the final output by not generating llvm.dbg.cu.
158   if (EmitDebugInfo) {
159     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
160     NMD->addOperand(CUNode);
161   }
162 
163   trackIfUnresolved(CUNode);
164   return CUNode;
165 }
166 
167 static DIImportedEntity *
createImportedModule(LLVMContext & C,dwarf::Tag Tag,DIScope * Context,Metadata * NS,unsigned Line,StringRef Name,SmallVectorImpl<TrackingMDNodeRef> & AllImportedModules)168 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
169                      Metadata *NS, unsigned Line, StringRef Name,
170                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
171   auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
172   AllImportedModules.emplace_back(M);
173   return M;
174 }
175 
createImportedModule(DIScope * Context,DINamespace * NS,unsigned Line)176 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
177                                                   DINamespace *NS,
178                                                   unsigned Line) {
179   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
180                                 Context, NS, Line, StringRef(), AllImportedModules);
181 }
182 
createImportedModule(DIScope * Context,DIImportedEntity * NS,unsigned Line)183 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
184                                                   DIImportedEntity *NS,
185                                                   unsigned Line) {
186   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
187                                 Context, NS, Line, StringRef(), AllImportedModules);
188 }
189 
createImportedModule(DIScope * Context,DIModule * M,unsigned Line)190 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
191                                                   unsigned Line) {
192   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
193                                 Context, M, Line, StringRef(), AllImportedModules);
194 }
195 
createImportedDeclaration(DIScope * Context,DINode * Decl,unsigned Line,StringRef Name)196 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
197                                                        DINode *Decl,
198                                                        unsigned Line,
199                                                        StringRef Name) {
200   // Make sure to use the unique identifier based metadata reference for
201   // types that have one.
202   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
203                                 Context, DINodeRef::get(Decl), Line, Name,
204                                 AllImportedModules);
205 }
206 
createFile(StringRef Filename,StringRef Directory)207 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
208   return DIFile::get(VMContext, Filename, Directory);
209 }
210 
createEnumerator(StringRef Name,int64_t Val)211 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
212   assert(!Name.empty() && "Unable to create enumerator without name");
213   return DIEnumerator::get(VMContext, Val, Name);
214 }
215 
createUnspecifiedType(StringRef Name)216 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
217   assert(!Name.empty() && "Unable to create type without name");
218   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
219 }
220 
createNullPtrType()221 DIBasicType *DIBuilder::createNullPtrType() {
222   return createUnspecifiedType("decltype(nullptr)");
223 }
224 
createBasicType(StringRef Name,uint64_t SizeInBits,uint64_t AlignInBits,unsigned Encoding)225 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
226                                         uint64_t AlignInBits,
227                                         unsigned Encoding) {
228   assert(!Name.empty() && "Unable to create type without name");
229   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
230                           AlignInBits, Encoding);
231 }
232 
createQualifiedType(unsigned Tag,DIType * FromTy)233 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
234   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
235                             DITypeRef::get(FromTy), 0, 0, 0, 0);
236 }
237 
createPointerType(DIType * PointeeTy,uint64_t SizeInBits,uint64_t AlignInBits,StringRef Name)238 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
239                                             uint64_t SizeInBits,
240                                             uint64_t AlignInBits,
241                                             StringRef Name) {
242   // FIXME: Why is there a name here?
243   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
244                             nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
245                             SizeInBits, AlignInBits, 0, 0);
246 }
247 
createMemberPointerType(DIType * PointeeTy,DIType * Base,uint64_t SizeInBits,uint64_t AlignInBits)248 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
249                                                   DIType *Base,
250                                                   uint64_t SizeInBits,
251                                                   uint64_t AlignInBits) {
252   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
253                             nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
254                             SizeInBits, AlignInBits, 0, 0,
255                             DITypeRef::get(Base));
256 }
257 
createReferenceType(unsigned Tag,DIType * RTy,uint64_t SizeInBits,uint64_t AlignInBits)258 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy,
259                                               uint64_t SizeInBits,
260                                               uint64_t AlignInBits) {
261   assert(RTy && "Unable to create reference type");
262   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
263                             DITypeRef::get(RTy), SizeInBits, AlignInBits, 0, 0);
264 }
265 
createTypedef(DIType * Ty,StringRef Name,DIFile * File,unsigned LineNo,DIScope * Context)266 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
267                                         DIFile *File, unsigned LineNo,
268                                         DIScope *Context) {
269   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
270                             LineNo,
271                             DIScopeRef::get(getNonCompileUnitScope(Context)),
272                             DITypeRef::get(Ty), 0, 0, 0, 0);
273 }
274 
createFriend(DIType * Ty,DIType * FriendTy)275 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
276   assert(Ty && "Invalid type!");
277   assert(FriendTy && "Invalid friend type!");
278   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
279                             DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
280                             0, 0);
281 }
282 
createInheritance(DIType * Ty,DIType * BaseTy,uint64_t BaseOffset,unsigned Flags)283 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
284                                             uint64_t BaseOffset,
285                                             unsigned Flags) {
286   assert(Ty && "Unable to create inheritance");
287   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
288                             0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
289                             BaseOffset, Flags);
290 }
291 
createMemberType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,uint64_t OffsetInBits,unsigned Flags,DIType * Ty)292 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
293                                            DIFile *File, unsigned LineNumber,
294                                            uint64_t SizeInBits,
295                                            uint64_t AlignInBits,
296                                            uint64_t OffsetInBits,
297                                            unsigned Flags, DIType *Ty) {
298   return DIDerivedType::get(
299       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
300       DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
301       SizeInBits, AlignInBits, OffsetInBits, Flags);
302 }
303 
getConstantOrNull(Constant * C)304 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
305   if (C)
306     return ConstantAsMetadata::get(C);
307   return nullptr;
308 }
309 
createStaticMemberType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,DIType * Ty,unsigned Flags,llvm::Constant * Val)310 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
311                                                  DIFile *File,
312                                                  unsigned LineNumber,
313                                                  DIType *Ty, unsigned Flags,
314                                                  llvm::Constant *Val) {
315   Flags |= DINode::FlagStaticMember;
316   return DIDerivedType::get(
317       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
318       DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
319       0, Flags, getConstantOrNull(Val));
320 }
321 
createObjCIVar(StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,uint64_t OffsetInBits,unsigned Flags,DIType * Ty,MDNode * PropertyNode)322 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
323                                          unsigned LineNumber,
324                                          uint64_t SizeInBits,
325                                          uint64_t AlignInBits,
326                                          uint64_t OffsetInBits, unsigned Flags,
327                                          DIType *Ty, MDNode *PropertyNode) {
328   return DIDerivedType::get(
329       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
330       DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
331       SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
332 }
333 
334 DIObjCProperty *
createObjCProperty(StringRef Name,DIFile * File,unsigned LineNumber,StringRef GetterName,StringRef SetterName,unsigned PropertyAttributes,DIType * Ty)335 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
336                               StringRef GetterName, StringRef SetterName,
337                               unsigned PropertyAttributes, DIType *Ty) {
338   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
339                              SetterName, PropertyAttributes,
340                              DITypeRef::get(Ty));
341 }
342 
343 DITemplateTypeParameter *
createTemplateTypeParameter(DIScope * Context,StringRef Name,DIType * Ty)344 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
345                                        DIType *Ty) {
346   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
347   return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
348 }
349 
350 static DITemplateValueParameter *
createTemplateValueParameterHelper(LLVMContext & VMContext,unsigned Tag,DIScope * Context,StringRef Name,DIType * Ty,Metadata * MD)351 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
352                                    DIScope *Context, StringRef Name, DIType *Ty,
353                                    Metadata *MD) {
354   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
355   return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
356                                        MD);
357 }
358 
359 DITemplateValueParameter *
createTemplateValueParameter(DIScope * Context,StringRef Name,DIType * Ty,Constant * Val)360 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
361                                         DIType *Ty, Constant *Val) {
362   return createTemplateValueParameterHelper(
363       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
364       getConstantOrNull(Val));
365 }
366 
367 DITemplateValueParameter *
createTemplateTemplateParameter(DIScope * Context,StringRef Name,DIType * Ty,StringRef Val)368 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
369                                            DIType *Ty, StringRef Val) {
370   return createTemplateValueParameterHelper(
371       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
372       MDString::get(VMContext, Val));
373 }
374 
375 DITemplateValueParameter *
createTemplateParameterPack(DIScope * Context,StringRef Name,DIType * Ty,DINodeArray Val)376 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
377                                        DIType *Ty, DINodeArray Val) {
378   return createTemplateValueParameterHelper(
379       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
380       Val.get());
381 }
382 
createClassType(DIScope * Context,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,uint64_t OffsetInBits,unsigned Flags,DIType * DerivedFrom,DINodeArray Elements,DIType * VTableHolder,MDNode * TemplateParams,StringRef UniqueIdentifier)383 DICompositeType *DIBuilder::createClassType(
384     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
385     uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
386     unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
387     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
388   assert((!Context || isa<DIScope>(Context)) &&
389          "createClassType should be called with a valid Context");
390 
391   auto *R = DICompositeType::get(
392       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
393       DIScopeRef::get(getNonCompileUnitScope(Context)),
394       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
395       Elements, 0, DITypeRef::get(VTableHolder),
396       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
397   if (!UniqueIdentifier.empty())
398     retainType(R);
399   trackIfUnresolved(R);
400   return R;
401 }
402 
createStructType(DIScope * Context,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,unsigned Flags,DIType * DerivedFrom,DINodeArray Elements,unsigned RunTimeLang,DIType * VTableHolder,StringRef UniqueIdentifier)403 DICompositeType *DIBuilder::createStructType(
404     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
405     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
406     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
407     DIType *VTableHolder, StringRef UniqueIdentifier) {
408   auto *R = DICompositeType::get(
409       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
410       DIScopeRef::get(getNonCompileUnitScope(Context)),
411       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
412       RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
413   if (!UniqueIdentifier.empty())
414     retainType(R);
415   trackIfUnresolved(R);
416   return R;
417 }
418 
createUnionType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,unsigned Flags,DINodeArray Elements,unsigned RunTimeLang,StringRef UniqueIdentifier)419 DICompositeType *DIBuilder::createUnionType(
420     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
421     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
422     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
423   auto *R = DICompositeType::get(
424       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
425       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
426       AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
427       UniqueIdentifier);
428   if (!UniqueIdentifier.empty())
429     retainType(R);
430   trackIfUnresolved(R);
431   return R;
432 }
433 
createSubroutineType(DITypeRefArray ParameterTypes,unsigned Flags)434 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
435                                                   unsigned Flags) {
436   return DISubroutineType::get(VMContext, Flags, ParameterTypes);
437 }
438 
createExternalTypeRef(unsigned Tag,DIFile * File,StringRef UniqueIdentifier)439 DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File,
440                                                   StringRef UniqueIdentifier) {
441   assert(!UniqueIdentifier.empty() && "external type ref without uid");
442   auto *CTy =
443       DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr, 0,
444                            0, 0, DINode::FlagExternalTypeRef, nullptr, 0,
445                            nullptr, nullptr, UniqueIdentifier);
446   // Types with unique IDs need to be in the type map.
447   retainType(CTy);
448   return CTy;
449 }
450 
createEnumerationType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,DINodeArray Elements,DIType * UnderlyingType,StringRef UniqueIdentifier)451 DICompositeType *DIBuilder::createEnumerationType(
452     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
453     uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
454     DIType *UnderlyingType, StringRef UniqueIdentifier) {
455   auto *CTy = DICompositeType::get(
456       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
457       DIScopeRef::get(getNonCompileUnitScope(Scope)),
458       DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
459       0, nullptr, nullptr, UniqueIdentifier);
460   AllEnumTypes.push_back(CTy);
461   if (!UniqueIdentifier.empty())
462     retainType(CTy);
463   trackIfUnresolved(CTy);
464   return CTy;
465 }
466 
createArrayType(uint64_t Size,uint64_t AlignInBits,DIType * Ty,DINodeArray Subscripts)467 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
468                                             DIType *Ty,
469                                             DINodeArray Subscripts) {
470   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
471                                  nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
472                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
473   trackIfUnresolved(R);
474   return R;
475 }
476 
createVectorType(uint64_t Size,uint64_t AlignInBits,DIType * Ty,DINodeArray Subscripts)477 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
478                                              uint64_t AlignInBits, DIType *Ty,
479                                              DINodeArray Subscripts) {
480   auto *R =
481       DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
482                            nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
483                            DINode::FlagVector, Subscripts, 0, nullptr);
484   trackIfUnresolved(R);
485   return R;
486 }
487 
createTypeWithFlags(LLVMContext & Context,DIType * Ty,unsigned FlagsToSet)488 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
489                                    unsigned FlagsToSet) {
490   auto NewTy = Ty->clone();
491   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
492   return MDNode::replaceWithUniqued(std::move(NewTy));
493 }
494 
createArtificialType(DIType * Ty)495 DIType *DIBuilder::createArtificialType(DIType *Ty) {
496   // FIXME: Restrict this to the nodes where it's valid.
497   if (Ty->isArtificial())
498     return Ty;
499   return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
500 }
501 
createObjectPointerType(DIType * Ty)502 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
503   // FIXME: Restrict this to the nodes where it's valid.
504   if (Ty->isObjectPointer())
505     return Ty;
506   unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
507   return createTypeWithFlags(VMContext, Ty, Flags);
508 }
509 
retainType(DIType * T)510 void DIBuilder::retainType(DIType *T) {
511   assert(T && "Expected non-null type");
512   AllRetainTypes.emplace_back(T);
513 }
514 
createUnspecifiedParameter()515 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
516 
517 DICompositeType *
createForwardDecl(unsigned Tag,StringRef Name,DIScope * Scope,DIFile * F,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint64_t AlignInBits,StringRef UniqueIdentifier)518 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
519                              DIFile *F, unsigned Line, unsigned RuntimeLang,
520                              uint64_t SizeInBits, uint64_t AlignInBits,
521                              StringRef UniqueIdentifier) {
522   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
523   // replaceWithUniqued().
524   auto *RetTy = DICompositeType::get(
525       VMContext, Tag, Name, F, Line,
526       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
527       AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
528       nullptr, UniqueIdentifier);
529   if (!UniqueIdentifier.empty())
530     retainType(RetTy);
531   trackIfUnresolved(RetTy);
532   return RetTy;
533 }
534 
createReplaceableCompositeType(unsigned Tag,StringRef Name,DIScope * Scope,DIFile * F,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint64_t AlignInBits,unsigned Flags,StringRef UniqueIdentifier)535 DICompositeType *DIBuilder::createReplaceableCompositeType(
536     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
537     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
538     unsigned Flags, StringRef UniqueIdentifier) {
539   auto *RetTy = DICompositeType::getTemporary(
540                     VMContext, Tag, Name, F, Line,
541                     DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
542                     SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
543                     nullptr, nullptr, UniqueIdentifier)
544                     .release();
545   if (!UniqueIdentifier.empty())
546     retainType(RetTy);
547   trackIfUnresolved(RetTy);
548   return RetTy;
549 }
550 
getOrCreateArray(ArrayRef<Metadata * > Elements)551 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
552   return MDTuple::get(VMContext, Elements);
553 }
554 
getOrCreateTypeArray(ArrayRef<Metadata * > Elements)555 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
556   SmallVector<llvm::Metadata *, 16> Elts;
557   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
558     if (Elements[i] && isa<MDNode>(Elements[i]))
559       Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
560     else
561       Elts.push_back(Elements[i]);
562   }
563   return DITypeRefArray(MDNode::get(VMContext, Elts));
564 }
565 
getOrCreateSubrange(int64_t Lo,int64_t Count)566 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
567   return DISubrange::get(VMContext, Count, Lo);
568 }
569 
checkGlobalVariableScope(DIScope * Context)570 static void checkGlobalVariableScope(DIScope *Context) {
571 #ifndef NDEBUG
572   if (auto *CT =
573           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
574     assert(CT->getIdentifier().empty() &&
575            "Context of a global variable should not be a type with identifier");
576 #endif
577 }
578 
createGlobalVariable(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * F,unsigned LineNumber,DIType * Ty,bool isLocalToUnit,Constant * Val,MDNode * Decl)579 DIGlobalVariable *DIBuilder::createGlobalVariable(
580     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
581     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
582     MDNode *Decl) {
583   checkGlobalVariableScope(Context);
584 
585   auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
586                                   Name, LinkageName, F, LineNumber,
587                                   DITypeRef::get(Ty), isLocalToUnit, true, Val,
588                                   cast_or_null<DIDerivedType>(Decl));
589   AllGVs.push_back(N);
590   return N;
591 }
592 
createTempGlobalVariableFwdDecl(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * F,unsigned LineNumber,DIType * Ty,bool isLocalToUnit,Constant * Val,MDNode * Decl)593 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
594     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
595     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
596     MDNode *Decl) {
597   checkGlobalVariableScope(Context);
598 
599   return DIGlobalVariable::getTemporary(
600              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
601              LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
602              cast_or_null<DIDerivedType>(Decl))
603       .release();
604 }
605 
createLocalVariable(LLVMContext & VMContext,DenseMap<MDNode *,std::vector<TrackingMDNodeRef>> & PreservedVariables,DIScope * Scope,StringRef Name,unsigned ArgNo,DIFile * File,unsigned LineNo,DIType * Ty,bool AlwaysPreserve,unsigned Flags)606 static DILocalVariable *createLocalVariable(
607     LLVMContext &VMContext,
608     DenseMap<MDNode *, std::vector<TrackingMDNodeRef>> &PreservedVariables,
609     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
610     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
611   // FIXME: Why getNonCompileUnitScope()?
612   // FIXME: Why is "!Context" okay here?
613   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
614   // the only valid scopes)?
615   DIScope *Context = getNonCompileUnitScope(Scope);
616 
617   auto *Node =
618       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
619                            File, LineNo, DITypeRef::get(Ty), ArgNo, Flags);
620   if (AlwaysPreserve) {
621     // The optimizer may remove local variables. If there is an interest
622     // to preserve variable info in such situation then stash it in a
623     // named mdnode.
624     DISubprogram *Fn = getDISubprogram(Scope);
625     assert(Fn && "Missing subprogram for local variable");
626     PreservedVariables[Fn].emplace_back(Node);
627   }
628   return Node;
629 }
630 
createAutoVariable(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNo,DIType * Ty,bool AlwaysPreserve,unsigned Flags)631 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
632                                                DIFile *File, unsigned LineNo,
633                                                DIType *Ty, bool AlwaysPreserve,
634                                                unsigned Flags) {
635   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
636                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
637                              Flags);
638 }
639 
createParameterVariable(DIScope * Scope,StringRef Name,unsigned ArgNo,DIFile * File,unsigned LineNo,DIType * Ty,bool AlwaysPreserve,unsigned Flags)640 DILocalVariable *DIBuilder::createParameterVariable(
641     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
642     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
643   assert(ArgNo && "Expected non-zero argument number for parameter");
644   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
645                              File, LineNo, Ty, AlwaysPreserve, Flags);
646 }
647 
createExpression(ArrayRef<uint64_t> Addr)648 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
649   return DIExpression::get(VMContext, Addr);
650 }
651 
createExpression(ArrayRef<int64_t> Signed)652 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
653   // TODO: Remove the callers of this signed version and delete.
654   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
655   return createExpression(Addr);
656 }
657 
createBitPieceExpression(unsigned OffsetInBytes,unsigned SizeInBytes)658 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
659                                                   unsigned SizeInBytes) {
660   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
661   return DIExpression::get(VMContext, Addr);
662 }
663 
createFunction(DIScopeRef Context,StringRef Name,StringRef LinkageName,DIFile * File,unsigned LineNo,DISubroutineType * Ty,bool isLocalToUnit,bool isDefinition,unsigned ScopeLine,unsigned Flags,bool isOptimized,DITemplateParameterArray TParams,DISubprogram * Decl)664 DISubprogram *DIBuilder::createFunction(
665     DIScopeRef Context, StringRef Name, StringRef LinkageName, DIFile *File,
666     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
667     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
668     DITemplateParameterArray TParams, DISubprogram *Decl) {
669   // dragonegg does not generate identifier for types, so using an empty map
670   // to resolve the context should be fine.
671   DITypeIdentifierMap EmptyMap;
672   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
673                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
674                         Flags, isOptimized, TParams, Decl);
675 }
676 
677 template <class... Ts>
getSubprogram(bool IsDistinct,Ts &&...Args)678 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
679   if (IsDistinct)
680     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
681   return DISubprogram::get(std::forward<Ts>(Args)...);
682 }
683 
createFunction(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * File,unsigned LineNo,DISubroutineType * Ty,bool isLocalToUnit,bool isDefinition,unsigned ScopeLine,unsigned Flags,bool isOptimized,DITemplateParameterArray TParams,DISubprogram * Decl)684 DISubprogram *DIBuilder::createFunction(
685     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
686     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
687     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
688     DITemplateParameterArray TParams, DISubprogram *Decl) {
689   auto *Node =
690       getSubprogram(/* IsDistinct = */ isDefinition, VMContext,
691                     DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
692                     LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
693                     ScopeLine, nullptr, 0, 0, Flags, isOptimized, TParams, Decl,
694                     MDTuple::getTemporary(VMContext, None).release());
695 
696   if (isDefinition)
697     AllSubprograms.push_back(Node);
698   trackIfUnresolved(Node);
699   return Node;
700 }
701 
createTempFunctionFwdDecl(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * File,unsigned LineNo,DISubroutineType * Ty,bool isLocalToUnit,bool isDefinition,unsigned ScopeLine,unsigned Flags,bool isOptimized,DITemplateParameterArray TParams,DISubprogram * Decl)702 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
703     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
704     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
705     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
706     DITemplateParameterArray TParams, DISubprogram *Decl) {
707   return DISubprogram::getTemporary(
708              VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
709              LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
710              ScopeLine, nullptr, 0, 0, Flags, isOptimized, TParams, Decl,
711              nullptr)
712       .release();
713 }
714 
715 DISubprogram *
createMethod(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * F,unsigned LineNo,DISubroutineType * Ty,bool isLocalToUnit,bool isDefinition,unsigned VK,unsigned VIndex,DIType * VTableHolder,unsigned Flags,bool isOptimized,DITemplateParameterArray TParams)716 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
717                         DIFile *F, unsigned LineNo, DISubroutineType *Ty,
718                         bool isLocalToUnit, bool isDefinition, unsigned VK,
719                         unsigned VIndex, DIType *VTableHolder, unsigned Flags,
720                         bool isOptimized, DITemplateParameterArray TParams) {
721   assert(getNonCompileUnitScope(Context) &&
722          "Methods should have both a Context and a context that isn't "
723          "the compile unit.");
724   // FIXME: Do we want to use different scope/lines?
725   auto *SP = getSubprogram(
726       /* IsDistinct = */ isDefinition, VMContext,
727       DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F, LineNo, Ty,
728       isLocalToUnit, isDefinition, LineNo, DITypeRef::get(VTableHolder), VK,
729       VIndex, Flags, isOptimized, TParams, nullptr, nullptr);
730 
731   if (isDefinition)
732     AllSubprograms.push_back(SP);
733   trackIfUnresolved(SP);
734   return SP;
735 }
736 
createNameSpace(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNo)737 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
738                                         DIFile *File, unsigned LineNo) {
739   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
740                           LineNo);
741 }
742 
createModule(DIScope * Scope,StringRef Name,StringRef ConfigurationMacros,StringRef IncludePath,StringRef ISysRoot)743 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
744                                   StringRef ConfigurationMacros,
745                                   StringRef IncludePath,
746                                   StringRef ISysRoot) {
747  return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
748                       ConfigurationMacros, IncludePath, ISysRoot);
749 }
750 
createLexicalBlockFile(DIScope * Scope,DIFile * File,unsigned Discriminator)751 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
752                                                       DIFile *File,
753                                                       unsigned Discriminator) {
754   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
755 }
756 
createLexicalBlock(DIScope * Scope,DIFile * File,unsigned Line,unsigned Col)757 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
758                                               unsigned Line, unsigned Col) {
759   // Make these distinct, to avoid merging two lexical blocks on the same
760   // file/line/column.
761   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
762                                      File, Line, Col);
763 }
764 
getDbgIntrinsicValueImpl(LLVMContext & VMContext,Value * V)765 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
766   assert(V && "no value passed to dbg intrinsic");
767   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
768 }
769 
withDebugLoc(Instruction * I,const DILocation * DL)770 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
771   I->setDebugLoc(const_cast<DILocation *>(DL));
772   return I;
773 }
774 
insertDeclare(Value * Storage,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,Instruction * InsertBefore)775 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
776                                       DIExpression *Expr, const DILocation *DL,
777                                       Instruction *InsertBefore) {
778   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
779   assert(DL && "Expected debug loc");
780   assert(DL->getScope()->getSubprogram() ==
781              VarInfo->getScope()->getSubprogram() &&
782          "Expected matching subprograms");
783   if (!DeclareFn)
784     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
785 
786   trackIfUnresolved(VarInfo);
787   trackIfUnresolved(Expr);
788   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
789                    MetadataAsValue::get(VMContext, VarInfo),
790                    MetadataAsValue::get(VMContext, Expr)};
791   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
792 }
793 
insertDeclare(Value * Storage,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,BasicBlock * InsertAtEnd)794 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
795                                       DIExpression *Expr, const DILocation *DL,
796                                       BasicBlock *InsertAtEnd) {
797   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
798   assert(DL && "Expected debug loc");
799   assert(DL->getScope()->getSubprogram() ==
800              VarInfo->getScope()->getSubprogram() &&
801          "Expected matching subprograms");
802   if (!DeclareFn)
803     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
804 
805   trackIfUnresolved(VarInfo);
806   trackIfUnresolved(Expr);
807   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
808                    MetadataAsValue::get(VMContext, VarInfo),
809                    MetadataAsValue::get(VMContext, Expr)};
810 
811   // If this block already has a terminator then insert this intrinsic
812   // before the terminator.
813   if (TerminatorInst *T = InsertAtEnd->getTerminator())
814     return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
815   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
816 }
817 
insertDbgValueIntrinsic(Value * V,uint64_t Offset,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,Instruction * InsertBefore)818 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
819                                                 DILocalVariable *VarInfo,
820                                                 DIExpression *Expr,
821                                                 const DILocation *DL,
822                                                 Instruction *InsertBefore) {
823   assert(V && "no value passed to dbg.value");
824   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
825   assert(DL && "Expected debug loc");
826   assert(DL->getScope()->getSubprogram() ==
827              VarInfo->getScope()->getSubprogram() &&
828          "Expected matching subprograms");
829   if (!ValueFn)
830     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
831 
832   trackIfUnresolved(VarInfo);
833   trackIfUnresolved(Expr);
834   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
835                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
836                    MetadataAsValue::get(VMContext, VarInfo),
837                    MetadataAsValue::get(VMContext, Expr)};
838   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
839 }
840 
insertDbgValueIntrinsic(Value * V,uint64_t Offset,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,BasicBlock * InsertAtEnd)841 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
842                                                 DILocalVariable *VarInfo,
843                                                 DIExpression *Expr,
844                                                 const DILocation *DL,
845                                                 BasicBlock *InsertAtEnd) {
846   assert(V && "no value passed to dbg.value");
847   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
848   assert(DL && "Expected debug loc");
849   assert(DL->getScope()->getSubprogram() ==
850              VarInfo->getScope()->getSubprogram() &&
851          "Expected matching subprograms");
852   if (!ValueFn)
853     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
854 
855   trackIfUnresolved(VarInfo);
856   trackIfUnresolved(Expr);
857   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
858                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
859                    MetadataAsValue::get(VMContext, VarInfo),
860                    MetadataAsValue::get(VMContext, Expr)};
861 
862   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
863 }
864 
replaceVTableHolder(DICompositeType * & T,DICompositeType * VTableHolder)865 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
866                                     DICompositeType *VTableHolder) {
867   {
868     TypedTrackingMDRef<DICompositeType> N(T);
869     N->replaceVTableHolder(DITypeRef::get(VTableHolder));
870     T = N.get();
871   }
872 
873   // If this didn't create a self-reference, just return.
874   if (T != VTableHolder)
875     return;
876 
877   // Look for unresolved operands.  T will drop RAUW support, orphaning any
878   // cycles underneath it.
879   if (T->isResolved())
880     for (const MDOperand &O : T->operands())
881       if (auto *N = dyn_cast_or_null<MDNode>(O))
882         trackIfUnresolved(N);
883 }
884 
replaceArrays(DICompositeType * & T,DINodeArray Elements,DINodeArray TParams)885 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
886                               DINodeArray TParams) {
887   {
888     TypedTrackingMDRef<DICompositeType> N(T);
889     if (Elements)
890       N->replaceElements(Elements);
891     if (TParams)
892       N->replaceTemplateParams(DITemplateParameterArray(TParams));
893     T = N.get();
894   }
895 
896   // If T isn't resolved, there's no problem.
897   if (!T->isResolved())
898     return;
899 
900   // If T is resolved, it may be due to a self-reference cycle.  Track the
901   // arrays explicitly if they're unresolved, or else the cycles will be
902   // orphaned.
903   if (Elements)
904     trackIfUnresolved(Elements.get());
905   if (TParams)
906     trackIfUnresolved(TParams.get());
907 }
908