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