1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the DIBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/DIBuilder.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfo.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Dwarf.h"
22 #include "LLVMContextImpl.h"
23 
24 using namespace llvm;
25 using namespace llvm::dwarf;
26 
27 namespace {
28 class HeaderBuilder {
29   /// \brief Whether there are any fields yet.
30   ///
31   /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
32   /// may have been called already with an empty string.
33   bool IsEmpty;
34   SmallVector<char, 256> Chars;
35 
36 public:
37   HeaderBuilder() : IsEmpty(true) {}
38   HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
39   HeaderBuilder(HeaderBuilder &&X)
40       : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
41 
42   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
43     if (IsEmpty)
44       IsEmpty = false;
45     else
46       Chars.push_back(0);
47     Twine(X).toVector(Chars);
48     return *this;
49   }
50 
51   MDString *get(LLVMContext &Context) const {
52     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
53   }
54 
55   static HeaderBuilder get(unsigned Tag) {
56     return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
57   }
58 };
59 }
60 
61 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
62   : M(m), VMContext(M.getContext()), CUNode(nullptr),
63       DeclareFn(nullptr), ValueFn(nullptr),
64       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
65 
66 void DIBuilder::trackIfUnresolved(MDNode *N) {
67   if (!N)
68     return;
69   if (N->isResolved())
70     return;
71 
72   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
73   UnresolvedNodes.emplace_back(N);
74 }
75 
76 void DIBuilder::finalize() {
77   if (!CUNode) {
78     assert(!AllowUnresolvedNodes &&
79            "creating type nodes without a CU is not supported");
80     return;
81   }
82 
83   CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
84 
85   SmallVector<Metadata *, 16> RetainValues;
86   // Declarations and definitions of the same type may be retained. Some
87   // clients RAUW these pairs, leaving duplicates in the retained types
88   // list. Use a set to remove the duplicates while we transform the
89   // TrackingVHs back into Values.
90   SmallPtrSet<Metadata *, 16> RetainSet;
91   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
92     if (RetainSet.insert(AllRetainTypes[I]).second)
93       RetainValues.push_back(AllRetainTypes[I]);
94 
95   if (!RetainValues.empty())
96     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
97 
98   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
99   auto resolveVariables = [&](DISubprogram *SP) {
100     MDTuple *Temp = SP->getVariables().get();
101     if (!Temp)
102       return;
103 
104     SmallVector<Metadata *, 4> Variables;
105 
106     auto PV = PreservedVariables.find(SP);
107     if (PV != PreservedVariables.end())
108       Variables.append(PV->second.begin(), PV->second.end());
109 
110     DINodeArray AV = getOrCreateArray(Variables);
111     TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
112   };
113   for (auto *SP : SPs)
114     resolveVariables(SP);
115   for (auto *N : RetainValues)
116     if (auto *SP = dyn_cast<DISubprogram>(N))
117       resolveVariables(SP);
118 
119   if (!AllGVs.empty())
120     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
121 
122   if (!AllImportedModules.empty())
123     CUNode->replaceImportedEntities(MDTuple::get(
124         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
125                                                AllImportedModules.end())));
126 
127   // Now that all temp nodes have been replaced or deleted, resolve remaining
128   // cycles.
129   for (const auto &N : UnresolvedNodes)
130     if (N && !N->isResolved())
131       N->resolveCycles();
132   UnresolvedNodes.clear();
133 
134   // Can't handle unresolved nodes anymore.
135   AllowUnresolvedNodes = false;
136 }
137 
138 /// If N is compile unit return NULL otherwise return N.
139 static DIScope *getNonCompileUnitScope(DIScope *N) {
140   if (!N || isa<DICompileUnit>(N))
141     return nullptr;
142   return cast<DIScope>(N);
143 }
144 
145 DICompileUnit *DIBuilder::createCompileUnit(
146     unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
147     bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
148     DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId) {
149 
150   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
151           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
152          "Invalid Language tag");
153   assert(!Filename.empty() &&
154          "Unable to create compile unit without filename");
155 
156   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
157   CUNode = DICompileUnit::getDistinct(
158       VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
159       isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr, nullptr,
160       nullptr, nullptr, nullptr, DWOId);
161 
162   // Create a named metadata so that it is easier to find cu in a module.
163   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
164   NMD->addOperand(CUNode);
165   trackIfUnresolved(CUNode);
166   return CUNode;
167 }
168 
169 static DIImportedEntity *
170 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
171                      Metadata *NS, unsigned Line, StringRef Name,
172                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
173   unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
174   auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
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,
184                                                   unsigned Line) {
185   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
186                                 Context, NS, Line, StringRef(), AllImportedModules);
187 }
188 
189 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
190                                                   DIImportedEntity *NS,
191                                                   unsigned Line) {
192   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
193                                 Context, NS, Line, StringRef(), AllImportedModules);
194 }
195 
196 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
197                                                   unsigned Line) {
198   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
199                                 Context, M, Line, StringRef(), AllImportedModules);
200 }
201 
202 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
203                                                        DINode *Decl,
204                                                        unsigned Line,
205                                                        StringRef Name) {
206   // Make sure to use the unique identifier based metadata reference for
207   // types that have one.
208   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
209                                 Context, Decl, Line, Name, AllImportedModules);
210 }
211 
212 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
213   return DIFile::get(VMContext, Filename, Directory);
214 }
215 
216 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
217   assert(!Name.empty() && "Unable to create enumerator without name");
218   return DIEnumerator::get(VMContext, Val, Name);
219 }
220 
221 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
222   assert(!Name.empty() && "Unable to create type without name");
223   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
224 }
225 
226 DIBasicType *DIBuilder::createNullPtrType() {
227   return createUnspecifiedType("decltype(nullptr)");
228 }
229 
230 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
231                                         uint64_t AlignInBits,
232                                         unsigned Encoding) {
233   assert(!Name.empty() && "Unable to create type without name");
234   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
235                           AlignInBits, Encoding);
236 }
237 
238 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
239   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
240                             0, 0, 0);
241 }
242 
243 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
244                                             uint64_t SizeInBits,
245                                             uint64_t AlignInBits,
246                                             StringRef Name) {
247   // FIXME: Why is there a name here?
248   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
249                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
250                             AlignInBits, 0, 0);
251 }
252 
253 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
254                                                   DIType *Base,
255                                                   uint64_t SizeInBits,
256                                                   uint64_t AlignInBits,
257                                                   unsigned Flags) {
258   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
259                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
260                             AlignInBits, 0, Flags, Base);
261 }
262 
263 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy,
264                                               uint64_t SizeInBits,
265                                               uint64_t AlignInBits) {
266   assert(RTy && "Unable to create reference type");
267   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
268                             SizeInBits, AlignInBits, 0, 0);
269 }
270 
271 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
272                                         DIFile *File, unsigned LineNo,
273                                         DIScope *Context) {
274   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
275                             LineNo, getNonCompileUnitScope(Context), Ty, 0, 0,
276                             0, 0);
277 }
278 
279 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
280   assert(Ty && "Invalid type!");
281   assert(FriendTy && "Invalid friend type!");
282   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
283                             FriendTy, 0, 0, 0, 0);
284 }
285 
286 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
287                                             uint64_t BaseOffset,
288                                             unsigned Flags) {
289   assert(Ty && "Unable to create inheritance");
290   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
291                             0, Ty, BaseTy, 0, 0, BaseOffset, Flags);
292 }
293 
294 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
295                                            DIFile *File, unsigned LineNumber,
296                                            uint64_t SizeInBits,
297                                            uint64_t AlignInBits,
298                                            uint64_t OffsetInBits,
299                                            unsigned Flags, DIType *Ty) {
300   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
301                             LineNumber, getNonCompileUnitScope(Scope), Ty,
302                             SizeInBits, AlignInBits, OffsetInBits, Flags);
303 }
304 
305 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
306   if (C)
307     return ConstantAsMetadata::get(C);
308   return nullptr;
309 }
310 
311 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
312                                                  DIFile *File,
313                                                  unsigned LineNumber,
314                                                  DIType *Ty, unsigned Flags,
315                                                  llvm::Constant *Val) {
316   Flags |= DINode::FlagStaticMember;
317   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
318                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0, 0,
319                             0, Flags, getConstantOrNull(Val));
320 }
321 
322 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
323                                          unsigned LineNumber,
324                                          uint64_t SizeInBits,
325                                          uint64_t AlignInBits,
326                                          uint64_t OffsetInBits, unsigned Flags,
327                                          DIType *Ty, MDNode *PropertyNode) {
328   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
329                             LineNumber, getNonCompileUnitScope(File), Ty,
330                             SizeInBits, AlignInBits, OffsetInBits, Flags,
331                             PropertyNode);
332 }
333 
334 DIObjCProperty *
335 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
336                               StringRef GetterName, StringRef SetterName,
337                               unsigned PropertyAttributes, DIType *Ty) {
338   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
339                              SetterName, PropertyAttributes, Ty);
340 }
341 
342 DITemplateTypeParameter *
343 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
344                                        DIType *Ty) {
345   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
346   return DITemplateTypeParameter::get(VMContext, Name, Ty);
347 }
348 
349 static DITemplateValueParameter *
350 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
351                                    DIScope *Context, StringRef Name, DIType *Ty,
352                                    Metadata *MD) {
353   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
354   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD);
355 }
356 
357 DITemplateValueParameter *
358 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
359                                         DIType *Ty, Constant *Val) {
360   return createTemplateValueParameterHelper(
361       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
362       getConstantOrNull(Val));
363 }
364 
365 DITemplateValueParameter *
366 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
367                                            DIType *Ty, StringRef Val) {
368   return createTemplateValueParameterHelper(
369       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
370       MDString::get(VMContext, Val));
371 }
372 
373 DITemplateValueParameter *
374 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
375                                        DIType *Ty, DINodeArray Val) {
376   return createTemplateValueParameterHelper(
377       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
378       Val.get());
379 }
380 
381 DICompositeType *DIBuilder::createClassType(
382     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
383     uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
384     unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
385     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
386   assert((!Context || isa<DIScope>(Context)) &&
387          "createClassType should be called with a valid Context");
388 
389   auto *R = DICompositeType::get(
390       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
391       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
392       OffsetInBits, Flags, Elements, 0, VTableHolder,
393       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
394   trackIfUnresolved(R);
395   return R;
396 }
397 
398 DICompositeType *DIBuilder::createStructType(
399     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
400     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
401     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
402     DIType *VTableHolder, StringRef UniqueIdentifier) {
403   auto *R = DICompositeType::get(
404       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
405       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
406       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
407   trackIfUnresolved(R);
408   return R;
409 }
410 
411 DICompositeType *DIBuilder::createUnionType(
412     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
413     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
414     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
415   auto *R = DICompositeType::get(
416       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
417       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
418       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
419   trackIfUnresolved(R);
420   return R;
421 }
422 
423 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
424                                                   unsigned Flags, unsigned CC) {
425   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
426 }
427 
428 DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File,
429                                                   StringRef UniqueIdentifier) {
430   assert(!UniqueIdentifier.empty() && "external type ref without uid");
431   return DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr,
432                               0, 0, 0, DINode::FlagExternalTypeRef, nullptr, 0,
433                               nullptr, nullptr, UniqueIdentifier);
434 }
435 
436 DICompositeType *DIBuilder::createEnumerationType(
437     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
438     uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
439     DIType *UnderlyingType, StringRef UniqueIdentifier) {
440   auto *CTy = DICompositeType::get(
441       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
442       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
443       0, Elements, 0, nullptr, nullptr, UniqueIdentifier);
444   AllEnumTypes.push_back(CTy);
445   trackIfUnresolved(CTy);
446   return CTy;
447 }
448 
449 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
450                                             DIType *Ty,
451                                             DINodeArray Subscripts) {
452   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
453                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
454                                  0, Subscripts, 0, nullptr);
455   trackIfUnresolved(R);
456   return R;
457 }
458 
459 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
460                                              uint64_t AlignInBits, DIType *Ty,
461                                              DINodeArray Subscripts) {
462   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
463                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
464                                  DINode::FlagVector, Subscripts, 0, nullptr);
465   trackIfUnresolved(R);
466   return R;
467 }
468 
469 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
470                                    unsigned FlagsToSet) {
471   auto NewTy = Ty->clone();
472   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
473   return MDNode::replaceWithUniqued(std::move(NewTy));
474 }
475 
476 DIType *DIBuilder::createArtificialType(DIType *Ty) {
477   // FIXME: Restrict this to the nodes where it's valid.
478   if (Ty->isArtificial())
479     return Ty;
480   return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
481 }
482 
483 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
484   // FIXME: Restrict this to the nodes where it's valid.
485   if (Ty->isObjectPointer())
486     return Ty;
487   unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
488   return createTypeWithFlags(VMContext, Ty, Flags);
489 }
490 
491 void DIBuilder::retainType(DIScope *T) {
492   assert(T && "Expected non-null type");
493   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
494                              cast<DISubprogram>(T)->isDefinition() == false)) &&
495          "Expected type or subprogram declaration");
496   AllRetainTypes.emplace_back(T);
497 }
498 
499 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
500 
501 DICompositeType *
502 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
503                              DIFile *F, unsigned Line, unsigned RuntimeLang,
504                              uint64_t SizeInBits, uint64_t AlignInBits,
505                              StringRef UniqueIdentifier) {
506   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
507   // replaceWithUniqued().
508   auto *RetTy = DICompositeType::get(
509       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
510       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
511       nullptr, nullptr, UniqueIdentifier);
512   trackIfUnresolved(RetTy);
513   return RetTy;
514 }
515 
516 DICompositeType *DIBuilder::createReplaceableCompositeType(
517     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
518     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
519     unsigned Flags, StringRef UniqueIdentifier) {
520   auto *RetTy =
521       DICompositeType::getTemporary(
522           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
523           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
524           nullptr, UniqueIdentifier)
525           .release();
526   trackIfUnresolved(RetTy);
527   return RetTy;
528 }
529 
530 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
531   return MDTuple::get(VMContext, Elements);
532 }
533 
534 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
535   SmallVector<llvm::Metadata *, 16> Elts;
536   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
537     if (Elements[i] && isa<MDNode>(Elements[i]))
538       Elts.push_back(cast<DIType>(Elements[i]));
539     else
540       Elts.push_back(Elements[i]);
541   }
542   return DITypeRefArray(MDNode::get(VMContext, Elts));
543 }
544 
545 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
546   return DISubrange::get(VMContext, Count, Lo);
547 }
548 
549 static void checkGlobalVariableScope(DIScope *Context) {
550 #ifndef NDEBUG
551   if (auto *CT =
552           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
553     assert(CT->getIdentifier().empty() &&
554            "Context of a global variable should not be a type with identifier");
555 #endif
556 }
557 
558 DIGlobalVariable *DIBuilder::createGlobalVariable(
559     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
560     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
561     MDNode *Decl) {
562   checkGlobalVariableScope(Context);
563 
564   auto *N = DIGlobalVariable::getDistinct(
565       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
566       LineNumber, Ty, isLocalToUnit, true, Val,
567       cast_or_null<DIDerivedType>(Decl));
568   AllGVs.push_back(N);
569   return N;
570 }
571 
572 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
573     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
574     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
575     MDNode *Decl) {
576   checkGlobalVariableScope(Context);
577 
578   return DIGlobalVariable::getTemporary(
579              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
580              LineNumber, Ty, isLocalToUnit, false, Val,
581              cast_or_null<DIDerivedType>(Decl))
582       .release();
583 }
584 
585 static DILocalVariable *createLocalVariable(
586     LLVMContext &VMContext,
587     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
588     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
589     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
590   // FIXME: Why getNonCompileUnitScope()?
591   // FIXME: Why is "!Context" okay here?
592   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
593   // the only valid scopes)?
594   DIScope *Context = getNonCompileUnitScope(Scope);
595 
596   auto *Node =
597       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
598                            File, LineNo, Ty, ArgNo, Flags);
599   if (AlwaysPreserve) {
600     // The optimizer may remove local variables. If there is an interest
601     // to preserve variable info in such situation then stash it in a
602     // named mdnode.
603     DISubprogram *Fn = getDISubprogram(Scope);
604     assert(Fn && "Missing subprogram for local variable");
605     PreservedVariables[Fn].emplace_back(Node);
606   }
607   return Node;
608 }
609 
610 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
611                                                DIFile *File, unsigned LineNo,
612                                                DIType *Ty, bool AlwaysPreserve,
613                                                unsigned Flags) {
614   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
615                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
616                              Flags);
617 }
618 
619 DILocalVariable *DIBuilder::createParameterVariable(
620     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
621     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
622   assert(ArgNo && "Expected non-zero argument number for parameter");
623   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
624                              File, LineNo, Ty, AlwaysPreserve, Flags);
625 }
626 
627 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
628   return DIExpression::get(VMContext, Addr);
629 }
630 
631 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
632   // TODO: Remove the callers of this signed version and delete.
633   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
634   return createExpression(Addr);
635 }
636 
637 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
638                                                   unsigned SizeInBytes) {
639   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
640   return DIExpression::get(VMContext, Addr);
641 }
642 
643 template <class... Ts>
644 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
645   if (IsDistinct)
646     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
647   return DISubprogram::get(std::forward<Ts>(Args)...);
648 }
649 
650 DISubprogram *DIBuilder::createFunction(
651     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
652     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
653     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
654     DITemplateParameterArray TParams, DISubprogram *Decl) {
655   auto *Node = getSubprogram(
656       /* IsDistinct = */ isDefinition, VMContext,
657       getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty,
658       isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
659       isDefinition ? CUNode : nullptr, TParams, Decl,
660       MDTuple::getTemporary(VMContext, None).release());
661 
662   if (isDefinition)
663     AllSubprograms.push_back(Node);
664   trackIfUnresolved(Node);
665   return Node;
666 }
667 
668 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
669     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
670     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
671     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
672     DITemplateParameterArray TParams, DISubprogram *Decl) {
673   return DISubprogram::getTemporary(
674              VMContext, getNonCompileUnitScope(Context), Name, LinkageName,
675              File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr,
676              0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr, TParams,
677              Decl, nullptr)
678       .release();
679 }
680 
681 DISubprogram *
682 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
683                         DIFile *F, unsigned LineNo, DISubroutineType *Ty,
684                         bool isLocalToUnit, bool isDefinition, unsigned VK,
685                         unsigned VIndex, DIType *VTableHolder, unsigned Flags,
686                         bool isOptimized, DITemplateParameterArray TParams) {
687   assert(getNonCompileUnitScope(Context) &&
688          "Methods should have both a Context and a context that isn't "
689          "the compile unit.");
690   // FIXME: Do we want to use different scope/lines?
691   auto *SP = getSubprogram(
692       /* IsDistinct = */ isDefinition, VMContext, cast<DIScope>(Context), Name,
693       LinkageName, F, LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
694       VTableHolder, VK, VIndex, Flags, isOptimized,
695       isDefinition ? CUNode : nullptr, TParams, nullptr, nullptr);
696 
697   if (isDefinition)
698     AllSubprograms.push_back(SP);
699   trackIfUnresolved(SP);
700   return SP;
701 }
702 
703 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
704                                         DIFile *File, unsigned LineNo) {
705   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
706                           LineNo);
707 }
708 
709 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
710                                   StringRef ConfigurationMacros,
711                                   StringRef IncludePath,
712                                   StringRef ISysRoot) {
713  return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
714                       ConfigurationMacros, IncludePath, ISysRoot);
715 }
716 
717 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
718                                                       DIFile *File,
719                                                       unsigned Discriminator) {
720   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
721 }
722 
723 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
724                                               unsigned Line, unsigned Col) {
725   // Make these distinct, to avoid merging two lexical blocks on the same
726   // file/line/column.
727   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
728                                      File, Line, Col);
729 }
730 
731 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
732   assert(V && "no value passed to dbg intrinsic");
733   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
734 }
735 
736 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
737   I->setDebugLoc(const_cast<DILocation *>(DL));
738   return I;
739 }
740 
741 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
742                                       DIExpression *Expr, const DILocation *DL,
743                                       Instruction *InsertBefore) {
744   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
745   assert(DL && "Expected debug loc");
746   assert(DL->getScope()->getSubprogram() ==
747              VarInfo->getScope()->getSubprogram() &&
748          "Expected matching subprograms");
749   if (!DeclareFn)
750     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
751 
752   trackIfUnresolved(VarInfo);
753   trackIfUnresolved(Expr);
754   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
755                    MetadataAsValue::get(VMContext, VarInfo),
756                    MetadataAsValue::get(VMContext, Expr)};
757   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
758 }
759 
760 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
761                                       DIExpression *Expr, const DILocation *DL,
762                                       BasicBlock *InsertAtEnd) {
763   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
764   assert(DL && "Expected debug loc");
765   assert(DL->getScope()->getSubprogram() ==
766              VarInfo->getScope()->getSubprogram() &&
767          "Expected matching subprograms");
768   if (!DeclareFn)
769     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
770 
771   trackIfUnresolved(VarInfo);
772   trackIfUnresolved(Expr);
773   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
774                    MetadataAsValue::get(VMContext, VarInfo),
775                    MetadataAsValue::get(VMContext, Expr)};
776 
777   // If this block already has a terminator then insert this intrinsic
778   // before the terminator.
779   if (TerminatorInst *T = InsertAtEnd->getTerminator())
780     return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
781   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
782 }
783 
784 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
785                                                 DILocalVariable *VarInfo,
786                                                 DIExpression *Expr,
787                                                 const DILocation *DL,
788                                                 Instruction *InsertBefore) {
789   assert(V && "no value passed to dbg.value");
790   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
791   assert(DL && "Expected debug loc");
792   assert(DL->getScope()->getSubprogram() ==
793              VarInfo->getScope()->getSubprogram() &&
794          "Expected matching subprograms");
795   if (!ValueFn)
796     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
797 
798   trackIfUnresolved(VarInfo);
799   trackIfUnresolved(Expr);
800   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
801                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
802                    MetadataAsValue::get(VMContext, VarInfo),
803                    MetadataAsValue::get(VMContext, Expr)};
804   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
805 }
806 
807 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
808                                                 DILocalVariable *VarInfo,
809                                                 DIExpression *Expr,
810                                                 const DILocation *DL,
811                                                 BasicBlock *InsertAtEnd) {
812   assert(V && "no value passed to dbg.value");
813   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
814   assert(DL && "Expected debug loc");
815   assert(DL->getScope()->getSubprogram() ==
816              VarInfo->getScope()->getSubprogram() &&
817          "Expected matching subprograms");
818   if (!ValueFn)
819     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
820 
821   trackIfUnresolved(VarInfo);
822   trackIfUnresolved(Expr);
823   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
824                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
825                    MetadataAsValue::get(VMContext, VarInfo),
826                    MetadataAsValue::get(VMContext, Expr)};
827 
828   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
829 }
830 
831 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
832                                     DICompositeType *VTableHolder) {
833   {
834     TypedTrackingMDRef<DICompositeType> N(T);
835     N->replaceVTableHolder(VTableHolder);
836     T = N.get();
837   }
838 
839   // If this didn't create a self-reference, just return.
840   if (T != VTableHolder)
841     return;
842 
843   // Look for unresolved operands.  T will drop RAUW support, orphaning any
844   // cycles underneath it.
845   if (T->isResolved())
846     for (const MDOperand &O : T->operands())
847       if (auto *N = dyn_cast_or_null<MDNode>(O))
848         trackIfUnresolved(N);
849 }
850 
851 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
852                               DINodeArray TParams) {
853   {
854     TypedTrackingMDRef<DICompositeType> N(T);
855     if (Elements)
856       N->replaceElements(Elements);
857     if (TParams)
858       N->replaceTemplateParams(DITemplateParameterArray(TParams));
859     T = N.get();
860   }
861 
862   // If T isn't resolved, there's no problem.
863   if (!T->isResolved())
864     return;
865 
866   // If T is resolved, it may be due to a self-reference cycle.  Track the
867   // arrays explicitly if they're unresolved, or else the cycles will be
868   // orphaned.
869   if (Elements)
870     trackIfUnresolved(Elements.get());
871   if (TParams)
872     trackIfUnresolved(TParams.get());
873 }
874