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