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