Coverage Report

Created: 2022-05-14 11:35

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGDebugInfo.h
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDebugInfo.h - DebugInfo for LLVM CodeGen -------------*- 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 is the source-level debug info generator for llvm translation.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#ifndef LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
14
#define LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
15
16
#include "CGBuilder.h"
17
#include "clang/AST/DeclCXX.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/ExternalASTSource.h"
20
#include "clang/AST/PrettyPrinter.h"
21
#include "clang/AST/Type.h"
22
#include "clang/AST/TypeOrdering.h"
23
#include "clang/Basic/CodeGenOptions.h"
24
#include "clang/Basic/Module.h"
25
#include "clang/Basic/SourceLocation.h"
26
#include "llvm/ADT/DenseMap.h"
27
#include "llvm/ADT/DenseSet.h"
28
#include "llvm/ADT/Optional.h"
29
#include "llvm/IR/DIBuilder.h"
30
#include "llvm/IR/DebugInfo.h"
31
#include "llvm/IR/ValueHandle.h"
32
#include "llvm/Support/Allocator.h"
33
34
namespace llvm {
35
class MDNode;
36
}
37
38
namespace clang {
39
class ClassTemplateSpecializationDecl;
40
class GlobalDecl;
41
class ModuleMap;
42
class ObjCInterfaceDecl;
43
class UsingDecl;
44
class VarDecl;
45
enum class DynamicInitKind : unsigned;
46
47
namespace CodeGen {
48
class CodeGenModule;
49
class CodeGenFunction;
50
class CGBlockInfo;
51
52
/// This class gathers all debug information during compilation and is
53
/// responsible for emitting to llvm globals or pass directly to the
54
/// backend.
55
class CGDebugInfo {
56
  friend class ApplyDebugLocation;
57
  friend class SaveAndRestoreLocation;
58
  CodeGenModule &CGM;
59
  const codegenoptions::DebugInfoKind DebugKind;
60
  bool DebugTypeExtRefs;
61
  llvm::DIBuilder DBuilder;
62
  llvm::DICompileUnit *TheCU = nullptr;
63
  ModuleMap *ClangModuleMap = nullptr;
64
  ASTSourceDescriptor PCHDescriptor;
65
  SourceLocation CurLoc;
66
  llvm::MDNode *CurInlinedAt = nullptr;
67
  llvm::DIType *VTablePtrType = nullptr;
68
  llvm::DIType *ClassTy = nullptr;
69
  llvm::DICompositeType *ObjTy = nullptr;
70
  llvm::DIType *SelTy = nullptr;
71
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
72
  llvm::DIType *SingletonId = nullptr;
73
#include "clang/Basic/OpenCLImageTypes.def"
74
  llvm::DIType *OCLSamplerDITy = nullptr;
75
  llvm::DIType *OCLEventDITy = nullptr;
76
  llvm::DIType *OCLClkEventDITy = nullptr;
77
  llvm::DIType *OCLQueueDITy = nullptr;
78
  llvm::DIType *OCLNDRangeDITy = nullptr;
79
  llvm::DIType *OCLReserveIDDITy = nullptr;
80
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
81
  llvm::DIType *Id##Ty = nullptr;
82
#include "clang/Basic/OpenCLExtensionTypes.def"
83
84
  /// Cache of previously constructed Types.
85
  llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
86
87
  std::map<llvm::StringRef, llvm::StringRef, std::greater<llvm::StringRef>>
88
      DebugPrefixMap;
89
90
  /// Cache that maps VLA types to size expressions for that type,
91
  /// represented by instantiated Metadata nodes.
92
  llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;
93
94
  /// Callbacks to use when printing names and types.
95
  class PrintingCallbacks final : public clang::PrintingCallbacks {
96
    const CGDebugInfo &Self;
97
98
  public:
99
10.6k
    PrintingCallbacks(const CGDebugInfo &Self) : Self(Self) {}
100
2.82k
    std::string remapPath(StringRef Path) const override {
101
2.82k
      return Self.remapDIPath(Path);
102
2.82k
    }
103
  };
104
  PrintingCallbacks PrintCB = {*this};
105
106
  struct ObjCInterfaceCacheEntry {
107
    const ObjCInterfaceType *Type;
108
    llvm::DIType *Decl;
109
    llvm::DIFile *Unit;
110
    ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType *Decl,
111
                            llvm::DIFile *Unit)
112
3.22k
        : Type(Type), Decl(Decl), Unit(Unit) {}
113
  };
114
115
  /// Cache of previously constructed interfaces which may change.
116
  llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
117
118
  /// Cache of forward declarations for methods belonging to the interface.
119
  /// The extra bit on the DISubprogram specifies whether a method is
120
  /// "objc_direct".
121
  llvm::DenseMap<const ObjCInterfaceDecl *,
122
                 std::vector<llvm::PointerIntPair<llvm::DISubprogram *, 1>>>
123
      ObjCMethodCache;
124
125
  /// Cache of references to clang modules and precompiled headers.
126
  llvm::DenseMap<const Module *, llvm::TrackingMDRef> ModuleCache;
127
128
  /// List of interfaces we want to keep even if orphaned.
129
  std::vector<void *> RetainedTypes;
130
131
  /// Cache of forward declared types to RAUW at the end of compilation.
132
  std::vector<std::pair<const TagType *, llvm::TrackingMDRef>> ReplaceMap;
133
134
  /// Cache of replaceable forward declarations (functions and
135
  /// variables) to RAUW at the end of compilation.
136
  std::vector<std::pair<const DeclaratorDecl *, llvm::TrackingMDRef>>
137
      FwdDeclReplaceMap;
138
139
  /// Keep track of our current nested lexical block.
140
  std::vector<llvm::TypedTrackingMDRef<llvm::DIScope>> LexicalBlockStack;
141
  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> RegionMap;
142
  /// Keep track of LexicalBlockStack counter at the beginning of a
143
  /// function. This is used to pop unbalanced regions at the end of a
144
  /// function.
145
  std::vector<unsigned> FnBeginRegionCount;
146
147
  /// This is a storage for names that are constructed on demand. For
148
  /// example, C++ destructors, C++ operators etc..
149
  llvm::BumpPtrAllocator DebugInfoNames;
150
  StringRef CWDName;
151
152
  llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;
153
  llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;
154
  /// Cache declarations relevant to DW_TAG_imported_declarations (C++
155
  /// using declarations and global alias variables) that aren't covered
156
  /// by other more specific caches.
157
  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;
158
  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> ImportedDeclCache;
159
  llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache;
160
  llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>
161
      NamespaceAliasCache;
162
  llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>>
163
      StaticDataMemberCache;
164
165
  using ParamDecl2StmtTy = llvm::DenseMap<const ParmVarDecl *, const Stmt *>;
166
  using Param2DILocTy =
167
      llvm::DenseMap<const ParmVarDecl *, llvm::DILocalVariable *>;
168
169
  /// The key is coroutine real parameters, value is coroutine move parameters.
170
  ParamDecl2StmtTy CoroutineParameterMappings;
171
  /// The key is coroutine real parameters, value is DIVariable in LLVM IR.
172
  Param2DILocTy ParamDbgMappings;
173
174
  /// Helper functions for getOrCreateType.
175
  /// @{
176
  /// Currently the checksum of an interface includes the number of
177
  /// ivars and property accessors.
178
  llvm::DIType *CreateType(const BuiltinType *Ty);
179
  llvm::DIType *CreateType(const ComplexType *Ty);
180
  llvm::DIType *CreateType(const AutoType *Ty);
181
  llvm::DIType *CreateType(const BitIntType *Ty);
182
  llvm::DIType *CreateQualifiedType(QualType Ty, llvm::DIFile *Fg);
183
  llvm::DIType *CreateQualifiedType(const FunctionProtoType *Ty,
184
                                    llvm::DIFile *Fg);
185
  llvm::DIType *CreateType(const TypedefType *Ty, llvm::DIFile *Fg);
186
  llvm::DIType *CreateType(const TemplateSpecializationType *Ty,
187
                           llvm::DIFile *Fg);
188
  llvm::DIType *CreateType(const ObjCObjectPointerType *Ty, llvm::DIFile *F);
189
  llvm::DIType *CreateType(const PointerType *Ty, llvm::DIFile *F);
190
  llvm::DIType *CreateType(const BlockPointerType *Ty, llvm::DIFile *F);
191
  llvm::DIType *CreateType(const FunctionType *Ty, llvm::DIFile *F);
192
  /// Get structure or union type.
193
  llvm::DIType *CreateType(const RecordType *Tyg);
194
  llvm::DIType *CreateTypeDefinition(const RecordType *Ty);
195
  llvm::DICompositeType *CreateLimitedType(const RecordType *Ty);
196
  void CollectContainingType(const CXXRecordDecl *RD,
197
                             llvm::DICompositeType *CT);
198
  /// Get Objective-C interface type.
199
  llvm::DIType *CreateType(const ObjCInterfaceType *Ty, llvm::DIFile *F);
200
  llvm::DIType *CreateTypeDefinition(const ObjCInterfaceType *Ty,
201
                                     llvm::DIFile *F);
202
  /// Get Objective-C object type.
203
  llvm::DIType *CreateType(const ObjCObjectType *Ty, llvm::DIFile *F);
204
  llvm::DIType *CreateType(const ObjCTypeParamType *Ty, llvm::DIFile *Unit);
205
206
  llvm::DIType *CreateType(const VectorType *Ty, llvm::DIFile *F);
207
  llvm::DIType *CreateType(const ConstantMatrixType *Ty, llvm::DIFile *F);
208
  llvm::DIType *CreateType(const ArrayType *Ty, llvm::DIFile *F);
209
  llvm::DIType *CreateType(const LValueReferenceType *Ty, llvm::DIFile *F);
210
  llvm::DIType *CreateType(const RValueReferenceType *Ty, llvm::DIFile *Unit);
211
  llvm::DIType *CreateType(const MemberPointerType *Ty, llvm::DIFile *F);
212
  llvm::DIType *CreateType(const AtomicType *Ty, llvm::DIFile *F);
213
  llvm::DIType *CreateType(const PipeType *Ty, llvm::DIFile *F);
214
  /// Get enumeration type.
215
  llvm::DIType *CreateEnumType(const EnumType *Ty);
216
  llvm::DIType *CreateTypeDefinition(const EnumType *Ty);
217
  /// Look up the completed type for a self pointer in the TypeCache and
218
  /// create a copy of it with the ObjectPointer and Artificial flags
219
  /// set. If the type is not cached, a new one is created. This should
220
  /// never happen though, since creating a type for the implicit self
221
  /// argument implies that we already parsed the interface definition
222
  /// and the ivar declarations in the implementation.
223
  llvm::DIType *CreateSelfType(const QualType &QualTy, llvm::DIType *Ty);
224
  /// @}
225
226
  /// Get the type from the cache or return null type if it doesn't
227
  /// exist.
228
  llvm::DIType *getTypeOrNull(const QualType);
229
  /// Return the debug type for a C++ method.
230
  /// \arg CXXMethodDecl is of FunctionType. This function type is
231
  /// not updated to include implicit \c this pointer. Use this routine
232
  /// to get a method type which includes \c this pointer.
233
  llvm::DISubroutineType *getOrCreateMethodType(const CXXMethodDecl *Method,
234
                                                llvm::DIFile *F, bool decl);
235
  llvm::DISubroutineType *
236
  getOrCreateInstanceMethodType(QualType ThisPtr, const FunctionProtoType *Func,
237
                                llvm::DIFile *Unit, bool decl);
238
  llvm::DISubroutineType *
239
  getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F);
240
  /// \return debug info descriptor for vtable.
241
  llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F);
242
243
  /// \return namespace descriptor for the given namespace decl.
244
  llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N);
245
  llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty,
246
                                      QualType PointeeTy, llvm::DIFile *F);
247
  llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache);
248
249
  /// A helper function to create a subprogram for a single member
250
  /// function GlobalDecl.
251
  llvm::DISubprogram *CreateCXXMemberFunction(const CXXMethodDecl *Method,
252
                                              llvm::DIFile *F,
253
                                              llvm::DIType *RecordTy);
254
255
  /// A helper function to collect debug info for C++ member
256
  /// functions. This is used while creating debug info entry for a
257
  /// Record.
258
  void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile *F,
259
                                 SmallVectorImpl<llvm::Metadata *> &E,
260
                                 llvm::DIType *T);
261
262
  /// A helper function to collect debug info for C++ base
263
  /// classes. This is used while creating debug info entry for a
264
  /// Record.
265
  void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile *F,
266
                       SmallVectorImpl<llvm::Metadata *> &EltTys,
267
                       llvm::DIType *RecordTy);
268
269
  /// Helper function for CollectCXXBases.
270
  /// Adds debug info entries for types in Bases that are not in SeenTypes.
271
  void CollectCXXBasesAux(
272
      const CXXRecordDecl *RD, llvm::DIFile *Unit,
273
      SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
274
      const CXXRecordDecl::base_class_const_range &Bases,
275
      llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
276
      llvm::DINode::DIFlags StartingFlags);
277
278
  struct TemplateArgs {
279
    const TemplateParameterList *TList;
280
    llvm::ArrayRef<TemplateArgument> Args;
281
  };
282
  /// A helper function to collect template parameters.
283
  llvm::DINodeArray CollectTemplateParams(Optional<TemplateArgs> Args,
284
                                          llvm::DIFile *Unit);
285
  /// A helper function to collect debug info for function template
286
  /// parameters.
287
  llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,
288
                                                  llvm::DIFile *Unit);
289
290
  /// A helper function to collect debug info for function template
291
  /// parameters.
292
  llvm::DINodeArray CollectVarTemplateParams(const VarDecl *VD,
293
                                             llvm::DIFile *Unit);
294
295
  Optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const;
296
  Optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const;
297
  Optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const;
298
299
  /// A helper function to collect debug info for template
300
  /// parameters.
301
  llvm::DINodeArray CollectCXXTemplateParams(const RecordDecl *TS,
302
                                             llvm::DIFile *F);
303
304
  /// A helper function to collect debug info for btf_decl_tag annotations.
305
  llvm::DINodeArray CollectBTFDeclTagAnnotations(const Decl *D);
306
307
  llvm::DIType *createFieldType(StringRef name, QualType type,
308
                                SourceLocation loc, AccessSpecifier AS,
309
                                uint64_t offsetInBits, uint32_t AlignInBits,
310
                                llvm::DIFile *tunit, llvm::DIScope *scope,
311
                                const RecordDecl *RD = nullptr,
312
                                llvm::DINodeArray Annotations = nullptr);
313
314
  llvm::DIType *createFieldType(StringRef name, QualType type,
315
                                SourceLocation loc, AccessSpecifier AS,
316
                                uint64_t offsetInBits, llvm::DIFile *tunit,
317
                                llvm::DIScope *scope,
318
846
                                const RecordDecl *RD = nullptr) {
319
846
    return createFieldType(name, type, loc, AS, offsetInBits, 0, tunit, scope,
320
846
                           RD);
321
846
  }
322
323
  /// Create new bit field member.
324
  llvm::DIType *createBitFieldType(const FieldDecl *BitFieldDecl,
325
                                   llvm::DIScope *RecordTy,
326
                                   const RecordDecl *RD);
327
328
  /// Helpers for collecting fields of a record.
329
  /// @{
330
  void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
331
                                 SmallVectorImpl<llvm::Metadata *> &E,
332
                                 llvm::DIType *RecordTy);
333
  llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,
334
                                               llvm::DIType *RecordTy,
335
                                               const RecordDecl *RD);
336
  void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
337
                                llvm::DIFile *F,
338
                                SmallVectorImpl<llvm::Metadata *> &E,
339
                                llvm::DIType *RecordTy, const RecordDecl *RD);
340
  void CollectRecordNestedType(const TypeDecl *RD,
341
                               SmallVectorImpl<llvm::Metadata *> &E);
342
  void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,
343
                           SmallVectorImpl<llvm::Metadata *> &E,
344
                           llvm::DICompositeType *RecordTy);
345
346
  /// If the C++ class has vtable info then insert appropriate debug
347
  /// info entry in EltTys vector.
348
  void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,
349
                         SmallVectorImpl<llvm::Metadata *> &EltTys);
350
  /// @}
351
352
  /// Create a new lexical block node and push it on the stack.
353
  void CreateLexicalBlock(SourceLocation Loc);
354
355
  /// If target-specific LLVM \p AddressSpace directly maps to target-specific
356
  /// DWARF address space, appends extended dereferencing mechanism to complex
357
  /// expression \p Expr. Otherwise, does nothing.
358
  ///
359
  /// Extended dereferencing mechanism is has the following format:
360
  ///     DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
361
  void AppendAddressSpaceXDeref(unsigned AddressSpace,
362
                                SmallVectorImpl<uint64_t> &Expr) const;
363
364
  /// A helper function to collect debug info for the default elements of a
365
  /// block.
366
  ///
367
  /// \returns The next available field offset after the default elements.
368
  uint64_t collectDefaultElementTypesForBlockPointer(
369
      const BlockPointerType *Ty, llvm::DIFile *Unit,
370
      llvm::DIDerivedType *DescTy, unsigned LineNo,
371
      SmallVectorImpl<llvm::Metadata *> &EltTys);
372
373
  /// A helper function to collect debug info for the default fields of a
374
  /// block.
375
  void collectDefaultFieldsForBlockLiteralDeclare(
376
      const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
377
      const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
378
      SmallVectorImpl<llvm::Metadata *> &Fields);
379
380
public:
381
  CGDebugInfo(CodeGenModule &CGM);
382
  ~CGDebugInfo();
383
384
  void finalize();
385
386
  /// Remap a given path with the current debug prefix map
387
  std::string remapDIPath(StringRef) const;
388
389
  /// Register VLA size expression debug node with the qualified type.
390
41
  void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {
391
41
    SizeExprCache[Ty] = SizeExpr;
392
41
  }
393
394
  /// Module debugging: Support for building PCMs.
395
  /// @{
396
  /// Set the main CU's DwoId field to \p Signature.
397
  void setDwoId(uint64_t Signature);
398
399
  /// When generating debug information for a clang module or
400
  /// precompiled header, this module map will be used to determine
401
  /// the module of origin of each Decl.
402
327
  void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }
403
404
  /// When generating debug information for a clang module or
405
  /// precompiled header, this module map will be used to determine
406
  /// the module of origin of each Decl.
407
327
  void setPCHDescriptor(ASTSourceDescriptor PCH) { PCHDescriptor = PCH; }
408
  /// @}
409
410
  /// Update the current source location. If \arg loc is invalid it is
411
  /// ignored.
412
  void setLocation(SourceLocation Loc);
413
414
  /// Return the current source location. This does not necessarily correspond
415
  /// to the IRBuilder's current DebugLoc.
416
3
  SourceLocation getLocation() const { return CurLoc; }
417
418
  /// Update the current inline scope. All subsequent calls to \p EmitLocation
419
  /// will create a location with this inlinedAt field.
420
6
  void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }
421
422
  /// \return the current inline scope.
423
11.9k
  llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }
424
425
  // Converts a SourceLocation to a DebugLoc
426
  llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);
427
428
  /// Emit metadata to indicate a change in line/column information in
429
  /// the source file. If the location is invalid, the previous
430
  /// location will be reused.
431
  void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
432
433
  QualType getFunctionType(const FunctionDecl *FD, QualType RetTy,
434
                           const SmallVectorImpl<const VarDecl *> &Args);
435
436
  /// Emit a call to llvm.dbg.function.start to indicate
437
  /// start of a new function.
438
  /// \param Loc       The location of the function header.
439
  /// \param ScopeLoc  The location of the function body.
440
  void emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
441
                         SourceLocation ScopeLoc, QualType FnType,
442
                         llvm::Function *Fn, bool CurFnIsThunk);
443
444
  /// Start a new scope for an inlined function.
445
  void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);
446
  /// End an inlined function scope.
447
  void EmitInlineFunctionEnd(CGBuilderTy &Builder);
448
449
  /// Emit debug info for a function declaration.
450
  /// \p Fn is set only when a declaration for a debug call site gets created.
451
  void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
452
                        QualType FnType, llvm::Function *Fn = nullptr);
453
454
  /// Emit debug info for an extern function being called.
455
  /// This is needed for call site debug info.
456
  void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
457
                               QualType CalleeType,
458
                               const FunctionDecl *CalleeDecl);
459
460
  /// Constructs the debug code for exiting a function.
461
  void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);
462
463
  /// Emit metadata to indicate the beginning of a new lexical block
464
  /// and push the block onto the stack.
465
  void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
466
467
  /// Emit metadata to indicate the end of a new lexical block and pop
468
  /// the current block.
469
  void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
470
471
  /// Emit call to \c llvm.dbg.declare for an automatic variable
472
  /// declaration.
473
  /// Returns a pointer to the DILocalVariable associated with the
474
  /// llvm.dbg.declare, or nullptr otherwise.
475
  llvm::DILocalVariable *
476
  EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,
477
                            CGBuilderTy &Builder,
478
                            const bool UsePointerValue = false);
479
480
  /// Emit call to \c llvm.dbg.label for an label.
481
  void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder);
482
483
  /// Emit call to \c llvm.dbg.declare for an imported variable
484
  /// declaration in a block.
485
  void EmitDeclareOfBlockDeclRefVariable(
486
      const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,
487
      const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);
488
489
  /// Emit call to \c llvm.dbg.declare for an argument variable
490
  /// declaration.
491
  llvm::DILocalVariable *EmitDeclareOfArgVariable(const VarDecl *Decl,
492
                                                  llvm::Value *AI,
493
                                                  unsigned ArgNo,
494
                                                  CGBuilderTy &Builder);
495
496
  /// Emit call to \c llvm.dbg.declare for the block-literal argument
497
  /// to a block invocation function.
498
  void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
499
                                            StringRef Name, unsigned ArgNo,
500
                                            llvm::AllocaInst *LocalAddr,
501
                                            CGBuilderTy &Builder);
502
503
  /// Emit information about a global variable.
504
  void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
505
506
  /// Emit a constant global variable's debug info.
507
  void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
508
509
  /// Emit information about an external variable.
510
  void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
511
512
  /// Emit information about global variable alias.
513
  void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);
514
515
  /// Emit C++ using directive.
516
  void EmitUsingDirective(const UsingDirectiveDecl &UD);
517
518
  /// Emit the type explicitly casted to.
519
  void EmitExplicitCastType(QualType Ty);
520
521
  /// Emit the type even if it might not be used.
522
  void EmitAndRetainType(QualType Ty);
523
524
  /// Emit a shadow decl brought in by a using or using-enum
525
  void EmitUsingShadowDecl(const UsingShadowDecl &USD);
526
527
  /// Emit C++ using declaration.
528
  void EmitUsingDecl(const UsingDecl &UD);
529
530
  /// Emit C++ using-enum declaration.
531
  void EmitUsingEnumDecl(const UsingEnumDecl &UD);
532
533
  /// Emit an @import declaration.
534
  void EmitImportDecl(const ImportDecl &ID);
535
536
  /// Emit C++ namespace alias.
537
  llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
538
539
  /// Emit record type's standalone debug info.
540
  llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
541
542
  /// Emit an Objective-C interface type standalone debug info.
543
  llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
544
545
  /// Emit standalone debug info for a type.
546
  llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
547
548
  /// Add heapallocsite metadata for MSAllocator calls.
549
  void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy,
550
                                SourceLocation Loc);
551
552
  void completeType(const EnumDecl *ED);
553
  void completeType(const RecordDecl *RD);
554
  void completeRequiredType(const RecordDecl *RD);
555
  void completeClassData(const RecordDecl *RD);
556
  void completeClass(const RecordDecl *RD);
557
558
  void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
559
  void completeUnusedClass(const CXXRecordDecl &D);
560
561
  /// Create debug info for a macro defined by a #define directive or a macro
562
  /// undefined by a #undef directive.
563
  llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,
564
                             SourceLocation LineLoc, StringRef Name,
565
                             StringRef Value);
566
567
  /// Create debug info for a file referenced by an #include directive.
568
  llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,
569
                                         SourceLocation LineLoc,
570
                                         SourceLocation FileLoc);
571
572
102k
  Param2DILocTy &getParamDbgMappings() { return ParamDbgMappings; }
573
6
  ParamDecl2StmtTy &getCoroutineParameterMappings() {
574
6
    return CoroutineParameterMappings;
575
6
  }
576
577
private:
578
  /// Emit call to llvm.dbg.declare for a variable declaration.
579
  /// Returns a pointer to the DILocalVariable associated with the
580
  /// llvm.dbg.declare, or nullptr otherwise.
581
  llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,
582
                                     llvm::Optional<unsigned> ArgNo,
583
                                     CGBuilderTy &Builder,
584
                                     const bool UsePointerValue = false);
585
586
  /// Emit call to llvm.dbg.declare for a binding declaration.
587
  /// Returns a pointer to the DILocalVariable associated with the
588
  /// llvm.dbg.declare, or nullptr otherwise.
589
  llvm::DILocalVariable *EmitDeclare(const BindingDecl *decl, llvm::Value *AI,
590
                                     llvm::Optional<unsigned> ArgNo,
591
                                     CGBuilderTy &Builder,
592
                                     const bool UsePointerValue = false);
593
594
  struct BlockByRefType {
595
    /// The wrapper struct used inside the __block_literal struct.
596
    llvm::DIType *BlockByRefWrapper;
597
    /// The type as it appears in the source code.
598
    llvm::DIType *WrappedType;
599
  };
600
601
  std::string GetName(const Decl*, bool Qualified = false) const;
602
603
  /// Build up structure info for the byref.  See \a BuildByRefType.
604
  BlockByRefType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
605
                                              uint64_t *OffSet);
606
607
  /// Get context info for the DeclContext of \p Decl.
608
  llvm::DIScope *getDeclContextDescriptor(const Decl *D);
609
  /// Get context info for a given DeclContext \p Decl.
610
  llvm::DIScope *getContextDescriptor(const Decl *Context,
611
                                      llvm::DIScope *Default);
612
613
  llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
614
615
  /// Create a forward decl for a RecordType in a given context.
616
  llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
617
                                                  llvm::DIScope *);
618
619
  /// Return current directory name.
620
  StringRef getCurrentDirname();
621
622
  /// Create new compile unit.
623
  void CreateCompileUnit();
624
625
  /// Compute the file checksum debug info for input file ID.
626
  Optional<llvm::DIFile::ChecksumKind>
627
  computeChecksum(FileID FID, SmallString<32> &Checksum) const;
628
629
  /// Get the source of the given file ID.
630
  Optional<StringRef> getSource(const SourceManager &SM, FileID FID);
631
632
  /// Convenience function to get the file debug info descriptor for the input
633
  /// location.
634
  llvm::DIFile *getOrCreateFile(SourceLocation Loc);
635
636
  /// Create a file debug info descriptor for a source file.
637
  llvm::DIFile *
638
  createFile(StringRef FileName,
639
             Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
640
             Optional<StringRef> Source);
641
642
  /// Get the type from the cache or create a new type if necessary.
643
  llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
644
645
  /// Get a reference to a clang module.  If \p CreateSkeletonCU is true,
646
  /// this also creates a split dwarf skeleton compile unit.
647
  llvm::DIModule *getOrCreateModuleRef(ASTSourceDescriptor Mod,
648
                                       bool CreateSkeletonCU);
649
650
  /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
651
  llvm::DIModule *getParentModuleOrNull(const Decl *D);
652
653
  /// Get the type from the cache or create a new partial type if
654
  /// necessary.
655
  llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty);
656
657
  /// Create type metadata for a source language type.
658
  llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
659
660
  /// Create new member and increase Offset by FType's size.
661
  llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
662
                                 StringRef Name, uint64_t *Offset);
663
664
  /// Retrieve the DIDescriptor, if any, for the canonical form of this
665
  /// declaration.
666
  llvm::DINode *getDeclarationOrDefinition(const Decl *D);
667
668
  /// \return debug info descriptor to describe method
669
  /// declaration for the given method definition.
670
  llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
671
672
  /// \return          debug info descriptor to the describe method declaration
673
  ///                  for the given method definition.
674
  /// \param FnType    For Objective-C methods, their type.
675
  /// \param LineNo    The declaration's line number.
676
  /// \param Flags     The DIFlags for the method declaration.
677
  /// \param SPFlags   The subprogram-spcific flags for the method declaration.
678
  llvm::DISubprogram *
679
  getObjCMethodDeclaration(const Decl *D, llvm::DISubroutineType *FnType,
680
                           unsigned LineNo, llvm::DINode::DIFlags Flags,
681
                           llvm::DISubprogram::DISPFlags SPFlags);
682
683
  /// \return debug info descriptor to describe in-class static data
684
  /// member declaration for the given out-of-class definition.  If D
685
  /// is an out-of-class definition of a static data member of a
686
  /// class, find its corresponding in-class declaration.
687
  llvm::DIDerivedType *
688
  getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
689
690
  /// Helper that either creates a forward declaration or a stub.
691
  llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
692
693
  /// Create a subprogram describing the forward declaration
694
  /// represented in the given FunctionDecl wrapped in a GlobalDecl.
695
  llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
696
697
  /// Create a DISubprogram describing the function
698
  /// represented in the given FunctionDecl wrapped in a GlobalDecl.
699
  llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
700
701
  /// Create a global variable describing the forward declaration
702
  /// represented in the given VarDecl.
703
  llvm::DIGlobalVariable *
704
  getGlobalVariableForwardDeclaration(const VarDecl *VD);
705
706
  /// Return a global variable that represents one of the collection of global
707
  /// variables created for an anonmyous union.
708
  ///
709
  /// Recursively collect all of the member fields of a global
710
  /// anonymous decl and create static variables for them. The first
711
  /// time this is called it needs to be on a union and then from
712
  /// there we can have additional unnamed fields.
713
  llvm::DIGlobalVariableExpression *
714
  CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
715
                         unsigned LineNo, StringRef LinkageName,
716
                         llvm::GlobalVariable *Var, llvm::DIScope *DContext);
717
718
719
  /// Return flags which enable debug info emission for call sites, provided
720
  /// that it is supported and enabled.
721
  llvm::DINode::DIFlags getCallSiteRelatedAttrs() const;
722
723
  /// Get the printing policy for producing names for debug info.
724
  PrintingPolicy getPrintingPolicy() const;
725
726
  /// Get function name for the given FunctionDecl. If the name is
727
  /// constructed on demand (e.g., C++ destructor) then the name is
728
  /// stored on the side.
729
  StringRef getFunctionName(const FunctionDecl *FD);
730
731
  /// Returns the unmangled name of an Objective-C method.
732
  /// This is the display name for the debugging info.
733
  StringRef getObjCMethodName(const ObjCMethodDecl *FD);
734
735
  /// Return selector name. This is used for debugging
736
  /// info.
737
  StringRef getSelectorName(Selector S);
738
739
  /// Get class name including template argument list.
740
  StringRef getClassName(const RecordDecl *RD);
741
742
  /// Get the vtable name for the given class.
743
  StringRef getVTableName(const CXXRecordDecl *Decl);
744
745
  /// Get the name to use in the debug info for a dynamic initializer or atexit
746
  /// stub function.
747
  StringRef getDynamicInitializerName(const VarDecl *VD,
748
                                      DynamicInitKind StubKind,
749
                                      llvm::Function *InitFn);
750
751
  /// Get line number for the location. If location is invalid
752
  /// then use current location.
753
  unsigned getLineNumber(SourceLocation Loc);
754
755
  /// Get column number for the location. If location is
756
  /// invalid then use current location.
757
  /// \param Force  Assume DebugColumnInfo option is true.
758
  unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
759
760
  /// Collect various properties of a FunctionDecl.
761
  /// \param GD  A GlobalDecl whose getDecl() must return a FunctionDecl.
762
  void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
763
                                StringRef &Name, StringRef &LinkageName,
764
                                llvm::DIScope *&FDContext,
765
                                llvm::DINodeArray &TParamsArray,
766
                                llvm::DINode::DIFlags &Flags);
767
768
  /// Collect various properties of a VarDecl.
769
  void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
770
                           unsigned &LineNo, QualType &T, StringRef &Name,
771
                           StringRef &LinkageName,
772
                           llvm::MDTuple *&TemplateParameters,
773
                           llvm::DIScope *&VDContext);
774
775
  /// Allocate a copy of \p A using the DebugInfoNames allocator
776
  /// and return a reference to it. If multiple arguments are given the strings
777
  /// are concatenated.
778
823k
  StringRef internString(StringRef A, StringRef B = StringRef()) {
779
823k
    char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
780
823k
    if (!A.empty())
781
823k
      std::memcpy(Data, A.data(), A.size());
782
823k
    if (!B.empty())
783
891
      std::memcpy(Data + A.size(), B.data(), B.size());
784
823k
    return StringRef(Data, A.size() + B.size());
785
823k
  }
786
};
787
788
/// A scoped helper to set the current debug location to the specified
789
/// location or preferred location of the specified Expr.
790
class ApplyDebugLocation {
791
private:
792
  void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
793
  ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
794
                     SourceLocation TemporaryLocation);
795
796
  llvm::DebugLoc OriginalLocation;
797
  CodeGenFunction *CGF;
798
799
public:
800
  /// Set the location to the (valid) TemporaryLocation.
801
  ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
802
  ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
803
  ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
804
1.11k
  ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
805
1.11k
    Other.CGF = nullptr;
806
1.11k
  }
807
0
  ApplyDebugLocation &operator=(ApplyDebugLocation &&) = default;
808
809
  ~ApplyDebugLocation();
810
811
  /// Apply TemporaryLocation if it is valid. Otherwise switch
812
  /// to an artificial debug location that has a valid scope, but no
813
  /// line information.
814
  ///
815
  /// Artificial locations are useful when emitting compiler-generated
816
  /// helper functions that have no source location associated with
817
  /// them. The DWARF specification allows the compiler to use the
818
  /// special line number 0 to indicate code that can not be
819
  /// attributed to any source location. Note that passing an empty
820
  /// SourceLocation to CGDebugInfo::setLocation() will result in the
821
  /// last valid location being reused.
822
11.5k
  static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
823
11.5k
    return ApplyDebugLocation(CGF, false, SourceLocation());
824
11.5k
  }
825
  /// Apply TemporaryLocation if it is valid. Otherwise switch
826
  /// to an artificial debug location that has a valid scope, but no
827
  /// line information.
828
  static ApplyDebugLocation
829
  CreateDefaultArtificial(CodeGenFunction &CGF,
830
270k
                          SourceLocation TemporaryLocation) {
831
270k
    return ApplyDebugLocation(CGF, false, TemporaryLocation);
832
270k
  }
833
834
  /// Set the IRBuilder to not attach debug locations.  Note that
835
  /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
836
  /// will result in the last valid location being reused.  Note that
837
  /// all instructions that do not have a location at the beginning of
838
  /// a function are counted towards to function prologue.
839
35.7k
  static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
840
35.7k
    return ApplyDebugLocation(CGF, true, SourceLocation());
841
35.7k
  }
842
};
843
844
/// A scoped helper to set the current debug location to an inlined location.
845
class ApplyInlineDebugLocation {
846
  SourceLocation SavedLocation;
847
  CodeGenFunction *CGF;
848
849
public:
850
  /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
851
  /// function \p InlinedFn. The current debug location becomes the inlined call
852
  /// site of the inlined function.
853
  ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
854
  /// Restore everything back to the original state.
855
  ~ApplyInlineDebugLocation();
856
};
857
858
} // namespace CodeGen
859
} // namespace clang
860
861
#endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H