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