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