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