1 //===- DIBuilder.h - Debug Information Builder ------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a DIBuilder that is useful for creating debugging
10 // information entries in LLVM IR form.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_DIBUILDER_H
15 #define LLVM_IR_DIBUILDER_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/IR/TrackingMDRef.h"
27 #include "llvm/Support/Casting.h"
28 #include <algorithm>
29 #include <cstdint>
30 
31 namespace llvm {
32 
33   class BasicBlock;
34   class Constant;
35   class Function;
36   class Instruction;
37   class LLVMContext;
38   class Module;
39   class Value;
40 
41   class DIBuilder {
42     Module &M;
43     LLVMContext &VMContext;
44 
45     DICompileUnit *CUNode;   ///< The one compile unit created by this DIBuiler.
46     Function *DeclareFn;     ///< llvm.dbg.declare
47     Function *ValueFn;       ///< llvm.dbg.value
48     Function *LabelFn;       ///< llvm.dbg.label
49 
50     SmallVector<Metadata *, 4> AllEnumTypes;
51     /// Track the RetainTypes, since they can be updated later on.
52     SmallVector<TrackingMDNodeRef, 4> AllRetainTypes;
53     SmallVector<Metadata *, 4> AllSubprograms;
54     SmallVector<Metadata *, 4> AllGVs;
55     SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
56     /// Map Macro parent (which can be DIMacroFile or nullptr) to a list of
57     /// Metadata all of type DIMacroNode.
58     /// DIMacroNode's with nullptr parent are DICompileUnit direct children.
59     MapVector<MDNode *, SetVector<Metadata *>> AllMacrosPerParent;
60 
61     /// Track nodes that may be unresolved.
62     SmallVector<TrackingMDNodeRef, 4> UnresolvedNodes;
63     bool AllowUnresolvedNodes;
64 
65     /// Each subprogram's preserved local variables.
66     ///
67     /// Do not use a std::vector.  Some versions of libc++ apparently copy
68     /// instead of move on grow operations, and TrackingMDRef is expensive to
69     /// copy.
70     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> PreservedVariables;
71 
72     /// Each subprogram's preserved labels.
73     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> PreservedLabels;
74 
75     /// Create a temporary.
76     ///
77     /// Create an \a temporary node and track it in \a UnresolvedNodes.
78     void trackIfUnresolved(MDNode *N);
79 
80     /// Internal helper for insertDeclare.
81     Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
82                                DIExpression *Expr, const DILocation *DL,
83                                BasicBlock *InsertBB, Instruction *InsertBefore);
84 
85     /// Internal helper for insertLabel.
86     Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
87                              BasicBlock *InsertBB, Instruction *InsertBefore);
88 
89     /// Internal helper for insertDbgValueIntrinsic.
90     Instruction *
91     insertDbgValueIntrinsic(llvm::Value *Val, DILocalVariable *VarInfo,
92                             DIExpression *Expr, const DILocation *DL,
93                             BasicBlock *InsertBB, Instruction *InsertBefore);
94 
95   public:
96     /// Construct a builder for a module.
97     ///
98     /// If \c AllowUnresolved, collect unresolved nodes attached to the module
99     /// in order to resolve cycles during \a finalize().
100     ///
101     /// If \p CU is given a value other than nullptr, then set \p CUNode to CU.
102     explicit DIBuilder(Module &M, bool AllowUnresolved = true,
103                        DICompileUnit *CU = nullptr);
104     DIBuilder(const DIBuilder &) = delete;
105     DIBuilder &operator=(const DIBuilder &) = delete;
106 
107     /// Construct any deferred debug info descriptors.
108     void finalize();
109 
110     /// Finalize a specific subprogram - no new variables may be added to this
111     /// subprogram afterwards.
112     void finalizeSubprogram(DISubprogram *SP);
113 
114     /// A CompileUnit provides an anchor for all debugging
115     /// information generated during this instance of compilation.
116     /// \param Lang          Source programming language, eg. dwarf::DW_LANG_C99
117     /// \param File          File info.
118     /// \param Producer      Identify the producer of debugging information
119     ///                      and code.  Usually this is a compiler
120     ///                      version string.
121     /// \param isOptimized   A boolean flag which indicates whether optimization
122     ///                      is enabled or not.
123     /// \param Flags         This string lists command line options. This
124     ///                      string is directly embedded in debug info
125     ///                      output which may be used by a tool
126     ///                      analyzing generated debugging information.
127     /// \param RV            This indicates runtime version for languages like
128     ///                      Objective-C.
129     /// \param SplitName     The name of the file that we'll split debug info
130     ///                      out into.
131     /// \param Kind          The kind of debug information to generate.
132     /// \param DWOId         The DWOId if this is a split skeleton compile unit.
133     /// \param SplitDebugInlining    Whether to emit inline debug info.
134     /// \param DebugInfoForProfiling Whether to emit extra debug info for
135     ///                              profile collection.
136     /// \param NameTableKind  Whether to emit .debug_gnu_pubnames,
137     ///                      .debug_pubnames, or no pubnames at all.
138     /// \param SysRoot       The clang system root (value of -isysroot).
139     /// \param SDK           The SDK name. On Darwin, this is the last component
140     ///                      of the sysroot.
141     DICompileUnit *
142     createCompileUnit(unsigned Lang, DIFile *File, StringRef Producer,
143                       bool isOptimized, StringRef Flags, unsigned RV,
144                       StringRef SplitName = StringRef(),
145                       DICompileUnit::DebugEmissionKind Kind =
146                           DICompileUnit::DebugEmissionKind::FullDebug,
147                       uint64_t DWOId = 0, bool SplitDebugInlining = true,
148                       bool DebugInfoForProfiling = false,
149                       DICompileUnit::DebugNameTableKind NameTableKind =
150                           DICompileUnit::DebugNameTableKind::Default,
151                       bool RangesBaseAddress = false, StringRef SysRoot = {},
152                       StringRef SDK = {});
153 
154     /// Create a file descriptor to hold debugging information for a file.
155     /// \param Filename  File name.
156     /// \param Directory Directory.
157     /// \param Checksum  Optional checksum kind (e.g. CSK_MD5, CSK_SHA1, etc.)
158     ///                  and value.
159     /// \param Source    Optional source text.
160     DIFile *
161     createFile(StringRef Filename, StringRef Directory,
162                Optional<DIFile::ChecksumInfo<StringRef>> Checksum = None,
163                Optional<StringRef> Source = None);
164 
165     /// Create debugging information entry for a macro.
166     /// \param Parent     Macro parent (could be nullptr).
167     /// \param Line       Source line number where the macro is defined.
168     /// \param MacroType  DW_MACINFO_define or DW_MACINFO_undef.
169     /// \param Name       Macro name.
170     /// \param Value      Macro value.
171     DIMacro *createMacro(DIMacroFile *Parent, unsigned Line, unsigned MacroType,
172                          StringRef Name, StringRef Value = StringRef());
173 
174     /// Create debugging information temporary entry for a macro file.
175     /// List of macro node direct children will be calculated by DIBuilder,
176     /// using the \p Parent relationship.
177     /// \param Parent     Macro file parent (could be nullptr).
178     /// \param Line       Source line number where the macro file is included.
179     /// \param File       File descriptor containing the name of the macro file.
180     DIMacroFile *createTempMacroFile(DIMacroFile *Parent, unsigned Line,
181                                      DIFile *File);
182 
183     /// Create a single enumerator value.
184     DIEnumerator *createEnumerator(StringRef Name, int64_t Val, bool IsUnsigned = false);
185 
186     /// Create a DWARF unspecified type.
187     DIBasicType *createUnspecifiedType(StringRef Name);
188 
189     /// Create C++11 nullptr type.
190     DIBasicType *createNullPtrType();
191 
192     /// Create debugging information entry for a basic
193     /// type.
194     /// \param Name        Type name.
195     /// \param SizeInBits  Size of the type.
196     /// \param Encoding    DWARF encoding code, e.g., dwarf::DW_ATE_float.
197     /// \param Flags       Optional DWARF attributes, e.g., DW_AT_endianity.
198     DIBasicType *createBasicType(StringRef Name, uint64_t SizeInBits,
199                                  unsigned Encoding,
200                                  DINode::DIFlags Flags = DINode::FlagZero);
201 
202     /// Create debugging information entry for a qualified
203     /// type, e.g. 'const int'.
204     /// \param Tag         Tag identifing type, e.g. dwarf::TAG_volatile_type
205     /// \param FromTy      Base Type.
206     DIDerivedType *createQualifiedType(unsigned Tag, DIType *FromTy);
207 
208     /// Create debugging information entry for a pointer.
209     /// \param PointeeTy         Type pointed by this pointer.
210     /// \param SizeInBits        Size.
211     /// \param AlignInBits       Alignment. (optional)
212     /// \param DWARFAddressSpace DWARF address space. (optional)
213     /// \param Name              Pointer type name. (optional)
214     DIDerivedType *createPointerType(DIType *PointeeTy, uint64_t SizeInBits,
215                                      uint32_t AlignInBits = 0,
216                                      Optional<unsigned> DWARFAddressSpace =
217                                          None,
218                                      StringRef Name = "");
219 
220     /// Create debugging information entry for a pointer to member.
221     /// \param PointeeTy Type pointed to by this pointer.
222     /// \param SizeInBits  Size.
223     /// \param AlignInBits Alignment. (optional)
224     /// \param Class Type for which this pointer points to members of.
225     DIDerivedType *
226     createMemberPointerType(DIType *PointeeTy, DIType *Class,
227                             uint64_t SizeInBits, uint32_t AlignInBits = 0,
228                             DINode::DIFlags Flags = DINode::FlagZero);
229 
230     /// Create debugging information entry for a c++
231     /// style reference or rvalue reference type.
232     DIDerivedType *createReferenceType(unsigned Tag, DIType *RTy,
233                                        uint64_t SizeInBits = 0,
234                                        uint32_t AlignInBits = 0,
235                                        Optional<unsigned> DWARFAddressSpace =
236                                            None);
237 
238     /// Create debugging information entry for a typedef.
239     /// \param Ty          Original type.
240     /// \param Name        Typedef name.
241     /// \param File        File where this type is defined.
242     /// \param LineNo      Line number.
243     /// \param Context     The surrounding context for the typedef.
244     /// \param AlignInBits Alignment. (optional)
245     DIDerivedType *createTypedef(DIType *Ty, StringRef Name, DIFile *File,
246                                  unsigned LineNo, DIScope *Context,
247                                  uint32_t AlignInBits = 0);
248 
249     /// Create debugging information entry for a 'friend'.
250     DIDerivedType *createFriend(DIType *Ty, DIType *FriendTy);
251 
252     /// Create debugging information entry to establish
253     /// inheritance relationship between two types.
254     /// \param Ty           Original type.
255     /// \param BaseTy       Base type. Ty is inherits from base.
256     /// \param BaseOffset   Base offset.
257     /// \param VBPtrOffset  Virtual base pointer offset.
258     /// \param Flags        Flags to describe inheritance attribute,
259     ///                     e.g. private
260     DIDerivedType *createInheritance(DIType *Ty, DIType *BaseTy,
261                                      uint64_t BaseOffset, uint32_t VBPtrOffset,
262                                      DINode::DIFlags Flags);
263 
264     /// Create debugging information entry for a member.
265     /// \param Scope        Member scope.
266     /// \param Name         Member name.
267     /// \param File         File where this member is defined.
268     /// \param LineNo       Line number.
269     /// \param SizeInBits   Member size.
270     /// \param AlignInBits  Member alignment.
271     /// \param OffsetInBits Member offset.
272     /// \param Flags        Flags to encode member attribute, e.g. private
273     /// \param Ty           Parent type.
274     DIDerivedType *createMemberType(DIScope *Scope, StringRef Name,
275                                     DIFile *File, unsigned LineNo,
276                                     uint64_t SizeInBits,
277                                     uint32_t AlignInBits,
278                                     uint64_t OffsetInBits,
279                                     DINode::DIFlags Flags, DIType *Ty);
280 
281     /// Create debugging information entry for a variant.  A variant
282     /// normally should be a member of a variant part.
283     /// \param Scope        Member scope.
284     /// \param Name         Member name.
285     /// \param File         File where this member is defined.
286     /// \param LineNo       Line number.
287     /// \param SizeInBits   Member size.
288     /// \param AlignInBits  Member alignment.
289     /// \param OffsetInBits Member offset.
290     /// \param Flags        Flags to encode member attribute, e.g. private
291     /// \param Discriminant The discriminant for this branch; null for
292     ///                     the default branch
293     /// \param Ty           Parent type.
294     DIDerivedType *createVariantMemberType(DIScope *Scope, StringRef Name,
295 					   DIFile *File, unsigned LineNo,
296 					   uint64_t SizeInBits,
297 					   uint32_t AlignInBits,
298 					   uint64_t OffsetInBits,
299 					   Constant *Discriminant,
300 					   DINode::DIFlags Flags, DIType *Ty);
301 
302     /// Create debugging information entry for a bit field member.
303     /// \param Scope               Member scope.
304     /// \param Name                Member name.
305     /// \param File                File where this member is defined.
306     /// \param LineNo              Line number.
307     /// \param SizeInBits          Member size.
308     /// \param OffsetInBits        Member offset.
309     /// \param StorageOffsetInBits Member storage offset.
310     /// \param Flags               Flags to encode member attribute.
311     /// \param Ty                  Parent type.
312     DIDerivedType *createBitFieldMemberType(
313         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
314         uint64_t SizeInBits, uint64_t OffsetInBits,
315         uint64_t StorageOffsetInBits, DINode::DIFlags Flags, DIType *Ty);
316 
317     /// Create debugging information entry for a
318     /// C++ static data member.
319     /// \param Scope      Member scope.
320     /// \param Name       Member name.
321     /// \param File       File where this member is declared.
322     /// \param LineNo     Line number.
323     /// \param Ty         Type of the static member.
324     /// \param Flags      Flags to encode member attribute, e.g. private.
325     /// \param Val        Const initializer of the member.
326     /// \param AlignInBits  Member alignment.
327     DIDerivedType *createStaticMemberType(DIScope *Scope, StringRef Name,
328                                           DIFile *File, unsigned LineNo,
329                                           DIType *Ty, DINode::DIFlags Flags,
330                                           Constant *Val,
331                                           uint32_t AlignInBits = 0);
332 
333     /// Create debugging information entry for Objective-C
334     /// instance variable.
335     /// \param Name         Member name.
336     /// \param File         File where this member is defined.
337     /// \param LineNo       Line number.
338     /// \param SizeInBits   Member size.
339     /// \param AlignInBits  Member alignment.
340     /// \param OffsetInBits Member offset.
341     /// \param Flags        Flags to encode member attribute, e.g. private
342     /// \param Ty           Parent type.
343     /// \param PropertyNode Property associated with this ivar.
344     DIDerivedType *createObjCIVar(StringRef Name, DIFile *File, unsigned LineNo,
345                                   uint64_t SizeInBits, uint32_t AlignInBits,
346                                   uint64_t OffsetInBits, DINode::DIFlags Flags,
347                                   DIType *Ty, MDNode *PropertyNode);
348 
349     /// Create debugging information entry for Objective-C
350     /// property.
351     /// \param Name         Property name.
352     /// \param File         File where this property is defined.
353     /// \param LineNumber   Line number.
354     /// \param GetterName   Name of the Objective C property getter selector.
355     /// \param SetterName   Name of the Objective C property setter selector.
356     /// \param PropertyAttributes Objective C property attributes.
357     /// \param Ty           Type.
358     DIObjCProperty *createObjCProperty(StringRef Name, DIFile *File,
359                                        unsigned LineNumber,
360                                        StringRef GetterName,
361                                        StringRef SetterName,
362                                        unsigned PropertyAttributes, DIType *Ty);
363 
364     /// Create debugging information entry for a class.
365     /// \param Scope        Scope in which this class is defined.
366     /// \param Name         class name.
367     /// \param File         File where this member is defined.
368     /// \param LineNumber   Line number.
369     /// \param SizeInBits   Member size.
370     /// \param AlignInBits  Member alignment.
371     /// \param OffsetInBits Member offset.
372     /// \param Flags        Flags to encode member attribute, e.g. private
373     /// \param Elements     class members.
374     /// \param VTableHolder Debug info of the base class that contains vtable
375     ///                     for this type. This is used in
376     ///                     DW_AT_containing_type. See DWARF documentation
377     ///                     for more info.
378     /// \param TemplateParms Template type parameters.
379     /// \param UniqueIdentifier A unique identifier for the class.
380     DICompositeType *createClassType(
381         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
382         uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
383         DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
384         DIType *VTableHolder = nullptr, MDNode *TemplateParms = nullptr,
385         StringRef UniqueIdentifier = "");
386 
387     /// Create debugging information entry for a struct.
388     /// \param Scope        Scope in which this struct is defined.
389     /// \param Name         Struct name.
390     /// \param File         File where this member is defined.
391     /// \param LineNumber   Line number.
392     /// \param SizeInBits   Member size.
393     /// \param AlignInBits  Member alignment.
394     /// \param Flags        Flags to encode member attribute, e.g. private
395     /// \param Elements     Struct elements.
396     /// \param RunTimeLang  Optional parameter, Objective-C runtime version.
397     /// \param UniqueIdentifier A unique identifier for the struct.
398     DICompositeType *createStructType(
399         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
400         uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
401         DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang = 0,
402         DIType *VTableHolder = nullptr, StringRef UniqueIdentifier = "");
403 
404     /// Create debugging information entry for an union.
405     /// \param Scope        Scope in which this union is defined.
406     /// \param Name         Union name.
407     /// \param File         File where this member is defined.
408     /// \param LineNumber   Line number.
409     /// \param SizeInBits   Member size.
410     /// \param AlignInBits  Member alignment.
411     /// \param Flags        Flags to encode member attribute, e.g. private
412     /// \param Elements     Union elements.
413     /// \param RunTimeLang  Optional parameter, Objective-C runtime version.
414     /// \param UniqueIdentifier A unique identifier for the union.
415     DICompositeType *createUnionType(DIScope *Scope, StringRef Name,
416                                      DIFile *File, unsigned LineNumber,
417                                      uint64_t SizeInBits, uint32_t AlignInBits,
418                                      DINode::DIFlags Flags,
419                                      DINodeArray Elements,
420                                      unsigned RunTimeLang = 0,
421                                      StringRef UniqueIdentifier = "");
422 
423     /// Create debugging information entry for a variant part.  A
424     /// variant part normally has a discriminator (though this is not
425     /// required) and a number of variant children.
426     /// \param Scope        Scope in which this union is defined.
427     /// \param Name         Union name.
428     /// \param File         File where this member is defined.
429     /// \param LineNumber   Line number.
430     /// \param SizeInBits   Member size.
431     /// \param AlignInBits  Member alignment.
432     /// \param Flags        Flags to encode member attribute, e.g. private
433     /// \param Discriminator Discriminant member
434     /// \param Elements     Variant elements.
435     /// \param UniqueIdentifier A unique identifier for the union.
436     DICompositeType *createVariantPart(DIScope *Scope, StringRef Name,
437 				       DIFile *File, unsigned LineNumber,
438 				       uint64_t SizeInBits, uint32_t AlignInBits,
439 				       DINode::DIFlags Flags,
440 				       DIDerivedType *Discriminator,
441 				       DINodeArray Elements,
442 				       StringRef UniqueIdentifier = "");
443 
444     /// Create debugging information for template
445     /// type parameter.
446     /// \param Scope        Scope in which this type is defined.
447     /// \param Name         Type parameter name.
448     /// \param Ty           Parameter type.
449     /// \param IsDefault    Parameter is default or not
450     DITemplateTypeParameter *createTemplateTypeParameter(DIScope *Scope,
451                                                          StringRef Name,
452                                                          DIType *Ty,
453                                                          bool IsDefault);
454 
455     /// Create debugging information for template
456     /// value parameter.
457     /// \param Scope        Scope in which this type is defined.
458     /// \param Name         Value parameter name.
459     /// \param Ty           Parameter type.
460     /// \param IsDefault    Parameter is default or not
461     /// \param Val          Constant parameter value.
462     DITemplateValueParameter *
463     createTemplateValueParameter(DIScope *Scope, StringRef Name, DIType *Ty,
464                                  bool IsDefault, Constant *Val);
465 
466     /// Create debugging information for a template template parameter.
467     /// \param Scope        Scope in which this type is defined.
468     /// \param Name         Value parameter name.
469     /// \param Ty           Parameter type.
470     /// \param Val          The fully qualified name of the template.
471     DITemplateValueParameter *createTemplateTemplateParameter(DIScope *Scope,
472                                                               StringRef Name,
473                                                               DIType *Ty,
474                                                               StringRef Val);
475 
476     /// Create debugging information for a template parameter pack.
477     /// \param Scope        Scope in which this type is defined.
478     /// \param Name         Value parameter name.
479     /// \param Ty           Parameter type.
480     /// \param Val          An array of types in the pack.
481     DITemplateValueParameter *createTemplateParameterPack(DIScope *Scope,
482                                                           StringRef Name,
483                                                           DIType *Ty,
484                                                           DINodeArray Val);
485 
486     /// Create debugging information entry for an array.
487     /// \param Size         Array size.
488     /// \param AlignInBits  Alignment.
489     /// \param Ty           Element type.
490     /// \param Subscripts   Subscripts.
491     DICompositeType *createArrayType(uint64_t Size, uint32_t AlignInBits,
492                                      DIType *Ty, DINodeArray Subscripts);
493 
494     /// Create debugging information entry for a vector type.
495     /// \param Size         Array size.
496     /// \param AlignInBits  Alignment.
497     /// \param Ty           Element type.
498     /// \param Subscripts   Subscripts.
499     DICompositeType *createVectorType(uint64_t Size, uint32_t AlignInBits,
500                                       DIType *Ty, DINodeArray Subscripts);
501 
502     /// Create debugging information entry for an
503     /// enumeration.
504     /// \param Scope          Scope in which this enumeration is defined.
505     /// \param Name           Union name.
506     /// \param File           File where this member is defined.
507     /// \param LineNumber     Line number.
508     /// \param SizeInBits     Member size.
509     /// \param AlignInBits    Member alignment.
510     /// \param Elements       Enumeration elements.
511     /// \param UnderlyingType Underlying type of a C++11/ObjC fixed enum.
512     /// \param UniqueIdentifier A unique identifier for the enum.
513     /// \param IsScoped Boolean flag indicate if this is C++11/ObjC 'enum class'.
514     DICompositeType *createEnumerationType(
515         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
516         uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
517         DIType *UnderlyingType, StringRef UniqueIdentifier = "", bool IsScoped = false);
518 
519     /// Create subroutine type.
520     /// \param ParameterTypes  An array of subroutine parameter types. This
521     ///                        includes return type at 0th index.
522     /// \param Flags           E.g.: LValueReference.
523     ///                        These flags are used to emit dwarf attributes.
524     /// \param CC              Calling convention, e.g. dwarf::DW_CC_normal
525     DISubroutineType *
526     createSubroutineType(DITypeRefArray ParameterTypes,
527                          DINode::DIFlags Flags = DINode::FlagZero,
528                          unsigned CC = 0);
529 
530     /// Create a distinct clone of \p SP with FlagArtificial set.
531     static DISubprogram *createArtificialSubprogram(DISubprogram *SP);
532 
533     /// Create a uniqued clone of \p Ty with FlagArtificial set.
534     static DIType *createArtificialType(DIType *Ty);
535 
536     /// Create a uniqued clone of \p Ty with FlagObjectPointer and
537     /// FlagArtificial set.
538     static DIType *createObjectPointerType(DIType *Ty);
539 
540     /// Create a permanent forward-declared type.
541     DICompositeType *createForwardDecl(unsigned Tag, StringRef Name,
542                                        DIScope *Scope, DIFile *F, unsigned Line,
543                                        unsigned RuntimeLang = 0,
544                                        uint64_t SizeInBits = 0,
545                                        uint32_t AlignInBits = 0,
546                                        StringRef UniqueIdentifier = "");
547 
548     /// Create a temporary forward-declared type.
549     DICompositeType *createReplaceableCompositeType(
550         unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
551         unsigned RuntimeLang = 0, uint64_t SizeInBits = 0,
552         uint32_t AlignInBits = 0, DINode::DIFlags Flags = DINode::FlagFwdDecl,
553         StringRef UniqueIdentifier = "");
554 
555     /// Retain DIScope* in a module even if it is not referenced
556     /// through debug info anchors.
557     void retainType(DIScope *T);
558 
559     /// Create unspecified parameter type
560     /// for a subroutine type.
561     DIBasicType *createUnspecifiedParameter();
562 
563     /// Get a DINodeArray, create one if required.
564     DINodeArray getOrCreateArray(ArrayRef<Metadata *> Elements);
565 
566     /// Get a DIMacroNodeArray, create one if required.
567     DIMacroNodeArray getOrCreateMacroArray(ArrayRef<Metadata *> Elements);
568 
569     /// Get a DITypeRefArray, create one if required.
570     DITypeRefArray getOrCreateTypeArray(ArrayRef<Metadata *> Elements);
571 
572     /// Create a descriptor for a value range.  This
573     /// implicitly uniques the values returned.
574     DISubrange *getOrCreateSubrange(int64_t Lo, int64_t Count);
575     DISubrange *getOrCreateSubrange(int64_t Lo, Metadata *CountNode);
576     DISubrange *getOrCreateSubrange(Metadata *Count, Metadata *LowerBound,
577                                     Metadata *UpperBound, Metadata *Stride);
578 
579     /// Create a new descriptor for the specified variable.
580     /// \param Context     Variable scope.
581     /// \param Name        Name of the variable.
582     /// \param LinkageName Mangled  name of the variable.
583     /// \param File        File where this variable is defined.
584     /// \param LineNo      Line number.
585     /// \param Ty          Variable Type.
586     /// \param IsLocalToUnit Boolean flag indicate whether this variable is
587     ///                      externally visible or not.
588     /// \param Expr        The location of the global relative to the attached
589     ///                    GlobalVariable.
590     /// \param Decl        Reference to the corresponding declaration.
591     /// \param AlignInBits Variable alignment(or 0 if no alignment attr was
592     ///                    specified)
593     DIGlobalVariableExpression *createGlobalVariableExpression(
594         DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
595         unsigned LineNo, DIType *Ty, bool IsLocalToUnit, bool isDefined = true,
596         DIExpression *Expr = nullptr, MDNode *Decl = nullptr,
597         MDTuple *TemplateParams = nullptr, uint32_t AlignInBits = 0);
598 
599     /// Identical to createGlobalVariable
600     /// except that the resulting DbgNode is temporary and meant to be RAUWed.
601     DIGlobalVariable *createTempGlobalVariableFwdDecl(
602         DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
603         unsigned LineNo, DIType *Ty, bool IsLocalToUnit, MDNode *Decl = nullptr,
604         MDTuple *TemplateParams= nullptr, uint32_t AlignInBits = 0);
605 
606     /// Create a new descriptor for an auto variable.  This is a local variable
607     /// that is not a subprogram parameter.
608     ///
609     /// \c Scope must be a \a DILocalScope, and thus its scope chain eventually
610     /// leads to a \a DISubprogram.
611     ///
612     /// If \c AlwaysPreserve, this variable will be referenced from its
613     /// containing subprogram, and will survive some optimizations.
614     DILocalVariable *
615     createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File,
616                        unsigned LineNo, DIType *Ty, bool AlwaysPreserve = false,
617                        DINode::DIFlags Flags = DINode::FlagZero,
618                        uint32_t AlignInBits = 0);
619 
620     /// Create a new descriptor for an label.
621     ///
622     /// \c Scope must be a \a DILocalScope, and thus its scope chain eventually
623     /// leads to a \a DISubprogram.
624     DILabel *
625     createLabel(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
626                 bool AlwaysPreserve = false);
627 
628     /// Create a new descriptor for a parameter variable.
629     ///
630     /// \c Scope must be a \a DILocalScope, and thus its scope chain eventually
631     /// leads to a \a DISubprogram.
632     ///
633     /// \c ArgNo is the index (starting from \c 1) of this variable in the
634     /// subprogram parameters.  \c ArgNo should not conflict with other
635     /// parameters of the same subprogram.
636     ///
637     /// If \c AlwaysPreserve, this variable will be referenced from its
638     /// containing subprogram, and will survive some optimizations.
639     DILocalVariable *
640     createParameterVariable(DIScope *Scope, StringRef Name, unsigned ArgNo,
641                             DIFile *File, unsigned LineNo, DIType *Ty,
642                             bool AlwaysPreserve = false,
643                             DINode::DIFlags Flags = DINode::FlagZero);
644 
645     /// Create a new descriptor for the specified
646     /// variable which has a complex address expression for its address.
647     /// \param Addr        An array of complex address operations.
648     DIExpression *createExpression(ArrayRef<uint64_t> Addr = None);
649     DIExpression *createExpression(ArrayRef<int64_t> Addr);
650 
651     /// Create an expression for a variable that does not have an address, but
652     /// does have a constant value.
653     DIExpression *createConstantValueExpression(uint64_t Val) {
654       return DIExpression::get(
655           VMContext, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_stack_value});
656     }
657 
658     /// Create a new descriptor for the specified subprogram.
659     /// See comments in DISubprogram* for descriptions of these fields.
660     /// \param Scope         Function scope.
661     /// \param Name          Function name.
662     /// \param LinkageName   Mangled function name.
663     /// \param File          File where this variable is defined.
664     /// \param LineNo        Line number.
665     /// \param Ty            Function type.
666     /// \param ScopeLine     Set to the beginning of the scope this starts
667     /// \param Flags         e.g. is this function prototyped or not.
668     ///                      These flags are used to emit dwarf attributes.
669     /// \param SPFlags       Additional flags specific to subprograms.
670     /// \param TParams       Function template parameters.
671     /// \param ThrownTypes   Exception types this function may throw.
672     DISubprogram *
673     createFunction(DIScope *Scope, StringRef Name, StringRef LinkageName,
674                    DIFile *File, unsigned LineNo, DISubroutineType *Ty,
675                    unsigned ScopeLine, DINode::DIFlags Flags = DINode::FlagZero,
676                    DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagZero,
677                    DITemplateParameterArray TParams = nullptr,
678                    DISubprogram *Decl = nullptr,
679                    DITypeArray ThrownTypes = nullptr);
680 
681     /// Identical to createFunction,
682     /// except that the resulting DbgNode is meant to be RAUWed.
683     DISubprogram *createTempFunctionFwdDecl(
684         DIScope *Scope, StringRef Name, StringRef LinkageName, DIFile *File,
685         unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
686         DINode::DIFlags Flags = DINode::FlagZero,
687         DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagZero,
688         DITemplateParameterArray TParams = nullptr,
689         DISubprogram *Decl = nullptr, DITypeArray ThrownTypes = nullptr);
690 
691     /// Create a new descriptor for the specified C++ method.
692     /// See comments in \a DISubprogram* for descriptions of these fields.
693     /// \param Scope         Function scope.
694     /// \param Name          Function name.
695     /// \param LinkageName   Mangled function name.
696     /// \param File          File where this variable is defined.
697     /// \param LineNo        Line number.
698     /// \param Ty            Function type.
699     /// \param VTableIndex   Index no of this method in virtual table, or -1u if
700     ///                      unrepresentable.
701     /// \param ThisAdjustment
702     ///                      MS ABI-specific adjustment of 'this' that occurs
703     ///                      in the prologue.
704     /// \param VTableHolder  Type that holds vtable.
705     /// \param Flags         e.g. is this function prototyped or not.
706     ///                      This flags are used to emit dwarf attributes.
707     /// \param SPFlags       Additional flags specific to subprograms.
708     /// \param TParams       Function template parameters.
709     /// \param ThrownTypes   Exception types this function may throw.
710     DISubprogram *
711     createMethod(DIScope *Scope, StringRef Name, StringRef LinkageName,
712                  DIFile *File, unsigned LineNo, DISubroutineType *Ty,
713                  unsigned VTableIndex = 0, int ThisAdjustment = 0,
714                  DIType *VTableHolder = nullptr,
715                  DINode::DIFlags Flags = DINode::FlagZero,
716                  DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagZero,
717                  DITemplateParameterArray TParams = nullptr,
718                  DITypeArray ThrownTypes = nullptr);
719 
720     /// Create common block entry for a Fortran common block.
721     /// \param Scope       Scope of this common block.
722     /// \param decl        Global variable declaration.
723     /// \param Name        The name of this common block.
724     /// \param File        The file this common block is defined.
725     /// \param LineNo      Line number.
726     DICommonBlock *createCommonBlock(DIScope *Scope, DIGlobalVariable *decl,
727                                      StringRef Name, DIFile *File,
728                                      unsigned LineNo);
729 
730     /// This creates new descriptor for a namespace with the specified
731     /// parent scope.
732     /// \param Scope       Namespace scope
733     /// \param Name        Name of this namespace
734     /// \param ExportSymbols True for C++ inline namespaces.
735     DINamespace *createNameSpace(DIScope *Scope, StringRef Name,
736                                  bool ExportSymbols);
737 
738     /// This creates new descriptor for a module with the specified
739     /// parent scope.
740     /// \param Scope       Parent scope
741     /// \param Name        Name of this module
742     /// \param ConfigurationMacros
743     ///                    A space-separated shell-quoted list of -D macro
744     ///                    definitions as they would appear on a command line.
745     /// \param IncludePath The path to the module map file.
746     /// \param APINotesFile The path to an API notes file for this module.
747     /// \param File        Source file of the module declaration. Used for
748     ///                    Fortran modules.
749     /// \param LineNo      Source line number of the  module declaration.
750     ///                    Used for Fortran modules.
751     DIModule *createModule(DIScope *Scope, StringRef Name,
752                            StringRef ConfigurationMacros, StringRef IncludePath,
753                            StringRef APINotesFile = {}, DIFile *File = nullptr,
754                            unsigned LineNo = 0);
755 
756     /// This creates a descriptor for a lexical block with a new file
757     /// attached. This merely extends the existing
758     /// lexical block as it crosses a file.
759     /// \param Scope       Lexical block.
760     /// \param File        Source file.
761     /// \param Discriminator DWARF path discriminator value.
762     DILexicalBlockFile *createLexicalBlockFile(DIScope *Scope, DIFile *File,
763                                                unsigned Discriminator = 0);
764 
765     /// This creates a descriptor for a lexical block with the
766     /// specified parent context.
767     /// \param Scope         Parent lexical scope.
768     /// \param File          Source file.
769     /// \param Line          Line number.
770     /// \param Col           Column number.
771     DILexicalBlock *createLexicalBlock(DIScope *Scope, DIFile *File,
772                                        unsigned Line, unsigned Col);
773 
774     /// Create a descriptor for an imported module.
775     /// \param Context The scope this module is imported into
776     /// \param NS      The namespace being imported here.
777     /// \param File    File where the declaration is located.
778     /// \param Line    Line number of the declaration.
779     DIImportedEntity *createImportedModule(DIScope *Context, DINamespace *NS,
780                                            DIFile *File, unsigned Line);
781 
782     /// Create a descriptor for an imported module.
783     /// \param Context The scope this module is imported into.
784     /// \param NS      An aliased namespace.
785     /// \param File    File where the declaration is located.
786     /// \param Line    Line number of the declaration.
787     DIImportedEntity *createImportedModule(DIScope *Context,
788                                            DIImportedEntity *NS, DIFile *File,
789                                            unsigned Line);
790 
791     /// Create a descriptor for an imported module.
792     /// \param Context The scope this module is imported into.
793     /// \param M       The module being imported here
794     /// \param File    File where the declaration is located.
795     /// \param Line    Line number of the declaration.
796     DIImportedEntity *createImportedModule(DIScope *Context, DIModule *M,
797                                            DIFile *File, unsigned Line);
798 
799     /// Create a descriptor for an imported function.
800     /// \param Context The scope this module is imported into.
801     /// \param Decl    The declaration (or definition) of a function, type, or
802     ///                variable.
803     /// \param File    File where the declaration is located.
804     /// \param Line    Line number of the declaration.
805     DIImportedEntity *createImportedDeclaration(DIScope *Context, DINode *Decl,
806                                                 DIFile *File, unsigned Line,
807                                                 StringRef Name = "");
808 
809     /// Insert a new llvm.dbg.declare intrinsic call.
810     /// \param Storage     llvm::Value of the variable
811     /// \param VarInfo     Variable's debug info descriptor.
812     /// \param Expr        A complex location expression.
813     /// \param DL          Debug info location.
814     /// \param InsertAtEnd Location for the new intrinsic.
815     Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
816                                DIExpression *Expr, const DILocation *DL,
817                                BasicBlock *InsertAtEnd);
818 
819     /// Insert a new llvm.dbg.declare intrinsic call.
820     /// \param Storage      llvm::Value of the variable
821     /// \param VarInfo      Variable's debug info descriptor.
822     /// \param Expr         A complex location expression.
823     /// \param DL           Debug info location.
824     /// \param InsertBefore Location for the new intrinsic.
825     Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
826                                DIExpression *Expr, const DILocation *DL,
827                                Instruction *InsertBefore);
828 
829     /// Insert a new llvm.dbg.label intrinsic call.
830     /// \param LabelInfo    Label's debug info descriptor.
831     /// \param DL           Debug info location.
832     /// \param InsertBefore Location for the new intrinsic.
833     Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
834                              Instruction *InsertBefore);
835 
836     /// Insert a new llvm.dbg.label intrinsic call.
837     /// \param LabelInfo    Label's debug info descriptor.
838     /// \param DL           Debug info location.
839     /// \param InsertAtEnd Location for the new intrinsic.
840     Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
841                              BasicBlock *InsertAtEnd);
842 
843     /// Insert a new llvm.dbg.value intrinsic call.
844     /// \param Val          llvm::Value of the variable
845     /// \param VarInfo      Variable's debug info descriptor.
846     /// \param Expr         A complex location expression.
847     /// \param DL           Debug info location.
848     /// \param InsertAtEnd Location for the new intrinsic.
849     Instruction *insertDbgValueIntrinsic(llvm::Value *Val,
850                                          DILocalVariable *VarInfo,
851                                          DIExpression *Expr,
852                                          const DILocation *DL,
853                                          BasicBlock *InsertAtEnd);
854 
855     /// Insert a new llvm.dbg.value intrinsic call.
856     /// \param Val          llvm::Value of the variable
857     /// \param VarInfo      Variable's debug info descriptor.
858     /// \param Expr         A complex location expression.
859     /// \param DL           Debug info location.
860     /// \param InsertBefore Location for the new intrinsic.
861     Instruction *insertDbgValueIntrinsic(llvm::Value *Val,
862                                          DILocalVariable *VarInfo,
863                                          DIExpression *Expr,
864                                          const DILocation *DL,
865                                          Instruction *InsertBefore);
866 
867     /// Replace the vtable holder in the given type.
868     ///
869     /// If this creates a self reference, it may orphan some unresolved cycles
870     /// in the operands of \c T, so \a DIBuilder needs to track that.
871     void replaceVTableHolder(DICompositeType *&T,
872                              DIType *VTableHolder);
873 
874     /// Replace arrays on a composite type.
875     ///
876     /// If \c T is resolved, but the arrays aren't -- which can happen if \c T
877     /// has a self-reference -- \a DIBuilder needs to track the array to
878     /// resolve cycles.
879     void replaceArrays(DICompositeType *&T, DINodeArray Elements,
880                        DINodeArray TParams = DINodeArray());
881 
882     /// Replace a temporary node.
883     ///
884     /// Call \a MDNode::replaceAllUsesWith() on \c N, replacing it with \c
885     /// Replacement.
886     ///
887     /// If \c Replacement is the same as \c N.get(), instead call \a
888     /// MDNode::replaceWithUniqued().  In this case, the uniqued node could
889     /// have a different address, so we return the final address.
890     template <class NodeTy>
891     NodeTy *replaceTemporary(TempMDNode &&N, NodeTy *Replacement) {
892       if (N.get() == Replacement)
893         return cast<NodeTy>(MDNode::replaceWithUniqued(std::move(N)));
894 
895       N->replaceAllUsesWith(Replacement);
896       return Replacement;
897     }
898   };
899 
900   // Create wrappers for C Binding types (see CBindingWrapping.h).
901   DEFINE_ISA_CONVERSION_FUNCTIONS(DIBuilder, LLVMDIBuilderRef)
902 
903 } // end namespace llvm
904 
905 #endif // LLVM_IR_DIBUILDER_H
906