OSDN Git Service

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