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