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