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, APSInt Value);
185     DIEnumerator *createEnumerator(StringRef Name, uint64_t Val,
186                                    bool IsUnsigned = false);
187 
188     /// Create a DWARF unspecified type.
189     DIBasicType *createUnspecifiedType(StringRef Name);
190 
191     /// Create C++11 nullptr type.
192     DIBasicType *createNullPtrType();
193 
194     /// Create debugging information entry for a basic
195     /// type.
196     /// \param Name        Type name.
197     /// \param SizeInBits  Size of the type.
198     /// \param Encoding    DWARF encoding code, e.g., dwarf::DW_ATE_float.
199     /// \param Flags       Optional DWARF attributes, e.g., DW_AT_endianity.
200     DIBasicType *createBasicType(StringRef Name, uint64_t SizeInBits,
201                                  unsigned Encoding,
202                                  DINode::DIFlags Flags = DINode::FlagZero);
203 
204     /// Create debugging information entry for a string
205     /// type.
206     /// \param Name        Type name.
207     /// \param SizeInBits  Size of the type.
208     DIStringType *createStringType(StringRef Name, uint64_t SizeInBits);
209 
210     /// Create debugging information entry for a qualified
211     /// type, e.g. 'const int'.
212     /// \param Tag         Tag identifing type, e.g. dwarf::TAG_volatile_type
213     /// \param FromTy      Base Type.
214     DIDerivedType *createQualifiedType(unsigned Tag, DIType *FromTy);
215 
216     /// Create debugging information entry for a pointer.
217     /// \param PointeeTy         Type pointed by this pointer.
218     /// \param SizeInBits        Size.
219     /// \param AlignInBits       Alignment. (optional)
220     /// \param DWARFAddressSpace DWARF address space. (optional)
221     /// \param Name              Pointer type name. (optional)
222     DIDerivedType *createPointerType(DIType *PointeeTy, uint64_t SizeInBits,
223                                      uint32_t AlignInBits = 0,
224                                      Optional<unsigned> DWARFAddressSpace =
225                                          None,
226                                      StringRef Name = "");
227 
228     /// Create debugging information entry for a pointer to member.
229     /// \param PointeeTy Type pointed to by this pointer.
230     /// \param SizeInBits  Size.
231     /// \param AlignInBits Alignment. (optional)
232     /// \param Class Type for which this pointer points to members of.
233     DIDerivedType *
234     createMemberPointerType(DIType *PointeeTy, DIType *Class,
235                             uint64_t SizeInBits, uint32_t AlignInBits = 0,
236                             DINode::DIFlags Flags = DINode::FlagZero);
237 
238     /// Create debugging information entry for a c++
239     /// style reference or rvalue reference type.
240     DIDerivedType *createReferenceType(unsigned Tag, DIType *RTy,
241                                        uint64_t SizeInBits = 0,
242                                        uint32_t AlignInBits = 0,
243                                        Optional<unsigned> DWARFAddressSpace =
244                                            None);
245 
246     /// Create debugging information entry for a typedef.
247     /// \param Ty          Original type.
248     /// \param Name        Typedef name.
249     /// \param File        File where this type is defined.
250     /// \param LineNo      Line number.
251     /// \param Context     The surrounding context for the typedef.
252     /// \param AlignInBits Alignment. (optional)
253     DIDerivedType *createTypedef(DIType *Ty, StringRef Name, DIFile *File,
254                                  unsigned LineNo, DIScope *Context,
255                                  uint32_t AlignInBits = 0);
256 
257     /// Create debugging information entry for a 'friend'.
258     DIDerivedType *createFriend(DIType *Ty, DIType *FriendTy);
259 
260     /// Create debugging information entry to establish
261     /// inheritance relationship between two types.
262     /// \param Ty           Original type.
263     /// \param BaseTy       Base type. Ty is inherits from base.
264     /// \param BaseOffset   Base offset.
265     /// \param VBPtrOffset  Virtual base pointer offset.
266     /// \param Flags        Flags to describe inheritance attribute,
267     ///                     e.g. private
268     DIDerivedType *createInheritance(DIType *Ty, DIType *BaseTy,
269                                      uint64_t BaseOffset, uint32_t VBPtrOffset,
270                                      DINode::DIFlags Flags);
271 
272     /// Create debugging information entry for a member.
273     /// \param Scope        Member scope.
274     /// \param Name         Member name.
275     /// \param File         File where this member is defined.
276     /// \param LineNo       Line number.
277     /// \param SizeInBits   Member size.
278     /// \param AlignInBits  Member alignment.
279     /// \param OffsetInBits Member offset.
280     /// \param Flags        Flags to encode member attribute, e.g. private
281     /// \param Ty           Parent type.
282     DIDerivedType *createMemberType(DIScope *Scope, StringRef Name,
283                                     DIFile *File, unsigned LineNo,
284                                     uint64_t SizeInBits,
285                                     uint32_t AlignInBits,
286                                     uint64_t OffsetInBits,
287                                     DINode::DIFlags Flags, DIType *Ty);
288 
289     /// Create debugging information entry for a variant.  A variant
290     /// normally should be a member of a variant part.
291     /// \param Scope        Member scope.
292     /// \param Name         Member name.
293     /// \param File         File where this member is defined.
294     /// \param LineNo       Line number.
295     /// \param SizeInBits   Member size.
296     /// \param AlignInBits  Member alignment.
297     /// \param OffsetInBits Member offset.
298     /// \param Flags        Flags to encode member attribute, e.g. private
299     /// \param Discriminant The discriminant for this branch; null for
300     ///                     the default branch
301     /// \param Ty           Parent type.
302     DIDerivedType *createVariantMemberType(DIScope *Scope, StringRef Name,
303 					   DIFile *File, unsigned LineNo,
304 					   uint64_t SizeInBits,
305 					   uint32_t AlignInBits,
306 					   uint64_t OffsetInBits,
307 					   Constant *Discriminant,
308 					   DINode::DIFlags Flags, DIType *Ty);
309 
310     /// Create debugging information entry for a bit field member.
311     /// \param Scope               Member scope.
312     /// \param Name                Member name.
313     /// \param File                File where this member is defined.
314     /// \param LineNo              Line number.
315     /// \param SizeInBits          Member size.
316     /// \param OffsetInBits        Member offset.
317     /// \param StorageOffsetInBits Member storage offset.
318     /// \param Flags               Flags to encode member attribute.
319     /// \param Ty                  Parent type.
320     DIDerivedType *createBitFieldMemberType(
321         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
322         uint64_t SizeInBits, uint64_t OffsetInBits,
323         uint64_t StorageOffsetInBits, DINode::DIFlags Flags, DIType *Ty);
324 
325     /// Create debugging information entry for a
326     /// C++ static data member.
327     /// \param Scope      Member scope.
328     /// \param Name       Member name.
329     /// \param File       File where this member is declared.
330     /// \param LineNo     Line number.
331     /// \param Ty         Type of the static member.
332     /// \param Flags      Flags to encode member attribute, e.g. private.
333     /// \param Val        Const initializer of the member.
334     /// \param AlignInBits  Member alignment.
335     DIDerivedType *createStaticMemberType(DIScope *Scope, StringRef Name,
336                                           DIFile *File, unsigned LineNo,
337                                           DIType *Ty, DINode::DIFlags Flags,
338                                           Constant *Val,
339                                           uint32_t AlignInBits = 0);
340 
341     /// Create debugging information entry for Objective-C
342     /// instance variable.
343     /// \param Name         Member name.
344     /// \param File         File where this member is defined.
345     /// \param LineNo       Line number.
346     /// \param SizeInBits   Member size.
347     /// \param AlignInBits  Member alignment.
348     /// \param OffsetInBits Member offset.
349     /// \param Flags        Flags to encode member attribute, e.g. private
350     /// \param Ty           Parent type.
351     /// \param PropertyNode Property associated with this ivar.
352     DIDerivedType *createObjCIVar(StringRef Name, DIFile *File, unsigned LineNo,
353                                   uint64_t SizeInBits, uint32_t AlignInBits,
354                                   uint64_t OffsetInBits, DINode::DIFlags Flags,
355                                   DIType *Ty, MDNode *PropertyNode);
356 
357     /// Create debugging information entry for Objective-C
358     /// property.
359     /// \param Name         Property name.
360     /// \param File         File where this property is defined.
361     /// \param LineNumber   Line number.
362     /// \param GetterName   Name of the Objective C property getter selector.
363     /// \param SetterName   Name of the Objective C property setter selector.
364     /// \param PropertyAttributes Objective C property attributes.
365     /// \param Ty           Type.
366     DIObjCProperty *createObjCProperty(StringRef Name, DIFile *File,
367                                        unsigned LineNumber,
368                                        StringRef GetterName,
369                                        StringRef SetterName,
370                                        unsigned PropertyAttributes, DIType *Ty);
371 
372     /// Create debugging information entry for a class.
373     /// \param Scope        Scope in which this class is defined.
374     /// \param Name         class name.
375     /// \param File         File where this member is defined.
376     /// \param LineNumber   Line number.
377     /// \param SizeInBits   Member size.
378     /// \param AlignInBits  Member alignment.
379     /// \param OffsetInBits Member offset.
380     /// \param Flags        Flags to encode member attribute, e.g. private
381     /// \param Elements     class members.
382     /// \param VTableHolder Debug info of the base class that contains vtable
383     ///                     for this type. This is used in
384     ///                     DW_AT_containing_type. See DWARF documentation
385     ///                     for more info.
386     /// \param TemplateParms Template type parameters.
387     /// \param UniqueIdentifier A unique identifier for the class.
388     DICompositeType *createClassType(
389         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
390         uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
391         DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
392         DIType *VTableHolder = nullptr, MDNode *TemplateParms = nullptr,
393         StringRef UniqueIdentifier = "");
394 
395     /// Create debugging information entry for a struct.
396     /// \param Scope        Scope in which this struct is defined.
397     /// \param Name         Struct name.
398     /// \param File         File where this member is defined.
399     /// \param LineNumber   Line number.
400     /// \param SizeInBits   Member size.
401     /// \param AlignInBits  Member alignment.
402     /// \param Flags        Flags to encode member attribute, e.g. private
403     /// \param Elements     Struct elements.
404     /// \param RunTimeLang  Optional parameter, Objective-C runtime version.
405     /// \param UniqueIdentifier A unique identifier for the struct.
406     DICompositeType *createStructType(
407         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
408         uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
409         DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang = 0,
410         DIType *VTableHolder = nullptr, StringRef UniqueIdentifier = "");
411 
412     /// Create debugging information entry for an union.
413     /// \param Scope        Scope in which this union is defined.
414     /// \param Name         Union name.
415     /// \param File         File where this member is defined.
416     /// \param LineNumber   Line number.
417     /// \param SizeInBits   Member size.
418     /// \param AlignInBits  Member alignment.
419     /// \param Flags        Flags to encode member attribute, e.g. private
420     /// \param Elements     Union elements.
421     /// \param RunTimeLang  Optional parameter, Objective-C runtime version.
422     /// \param UniqueIdentifier A unique identifier for the union.
423     DICompositeType *createUnionType(DIScope *Scope, StringRef Name,
424                                      DIFile *File, unsigned LineNumber,
425                                      uint64_t SizeInBits, uint32_t AlignInBits,
426                                      DINode::DIFlags Flags,
427                                      DINodeArray Elements,
428                                      unsigned RunTimeLang = 0,
429                                      StringRef UniqueIdentifier = "");
430 
431     /// Create debugging information entry for a variant part.  A
432     /// variant part normally has a discriminator (though this is not
433     /// required) and a number of variant children.
434     /// \param Scope        Scope in which this union is defined.
435     /// \param Name         Union name.
436     /// \param File         File where this member is defined.
437     /// \param LineNumber   Line number.
438     /// \param SizeInBits   Member size.
439     /// \param AlignInBits  Member alignment.
440     /// \param Flags        Flags to encode member attribute, e.g. private
441     /// \param Discriminator Discriminant member
442     /// \param Elements     Variant elements.
443     /// \param UniqueIdentifier A unique identifier for the union.
444     DICompositeType *createVariantPart(DIScope *Scope, StringRef Name,
445 				       DIFile *File, unsigned LineNumber,
446 				       uint64_t SizeInBits, uint32_t AlignInBits,
447 				       DINode::DIFlags Flags,
448 				       DIDerivedType *Discriminator,
449 				       DINodeArray Elements,
450 				       StringRef UniqueIdentifier = "");
451 
452     /// Create debugging information for template
453     /// type parameter.
454     /// \param Scope        Scope in which this type is defined.
455     /// \param Name         Type parameter name.
456     /// \param Ty           Parameter type.
457     /// \param IsDefault    Parameter is default or not
458     DITemplateTypeParameter *createTemplateTypeParameter(DIScope *Scope,
459                                                          StringRef Name,
460                                                          DIType *Ty,
461                                                          bool IsDefault);
462 
463     /// Create debugging information for template
464     /// value parameter.
465     /// \param Scope        Scope in which this type is defined.
466     /// \param Name         Value parameter name.
467     /// \param Ty           Parameter type.
468     /// \param IsDefault    Parameter is default or not
469     /// \param Val          Constant parameter value.
470     DITemplateValueParameter *
471     createTemplateValueParameter(DIScope *Scope, StringRef Name, DIType *Ty,
472                                  bool IsDefault, Constant *Val);
473 
474     /// Create debugging information for a template template parameter.
475     /// \param Scope        Scope in which this type is defined.
476     /// \param Name         Value parameter name.
477     /// \param Ty           Parameter type.
478     /// \param Val          The fully qualified name of the template.
479     DITemplateValueParameter *createTemplateTemplateParameter(DIScope *Scope,
480                                                               StringRef Name,
481                                                               DIType *Ty,
482                                                               StringRef Val);
483 
484     /// Create debugging information for a template parameter pack.
485     /// \param Scope        Scope in which this type is defined.
486     /// \param Name         Value parameter name.
487     /// \param Ty           Parameter type.
488     /// \param Val          An array of types in the pack.
489     DITemplateValueParameter *createTemplateParameterPack(DIScope *Scope,
490                                                           StringRef Name,
491                                                           DIType *Ty,
492                                                           DINodeArray Val);
493 
494     /// Create debugging information entry for an array.
495     /// \param Size         Array size.
496     /// \param AlignInBits  Alignment.
497     /// \param Ty           Element type.
498     /// \param Subscripts   Subscripts.
499     /// \param DataLocation The location of the raw data of a descriptor-based
500     ///                     Fortran array, either a DIExpression* or
501     ///                     a DIVariable*.
502     /// \param Associated   The associated attribute of a descriptor-based
503     ///                     Fortran array, either a DIExpression* or
504     ///                     a DIVariable*.
505     /// \param Allocated    The allocated attribute of a descriptor-based
506     ///                     Fortran array, either a DIExpression* or
507     ///                     a DIVariable*.
508     /// \param Rank         The rank attribute of a descriptor-based
509     ///                     Fortran array, either a DIExpression* or
510     ///                     a DIVariable*.
511     DICompositeType *createArrayType(
512         uint64_t Size, uint32_t AlignInBits, DIType *Ty, DINodeArray Subscripts,
513         PointerUnion<DIExpression *, DIVariable *> DataLocation = nullptr,
514         PointerUnion<DIExpression *, DIVariable *> Associated = nullptr,
515         PointerUnion<DIExpression *, DIVariable *> Allocated = nullptr,
516         PointerUnion<DIExpression *, DIVariable *> Rank = nullptr);
517 
518     /// Create debugging information entry for a vector type.
519     /// \param Size         Array size.
520     /// \param AlignInBits  Alignment.
521     /// \param Ty           Element type.
522     /// \param Subscripts   Subscripts.
523     DICompositeType *createVectorType(uint64_t Size, uint32_t AlignInBits,
524                                       DIType *Ty, DINodeArray Subscripts);
525 
526     /// Create debugging information entry for an
527     /// enumeration.
528     /// \param Scope          Scope in which this enumeration is defined.
529     /// \param Name           Union name.
530     /// \param File           File where this member is defined.
531     /// \param LineNumber     Line number.
532     /// \param SizeInBits     Member size.
533     /// \param AlignInBits    Member alignment.
534     /// \param Elements       Enumeration elements.
535     /// \param UnderlyingType Underlying type of a C++11/ObjC fixed enum.
536     /// \param UniqueIdentifier A unique identifier for the enum.
537     /// \param IsScoped Boolean flag indicate if this is C++11/ObjC 'enum class'.
538     DICompositeType *createEnumerationType(
539         DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
540         uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
541         DIType *UnderlyingType, StringRef UniqueIdentifier = "", bool IsScoped = false);
542 
543     /// Create debugging information entry for a set.
544     /// \param Scope          Scope in which this set is defined.
545     /// \param Name           Set name.
546     /// \param File           File where this set is defined.
547     /// \param LineNo         Line number.
548     /// \param SizeInBits     Set size.
549     /// \param AlignInBits    Set alignment.
550     /// \param Ty             Base type of the set.
551     DIDerivedType *createSetType(DIScope *Scope, StringRef Name, DIFile *File,
552                                  unsigned LineNo, uint64_t SizeInBits,
553                                  uint32_t AlignInBits, DIType *Ty);
554 
555     /// Create subroutine type.
556     /// \param ParameterTypes  An array of subroutine parameter types. This
557     ///                        includes return type at 0th index.
558     /// \param Flags           E.g.: LValueReference.
559     ///                        These flags are used to emit dwarf attributes.
560     /// \param CC              Calling convention, e.g. dwarf::DW_CC_normal
561     DISubroutineType *
562     createSubroutineType(DITypeRefArray ParameterTypes,
563                          DINode::DIFlags Flags = DINode::FlagZero,
564                          unsigned CC = 0);
565 
566     /// Create a distinct clone of \p SP with FlagArtificial set.
567     static DISubprogram *createArtificialSubprogram(DISubprogram *SP);
568 
569     /// Create a uniqued clone of \p Ty with FlagArtificial set.
570     static DIType *createArtificialType(DIType *Ty);
571 
572     /// Create a uniqued clone of \p Ty with FlagObjectPointer and
573     /// FlagArtificial set.
574     static DIType *createObjectPointerType(DIType *Ty);
575 
576     /// Create a permanent forward-declared type.
577     DICompositeType *createForwardDecl(unsigned Tag, StringRef Name,
578                                        DIScope *Scope, DIFile *F, unsigned Line,
579                                        unsigned RuntimeLang = 0,
580                                        uint64_t SizeInBits = 0,
581                                        uint32_t AlignInBits = 0,
582                                        StringRef UniqueIdentifier = "");
583 
584     /// Create a temporary forward-declared type.
585     DICompositeType *createReplaceableCompositeType(
586         unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
587         unsigned RuntimeLang = 0, uint64_t SizeInBits = 0,
588         uint32_t AlignInBits = 0, DINode::DIFlags Flags = DINode::FlagFwdDecl,
589         StringRef UniqueIdentifier = "");
590 
591     /// Retain DIScope* in a module even if it is not referenced
592     /// through debug info anchors.
593     void retainType(DIScope *T);
594 
595     /// Create unspecified parameter type
596     /// for a subroutine type.
597     DIBasicType *createUnspecifiedParameter();
598 
599     /// Get a DINodeArray, create one if required.
600     DINodeArray getOrCreateArray(ArrayRef<Metadata *> Elements);
601 
602     /// Get a DIMacroNodeArray, create one if required.
603     DIMacroNodeArray getOrCreateMacroArray(ArrayRef<Metadata *> Elements);
604 
605     /// Get a DITypeRefArray, create one if required.
606     DITypeRefArray getOrCreateTypeArray(ArrayRef<Metadata *> Elements);
607 
608     /// Create a descriptor for a value range.  This
609     /// implicitly uniques the values returned.
610     DISubrange *getOrCreateSubrange(int64_t Lo, int64_t Count);
611     DISubrange *getOrCreateSubrange(int64_t Lo, Metadata *CountNode);
612     DISubrange *getOrCreateSubrange(Metadata *Count, Metadata *LowerBound,
613                                     Metadata *UpperBound, Metadata *Stride);
614 
615     DIGenericSubrange *
616     getOrCreateGenericSubrange(DIGenericSubrange::BoundType Count,
617                                DIGenericSubrange::BoundType LowerBound,
618                                DIGenericSubrange::BoundType UpperBound,
619                                DIGenericSubrange::BoundType Stride);
620 
621     /// Create a new descriptor for the specified variable.
622     /// \param Context     Variable scope.
623     /// \param Name        Name of the variable.
624     /// \param LinkageName Mangled  name of the variable.
625     /// \param File        File where this variable is defined.
626     /// \param LineNo      Line number.
627     /// \param Ty          Variable Type.
628     /// \param IsLocalToUnit Boolean flag indicate whether this variable is
629     ///                      externally visible or not.
630     /// \param Expr        The location of the global relative to the attached
631     ///                    GlobalVariable.
632     /// \param Decl        Reference to the corresponding declaration.
633     /// \param AlignInBits Variable alignment(or 0 if no alignment attr was
634     ///                    specified)
635     DIGlobalVariableExpression *createGlobalVariableExpression(
636         DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
637         unsigned LineNo, DIType *Ty, bool IsLocalToUnit, bool isDefined = true,
638         DIExpression *Expr = nullptr, MDNode *Decl = nullptr,
639         MDTuple *TemplateParams = nullptr, uint32_t AlignInBits = 0);
640 
641     /// Identical to createGlobalVariable
642     /// except that the resulting DbgNode is temporary and meant to be RAUWed.
643     DIGlobalVariable *createTempGlobalVariableFwdDecl(
644         DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
645         unsigned LineNo, DIType *Ty, bool IsLocalToUnit, MDNode *Decl = nullptr,
646         MDTuple *TemplateParams= nullptr, uint32_t AlignInBits = 0);
647 
648     /// Create a new descriptor for an auto variable.  This is a local variable
649     /// that is not a subprogram parameter.
650     ///
651     /// \c Scope must be a \a DILocalScope, and thus its scope chain eventually
652     /// leads to a \a DISubprogram.
653     ///
654     /// If \c AlwaysPreserve, this variable will be referenced from its
655     /// containing subprogram, and will survive some optimizations.
656     DILocalVariable *
657     createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File,
658                        unsigned LineNo, DIType *Ty, bool AlwaysPreserve = false,
659                        DINode::DIFlags Flags = DINode::FlagZero,
660                        uint32_t AlignInBits = 0);
661 
662     /// Create a new descriptor for an label.
663     ///
664     /// \c Scope must be a \a DILocalScope, and thus its scope chain eventually
665     /// leads to a \a DISubprogram.
666     DILabel *
667     createLabel(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
668                 bool AlwaysPreserve = false);
669 
670     /// Create a new descriptor for a parameter variable.
671     ///
672     /// \c Scope must be a \a DILocalScope, and thus its scope chain eventually
673     /// leads to a \a DISubprogram.
674     ///
675     /// \c ArgNo is the index (starting from \c 1) of this variable in the
676     /// subprogram parameters.  \c ArgNo should not conflict with other
677     /// parameters of the same subprogram.
678     ///
679     /// If \c AlwaysPreserve, this variable will be referenced from its
680     /// containing subprogram, and will survive some optimizations.
681     DILocalVariable *
682     createParameterVariable(DIScope *Scope, StringRef Name, unsigned ArgNo,
683                             DIFile *File, unsigned LineNo, DIType *Ty,
684                             bool AlwaysPreserve = false,
685                             DINode::DIFlags Flags = DINode::FlagZero);
686 
687     /// Create a new descriptor for the specified
688     /// variable which has a complex address expression for its address.
689     /// \param Addr        An array of complex address operations.
690     DIExpression *createExpression(ArrayRef<uint64_t> Addr = None);
691     DIExpression *createExpression(ArrayRef<int64_t> Addr);
692 
693     /// Create an expression for a variable that does not have an address, but
694     /// does have a constant value.
createConstantValueExpression(uint64_t Val)695     DIExpression *createConstantValueExpression(uint64_t Val) {
696       return DIExpression::get(
697           VMContext, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_stack_value});
698     }
699 
700     /// Create a new descriptor for the specified subprogram.
701     /// See comments in DISubprogram* for descriptions of these fields.
702     /// \param Scope         Function scope.
703     /// \param Name          Function name.
704     /// \param LinkageName   Mangled function name.
705     /// \param File          File where this variable is defined.
706     /// \param LineNo        Line number.
707     /// \param Ty            Function type.
708     /// \param ScopeLine     Set to the beginning of the scope this starts
709     /// \param Flags         e.g. is this function prototyped or not.
710     ///                      These flags are used to emit dwarf attributes.
711     /// \param SPFlags       Additional flags specific to subprograms.
712     /// \param TParams       Function template parameters.
713     /// \param ThrownTypes   Exception types this function may throw.
714     DISubprogram *
715     createFunction(DIScope *Scope, StringRef Name, StringRef LinkageName,
716                    DIFile *File, unsigned LineNo, DISubroutineType *Ty,
717                    unsigned ScopeLine, DINode::DIFlags Flags = DINode::FlagZero,
718                    DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagZero,
719                    DITemplateParameterArray TParams = nullptr,
720                    DISubprogram *Decl = nullptr,
721                    DITypeArray ThrownTypes = nullptr);
722 
723     /// Identical to createFunction,
724     /// except that the resulting DbgNode is meant to be RAUWed.
725     DISubprogram *createTempFunctionFwdDecl(
726         DIScope *Scope, StringRef Name, StringRef LinkageName, DIFile *File,
727         unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
728         DINode::DIFlags Flags = DINode::FlagZero,
729         DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagZero,
730         DITemplateParameterArray TParams = nullptr,
731         DISubprogram *Decl = nullptr, DITypeArray ThrownTypes = nullptr);
732 
733     /// Create a new descriptor for the specified C++ method.
734     /// See comments in \a DISubprogram* for descriptions of these fields.
735     /// \param Scope         Function scope.
736     /// \param Name          Function name.
737     /// \param LinkageName   Mangled function name.
738     /// \param File          File where this variable is defined.
739     /// \param LineNo        Line number.
740     /// \param Ty            Function type.
741     /// \param VTableIndex   Index no of this method in virtual table, or -1u if
742     ///                      unrepresentable.
743     /// \param ThisAdjustment
744     ///                      MS ABI-specific adjustment of 'this' that occurs
745     ///                      in the prologue.
746     /// \param VTableHolder  Type that holds vtable.
747     /// \param Flags         e.g. is this function prototyped or not.
748     ///                      This flags are used to emit dwarf attributes.
749     /// \param SPFlags       Additional flags specific to subprograms.
750     /// \param TParams       Function template parameters.
751     /// \param ThrownTypes   Exception types this function may throw.
752     DISubprogram *
753     createMethod(DIScope *Scope, StringRef Name, StringRef LinkageName,
754                  DIFile *File, unsigned LineNo, DISubroutineType *Ty,
755                  unsigned VTableIndex = 0, int ThisAdjustment = 0,
756                  DIType *VTableHolder = nullptr,
757                  DINode::DIFlags Flags = DINode::FlagZero,
758                  DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagZero,
759                  DITemplateParameterArray TParams = nullptr,
760                  DITypeArray ThrownTypes = nullptr);
761 
762     /// Create common block entry for a Fortran common block.
763     /// \param Scope       Scope of this common block.
764     /// \param decl        Global variable declaration.
765     /// \param Name        The name of this common block.
766     /// \param File        The file this common block is defined.
767     /// \param LineNo      Line number.
768     DICommonBlock *createCommonBlock(DIScope *Scope, DIGlobalVariable *decl,
769                                      StringRef Name, DIFile *File,
770                                      unsigned LineNo);
771 
772     /// This creates new descriptor for a namespace with the specified
773     /// parent scope.
774     /// \param Scope       Namespace scope
775     /// \param Name        Name of this namespace
776     /// \param ExportSymbols True for C++ inline namespaces.
777     DINamespace *createNameSpace(DIScope *Scope, StringRef Name,
778                                  bool ExportSymbols);
779 
780     /// This creates new descriptor for a module with the specified
781     /// parent scope.
782     /// \param Scope       Parent scope
783     /// \param Name        Name of this module
784     /// \param ConfigurationMacros
785     ///                    A space-separated shell-quoted list of -D macro
786     ///                    definitions as they would appear on a command line.
787     /// \param IncludePath The path to the module map file.
788     /// \param APINotesFile The path to an API notes file for this module.
789     /// \param File        Source file of the module.
790     ///                    Used for Fortran modules.
791     /// \param LineNo      Source line number of the module.
792     ///                    Used for Fortran modules.
793     /// \param IsDecl      This is a module declaration; default to false;
794     ///                    when set to true, only Scope and Name are required
795     ///                    as this entry is just a hint for the debugger to find
796     ///                    the corresponding definition in the global scope.
797     DIModule *createModule(DIScope *Scope, StringRef Name,
798                            StringRef ConfigurationMacros, StringRef IncludePath,
799                            StringRef APINotesFile = {}, DIFile *File = nullptr,
800                            unsigned LineNo = 0, bool IsDecl = false);
801 
802     /// This creates a descriptor for a lexical block with a new file
803     /// attached. This merely extends the existing
804     /// lexical block as it crosses a file.
805     /// \param Scope       Lexical block.
806     /// \param File        Source file.
807     /// \param Discriminator DWARF path discriminator value.
808     DILexicalBlockFile *createLexicalBlockFile(DIScope *Scope, DIFile *File,
809                                                unsigned Discriminator = 0);
810 
811     /// This creates a descriptor for a lexical block with the
812     /// specified parent context.
813     /// \param Scope         Parent lexical scope.
814     /// \param File          Source file.
815     /// \param Line          Line number.
816     /// \param Col           Column number.
817     DILexicalBlock *createLexicalBlock(DIScope *Scope, DIFile *File,
818                                        unsigned Line, unsigned Col);
819 
820     /// Create a descriptor for an imported module.
821     /// \param Context The scope this module is imported into
822     /// \param NS      The namespace being imported here.
823     /// \param File    File where the declaration is located.
824     /// \param Line    Line number of the declaration.
825     DIImportedEntity *createImportedModule(DIScope *Context, DINamespace *NS,
826                                            DIFile *File, unsigned Line);
827 
828     /// Create a descriptor for an imported module.
829     /// \param Context The scope this module is imported into.
830     /// \param NS      An aliased namespace.
831     /// \param File    File where the declaration is located.
832     /// \param Line    Line number of the declaration.
833     DIImportedEntity *createImportedModule(DIScope *Context,
834                                            DIImportedEntity *NS, DIFile *File,
835                                            unsigned Line);
836 
837     /// Create a descriptor for an imported module.
838     /// \param Context The scope this module is imported into.
839     /// \param M       The module being imported here
840     /// \param File    File where the declaration is located.
841     /// \param Line    Line number of the declaration.
842     DIImportedEntity *createImportedModule(DIScope *Context, DIModule *M,
843                                            DIFile *File, unsigned Line);
844 
845     /// Create a descriptor for an imported function.
846     /// \param Context The scope this module is imported into.
847     /// \param Decl    The declaration (or definition) of a function, type, or
848     ///                variable.
849     /// \param File    File where the declaration is located.
850     /// \param Line    Line number of the declaration.
851     DIImportedEntity *createImportedDeclaration(DIScope *Context, DINode *Decl,
852                                                 DIFile *File, unsigned Line,
853                                                 StringRef Name = "");
854 
855     /// Insert a new llvm.dbg.declare intrinsic call.
856     /// \param Storage     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 InsertAtEnd Location for the new intrinsic.
861     Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
862                                DIExpression *Expr, const DILocation *DL,
863                                BasicBlock *InsertAtEnd);
864 
865     /// Insert a new llvm.dbg.declare intrinsic call.
866     /// \param Storage      llvm::Value of the variable
867     /// \param VarInfo      Variable's debug info descriptor.
868     /// \param Expr         A complex location expression.
869     /// \param DL           Debug info location.
870     /// \param InsertBefore Location for the new intrinsic.
871     Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
872                                DIExpression *Expr, const DILocation *DL,
873                                Instruction *InsertBefore);
874 
875     /// Insert a new llvm.dbg.label intrinsic call.
876     /// \param LabelInfo    Label's debug info descriptor.
877     /// \param DL           Debug info location.
878     /// \param InsertBefore Location for the new intrinsic.
879     Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
880                              Instruction *InsertBefore);
881 
882     /// Insert a new llvm.dbg.label intrinsic call.
883     /// \param LabelInfo    Label's debug info descriptor.
884     /// \param DL           Debug info location.
885     /// \param InsertAtEnd Location for the new intrinsic.
886     Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
887                              BasicBlock *InsertAtEnd);
888 
889     /// Insert a new llvm.dbg.value intrinsic call.
890     /// \param Val          llvm::Value of the variable
891     /// \param VarInfo      Variable's debug info descriptor.
892     /// \param Expr         A complex location expression.
893     /// \param DL           Debug info location.
894     /// \param InsertAtEnd Location for the new intrinsic.
895     Instruction *insertDbgValueIntrinsic(llvm::Value *Val,
896                                          DILocalVariable *VarInfo,
897                                          DIExpression *Expr,
898                                          const DILocation *DL,
899                                          BasicBlock *InsertAtEnd);
900 
901     /// Insert a new llvm.dbg.value intrinsic call.
902     /// \param Val          llvm::Value of the variable
903     /// \param VarInfo      Variable's debug info descriptor.
904     /// \param Expr         A complex location expression.
905     /// \param DL           Debug info location.
906     /// \param InsertBefore Location for the new intrinsic.
907     Instruction *insertDbgValueIntrinsic(llvm::Value *Val,
908                                          DILocalVariable *VarInfo,
909                                          DIExpression *Expr,
910                                          const DILocation *DL,
911                                          Instruction *InsertBefore);
912 
913     /// Replace the vtable holder in the given type.
914     ///
915     /// If this creates a self reference, it may orphan some unresolved cycles
916     /// in the operands of \c T, so \a DIBuilder needs to track that.
917     void replaceVTableHolder(DICompositeType *&T,
918                              DIType *VTableHolder);
919 
920     /// Replace arrays on a composite type.
921     ///
922     /// If \c T is resolved, but the arrays aren't -- which can happen if \c T
923     /// has a self-reference -- \a DIBuilder needs to track the array to
924     /// resolve cycles.
925     void replaceArrays(DICompositeType *&T, DINodeArray Elements,
926                        DINodeArray TParams = DINodeArray());
927 
928     /// Replace a temporary node.
929     ///
930     /// Call \a MDNode::replaceAllUsesWith() on \c N, replacing it with \c
931     /// Replacement.
932     ///
933     /// If \c Replacement is the same as \c N.get(), instead call \a
934     /// MDNode::replaceWithUniqued().  In this case, the uniqued node could
935     /// have a different address, so we return the final address.
936     template <class NodeTy>
replaceTemporary(TempMDNode && N,NodeTy * Replacement)937     NodeTy *replaceTemporary(TempMDNode &&N, NodeTy *Replacement) {
938       if (N.get() == Replacement)
939         return cast<NodeTy>(MDNode::replaceWithUniqued(std::move(N)));
940 
941       N->replaceAllUsesWith(Replacement);
942       return Replacement;
943     }
944   };
945 
946   // Create wrappers for C Binding types (see CBindingWrapping.h).
947   DEFINE_ISA_CONVERSION_FUNCTIONS(DIBuilder, LLVMDIBuilderRef)
948 
949 } // end namespace llvm
950 
951 #endif // LLVM_IR_DIBUILDER_H
952