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) {
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);
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, Val, IsUnsigned, Name);
250 }
251 
252 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
253   assert(!Name.empty() && "Unable to create type without name");
254   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
255 }
256 
257 DIBasicType *DIBuilder::createNullPtrType() {
258   return createUnspecifiedType("decltype(nullptr)");
259 }
260 
261 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
262                                         unsigned Encoding,
263                                         DINode::DIFlags Flags) {
264   assert(!Name.empty() && "Unable to create type without name");
265   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
266                           0, Encoding, Flags);
267 }
268 
269 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
270   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
271                             0, 0, None, DINode::FlagZero);
272 }
273 
274 DIDerivedType *DIBuilder::createPointerType(
275     DIType *PointeeTy,
276     uint64_t SizeInBits,
277     uint32_t AlignInBits,
278     Optional<unsigned> DWARFAddressSpace,
279     StringRef Name) {
280   // FIXME: Why is there a name here?
281   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
282                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
283                             AlignInBits, 0, DWARFAddressSpace,
284                             DINode::FlagZero);
285 }
286 
287 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
288                                                   DIType *Base,
289                                                   uint64_t SizeInBits,
290                                                   uint32_t AlignInBits,
291                                                   DINode::DIFlags Flags) {
292   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
293                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
294                             AlignInBits, 0, None, Flags, Base);
295 }
296 
297 DIDerivedType *DIBuilder::createReferenceType(
298     unsigned Tag, DIType *RTy,
299     uint64_t SizeInBits,
300     uint32_t AlignInBits,
301     Optional<unsigned> DWARFAddressSpace) {
302   assert(RTy && "Unable to create reference type");
303   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
304                             SizeInBits, AlignInBits, 0, DWARFAddressSpace,
305                             DINode::FlagZero);
306 }
307 
308 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
309                                         DIFile *File, unsigned LineNo,
310                                         DIScope *Context,
311                                         uint32_t AlignInBits) {
312   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
313                             LineNo, getNonCompileUnitScope(Context), Ty, 0,
314                             AlignInBits, 0, None, DINode::FlagZero);
315 }
316 
317 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
318   assert(Ty && "Invalid type!");
319   assert(FriendTy && "Invalid friend type!");
320   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
321                             FriendTy, 0, 0, 0, None, DINode::FlagZero);
322 }
323 
324 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
325                                             uint64_t BaseOffset,
326                                             uint32_t VBPtrOffset,
327                                             DINode::DIFlags Flags) {
328   assert(Ty && "Unable to create inheritance");
329   Metadata *ExtraData = ConstantAsMetadata::get(
330       ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
331   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
332                             0, Ty, BaseTy, 0, 0, BaseOffset, None,
333                             Flags, ExtraData);
334 }
335 
336 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
337                                            DIFile *File, unsigned LineNumber,
338                                            uint64_t SizeInBits,
339                                            uint32_t AlignInBits,
340                                            uint64_t OffsetInBits,
341                                            DINode::DIFlags Flags, DIType *Ty) {
342   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
343                             LineNumber, getNonCompileUnitScope(Scope), Ty,
344                             SizeInBits, AlignInBits, OffsetInBits, None, Flags);
345 }
346 
347 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
348   if (C)
349     return ConstantAsMetadata::get(C);
350   return nullptr;
351 }
352 
353 DIDerivedType *DIBuilder::createVariantMemberType(
354     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
355     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
356     Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
357   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
358                             LineNumber, getNonCompileUnitScope(Scope), Ty,
359                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
360                             getConstantOrNull(Discriminant));
361 }
362 
363 DIDerivedType *DIBuilder::createBitFieldMemberType(
364     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
365     uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
366     DINode::DIFlags Flags, DIType *Ty) {
367   Flags |= DINode::FlagBitField;
368   return DIDerivedType::get(
369       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
370       getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
371       OffsetInBits, None, Flags,
372       ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
373                                                StorageOffsetInBits)));
374 }
375 
376 DIDerivedType *
377 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
378                                   unsigned LineNumber, DIType *Ty,
379                                   DINode::DIFlags Flags, llvm::Constant *Val,
380                                   uint32_t AlignInBits) {
381   Flags |= DINode::FlagStaticMember;
382   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
383                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
384                             AlignInBits, 0, None, Flags,
385                             getConstantOrNull(Val));
386 }
387 
388 DIDerivedType *
389 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
390                           uint64_t SizeInBits, uint32_t AlignInBits,
391                           uint64_t OffsetInBits, DINode::DIFlags Flags,
392                           DIType *Ty, MDNode *PropertyNode) {
393   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
394                             LineNumber, getNonCompileUnitScope(File), Ty,
395                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
396                             PropertyNode);
397 }
398 
399 DIObjCProperty *
400 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
401                               StringRef GetterName, StringRef SetterName,
402                               unsigned PropertyAttributes, DIType *Ty) {
403   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
404                              SetterName, PropertyAttributes, Ty);
405 }
406 
407 DITemplateTypeParameter *
408 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
409                                        DIType *Ty, bool isDefault) {
410   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
411   return DITemplateTypeParameter::get(VMContext, Name, Ty, isDefault);
412 }
413 
414 static DITemplateValueParameter *
415 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
416                                    DIScope *Context, StringRef Name, DIType *Ty,
417                                    bool IsDefault, Metadata *MD) {
418   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
419   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, IsDefault, MD);
420 }
421 
422 DITemplateValueParameter *
423 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
424                                         DIType *Ty, bool isDefault,
425                                         Constant *Val) {
426   return createTemplateValueParameterHelper(
427       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
428       isDefault, getConstantOrNull(Val));
429 }
430 
431 DITemplateValueParameter *
432 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
433                                            DIType *Ty, StringRef Val) {
434   return createTemplateValueParameterHelper(
435       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
436       false, MDString::get(VMContext, Val));
437 }
438 
439 DITemplateValueParameter *
440 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
441                                        DIType *Ty, DINodeArray Val) {
442   return createTemplateValueParameterHelper(
443       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
444       false, Val.get());
445 }
446 
447 DICompositeType *DIBuilder::createClassType(
448     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
449     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
450     DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
451     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
452   assert((!Context || isa<DIScope>(Context)) &&
453          "createClassType should be called with a valid Context");
454 
455   auto *R = DICompositeType::get(
456       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
457       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
458       OffsetInBits, Flags, Elements, 0, VTableHolder,
459       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
460   trackIfUnresolved(R);
461   return R;
462 }
463 
464 DICompositeType *DIBuilder::createStructType(
465     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
466     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
467     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
468     DIType *VTableHolder, StringRef UniqueIdentifier) {
469   auto *R = DICompositeType::get(
470       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
471       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
472       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
473   trackIfUnresolved(R);
474   return R;
475 }
476 
477 DICompositeType *DIBuilder::createUnionType(
478     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
479     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
480     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
481   auto *R = DICompositeType::get(
482       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
483       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
484       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
485   trackIfUnresolved(R);
486   return R;
487 }
488 
489 DICompositeType *DIBuilder::createVariantPart(
490     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
491     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
492     DIDerivedType *Discriminator, DINodeArray Elements, StringRef UniqueIdentifier) {
493   auto *R = DICompositeType::get(
494       VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
495       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
496       Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
497   trackIfUnresolved(R);
498   return R;
499 }
500 
501 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
502                                                   DINode::DIFlags Flags,
503                                                   unsigned CC) {
504   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
505 }
506 
507 DICompositeType *DIBuilder::createEnumerationType(
508     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
509     uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
510     DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
511   auto *CTy = DICompositeType::get(
512       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
513       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
514       IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
515       nullptr, UniqueIdentifier);
516   AllEnumTypes.push_back(CTy);
517   trackIfUnresolved(CTy);
518   return CTy;
519 }
520 
521 DICompositeType *DIBuilder::createArrayType(uint64_t Size,
522                                             uint32_t AlignInBits, DIType *Ty,
523                                             DINodeArray Subscripts) {
524   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
525                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
526                                  DINode::FlagZero, Subscripts, 0, nullptr);
527   trackIfUnresolved(R);
528   return R;
529 }
530 
531 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
532                                              uint32_t AlignInBits, DIType *Ty,
533                                              DINodeArray Subscripts) {
534   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
535                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
536                                  DINode::FlagVector, Subscripts, 0, nullptr);
537   trackIfUnresolved(R);
538   return R;
539 }
540 
541 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
542   auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
543   return MDNode::replaceWithDistinct(std::move(NewSP));
544 }
545 
546 static DIType *createTypeWithFlags(const DIType *Ty,
547                                    DINode::DIFlags FlagsToSet) {
548   auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
549   return MDNode::replaceWithUniqued(std::move(NewTy));
550 }
551 
552 DIType *DIBuilder::createArtificialType(DIType *Ty) {
553   // FIXME: Restrict this to the nodes where it's valid.
554   if (Ty->isArtificial())
555     return Ty;
556   return createTypeWithFlags(Ty, DINode::FlagArtificial);
557 }
558 
559 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
560   // FIXME: Restrict this to the nodes where it's valid.
561   if (Ty->isObjectPointer())
562     return Ty;
563   DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
564   return createTypeWithFlags(Ty, Flags);
565 }
566 
567 void DIBuilder::retainType(DIScope *T) {
568   assert(T && "Expected non-null type");
569   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
570                              cast<DISubprogram>(T)->isDefinition() == false)) &&
571          "Expected type or subprogram declaration");
572   AllRetainTypes.emplace_back(T);
573 }
574 
575 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
576 
577 DICompositeType *
578 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
579                              DIFile *F, unsigned Line, unsigned RuntimeLang,
580                              uint64_t SizeInBits, uint32_t AlignInBits,
581                              StringRef UniqueIdentifier) {
582   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
583   // replaceWithUniqued().
584   auto *RetTy = DICompositeType::get(
585       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
586       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
587       nullptr, nullptr, UniqueIdentifier);
588   trackIfUnresolved(RetTy);
589   return RetTy;
590 }
591 
592 DICompositeType *DIBuilder::createReplaceableCompositeType(
593     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
594     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
595     DINode::DIFlags Flags, StringRef UniqueIdentifier) {
596   auto *RetTy =
597       DICompositeType::getTemporary(
598           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
599           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
600           nullptr, UniqueIdentifier)
601           .release();
602   trackIfUnresolved(RetTy);
603   return RetTy;
604 }
605 
606 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
607   return MDTuple::get(VMContext, Elements);
608 }
609 
610 DIMacroNodeArray
611 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
612   return MDTuple::get(VMContext, Elements);
613 }
614 
615 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
616   SmallVector<llvm::Metadata *, 16> Elts;
617   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
618     if (Elements[i] && isa<MDNode>(Elements[i]))
619       Elts.push_back(cast<DIType>(Elements[i]));
620     else
621       Elts.push_back(Elements[i]);
622   }
623   return DITypeRefArray(MDNode::get(VMContext, Elts));
624 }
625 
626 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
627   return DISubrange::get(VMContext, Count, Lo);
628 }
629 
630 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
631   return DISubrange::get(VMContext, CountNode, Lo);
632 }
633 
634 static void checkGlobalVariableScope(DIScope *Context) {
635 #ifndef NDEBUG
636   if (auto *CT =
637           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
638     assert(CT->getIdentifier().empty() &&
639            "Context of a global variable should not be a type with identifier");
640 #endif
641 }
642 
643 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
644     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
645     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit,
646     bool isDefined, DIExpression *Expr,
647     MDNode *Decl, MDTuple *TemplateParams, uint32_t AlignInBits) {
648   checkGlobalVariableScope(Context);
649 
650   auto *GV = DIGlobalVariable::getDistinct(
651       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
652       LineNumber, Ty, IsLocalToUnit, isDefined, cast_or_null<DIDerivedType>(Decl),
653       TemplateParams, AlignInBits);
654   if (!Expr)
655     Expr = createExpression();
656   auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
657   AllGVs.push_back(N);
658   return N;
659 }
660 
661 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
662     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
663     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
664     MDTuple *TemplateParams, uint32_t AlignInBits) {
665   checkGlobalVariableScope(Context);
666 
667   return DIGlobalVariable::getTemporary(
668              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
669              LineNumber, Ty, IsLocalToUnit, false,
670              cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits)
671       .release();
672 }
673 
674 static DILocalVariable *createLocalVariable(
675     LLVMContext &VMContext,
676     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
677     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
678     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
679     uint32_t AlignInBits) {
680   // FIXME: Why getNonCompileUnitScope()?
681   // FIXME: Why is "!Context" okay here?
682   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
683   // the only valid scopes)?
684   DIScope *Context = getNonCompileUnitScope(Scope);
685 
686   auto *Node =
687       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
688                            File, LineNo, Ty, ArgNo, Flags, AlignInBits);
689   if (AlwaysPreserve) {
690     // The optimizer may remove local variables. If there is an interest
691     // to preserve variable info in such situation then stash it in a
692     // named mdnode.
693     DISubprogram *Fn = getDISubprogram(Scope);
694     assert(Fn && "Missing subprogram for local variable");
695     PreservedVariables[Fn].emplace_back(Node);
696   }
697   return Node;
698 }
699 
700 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
701                                                DIFile *File, unsigned LineNo,
702                                                DIType *Ty, bool AlwaysPreserve,
703                                                DINode::DIFlags Flags,
704                                                uint32_t AlignInBits) {
705   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
706                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
707                              Flags, AlignInBits);
708 }
709 
710 DILocalVariable *DIBuilder::createParameterVariable(
711     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
712     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
713   assert(ArgNo && "Expected non-zero argument number for parameter");
714   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
715                              File, LineNo, Ty, AlwaysPreserve, Flags,
716                              /* AlignInBits */0);
717 }
718 
719 DILabel *DIBuilder::createLabel(
720     DIScope *Scope, StringRef Name, DIFile *File,
721     unsigned LineNo, bool AlwaysPreserve) {
722   DIScope *Context = getNonCompileUnitScope(Scope);
723 
724   auto *Node =
725       DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
726                    File, LineNo);
727 
728   if (AlwaysPreserve) {
729     /// The optimizer may remove labels. If there is an interest
730     /// to preserve label info in such situation then append it to
731     /// the list of retained nodes of the DISubprogram.
732     DISubprogram *Fn = getDISubprogram(Scope);
733     assert(Fn && "Missing subprogram for label");
734     PreservedLabels[Fn].emplace_back(Node);
735   }
736   return Node;
737 }
738 
739 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
740   return DIExpression::get(VMContext, Addr);
741 }
742 
743 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
744   // TODO: Remove the callers of this signed version and delete.
745   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
746   return createExpression(Addr);
747 }
748 
749 template <class... Ts>
750 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
751   if (IsDistinct)
752     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
753   return DISubprogram::get(std::forward<Ts>(Args)...);
754 }
755 
756 DISubprogram *DIBuilder::createFunction(
757     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
758     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
759     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
760     DITemplateParameterArray TParams, DISubprogram *Decl,
761     DITypeArray ThrownTypes) {
762   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
763   auto *Node = getSubprogram(
764       /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
765       Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
766       SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
767       MDTuple::getTemporary(VMContext, None).release(), ThrownTypes);
768 
769   if (IsDefinition)
770     AllSubprograms.push_back(Node);
771   trackIfUnresolved(Node);
772   return Node;
773 }
774 
775 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
776     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
777     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
778     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
779     DITemplateParameterArray TParams, DISubprogram *Decl,
780     DITypeArray ThrownTypes) {
781   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
782   return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
783                                     Name, LinkageName, File, LineNo, Ty,
784                                     ScopeLine, nullptr, 0, 0, Flags, SPFlags,
785                                     IsDefinition ? CUNode : nullptr, TParams,
786                                     Decl, nullptr, ThrownTypes)
787       .release();
788 }
789 
790 DISubprogram *DIBuilder::createMethod(
791     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
792     unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
793     DIType *VTableHolder, DINode::DIFlags Flags,
794     DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
795     DITypeArray ThrownTypes) {
796   assert(getNonCompileUnitScope(Context) &&
797          "Methods should have both a Context and a context that isn't "
798          "the compile unit.");
799   // FIXME: Do we want to use different scope/lines?
800   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
801   auto *SP = getSubprogram(
802       /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
803       LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
804       Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
805       nullptr, ThrownTypes);
806 
807   if (IsDefinition)
808     AllSubprograms.push_back(SP);
809   trackIfUnresolved(SP);
810   return SP;
811 }
812 
813 DICommonBlock *DIBuilder::createCommonBlock(
814     DIScope *Scope, DIGlobalVariable *Decl, StringRef Name, DIFile *File,
815     unsigned LineNo) {
816   return DICommonBlock::get(
817       VMContext, Scope, Decl, Name, File, LineNo);
818 }
819 
820 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
821                                         bool ExportSymbols) {
822 
823   // It is okay to *not* make anonymous top-level namespaces distinct, because
824   // all nodes that have an anonymous namespace as their parent scope are
825   // guaranteed to be unique and/or are linked to their containing
826   // DICompileUnit. This decision is an explicit tradeoff of link time versus
827   // memory usage versus code simplicity and may get revisited in the future.
828   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
829                           ExportSymbols);
830 }
831 
832 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
833                                   StringRef ConfigurationMacros,
834                                   StringRef IncludePath) {
835   return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
836                        ConfigurationMacros, IncludePath);
837 }
838 
839 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
840                                                       DIFile *File,
841                                                       unsigned Discriminator) {
842   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
843 }
844 
845 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
846                                               unsigned Line, unsigned Col) {
847   // Make these distinct, to avoid merging two lexical blocks on the same
848   // file/line/column.
849   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
850                                      File, Line, Col);
851 }
852 
853 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
854                                       DIExpression *Expr, const DILocation *DL,
855                                       Instruction *InsertBefore) {
856   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
857                        InsertBefore);
858 }
859 
860 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
861                                       DIExpression *Expr, const DILocation *DL,
862                                       BasicBlock *InsertAtEnd) {
863   // If this block already has a terminator then insert this intrinsic before
864   // the terminator. Otherwise, put it at the end of the block.
865   Instruction *InsertBefore = InsertAtEnd->getTerminator();
866   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
867 }
868 
869 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
870                                     Instruction *InsertBefore) {
871   return insertLabel(
872       LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
873       InsertBefore);
874 }
875 
876 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
877                                     BasicBlock *InsertAtEnd) {
878   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
879 }
880 
881 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
882                                                 DILocalVariable *VarInfo,
883                                                 DIExpression *Expr,
884                                                 const DILocation *DL,
885                                                 Instruction *InsertBefore) {
886   return insertDbgValueIntrinsic(
887       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
888       InsertBefore);
889 }
890 
891 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
892                                                 DILocalVariable *VarInfo,
893                                                 DIExpression *Expr,
894                                                 const DILocation *DL,
895                                                 BasicBlock *InsertAtEnd) {
896   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
897 }
898 
899 /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics.
900 /// This abstracts over the various ways to specify an insert position.
901 static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL,
902                           BasicBlock *InsertBB, Instruction *InsertBefore) {
903   if (InsertBefore)
904     Builder.SetInsertPoint(InsertBefore);
905   else if (InsertBB)
906     Builder.SetInsertPoint(InsertBB);
907   Builder.SetCurrentDebugLocation(DL);
908 }
909 
910 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
911   assert(V && "no value passed to dbg intrinsic");
912   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
913 }
914 
915 static Function *getDeclareIntrin(Module &M) {
916   return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
917                                                   : Intrinsic::dbg_declare);
918 }
919 
920 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
921                                       DIExpression *Expr, const DILocation *DL,
922                                       BasicBlock *InsertBB, Instruction *InsertBefore) {
923   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
924   assert(DL && "Expected debug loc");
925   assert(DL->getScope()->getSubprogram() ==
926              VarInfo->getScope()->getSubprogram() &&
927          "Expected matching subprograms");
928   if (!DeclareFn)
929     DeclareFn = getDeclareIntrin(M);
930 
931   trackIfUnresolved(VarInfo);
932   trackIfUnresolved(Expr);
933   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
934                    MetadataAsValue::get(VMContext, VarInfo),
935                    MetadataAsValue::get(VMContext, Expr)};
936 
937   IRBuilder<> B(DL->getContext());
938   initIRBuilder(B, DL, InsertBB, InsertBefore);
939   return B.CreateCall(DeclareFn, Args);
940 }
941 
942 Instruction *DIBuilder::insertDbgValueIntrinsic(
943     Value *V, DILocalVariable *VarInfo, DIExpression *Expr,
944     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
945   assert(V && "no value passed to dbg.value");
946   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
947   assert(DL && "Expected debug loc");
948   assert(DL->getScope()->getSubprogram() ==
949              VarInfo->getScope()->getSubprogram() &&
950          "Expected matching subprograms");
951   if (!ValueFn)
952     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
953 
954   trackIfUnresolved(VarInfo);
955   trackIfUnresolved(Expr);
956   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
957                    MetadataAsValue::get(VMContext, VarInfo),
958                    MetadataAsValue::get(VMContext, Expr)};
959 
960   IRBuilder<> B(DL->getContext());
961   initIRBuilder(B, DL, InsertBB, InsertBefore);
962   return B.CreateCall(ValueFn, Args);
963 }
964 
965 Instruction *DIBuilder::insertLabel(
966     DILabel *LabelInfo, const DILocation *DL,
967     BasicBlock *InsertBB, Instruction *InsertBefore) {
968   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
969   assert(DL && "Expected debug loc");
970   assert(DL->getScope()->getSubprogram() ==
971              LabelInfo->getScope()->getSubprogram() &&
972          "Expected matching subprograms");
973   if (!LabelFn)
974     LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
975 
976   trackIfUnresolved(LabelInfo);
977   Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
978 
979   IRBuilder<> B(DL->getContext());
980   initIRBuilder(B, DL, InsertBB, InsertBefore);
981   return B.CreateCall(LabelFn, Args);
982 }
983 
984 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
985                                     DIType *VTableHolder) {
986   {
987     TypedTrackingMDRef<DICompositeType> N(T);
988     N->replaceVTableHolder(VTableHolder);
989     T = N.get();
990   }
991 
992   // If this didn't create a self-reference, just return.
993   if (T != VTableHolder)
994     return;
995 
996   // Look for unresolved operands.  T will drop RAUW support, orphaning any
997   // cycles underneath it.
998   if (T->isResolved())
999     for (const MDOperand &O : T->operands())
1000       if (auto *N = dyn_cast_or_null<MDNode>(O))
1001         trackIfUnresolved(N);
1002 }
1003 
1004 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
1005                               DINodeArray TParams) {
1006   {
1007     TypedTrackingMDRef<DICompositeType> N(T);
1008     if (Elements)
1009       N->replaceElements(Elements);
1010     if (TParams)
1011       N->replaceTemplateParams(DITemplateParameterArray(TParams));
1012     T = N.get();
1013   }
1014 
1015   // If T isn't resolved, there's no problem.
1016   if (!T->isResolved())
1017     return;
1018 
1019   // If T is resolved, it may be due to a self-reference cycle.  Track the
1020   // arrays explicitly if they're unresolved, or else the cycles will be
1021   // orphaned.
1022   if (Elements)
1023     trackIfUnresolved(Elements.get());
1024   if (TParams)
1025     trackIfUnresolved(TParams.get());
1026 }
1027