1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the DIBuilder.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/DIBuilder.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 
26 using namespace llvm;
27 using namespace llvm::dwarf;
28 
29 static cl::opt<bool>
30     UseDbgAddr("use-dbg-addr",
31                llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
32                cl::init(false), cl::Hidden);
33 
34 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU)
35   : M(m), VMContext(M.getContext()), CUNode(CU),
36       DeclareFn(nullptr), ValueFn(nullptr), LabelFn(nullptr),
37       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
38 
39 void DIBuilder::trackIfUnresolved(MDNode *N) {
40   if (!N)
41     return;
42   if (N->isResolved())
43     return;
44 
45   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
46   UnresolvedNodes.emplace_back(N);
47 }
48 
49 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
50   MDTuple *Temp = SP->getRetainedNodes().get();
51   if (!Temp || !Temp->isTemporary())
52     return;
53 
54   SmallVector<Metadata *, 16> RetainedNodes;
55 
56   auto PV = PreservedVariables.find(SP);
57   if (PV != PreservedVariables.end())
58     RetainedNodes.append(PV->second.begin(), PV->second.end());
59 
60   auto PL = PreservedLabels.find(SP);
61   if (PL != PreservedLabels.end())
62     RetainedNodes.append(PL->second.begin(), PL->second.end());
63 
64   DINodeArray Node = getOrCreateArray(RetainedNodes);
65 
66   TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
67 }
68 
69 void DIBuilder::finalize() {
70   if (!CUNode) {
71     assert(!AllowUnresolvedNodes &&
72            "creating type nodes without a CU is not supported");
73     return;
74   }
75 
76   CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
77 
78   SmallVector<Metadata *, 16> RetainValues;
79   // Declarations and definitions of the same type may be retained. Some
80   // clients RAUW these pairs, leaving duplicates in the retained types
81   // list. Use a set to remove the duplicates while we transform the
82   // TrackingVHs back into Values.
83   SmallPtrSet<Metadata *, 16> RetainSet;
84   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
85     if (RetainSet.insert(AllRetainTypes[I]).second)
86       RetainValues.push_back(AllRetainTypes[I]);
87 
88   if (!RetainValues.empty())
89     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
90 
91   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
92   for (auto *SP : SPs)
93     finalizeSubprogram(SP);
94   for (auto *N : RetainValues)
95     if (auto *SP = dyn_cast<DISubprogram>(N))
96       finalizeSubprogram(SP);
97 
98   if (!AllGVs.empty())
99     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
100 
101   if (!AllImportedModules.empty())
102     CUNode->replaceImportedEntities(MDTuple::get(
103         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
104                                                AllImportedModules.end())));
105 
106   for (const auto &I : AllMacrosPerParent) {
107     // DIMacroNode's with nullptr parent are DICompileUnit direct children.
108     if (!I.first) {
109       CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
110       continue;
111     }
112     // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
113     auto *TMF = cast<DIMacroFile>(I.first);
114     auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
115                                 TMF->getLine(), TMF->getFile(),
116                                 getOrCreateMacroArray(I.second.getArrayRef()));
117     replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
118   }
119 
120   // Now that all temp nodes have been replaced or deleted, resolve remaining
121   // cycles.
122   for (const auto &N : UnresolvedNodes)
123     if (N && !N->isResolved())
124       N->resolveCycles();
125   UnresolvedNodes.clear();
126 
127   // Can't handle unresolved nodes anymore.
128   AllowUnresolvedNodes = false;
129 }
130 
131 /// If N is compile unit return NULL otherwise return N.
132 static DIScope *getNonCompileUnitScope(DIScope *N) {
133   if (!N || isa<DICompileUnit>(N))
134     return nullptr;
135   return cast<DIScope>(N);
136 }
137 
138 DICompileUnit *DIBuilder::createCompileUnit(
139     unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized,
140     StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
141     DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
142     bool SplitDebugInlining, bool DebugInfoForProfiling,
143     DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress,
144     StringRef SysRoot, StringRef SDK) {
145 
146   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
147           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
148          "Invalid Language tag");
149 
150   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
151   CUNode = DICompileUnit::getDistinct(
152       VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
153       SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
154       SplitDebugInlining, DebugInfoForProfiling, NameTableKind,
155       RangesBaseAddress, SysRoot, SDK);
156 
157   // Create a named metadata so that it is easier to find cu in a module.
158   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
159   NMD->addOperand(CUNode);
160   trackIfUnresolved(CUNode);
161   return CUNode;
162 }
163 
164 static DIImportedEntity *
165 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
166                      Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
167                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
168   if (Line)
169     assert(File && "Source location has line number but no file");
170   unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
171   auto *M = DIImportedEntity::get(C, Tag, Context, cast_or_null<DINode>(NS),
172                                   File, Line, Name);
173   if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
174     // A new Imported Entity was just added to the context.
175     // Add it to the Imported Modules list.
176     AllImportedModules.emplace_back(M);
177   return M;
178 }
179 
180 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
181                                                   DINamespace *NS, DIFile *File,
182                                                   unsigned Line) {
183   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
184                                 Context, NS, File, Line, StringRef(),
185                                 AllImportedModules);
186 }
187 
188 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
189                                                   DIImportedEntity *NS,
190                                                   DIFile *File, unsigned Line) {
191   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
192                                 Context, NS, File, Line, StringRef(),
193                                 AllImportedModules);
194 }
195 
196 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
197                                                   DIFile *File, unsigned Line) {
198   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
199                                 Context, M, File, Line, StringRef(),
200                                 AllImportedModules);
201 }
202 
203 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
204                                                        DINode *Decl,
205                                                        DIFile *File,
206                                                        unsigned Line,
207                                                        StringRef Name) {
208   // Make sure to use the unique identifier based metadata reference for
209   // types that have one.
210   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
211                                 Context, Decl, File, Line, Name,
212                                 AllImportedModules);
213 }
214 
215 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
216                               Optional<DIFile::ChecksumInfo<StringRef>> CS,
217                               Optional<StringRef> Source) {
218   return DIFile::get(VMContext, Filename, Directory, CS, Source);
219 }
220 
221 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
222                                 unsigned MacroType, StringRef Name,
223                                 StringRef Value) {
224   assert(!Name.empty() && "Unable to create macro without name");
225   assert((MacroType == dwarf::DW_MACINFO_undef ||
226           MacroType == dwarf::DW_MACINFO_define) &&
227          "Unexpected macro type");
228   auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
229   AllMacrosPerParent[Parent].insert(M);
230   return M;
231 }
232 
233 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
234                                             unsigned LineNumber, DIFile *File) {
235   auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
236                                        LineNumber, File, DIMacroNodeArray())
237                  .release();
238   AllMacrosPerParent[Parent].insert(MF);
239   // Add the new temporary DIMacroFile to the macro per parent map as a parent.
240   // This is needed to assure DIMacroFile with no children to have an entry in
241   // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
242   AllMacrosPerParent.insert({MF, {}});
243   return MF;
244 }
245 
246 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val,
247                                           bool IsUnsigned) {
248   assert(!Name.empty() && "Unable to create enumerator without name");
249   return DIEnumerator::get(VMContext, APInt(64, Val, !IsUnsigned), IsUnsigned,
250                            Name);
251 }
252 
253 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
254   assert(!Name.empty() && "Unable to create type without name");
255   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
256 }
257 
258 DIBasicType *DIBuilder::createNullPtrType() {
259   return createUnspecifiedType("decltype(nullptr)");
260 }
261 
262 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
263                                         unsigned Encoding,
264                                         DINode::DIFlags Flags) {
265   assert(!Name.empty() && "Unable to create type without name");
266   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
267                           0, Encoding, Flags);
268 }
269 
270 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
271   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
272                             0, 0, None, DINode::FlagZero);
273 }
274 
275 DIDerivedType *DIBuilder::createPointerType(
276     DIType *PointeeTy,
277     uint64_t SizeInBits,
278     uint32_t AlignInBits,
279     Optional<unsigned> DWARFAddressSpace,
280     StringRef Name) {
281   // FIXME: Why is there a name here?
282   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
283                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
284                             AlignInBits, 0, DWARFAddressSpace,
285                             DINode::FlagZero);
286 }
287 
288 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
289                                                   DIType *Base,
290                                                   uint64_t SizeInBits,
291                                                   uint32_t AlignInBits,
292                                                   DINode::DIFlags Flags) {
293   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
294                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
295                             AlignInBits, 0, None, Flags, Base);
296 }
297 
298 DIDerivedType *DIBuilder::createReferenceType(
299     unsigned Tag, DIType *RTy,
300     uint64_t SizeInBits,
301     uint32_t AlignInBits,
302     Optional<unsigned> DWARFAddressSpace) {
303   assert(RTy && "Unable to create reference type");
304   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
305                             SizeInBits, AlignInBits, 0, DWARFAddressSpace,
306                             DINode::FlagZero);
307 }
308 
309 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
310                                         DIFile *File, unsigned LineNo,
311                                         DIScope *Context,
312                                         uint32_t AlignInBits) {
313   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
314                             LineNo, getNonCompileUnitScope(Context), Ty, 0,
315                             AlignInBits, 0, None, DINode::FlagZero);
316 }
317 
318 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
319   assert(Ty && "Invalid type!");
320   assert(FriendTy && "Invalid friend type!");
321   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
322                             FriendTy, 0, 0, 0, None, DINode::FlagZero);
323 }
324 
325 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
326                                             uint64_t BaseOffset,
327                                             uint32_t VBPtrOffset,
328                                             DINode::DIFlags Flags) {
329   assert(Ty && "Unable to create inheritance");
330   Metadata *ExtraData = ConstantAsMetadata::get(
331       ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
332   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
333                             0, Ty, BaseTy, 0, 0, BaseOffset, None,
334                             Flags, ExtraData);
335 }
336 
337 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
338                                            DIFile *File, unsigned LineNumber,
339                                            uint64_t SizeInBits,
340                                            uint32_t AlignInBits,
341                                            uint64_t OffsetInBits,
342                                            DINode::DIFlags Flags, DIType *Ty) {
343   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
344                             LineNumber, getNonCompileUnitScope(Scope), Ty,
345                             SizeInBits, AlignInBits, OffsetInBits, None, Flags);
346 }
347 
348 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
349   if (C)
350     return ConstantAsMetadata::get(C);
351   return nullptr;
352 }
353 
354 DIDerivedType *DIBuilder::createVariantMemberType(
355     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
356     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
357     Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
358   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
359                             LineNumber, getNonCompileUnitScope(Scope), Ty,
360                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
361                             getConstantOrNull(Discriminant));
362 }
363 
364 DIDerivedType *DIBuilder::createBitFieldMemberType(
365     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
366     uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
367     DINode::DIFlags Flags, DIType *Ty) {
368   Flags |= DINode::FlagBitField;
369   return DIDerivedType::get(
370       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
371       getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
372       OffsetInBits, None, Flags,
373       ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
374                                                StorageOffsetInBits)));
375 }
376 
377 DIDerivedType *
378 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
379                                   unsigned LineNumber, DIType *Ty,
380                                   DINode::DIFlags Flags, llvm::Constant *Val,
381                                   uint32_t AlignInBits) {
382   Flags |= DINode::FlagStaticMember;
383   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
384                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
385                             AlignInBits, 0, None, Flags,
386                             getConstantOrNull(Val));
387 }
388 
389 DIDerivedType *
390 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
391                           uint64_t SizeInBits, uint32_t AlignInBits,
392                           uint64_t OffsetInBits, DINode::DIFlags Flags,
393                           DIType *Ty, MDNode *PropertyNode) {
394   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
395                             LineNumber, getNonCompileUnitScope(File), Ty,
396                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
397                             PropertyNode);
398 }
399 
400 DIObjCProperty *
401 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
402                               StringRef GetterName, StringRef SetterName,
403                               unsigned PropertyAttributes, DIType *Ty) {
404   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
405                              SetterName, PropertyAttributes, Ty);
406 }
407 
408 DITemplateTypeParameter *
409 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
410                                        DIType *Ty, bool isDefault) {
411   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
412   return DITemplateTypeParameter::get(VMContext, Name, Ty, isDefault);
413 }
414 
415 static DITemplateValueParameter *
416 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
417                                    DIScope *Context, StringRef Name, DIType *Ty,
418                                    bool IsDefault, Metadata *MD) {
419   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
420   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, IsDefault, MD);
421 }
422 
423 DITemplateValueParameter *
424 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
425                                         DIType *Ty, bool isDefault,
426                                         Constant *Val) {
427   return createTemplateValueParameterHelper(
428       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
429       isDefault, getConstantOrNull(Val));
430 }
431 
432 DITemplateValueParameter *
433 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
434                                            DIType *Ty, StringRef Val) {
435   return createTemplateValueParameterHelper(
436       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
437       false, MDString::get(VMContext, Val));
438 }
439 
440 DITemplateValueParameter *
441 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
442                                        DIType *Ty, DINodeArray Val) {
443   return createTemplateValueParameterHelper(
444       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
445       false, Val.get());
446 }
447 
448 DICompositeType *DIBuilder::createClassType(
449     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
450     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
451     DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
452     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
453   assert((!Context || isa<DIScope>(Context)) &&
454          "createClassType should be called with a valid Context");
455 
456   auto *R = DICompositeType::get(
457       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
458       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
459       OffsetInBits, Flags, Elements, 0, VTableHolder,
460       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
461   trackIfUnresolved(R);
462   return R;
463 }
464 
465 DICompositeType *DIBuilder::createStructType(
466     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
467     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
468     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
469     DIType *VTableHolder, StringRef UniqueIdentifier) {
470   auto *R = DICompositeType::get(
471       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
472       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
473       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
474   trackIfUnresolved(R);
475   return R;
476 }
477 
478 DICompositeType *DIBuilder::createUnionType(
479     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
480     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
481     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
482   auto *R = DICompositeType::get(
483       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
484       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
485       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
486   trackIfUnresolved(R);
487   return R;
488 }
489 
490 DICompositeType *DIBuilder::createVariantPart(
491     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
492     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
493     DIDerivedType *Discriminator, DINodeArray Elements, StringRef UniqueIdentifier) {
494   auto *R = DICompositeType::get(
495       VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
496       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
497       Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
498   trackIfUnresolved(R);
499   return R;
500 }
501 
502 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
503                                                   DINode::DIFlags Flags,
504                                                   unsigned CC) {
505   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
506 }
507 
508 DICompositeType *DIBuilder::createEnumerationType(
509     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
510     uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
511     DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
512   auto *CTy = DICompositeType::get(
513       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
514       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
515       IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
516       nullptr, UniqueIdentifier);
517   AllEnumTypes.push_back(CTy);
518   trackIfUnresolved(CTy);
519   return CTy;
520 }
521 
522 DICompositeType *DIBuilder::createArrayType(uint64_t Size,
523                                             uint32_t AlignInBits, DIType *Ty,
524                                             DINodeArray Subscripts) {
525   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
526                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
527                                  DINode::FlagZero, Subscripts, 0, nullptr);
528   trackIfUnresolved(R);
529   return R;
530 }
531 
532 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
533                                              uint32_t AlignInBits, DIType *Ty,
534                                              DINodeArray Subscripts) {
535   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
536                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
537                                  DINode::FlagVector, Subscripts, 0, nullptr);
538   trackIfUnresolved(R);
539   return R;
540 }
541 
542 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
543   auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
544   return MDNode::replaceWithDistinct(std::move(NewSP));
545 }
546 
547 static DIType *createTypeWithFlags(const DIType *Ty,
548                                    DINode::DIFlags FlagsToSet) {
549   auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
550   return MDNode::replaceWithUniqued(std::move(NewTy));
551 }
552 
553 DIType *DIBuilder::createArtificialType(DIType *Ty) {
554   // FIXME: Restrict this to the nodes where it's valid.
555   if (Ty->isArtificial())
556     return Ty;
557   return createTypeWithFlags(Ty, DINode::FlagArtificial);
558 }
559 
560 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
561   // FIXME: Restrict this to the nodes where it's valid.
562   if (Ty->isObjectPointer())
563     return Ty;
564   DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
565   return createTypeWithFlags(Ty, Flags);
566 }
567 
568 void DIBuilder::retainType(DIScope *T) {
569   assert(T && "Expected non-null type");
570   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
571                              cast<DISubprogram>(T)->isDefinition() == false)) &&
572          "Expected type or subprogram declaration");
573   AllRetainTypes.emplace_back(T);
574 }
575 
576 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
577 
578 DICompositeType *
579 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
580                              DIFile *F, unsigned Line, unsigned RuntimeLang,
581                              uint64_t SizeInBits, uint32_t AlignInBits,
582                              StringRef UniqueIdentifier) {
583   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
584   // replaceWithUniqued().
585   auto *RetTy = DICompositeType::get(
586       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
587       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
588       nullptr, nullptr, UniqueIdentifier);
589   trackIfUnresolved(RetTy);
590   return RetTy;
591 }
592 
593 DICompositeType *DIBuilder::createReplaceableCompositeType(
594     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
595     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
596     DINode::DIFlags Flags, StringRef UniqueIdentifier) {
597   auto *RetTy =
598       DICompositeType::getTemporary(
599           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
600           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
601           nullptr, UniqueIdentifier)
602           .release();
603   trackIfUnresolved(RetTy);
604   return RetTy;
605 }
606 
607 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
608   return MDTuple::get(VMContext, Elements);
609 }
610 
611 DIMacroNodeArray
612 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
613   return MDTuple::get(VMContext, Elements);
614 }
615 
616 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
617   SmallVector<llvm::Metadata *, 16> Elts;
618   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
619     if (Elements[i] && isa<MDNode>(Elements[i]))
620       Elts.push_back(cast<DIType>(Elements[i]));
621     else
622       Elts.push_back(Elements[i]);
623   }
624   return DITypeRefArray(MDNode::get(VMContext, Elts));
625 }
626 
627 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
628   return DISubrange::get(VMContext, Count, Lo);
629 }
630 
631 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
632   return DISubrange::get(VMContext, CountNode, Lo);
633 }
634 
635 static void checkGlobalVariableScope(DIScope *Context) {
636 #ifndef NDEBUG
637   if (auto *CT =
638           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
639     assert(CT->getIdentifier().empty() &&
640            "Context of a global variable should not be a type with identifier");
641 #endif
642 }
643 
644 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
645     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
646     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit,
647     bool isDefined, DIExpression *Expr,
648     MDNode *Decl, MDTuple *TemplateParams, uint32_t AlignInBits) {
649   checkGlobalVariableScope(Context);
650 
651   auto *GV = DIGlobalVariable::getDistinct(
652       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
653       LineNumber, Ty, IsLocalToUnit, isDefined, cast_or_null<DIDerivedType>(Decl),
654       TemplateParams, AlignInBits);
655   if (!Expr)
656     Expr = createExpression();
657   auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
658   AllGVs.push_back(N);
659   return N;
660 }
661 
662 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
663     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
664     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
665     MDTuple *TemplateParams, uint32_t AlignInBits) {
666   checkGlobalVariableScope(Context);
667 
668   return DIGlobalVariable::getTemporary(
669              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
670              LineNumber, Ty, IsLocalToUnit, false,
671              cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits)
672       .release();
673 }
674 
675 static DILocalVariable *createLocalVariable(
676     LLVMContext &VMContext,
677     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
678     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
679     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
680     uint32_t AlignInBits) {
681   // FIXME: Why getNonCompileUnitScope()?
682   // FIXME: Why is "!Context" okay here?
683   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
684   // the only valid scopes)?
685   DIScope *Context = getNonCompileUnitScope(Scope);
686 
687   auto *Node =
688       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
689                            File, LineNo, Ty, ArgNo, Flags, AlignInBits);
690   if (AlwaysPreserve) {
691     // The optimizer may remove local variables. If there is an interest
692     // to preserve variable info in such situation then stash it in a
693     // named mdnode.
694     DISubprogram *Fn = getDISubprogram(Scope);
695     assert(Fn && "Missing subprogram for local variable");
696     PreservedVariables[Fn].emplace_back(Node);
697   }
698   return Node;
699 }
700 
701 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
702                                                DIFile *File, unsigned LineNo,
703                                                DIType *Ty, bool AlwaysPreserve,
704                                                DINode::DIFlags Flags,
705                                                uint32_t AlignInBits) {
706   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
707                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
708                              Flags, AlignInBits);
709 }
710 
711 DILocalVariable *DIBuilder::createParameterVariable(
712     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
713     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
714   assert(ArgNo && "Expected non-zero argument number for parameter");
715   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
716                              File, LineNo, Ty, AlwaysPreserve, Flags,
717                              /* AlignInBits */0);
718 }
719 
720 DILabel *DIBuilder::createLabel(
721     DIScope *Scope, StringRef Name, DIFile *File,
722     unsigned LineNo, bool AlwaysPreserve) {
723   DIScope *Context = getNonCompileUnitScope(Scope);
724 
725   auto *Node =
726       DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
727                    File, LineNo);
728 
729   if (AlwaysPreserve) {
730     /// The optimizer may remove labels. If there is an interest
731     /// to preserve label info in such situation then append it to
732     /// the list of retained nodes of the DISubprogram.
733     DISubprogram *Fn = getDISubprogram(Scope);
734     assert(Fn && "Missing subprogram for label");
735     PreservedLabels[Fn].emplace_back(Node);
736   }
737   return Node;
738 }
739 
740 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
741   return DIExpression::get(VMContext, Addr);
742 }
743 
744 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
745   // TODO: Remove the callers of this signed version and delete.
746   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
747   return createExpression(Addr);
748 }
749 
750 template <class... Ts>
751 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
752   if (IsDistinct)
753     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
754   return DISubprogram::get(std::forward<Ts>(Args)...);
755 }
756 
757 DISubprogram *DIBuilder::createFunction(
758     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
759     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
760     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
761     DITemplateParameterArray TParams, DISubprogram *Decl,
762     DITypeArray ThrownTypes) {
763   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
764   auto *Node = getSubprogram(
765       /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
766       Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
767       SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
768       MDTuple::getTemporary(VMContext, None).release(), ThrownTypes);
769 
770   if (IsDefinition)
771     AllSubprograms.push_back(Node);
772   trackIfUnresolved(Node);
773   return Node;
774 }
775 
776 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
777     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
778     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
779     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
780     DITemplateParameterArray TParams, DISubprogram *Decl,
781     DITypeArray ThrownTypes) {
782   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
783   return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
784                                     Name, LinkageName, File, LineNo, Ty,
785                                     ScopeLine, nullptr, 0, 0, Flags, SPFlags,
786                                     IsDefinition ? CUNode : nullptr, TParams,
787                                     Decl, nullptr, ThrownTypes)
788       .release();
789 }
790 
791 DISubprogram *DIBuilder::createMethod(
792     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
793     unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
794     DIType *VTableHolder, DINode::DIFlags Flags,
795     DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
796     DITypeArray ThrownTypes) {
797   assert(getNonCompileUnitScope(Context) &&
798          "Methods should have both a Context and a context that isn't "
799          "the compile unit.");
800   // FIXME: Do we want to use different scope/lines?
801   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
802   auto *SP = getSubprogram(
803       /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
804       LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
805       Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
806       nullptr, ThrownTypes);
807 
808   if (IsDefinition)
809     AllSubprograms.push_back(SP);
810   trackIfUnresolved(SP);
811   return SP;
812 }
813 
814 DICommonBlock *DIBuilder::createCommonBlock(
815     DIScope *Scope, DIGlobalVariable *Decl, StringRef Name, DIFile *File,
816     unsigned LineNo) {
817   return DICommonBlock::get(
818       VMContext, Scope, Decl, Name, File, LineNo);
819 }
820 
821 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
822                                         bool ExportSymbols) {
823 
824   // It is okay to *not* make anonymous top-level namespaces distinct, because
825   // all nodes that have an anonymous namespace as their parent scope are
826   // guaranteed to be unique and/or are linked to their containing
827   // DICompileUnit. This decision is an explicit tradeoff of link time versus
828   // memory usage versus code simplicity and may get revisited in the future.
829   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
830                           ExportSymbols);
831 }
832 
833 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
834                                   StringRef ConfigurationMacros,
835                                   StringRef IncludePath, StringRef APINotesFile,
836                                   DIFile *File, unsigned LineNo) {
837   return DIModule::get(VMContext, File, getNonCompileUnitScope(Scope), Name,
838                        ConfigurationMacros, IncludePath, APINotesFile, LineNo);
839 }
840 
841 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
842                                                       DIFile *File,
843                                                       unsigned Discriminator) {
844   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
845 }
846 
847 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
848                                               unsigned Line, unsigned Col) {
849   // Make these distinct, to avoid merging two lexical blocks on the same
850   // file/line/column.
851   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
852                                      File, Line, Col);
853 }
854 
855 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
856                                       DIExpression *Expr, const DILocation *DL,
857                                       Instruction *InsertBefore) {
858   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
859                        InsertBefore);
860 }
861 
862 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
863                                       DIExpression *Expr, const DILocation *DL,
864                                       BasicBlock *InsertAtEnd) {
865   // If this block already has a terminator then insert this intrinsic before
866   // the terminator. Otherwise, put it at the end of the block.
867   Instruction *InsertBefore = InsertAtEnd->getTerminator();
868   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
869 }
870 
871 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
872                                     Instruction *InsertBefore) {
873   return insertLabel(
874       LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
875       InsertBefore);
876 }
877 
878 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
879                                     BasicBlock *InsertAtEnd) {
880   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
881 }
882 
883 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
884                                                 DILocalVariable *VarInfo,
885                                                 DIExpression *Expr,
886                                                 const DILocation *DL,
887                                                 Instruction *InsertBefore) {
888   return insertDbgValueIntrinsic(
889       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
890       InsertBefore);
891 }
892 
893 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
894                                                 DILocalVariable *VarInfo,
895                                                 DIExpression *Expr,
896                                                 const DILocation *DL,
897                                                 BasicBlock *InsertAtEnd) {
898   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
899 }
900 
901 /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics.
902 /// This abstracts over the various ways to specify an insert position.
903 static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL,
904                           BasicBlock *InsertBB, Instruction *InsertBefore) {
905   if (InsertBefore)
906     Builder.SetInsertPoint(InsertBefore);
907   else if (InsertBB)
908     Builder.SetInsertPoint(InsertBB);
909   Builder.SetCurrentDebugLocation(DL);
910 }
911 
912 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
913   assert(V && "no value passed to dbg intrinsic");
914   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
915 }
916 
917 static Function *getDeclareIntrin(Module &M) {
918   return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
919                                                   : Intrinsic::dbg_declare);
920 }
921 
922 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
923                                       DIExpression *Expr, const DILocation *DL,
924                                       BasicBlock *InsertBB, Instruction *InsertBefore) {
925   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
926   assert(DL && "Expected debug loc");
927   assert(DL->getScope()->getSubprogram() ==
928              VarInfo->getScope()->getSubprogram() &&
929          "Expected matching subprograms");
930   if (!DeclareFn)
931     DeclareFn = getDeclareIntrin(M);
932 
933   trackIfUnresolved(VarInfo);
934   trackIfUnresolved(Expr);
935   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
936                    MetadataAsValue::get(VMContext, VarInfo),
937                    MetadataAsValue::get(VMContext, Expr)};
938 
939   IRBuilder<> B(DL->getContext());
940   initIRBuilder(B, DL, InsertBB, InsertBefore);
941   return B.CreateCall(DeclareFn, Args);
942 }
943 
944 Instruction *DIBuilder::insertDbgValueIntrinsic(
945     Value *V, DILocalVariable *VarInfo, DIExpression *Expr,
946     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
947   assert(V && "no value passed to dbg.value");
948   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
949   assert(DL && "Expected debug loc");
950   assert(DL->getScope()->getSubprogram() ==
951              VarInfo->getScope()->getSubprogram() &&
952          "Expected matching subprograms");
953   if (!ValueFn)
954     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
955 
956   trackIfUnresolved(VarInfo);
957   trackIfUnresolved(Expr);
958   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
959                    MetadataAsValue::get(VMContext, VarInfo),
960                    MetadataAsValue::get(VMContext, Expr)};
961 
962   IRBuilder<> B(DL->getContext());
963   initIRBuilder(B, DL, InsertBB, InsertBefore);
964   return B.CreateCall(ValueFn, Args);
965 }
966 
967 Instruction *DIBuilder::insertLabel(
968     DILabel *LabelInfo, const DILocation *DL,
969     BasicBlock *InsertBB, Instruction *InsertBefore) {
970   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
971   assert(DL && "Expected debug loc");
972   assert(DL->getScope()->getSubprogram() ==
973              LabelInfo->getScope()->getSubprogram() &&
974          "Expected matching subprograms");
975   if (!LabelFn)
976     LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
977 
978   trackIfUnresolved(LabelInfo);
979   Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
980 
981   IRBuilder<> B(DL->getContext());
982   initIRBuilder(B, DL, InsertBB, InsertBefore);
983   return B.CreateCall(LabelFn, Args);
984 }
985 
986 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
987                                     DIType *VTableHolder) {
988   {
989     TypedTrackingMDRef<DICompositeType> N(T);
990     N->replaceVTableHolder(VTableHolder);
991     T = N.get();
992   }
993 
994   // If this didn't create a self-reference, just return.
995   if (T != VTableHolder)
996     return;
997 
998   // Look for unresolved operands.  T will drop RAUW support, orphaning any
999   // cycles underneath it.
1000   if (T->isResolved())
1001     for (const MDOperand &O : T->operands())
1002       if (auto *N = dyn_cast_or_null<MDNode>(O))
1003         trackIfUnresolved(N);
1004 }
1005 
1006 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
1007                               DINodeArray TParams) {
1008   {
1009     TypedTrackingMDRef<DICompositeType> N(T);
1010     if (Elements)
1011       N->replaceElements(Elements);
1012     if (TParams)
1013       N->replaceTemplateParams(DITemplateParameterArray(TParams));
1014     T = N.get();
1015   }
1016 
1017   // If T isn't resolved, there's no problem.
1018   if (!T->isResolved())
1019     return;
1020 
1021   // If T is resolved, it may be due to a self-reference cycle.  Track the
1022   // arrays explicitly if they're unresolved, or else the cycles will be
1023   // orphaned.
1024   if (Elements)
1025     trackIfUnresolved(Elements.get());
1026   if (TParams)
1027     trackIfUnresolved(TParams.get());
1028 }
1029