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