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