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