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