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