1//===--- CodeGenModule.h - Per-Module state 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 internal per-translation-unit state used for llvm translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
14#define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
15
16#include "CGVTables.h"
17#include "CodeGenTypeCache.h"
18#include "CodeGenTypes.h"
19#include "SanitizerMetadata.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclOpenMP.h"
23#include "clang/AST/GlobalDecl.h"
24#include "clang/AST/Mangle.h"
25#include "clang/Basic/ABI.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/Module.h"
28#include "clang/Basic/NoSanitizeList.h"
29#include "clang/Basic/ProfileList.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/XRayLists.h"
32#include "clang/Lex/PreprocessorOptions.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/MapVector.h"
35#include "llvm/ADT/SetVector.h"
36#include "llvm/ADT/SmallPtrSet.h"
37#include "llvm/ADT/StringMap.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/ValueHandle.h"
40#include "llvm/Transforms/Utils/SanitizerStats.h"
41#include <optional>
42
43namespace llvm {
44class Module;
45class Constant;
46class ConstantInt;
47class Function;
48class GlobalValue;
49class DataLayout;
50class FunctionType;
51class LLVMContext;
52class IndexedInstrProfReader;
53
54namespace vfs {
55class FileSystem;
56}
57}
58
59namespace clang {
60class ASTContext;
61class AtomicType;
62class FunctionDecl;
63class IdentifierInfo;
64class ObjCImplementationDecl;
65class ObjCEncodeExpr;
66class BlockExpr;
67class CharUnits;
68class Decl;
69class Expr;
70class Stmt;
71class StringLiteral;
72class NamedDecl;
73class ValueDecl;
74class VarDecl;
75class LangOptions;
76class CodeGenOptions;
77class HeaderSearchOptions;
78class DiagnosticsEngine;
79class AnnotateAttr;
80class CXXDestructorDecl;
81class Module;
82class CoverageSourceInfo;
83class InitSegAttr;
84
85namespace CodeGen {
86
87class CodeGenFunction;
88class CodeGenTBAA;
89class CGCXXABI;
90class CGDebugInfo;
91class CGObjCRuntime;
92class CGOpenCLRuntime;
93class CGOpenMPRuntime;
94class CGCUDARuntime;
95class CGHLSLRuntime;
96class CoverageMappingModuleGen;
97class TargetCodeGenInfo;
98
99enum ForDefinition_t : bool {
100 NotForDefinition = false,
101 ForDefinition = true
102};
103
104struct OrderGlobalInitsOrStermFinalizers {
105 unsigned int priority;
106 unsigned int lex_order;
107 OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l)
108 : priority(p), lex_order(l) {}
109
110 bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
111 return priority == RHS.priority && lex_order == RHS.lex_order;
112 }
113
114 bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const {
115 return std::tie(args: priority, args: lex_order) <
116 std::tie(args: RHS.priority, args: RHS.lex_order);
117 }
118};
119
120struct ObjCEntrypoints {
121 ObjCEntrypoints() { memset(s: this, c: 0, n: sizeof(*this)); }
122
123 /// void objc_alloc(id);
124 llvm::FunctionCallee objc_alloc;
125
126 /// void objc_allocWithZone(id);
127 llvm::FunctionCallee objc_allocWithZone;
128
129 /// void objc_alloc_init(id);
130 llvm::FunctionCallee objc_alloc_init;
131
132 /// void objc_autoreleasePoolPop(void*);
133 llvm::FunctionCallee objc_autoreleasePoolPop;
134
135 /// void objc_autoreleasePoolPop(void*);
136 /// Note this method is used when we are using exception handling
137 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
138
139 /// void *objc_autoreleasePoolPush(void);
140 llvm::Function *objc_autoreleasePoolPush;
141
142 /// id objc_autorelease(id);
143 llvm::Function *objc_autorelease;
144
145 /// id objc_autorelease(id);
146 /// Note this is the runtime method not the intrinsic.
147 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
148
149 /// id objc_autoreleaseReturnValue(id);
150 llvm::Function *objc_autoreleaseReturnValue;
151
152 /// void objc_copyWeak(id *dest, id *src);
153 llvm::Function *objc_copyWeak;
154
155 /// void objc_destroyWeak(id*);
156 llvm::Function *objc_destroyWeak;
157
158 /// id objc_initWeak(id*, id);
159 llvm::Function *objc_initWeak;
160
161 /// id objc_loadWeak(id*);
162 llvm::Function *objc_loadWeak;
163
164 /// id objc_loadWeakRetained(id*);
165 llvm::Function *objc_loadWeakRetained;
166
167 /// void objc_moveWeak(id *dest, id *src);
168 llvm::Function *objc_moveWeak;
169
170 /// id objc_retain(id);
171 llvm::Function *objc_retain;
172
173 /// id objc_retain(id);
174 /// Note this is the runtime method not the intrinsic.
175 llvm::FunctionCallee objc_retainRuntimeFunction;
176
177 /// id objc_retainAutorelease(id);
178 llvm::Function *objc_retainAutorelease;
179
180 /// id objc_retainAutoreleaseReturnValue(id);
181 llvm::Function *objc_retainAutoreleaseReturnValue;
182
183 /// id objc_retainAutoreleasedReturnValue(id);
184 llvm::Function *objc_retainAutoreleasedReturnValue;
185
186 /// id objc_retainBlock(id);
187 llvm::Function *objc_retainBlock;
188
189 /// void objc_release(id);
190 llvm::Function *objc_release;
191
192 /// void objc_release(id);
193 /// Note this is the runtime method not the intrinsic.
194 llvm::FunctionCallee objc_releaseRuntimeFunction;
195
196 /// void objc_storeStrong(id*, id);
197 llvm::Function *objc_storeStrong;
198
199 /// id objc_storeWeak(id*, id);
200 llvm::Function *objc_storeWeak;
201
202 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
203 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
204
205 /// A void(void) inline asm to use to mark that the return value of
206 /// a call will be immediately retain.
207 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
208
209 /// void clang.arc.use(...);
210 llvm::Function *clang_arc_use;
211
212 /// void clang.arc.noop.use(...);
213 llvm::Function *clang_arc_noop_use;
214};
215
216/// This class records statistics on instrumentation based profiling.
217class InstrProfStats {
218 uint32_t VisitedInMainFile = 0;
219 uint32_t MissingInMainFile = 0;
220 uint32_t Visited = 0;
221 uint32_t Missing = 0;
222 uint32_t Mismatched = 0;
223
224public:
225 InstrProfStats() = default;
226 /// Record that we've visited a function and whether or not that function was
227 /// in the main source file.
228 void addVisited(bool MainFile) {
229 if (MainFile)
230 ++VisitedInMainFile;
231 ++Visited;
232 }
233 /// Record that a function we've visited has no profile data.
234 void addMissing(bool MainFile) {
235 if (MainFile)
236 ++MissingInMainFile;
237 ++Missing;
238 }
239 /// Record that a function we've visited has mismatched profile data.
240 void addMismatched(bool MainFile) { ++Mismatched; }
241 /// Whether or not the stats we've gathered indicate any potential problems.
242 bool hasDiagnostics() { return Missing || Mismatched; }
243 /// Report potential problems we've found to \c Diags.
244 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
245};
246
247/// A pair of helper functions for a __block variable.
248class BlockByrefHelpers : public llvm::FoldingSetNode {
249 // MSVC requires this type to be complete in order to process this
250 // header.
251public:
252 llvm::Constant *CopyHelper;
253 llvm::Constant *DisposeHelper;
254
255 /// The alignment of the field. This is important because
256 /// different offsets to the field within the byref struct need to
257 /// have different helper functions.
258 CharUnits Alignment;
259
260 BlockByrefHelpers(CharUnits alignment)
261 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
262 BlockByrefHelpers(const BlockByrefHelpers &) = default;
263 virtual ~BlockByrefHelpers();
264
265 void Profile(llvm::FoldingSetNodeID &id) const {
266 id.AddInteger(I: Alignment.getQuantity());
267 profileImpl(id);
268 }
269 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
270
271 virtual bool needsCopy() const { return true; }
272 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
273
274 virtual bool needsDispose() const { return true; }
275 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
276};
277
278/// This class organizes the cross-function state that is used while generating
279/// LLVM code.
280class CodeGenModule : public CodeGenTypeCache {
281 CodeGenModule(const CodeGenModule &) = delete;
282 void operator=(const CodeGenModule &) = delete;
283
284public:
285 struct Structor {
286 Structor()
287 : Priority(0), LexOrder(~0u), Initializer(nullptr),
288 AssociatedData(nullptr) {}
289 Structor(int Priority, unsigned LexOrder, llvm::Constant *Initializer,
290 llvm::Constant *AssociatedData)
291 : Priority(Priority), LexOrder(LexOrder), Initializer(Initializer),
292 AssociatedData(AssociatedData) {}
293 int Priority;
294 unsigned LexOrder;
295 llvm::Constant *Initializer;
296 llvm::Constant *AssociatedData;
297 };
298
299 typedef std::vector<Structor> CtorList;
300
301private:
302 ASTContext &Context;
303 const LangOptions &LangOpts;
304 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS; // Only used for debug info.
305 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
306 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
307 const CodeGenOptions &CodeGenOpts;
308 unsigned NumAutoVarInit = 0;
309 llvm::Module &TheModule;
310 DiagnosticsEngine &Diags;
311 const TargetInfo &Target;
312 std::unique_ptr<CGCXXABI> ABI;
313 llvm::LLVMContext &VMContext;
314 std::string ModuleNameHash;
315 bool CXX20ModuleInits = false;
316 std::unique_ptr<CodeGenTBAA> TBAA;
317
318 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
319
320 // This should not be moved earlier, since its initialization depends on some
321 // of the previous reference members being already initialized and also checks
322 // if TheTargetCodeGenInfo is NULL
323 CodeGenTypes Types;
324
325 /// Holds information about C++ vtables.
326 CodeGenVTables VTables;
327
328 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
329 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
330 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
331 std::unique_ptr<CGCUDARuntime> CUDARuntime;
332 std::unique_ptr<CGHLSLRuntime> HLSLRuntime;
333 std::unique_ptr<CGDebugInfo> DebugInfo;
334 std::unique_ptr<ObjCEntrypoints> ObjCData;
335 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
336 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
337 InstrProfStats PGOStats;
338 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
339
340 // A set of references that have only been seen via a weakref so far. This is
341 // used to remove the weak of the reference if we ever see a direct reference
342 // or a definition.
343 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
344
345 /// This contains all the decls which have definitions but/ which are deferred
346 /// for emission and therefore should only be output if they are actually
347 /// used. If a decl is in this, then it is known to have not been referenced
348 /// yet.
349 llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
350
351 llvm::StringSet<llvm::BumpPtrAllocator> DeferredResolversToEmit;
352
353 /// This is a list of deferred decls which we have seen that *are* actually
354 /// referenced. These get code generated when the module is done.
355 std::vector<GlobalDecl> DeferredDeclsToEmit;
356 void addDeferredDeclToEmit(GlobalDecl GD) {
357 DeferredDeclsToEmit.emplace_back(args&: GD);
358 addEmittedDeferredDecl(GD);
359 }
360
361 /// Decls that were DeferredDecls and have now been emitted.
362 llvm::DenseMap<llvm::StringRef, GlobalDecl> EmittedDeferredDecls;
363
364 void addEmittedDeferredDecl(GlobalDecl GD) {
365 // Reemission is only needed in incremental mode.
366 if (!Context.getLangOpts().IncrementalExtensions)
367 return;
368
369 // Assume a linkage by default that does not need reemission.
370 auto L = llvm::GlobalValue::ExternalLinkage;
371 if (llvm::isa<FunctionDecl>(Val: GD.getDecl()))
372 L = getFunctionLinkage(GD);
373 else if (auto *VD = llvm::dyn_cast<VarDecl>(Val: GD.getDecl()))
374 L = getLLVMLinkageVarDefinition(VD);
375
376 if (llvm::GlobalValue::isInternalLinkage(Linkage: L) ||
377 llvm::GlobalValue::isLinkOnceLinkage(Linkage: L) ||
378 llvm::GlobalValue::isWeakLinkage(Linkage: L)) {
379 EmittedDeferredDecls[getMangledName(GD)] = GD;
380 }
381 }
382
383 /// List of alias we have emitted. Used to make sure that what they point to
384 /// is defined once we get to the end of the of the translation unit.
385 std::vector<GlobalDecl> Aliases;
386
387 /// List of multiversion functions to be emitted. This list is processed in
388 /// conjunction with other deferred symbols and is used to ensure that
389 /// multiversion function resolvers and ifuncs are defined and emitted.
390 std::vector<GlobalDecl> MultiVersionFuncs;
391
392 llvm::MapVector<StringRef, llvm::TrackingVH<llvm::Constant>> Replacements;
393
394 /// List of global values to be replaced with something else. Used when we
395 /// want to replace a GlobalValue but can't identify it by its mangled name
396 /// anymore (because the name is already taken).
397 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
398 GlobalValReplacements;
399
400 /// Variables for which we've emitted globals containing their constant
401 /// values along with the corresponding globals, for opportunistic reuse.
402 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
403
404 /// Set of global decls for which we already diagnosed mangled name conflict.
405 /// Required to not issue a warning (on a mangling conflict) multiple times
406 /// for the same decl.
407 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
408
409 /// A queue of (optional) vtables to consider emitting.
410 std::vector<const CXXRecordDecl*> DeferredVTables;
411
412 /// A queue of (optional) vtables that may be emitted opportunistically.
413 std::vector<const CXXRecordDecl *> OpportunisticVTables;
414
415 /// List of global values which are required to be present in the object file;
416 /// bitcast to i8*. This is used for forcing visibility of symbols which may
417 /// otherwise be optimized out.
418 std::vector<llvm::WeakTrackingVH> LLVMUsed;
419 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
420
421 /// Store the list of global constructors and their respective priorities to
422 /// be emitted when the translation unit is complete.
423 CtorList GlobalCtors;
424
425 /// Store the list of global destructors and their respective priorities to be
426 /// emitted when the translation unit is complete.
427 CtorList GlobalDtors;
428
429 /// An ordered map of canonical GlobalDecls to their mangled names.
430 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
431 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
432
433 /// Global annotations.
434 std::vector<llvm::Constant*> Annotations;
435
436 // Store deferred function annotations so they can be emitted at the end with
437 // most up to date ValueDecl that will have all the inherited annotations.
438 llvm::DenseMap<StringRef, const ValueDecl *> DeferredAnnotations;
439
440 /// Map used to get unique annotation strings.
441 llvm::StringMap<llvm::Constant*> AnnotationStrings;
442
443 /// Used for uniquing of annotation arguments.
444 llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
445
446 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
447
448 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
449 llvm::DenseMap<const UnnamedGlobalConstantDecl *, llvm::GlobalVariable *>
450 UnnamedGlobalConstantDeclMap;
451 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
452 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
453 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
454
455 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
456 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
457
458 /// Map used to get unique type descriptor constants for sanitizers.
459 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
460
461 /// Map used to track internal linkage functions declared within
462 /// extern "C" regions.
463 typedef llvm::MapVector<IdentifierInfo *,
464 llvm::GlobalValue *> StaticExternCMap;
465 StaticExternCMap StaticExternCValues;
466
467 /// thread_local variables defined or used in this TU.
468 std::vector<const VarDecl *> CXXThreadLocals;
469
470 /// thread_local variables with initializers that need to run
471 /// before any thread_local variable in this TU is odr-used.
472 std::vector<llvm::Function *> CXXThreadLocalInits;
473 std::vector<const VarDecl *> CXXThreadLocalInitVars;
474
475 /// Global variables with initializers that need to run before main.
476 std::vector<llvm::Function *> CXXGlobalInits;
477
478 /// When a C++ decl with an initializer is deferred, null is
479 /// appended to CXXGlobalInits, and the index of that null is placed
480 /// here so that the initializer will be performed in the correct
481 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
482 /// that we don't re-emit the initializer.
483 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
484
485 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
486 GlobalInitData;
487
488 struct GlobalInitPriorityCmp {
489 bool operator()(const GlobalInitData &LHS,
490 const GlobalInitData &RHS) const {
491 return LHS.first.priority < RHS.first.priority;
492 }
493 };
494
495 /// Global variables with initializers whose order of initialization is set by
496 /// init_priority attribute.
497 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
498
499 /// Global destructor functions and arguments that need to run on termination.
500 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
501 /// functions, which also run on unloading a shared library.
502 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
503 llvm::Constant *>
504 CXXGlobalDtorsOrStermFinalizer_t;
505 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
506 CXXGlobalDtorsOrStermFinalizers;
507
508 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
509 StermFinalizerData;
510
511 struct StermFinalizerPriorityCmp {
512 bool operator()(const StermFinalizerData &LHS,
513 const StermFinalizerData &RHS) const {
514 return LHS.first.priority < RHS.first.priority;
515 }
516 };
517
518 /// Global variables with sterm finalizers whose order of initialization is
519 /// set by init_priority attribute.
520 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
521
522 /// The complete set of modules that has been imported.
523 llvm::SetVector<clang::Module *> ImportedModules;
524
525 /// The set of modules for which the module initializers
526 /// have been emitted.
527 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
528
529 /// A vector of metadata strings for linker options.
530 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
531
532 /// A vector of metadata strings for dependent libraries for ELF.
533 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
534
535 /// @name Cache for Objective-C runtime types
536 /// @{
537
538 /// Cached reference to the class for constant strings. This value has type
539 /// int * but is actually an Obj-C class pointer.
540 llvm::WeakTrackingVH CFConstantStringClassRef;
541
542 /// The type used to describe the state of a fast enumeration in
543 /// Objective-C's for..in loop.
544 QualType ObjCFastEnumerationStateType;
545
546 /// @}
547
548 /// Lazily create the Objective-C runtime
549 void createObjCRuntime();
550
551 void createOpenCLRuntime();
552 void createOpenMPRuntime();
553 void createCUDARuntime();
554 void createHLSLRuntime();
555
556 bool isTriviallyRecursive(const FunctionDecl *F);
557 bool shouldEmitFunction(GlobalDecl GD);
558 bool shouldOpportunisticallyEmitVTables();
559 /// Map used to be sure we don't emit the same CompoundLiteral twice.
560 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
561 EmittedCompoundLiterals;
562
563 /// Map of the global blocks we've emitted, so that we don't have to re-emit
564 /// them if the constexpr evaluator gets aggressive.
565 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
566
567 /// @name Cache for Blocks Runtime Globals
568 /// @{
569
570 llvm::Constant *NSConcreteGlobalBlock = nullptr;
571 llvm::Constant *NSConcreteStackBlock = nullptr;
572
573 llvm::FunctionCallee BlockObjectAssign = nullptr;
574 llvm::FunctionCallee BlockObjectDispose = nullptr;
575
576 llvm::Type *BlockDescriptorType = nullptr;
577 llvm::Type *GenericBlockLiteralType = nullptr;
578
579 struct {
580 int GlobalUniqueCount;
581 } Block;
582
583 GlobalDecl initializedGlobalDecl;
584
585 /// @}
586
587 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
588 llvm::Function *LifetimeStartFn = nullptr;
589
590 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
591 llvm::Function *LifetimeEndFn = nullptr;
592
593 std::unique_ptr<SanitizerMetadata> SanitizerMD;
594
595 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
596
597 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
598
599 /// Mapping from canonical types to their metadata identifiers. We need to
600 /// maintain this mapping because identifiers may be formed from distinct
601 /// MDNodes.
602 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
603 MetadataTypeMap MetadataIdMap;
604 MetadataTypeMap VirtualMetadataIdMap;
605 MetadataTypeMap GeneralizedMetadataIdMap;
606
607 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
608 // when used with -fincremental-extensions.
609 std::pair<std::unique_ptr<CodeGenFunction>, const TopLevelStmtDecl *>
610 GlobalTopLevelStmtBlockInFlight;
611
612public:
613 CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
614 const HeaderSearchOptions &headersearchopts,
615 const PreprocessorOptions &ppopts,
616 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
617 DiagnosticsEngine &Diags,
618 CoverageSourceInfo *CoverageInfo = nullptr);
619
620 ~CodeGenModule();
621
622 void clear();
623
624 /// Finalize LLVM code generation.
625 void Release();
626
627 /// Return true if we should emit location information for expressions.
628 bool getExpressionLocationsEnabled() const;
629
630 /// Return a reference to the configured Objective-C runtime.
631 CGObjCRuntime &getObjCRuntime() {
632 if (!ObjCRuntime) createObjCRuntime();
633 return *ObjCRuntime;
634 }
635
636 /// Return true iff an Objective-C runtime has been configured.
637 bool hasObjCRuntime() { return !!ObjCRuntime; }
638
639 const std::string &getModuleNameHash() const { return ModuleNameHash; }
640
641 /// Return a reference to the configured OpenCL runtime.
642 CGOpenCLRuntime &getOpenCLRuntime() {
643 assert(OpenCLRuntime != nullptr);
644 return *OpenCLRuntime;
645 }
646
647 /// Return a reference to the configured OpenMP runtime.
648 CGOpenMPRuntime &getOpenMPRuntime() {
649 assert(OpenMPRuntime != nullptr);
650 return *OpenMPRuntime;
651 }
652
653 /// Return a reference to the configured CUDA runtime.
654 CGCUDARuntime &getCUDARuntime() {
655 assert(CUDARuntime != nullptr);
656 return *CUDARuntime;
657 }
658
659 /// Return a reference to the configured HLSL runtime.
660 CGHLSLRuntime &getHLSLRuntime() {
661 assert(HLSLRuntime != nullptr);
662 return *HLSLRuntime;
663 }
664
665 ObjCEntrypoints &getObjCEntrypoints() const {
666 assert(ObjCData != nullptr);
667 return *ObjCData;
668 }
669
670 // Version checking functions, used to implement ObjC's @available:
671 // i32 @__isOSVersionAtLeast(i32, i32, i32)
672 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
673 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
674 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
675
676 InstrProfStats &getPGOStats() { return PGOStats; }
677 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
678
679 CoverageMappingModuleGen *getCoverageMapping() const {
680 return CoverageMapping.get();
681 }
682
683 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
684 return StaticLocalDeclMap[D];
685 }
686 void setStaticLocalDeclAddress(const VarDecl *D,
687 llvm::Constant *C) {
688 StaticLocalDeclMap[D] = C;
689 }
690
691 llvm::Constant *
692 getOrCreateStaticVarDecl(const VarDecl &D,
693 llvm::GlobalValue::LinkageTypes Linkage);
694
695 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
696 return StaticLocalDeclGuardMap[D];
697 }
698 void setStaticLocalDeclGuardAddress(const VarDecl *D,
699 llvm::GlobalVariable *C) {
700 StaticLocalDeclGuardMap[D] = C;
701 }
702
703 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
704 CharUnits Align);
705
706 bool lookupRepresentativeDecl(StringRef MangledName,
707 GlobalDecl &Result) const;
708
709 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
710 return AtomicSetterHelperFnMap[Ty];
711 }
712 void setAtomicSetterHelperFnMap(QualType Ty,
713 llvm::Constant *Fn) {
714 AtomicSetterHelperFnMap[Ty] = Fn;
715 }
716
717 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
718 return AtomicGetterHelperFnMap[Ty];
719 }
720 void setAtomicGetterHelperFnMap(QualType Ty,
721 llvm::Constant *Fn) {
722 AtomicGetterHelperFnMap[Ty] = Fn;
723 }
724
725 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
726 return TypeDescriptorMap[Ty];
727 }
728 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
729 TypeDescriptorMap[Ty] = C;
730 }
731
732 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
733
734 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
735 if (!NoObjCARCExceptionsMetadata)
736 NoObjCARCExceptionsMetadata =
737 llvm::MDNode::get(Context&: getLLVMContext(), MDs: std::nullopt);
738 return NoObjCARCExceptionsMetadata;
739 }
740
741 ASTContext &getContext() const { return Context; }
742 const LangOptions &getLangOpts() const { return LangOpts; }
743 const IntrusiveRefCntPtr<llvm::vfs::FileSystem> &getFileSystem() const {
744 return FS;
745 }
746 const HeaderSearchOptions &getHeaderSearchOpts()
747 const { return HeaderSearchOpts; }
748 const PreprocessorOptions &getPreprocessorOpts()
749 const { return PreprocessorOpts; }
750 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
751 llvm::Module &getModule() const { return TheModule; }
752 DiagnosticsEngine &getDiags() const { return Diags; }
753 const llvm::DataLayout &getDataLayout() const {
754 return TheModule.getDataLayout();
755 }
756 const TargetInfo &getTarget() const { return Target; }
757 const llvm::Triple &getTriple() const { return Target.getTriple(); }
758 bool supportsCOMDAT() const;
759 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
760
761 CGCXXABI &getCXXABI() const { return *ABI; }
762 llvm::LLVMContext &getLLVMContext() { return VMContext; }
763
764 bool shouldUseTBAA() const { return TBAA != nullptr; }
765
766 const TargetCodeGenInfo &getTargetCodeGenInfo();
767
768 CodeGenTypes &getTypes() { return Types; }
769
770 CodeGenVTables &getVTables() { return VTables; }
771
772 ItaniumVTableContext &getItaniumVTableContext() {
773 return VTables.getItaniumVTableContext();
774 }
775
776 const ItaniumVTableContext &getItaniumVTableContext() const {
777 return VTables.getItaniumVTableContext();
778 }
779
780 MicrosoftVTableContext &getMicrosoftVTableContext() {
781 return VTables.getMicrosoftVTableContext();
782 }
783
784 CtorList &getGlobalCtors() { return GlobalCtors; }
785 CtorList &getGlobalDtors() { return GlobalDtors; }
786
787 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
788 /// the given type.
789 llvm::MDNode *getTBAATypeInfo(QualType QTy);
790
791 /// getTBAAAccessInfo - Get TBAA information that describes an access to
792 /// an object of the given type.
793 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
794
795 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
796 /// access to a virtual table pointer.
797 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
798
799 llvm::MDNode *getTBAAStructInfo(QualType QTy);
800
801 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
802 /// type. Return null if the type is not suitable for use in TBAA access tags.
803 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
804
805 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
806 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
807
808 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
809 /// type casts.
810 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
811 TBAAAccessInfo TargetInfo);
812
813 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
814 /// purposes of conditional operator.
815 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
816 TBAAAccessInfo InfoB);
817
818 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
819 /// purposes of memory transfer calls.
820 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
821 TBAAAccessInfo SrcInfo);
822
823 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
824 /// base lvalue.
825 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
826 if (Base.getTBAAInfo().isMayAlias())
827 return TBAAAccessInfo::getMayAliasInfo();
828 return getTBAAAccessInfo(AccessType);
829 }
830
831 bool isPaddedAtomicType(QualType type);
832 bool isPaddedAtomicType(const AtomicType *type);
833
834 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
835 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
836 TBAAAccessInfo TBAAInfo);
837
838 /// Adds !invariant.barrier !tag to instruction
839 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
840 const CXXRecordDecl *RD);
841
842 /// Emit the given number of characters as a value of type size_t.
843 llvm::ConstantInt *getSize(CharUnits numChars);
844
845 /// Set the visibility for the given LLVM GlobalValue.
846 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
847
848 void setDSOLocal(llvm::GlobalValue *GV) const;
849
850 bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const {
851 return getLangOpts().hasDefaultVisibilityExportMapping() && D &&
852 (D->getLinkageAndVisibility().getVisibility() ==
853 DefaultVisibility) &&
854 (getLangOpts().isAllDefaultVisibilityExportMapping() ||
855 (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
856 D->getLinkageAndVisibility().isVisibilityExplicit()));
857 }
858 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
859 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
860 /// Set visibility, dllimport/dllexport and dso_local.
861 /// This must be called after dllimport/dllexport is set.
862 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
863 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
864
865 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
866
867 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
868 /// variable declaration D.
869 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
870
871 /// Get LLVM TLS mode from CodeGenOptions.
872 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
873
874 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
875 switch (V) {
876 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
877 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
878 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
879 }
880 llvm_unreachable("unknown visibility!");
881 }
882
883 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
884 ForDefinition_t IsForDefinition
885 = NotForDefinition);
886
887 /// Will return a global variable of the given type. If a variable with a
888 /// different type already exists then a new variable with the right type
889 /// will be created and all uses of the old variable will be replaced with a
890 /// bitcast to the new variable.
891 llvm::GlobalVariable *
892 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
893 llvm::GlobalValue::LinkageTypes Linkage,
894 llvm::Align Alignment);
895
896 llvm::Function *CreateGlobalInitOrCleanUpFunction(
897 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
898 SourceLocation Loc = SourceLocation(), bool TLS = false,
899 llvm::GlobalVariable::LinkageTypes Linkage =
900 llvm::GlobalVariable::InternalLinkage);
901
902 /// Return the AST address space of the underlying global variable for D, as
903 /// determined by its declaration. Normally this is the same as the address
904 /// space of D's type, but in CUDA, address spaces are associated with
905 /// declarations, not types. If D is nullptr, return the default address
906 /// space for global variable.
907 ///
908 /// For languages without explicit address spaces, if D has default address
909 /// space, target-specific global or constant address space may be returned.
910 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
911
912 /// Return the AST address space of constant literal, which is used to emit
913 /// the constant literal as global variable in LLVM IR.
914 /// Note: This is not necessarily the address space of the constant literal
915 /// in AST. For address space agnostic language, e.g. C++, constant literal
916 /// in AST is always in default address space.
917 LangAS GetGlobalConstantAddressSpace() const;
918
919 /// Return the llvm::Constant for the address of the given global variable.
920 /// If Ty is non-null and if the global doesn't exist, then it will be created
921 /// with the specified type instead of whatever the normal requested type
922 /// would be. If IsForDefinition is true, it is guaranteed that an actual
923 /// global with type Ty will be returned, not conversion of a variable with
924 /// the same mangled name but some other type.
925 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
926 llvm::Type *Ty = nullptr,
927 ForDefinition_t IsForDefinition
928 = NotForDefinition);
929
930 /// Return the address of the given function. If Ty is non-null, then this
931 /// function will use the specified type if it has to create it.
932 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
933 bool ForVTable = false,
934 bool DontDefer = false,
935 ForDefinition_t IsForDefinition
936 = NotForDefinition);
937
938 // Return the function body address of the given function.
939 llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
940
941 // Return whether RTTI information should be emitted for this target.
942 bool shouldEmitRTTI(bool ForEH = false) {
943 return (ForEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
944 !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
945 getTriple().isNVPTX());
946 }
947
948 /// Get the address of the RTTI descriptor for the given type.
949 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
950
951 /// Get the address of a GUID.
952 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
953
954 /// Get the address of a UnnamedGlobalConstant
955 ConstantAddress
956 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD);
957
958 /// Get the address of a template parameter object.
959 ConstantAddress
960 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
961
962 /// Get the address of the thunk for the given global decl.
963 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
964 GlobalDecl GD);
965
966 /// Get a reference to the target of VD.
967 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
968
969 /// Returns the assumed alignment of an opaque pointer to the given class.
970 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
971
972 /// Returns the minimum object size for an object of the given class type
973 /// (or a class derived from it).
974 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
975
976 /// Returns the minimum object size for an object of the given type.
977 CharUnits getMinimumObjectSize(QualType Ty) {
978 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
979 return getMinimumClassObjectSize(CD: RD);
980 return getContext().getTypeSizeInChars(T: Ty);
981 }
982
983 /// Returns the assumed alignment of a virtual base of a class.
984 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
985 const CXXRecordDecl *Derived,
986 const CXXRecordDecl *VBase);
987
988 /// Given a class pointer with an actual known alignment, and the
989 /// expected alignment of an object at a dynamic offset w.r.t that
990 /// pointer, return the alignment to assume at the offset.
991 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
992 const CXXRecordDecl *Class,
993 CharUnits ExpectedTargetAlign);
994
995 CharUnits
996 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
997 CastExpr::path_const_iterator Start,
998 CastExpr::path_const_iterator End);
999
1000 /// Returns the offset from a derived class to a class. Returns null if the
1001 /// offset is 0.
1002 llvm::Constant *
1003 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
1004 CastExpr::path_const_iterator PathBegin,
1005 CastExpr::path_const_iterator PathEnd);
1006
1007 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
1008
1009 /// Fetches the global unique block count.
1010 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
1011
1012 /// Fetches the type of a generic block descriptor.
1013 llvm::Type *getBlockDescriptorType();
1014
1015 /// The type of a generic block literal.
1016 llvm::Type *getGenericBlockLiteralType();
1017
1018 /// Gets the address of a block which requires no captures.
1019 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
1020
1021 /// Returns the address of a block which requires no caputres, or null if
1022 /// we've yet to emit the block for BE.
1023 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
1024 return EmittedGlobalBlocks.lookup(Val: BE);
1025 }
1026
1027 /// Notes that BE's global block is available via Addr. Asserts that BE
1028 /// isn't already emitted.
1029 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
1030
1031 /// Return a pointer to a constant CFString object for the given string.
1032 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
1033
1034 /// Return a constant array for the given string.
1035 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
1036
1037 /// Return a pointer to a constant array for the given string literal.
1038 ConstantAddress
1039 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
1040 StringRef Name = ".str");
1041
1042 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1043 ConstantAddress
1044 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
1045
1046 /// Returns a pointer to a character array containing the literal and a
1047 /// terminating '\0' character. The result has pointer to array type.
1048 ///
1049 /// \param GlobalName If provided, the name to use for the global (if one is
1050 /// created).
1051 ConstantAddress
1052 GetAddrOfConstantCString(const std::string &Str,
1053 const char *GlobalName = nullptr);
1054
1055 /// Returns a pointer to a constant global variable for the given file-scope
1056 /// compound literal expression.
1057 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
1058
1059 /// If it's been emitted already, returns the GlobalVariable corresponding to
1060 /// a compound literal. Otherwise, returns null.
1061 llvm::GlobalVariable *
1062 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
1063
1064 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1065 /// emitted.
1066 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
1067 llvm::GlobalVariable *GV);
1068
1069 /// Returns a pointer to a global variable representing a temporary
1070 /// with static or thread storage duration.
1071 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
1072 const Expr *Inner);
1073
1074 /// Retrieve the record type that describes the state of an
1075 /// Objective-C fast enumeration loop (for..in).
1076 QualType getObjCFastEnumerationStateType();
1077
1078 // Produce code for this constructor/destructor. This method doesn't try
1079 // to apply any ABI rules about which other constructors/destructors
1080 // are needed or if they are alias to each other.
1081 llvm::Function *codegenCXXStructor(GlobalDecl GD);
1082
1083 /// Return the address of the constructor/destructor of the given type.
1084 llvm::Constant *
1085 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1086 llvm::FunctionType *FnType = nullptr,
1087 bool DontDefer = false,
1088 ForDefinition_t IsForDefinition = NotForDefinition) {
1089 return cast<llvm::Constant>(Val: getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1090 DontDefer,
1091 IsForDefinition)
1092 .getCallee());
1093 }
1094
1095 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1096 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1097 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1098 ForDefinition_t IsForDefinition = NotForDefinition);
1099
1100 /// Given a builtin id for a function like "__builtin_fabsf", return a
1101 /// Function* for "fabsf".
1102 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1103 unsigned BuiltinID);
1104
1105 llvm::Function *getIntrinsic(unsigned IID,
1106 ArrayRef<llvm::Type *> Tys = std::nullopt);
1107
1108 /// Emit code for a single top level declaration.
1109 void EmitTopLevelDecl(Decl *D);
1110
1111 /// Stored a deferred empty coverage mapping for an unused
1112 /// and thus uninstrumented top level declaration.
1113 void AddDeferredUnusedCoverageMapping(Decl *D);
1114
1115 /// Remove the deferred empty coverage mapping as this
1116 /// declaration is actually instrumented.
1117 void ClearUnusedCoverageMapping(const Decl *D);
1118
1119 /// Emit all the deferred coverage mappings
1120 /// for the uninstrumented functions.
1121 void EmitDeferredUnusedCoverageMappings();
1122
1123 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1124 void EmitMainVoidAlias();
1125
1126 /// Tell the consumer that this variable has been instantiated.
1127 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1128
1129 /// If the declaration has internal linkage but is inside an
1130 /// extern "C" linkage specification, prepare to emit an alias for it
1131 /// to the expected name.
1132 template<typename SomeDecl>
1133 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1134
1135 /// Add a global to a list to be added to the llvm.used metadata.
1136 void addUsedGlobal(llvm::GlobalValue *GV);
1137
1138 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1139 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1140
1141 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1142 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
1143
1144 /// Add a destructor and object to add to the C++ global destructor function.
1145 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1146 CXXGlobalDtorsOrStermFinalizers.emplace_back(Args: DtorFn.getFunctionType(),
1147 Args: DtorFn.getCallee(), Args&: Object);
1148 }
1149
1150 /// Add an sterm finalizer to the C++ global cleanup function.
1151 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1152 CXXGlobalDtorsOrStermFinalizers.emplace_back(Args: DtorFn.getFunctionType(),
1153 Args: DtorFn.getCallee(), Args: nullptr);
1154 }
1155
1156 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1157 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
1158 int Priority) {
1159 AddGlobalDtor(Dtor: StermFinalizer, Priority);
1160 }
1161
1162 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
1163 int Priority) {
1164 OrderGlobalInitsOrStermFinalizers Key(Priority,
1165 PrioritizedCXXStermFinalizers.size());
1166 PrioritizedCXXStermFinalizers.push_back(
1167 Elt: std::make_pair(x&: Key, y&: StermFinalizer));
1168 }
1169
1170 /// Create or return a runtime function declaration with the specified type
1171 /// and name. If \p AssumeConvergent is true, the call will have the
1172 /// convergent attribute added.
1173 llvm::FunctionCallee
1174 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1175 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1176 bool Local = false, bool AssumeConvergent = false);
1177
1178 /// Create a new runtime global variable with the specified type and name.
1179 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1180 StringRef Name);
1181
1182 ///@name Custom Blocks Runtime Interfaces
1183 ///@{
1184
1185 llvm::Constant *getNSConcreteGlobalBlock();
1186 llvm::Constant *getNSConcreteStackBlock();
1187 llvm::FunctionCallee getBlockObjectAssign();
1188 llvm::FunctionCallee getBlockObjectDispose();
1189
1190 ///@}
1191
1192 llvm::Function *getLLVMLifetimeStartFn();
1193 llvm::Function *getLLVMLifetimeEndFn();
1194
1195 // Make sure that this type is translated.
1196 void UpdateCompletedType(const TagDecl *TD);
1197
1198 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1199
1200 /// Emit type info if type of an expression is a variably modified
1201 /// type. Also emit proper debug info for cast types.
1202 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1203 CodeGenFunction *CGF = nullptr);
1204
1205 /// Return the result of value-initializing the given type, i.e. a null
1206 /// expression of the given type. This is usually, but not always, an LLVM
1207 /// null constant.
1208 llvm::Constant *EmitNullConstant(QualType T);
1209
1210 /// Return a null constant appropriate for zero-initializing a base class with
1211 /// the given type. This is usually, but not always, an LLVM null constant.
1212 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1213
1214 /// Emit a general error that something can't be done.
1215 void Error(SourceLocation loc, StringRef error);
1216
1217 /// Print out an error that codegen doesn't support the specified stmt yet.
1218 void ErrorUnsupported(const Stmt *S, const char *Type);
1219
1220 /// Print out an error that codegen doesn't support the specified decl yet.
1221 void ErrorUnsupported(const Decl *D, const char *Type);
1222
1223 /// Set the attributes on the LLVM function for the given decl and function
1224 /// info. This applies attributes necessary for handling the ABI as well as
1225 /// user specified attributes like section.
1226 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1227 const CGFunctionInfo &FI);
1228
1229 /// Set the LLVM function attributes (sext, zext, etc).
1230 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1231 llvm::Function *F, bool IsThunk);
1232
1233 /// Set the LLVM function attributes which only apply to a function
1234 /// definition.
1235 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1236
1237 /// Set the LLVM function attributes that represent floating point
1238 /// environment.
1239 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
1240
1241 /// Return true iff the given type uses 'sret' when used as a return type.
1242 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1243
1244 /// Return true iff the given type uses an argument slot when 'sret' is used
1245 /// as a return type.
1246 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1247
1248 /// Return true iff the given type uses 'fpret' when used as a return type.
1249 bool ReturnTypeUsesFPRet(QualType ResultType);
1250
1251 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1252 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1253
1254 /// Get the LLVM attributes and calling convention to use for a particular
1255 /// function type.
1256 ///
1257 /// \param Name - The function name.
1258 /// \param Info - The function type information.
1259 /// \param CalleeInfo - The callee information these attributes are being
1260 /// constructed for. If valid, the attributes applied to this decl may
1261 /// contribute to the function attributes and calling convention.
1262 /// \param Attrs [out] - On return, the attribute list to use.
1263 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1264 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1265 CGCalleeInfo CalleeInfo,
1266 llvm::AttributeList &Attrs, unsigned &CallingConv,
1267 bool AttrOnCallSite, bool IsThunk);
1268
1269 /// Adjust Memory attribute to ensure that the BE gets the right attribute
1270 // in order to generate the library call or the intrinsic for the function
1271 // name 'Name'.
1272 void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo,
1273 llvm::AttributeList &Attrs);
1274
1275 /// Like the overload taking a `Function &`, but intended specifically
1276 /// for frontends that want to build on Clang's target-configuration logic.
1277 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1278
1279 StringRef getMangledName(GlobalDecl GD);
1280 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1281 const GlobalDecl getMangledNameDecl(StringRef);
1282
1283 void EmitTentativeDefinition(const VarDecl *D);
1284
1285 void EmitExternalDeclaration(const VarDecl *D);
1286
1287 void EmitVTable(CXXRecordDecl *Class);
1288
1289 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1290
1291 /// Appends Opts to the "llvm.linker.options" metadata value.
1292 void AppendLinkerOptions(StringRef Opts);
1293
1294 /// Appends a detect mismatch command to the linker options.
1295 void AddDetectMismatch(StringRef Name, StringRef Value);
1296
1297 /// Appends a dependent lib to the appropriate metadata value.
1298 void AddDependentLib(StringRef Lib);
1299
1300
1301 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1302
1303 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1304 F->setLinkage(getFunctionLinkage(GD));
1305 }
1306
1307 /// Return the appropriate linkage for the vtable, VTT, and type information
1308 /// of the given class.
1309 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1310
1311 /// Return the store size, in character units, of the given LLVM type.
1312 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1313
1314 /// Returns LLVM linkage for a declarator.
1315 llvm::GlobalValue::LinkageTypes
1316 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage);
1317
1318 /// Returns LLVM linkage for a declarator.
1319 llvm::GlobalValue::LinkageTypes
1320 getLLVMLinkageVarDefinition(const VarDecl *VD);
1321
1322 /// Emit all the global annotations.
1323 void EmitGlobalAnnotations();
1324
1325 /// Emit an annotation string.
1326 llvm::Constant *EmitAnnotationString(StringRef Str);
1327
1328 /// Emit the annotation's translation unit.
1329 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1330
1331 /// Emit the annotation line number.
1332 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1333
1334 /// Emit additional args of the annotation.
1335 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
1336
1337 /// Generate the llvm::ConstantStruct which contains the annotation
1338 /// information for a given GlobalValue. The annotation struct is
1339 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1340 /// GlobalValue being annotated. The second field is the constant string
1341 /// created from the AnnotateAttr's annotation. The third field is a constant
1342 /// string containing the name of the translation unit. The fourth field is
1343 /// the line number in the file of the annotated value declaration.
1344 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1345 const AnnotateAttr *AA,
1346 SourceLocation L);
1347
1348 /// Add global annotations that are set on D, for the global GV. Those
1349 /// annotations are emitted during finalization of the LLVM code.
1350 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1351
1352 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
1353 SourceLocation Loc) const;
1354
1355 bool isInNoSanitizeList(SanitizerMask Kind, llvm::GlobalVariable *GV,
1356 SourceLocation Loc, QualType Ty,
1357 StringRef Category = StringRef()) const;
1358
1359 /// Imbue XRay attributes to a function, applying the always/never attribute
1360 /// lists in the process. Returns true if we did imbue attributes this way,
1361 /// false otherwise.
1362 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1363 StringRef Category = StringRef()) const;
1364
1365 /// \returns true if \p Fn at \p Loc should be excluded from profile
1366 /// instrumentation by the SCL passed by \p -fprofile-list.
1367 ProfileList::ExclusionType
1368 isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const;
1369
1370 /// \returns true if \p Fn at \p Loc should be excluded from profile
1371 /// instrumentation.
1372 ProfileList::ExclusionType
1373 isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
1374 SourceLocation Loc) const;
1375
1376 SanitizerMetadata *getSanitizerMetadata() {
1377 return SanitizerMD.get();
1378 }
1379
1380 void addDeferredVTable(const CXXRecordDecl *RD) {
1381 DeferredVTables.push_back(x: RD);
1382 }
1383
1384 /// Emit code for a single global function or var decl. Forward declarations
1385 /// are emitted lazily.
1386 void EmitGlobal(GlobalDecl D);
1387
1388 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1389
1390 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1391
1392 /// Set attributes which are common to any form of a global definition (alias,
1393 /// Objective-C method, function, global variable).
1394 ///
1395 /// NOTE: This should only be called for definitions.
1396 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1397
1398 void addReplacement(StringRef Name, llvm::Constant *C);
1399
1400 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1401
1402 /// Emit a code for threadprivate directive.
1403 /// \param D Threadprivate declaration.
1404 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1405
1406 /// Emit a code for declare reduction construct.
1407 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1408 CodeGenFunction *CGF = nullptr);
1409
1410 /// Emit a code for declare mapper construct.
1411 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1412 CodeGenFunction *CGF = nullptr);
1413
1414 /// Emit a code for requires directive.
1415 /// \param D Requires declaration
1416 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1417
1418 /// Emit a code for the allocate directive.
1419 /// \param D The allocate declaration
1420 void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
1421
1422 /// Return the alignment specified in an allocate directive, if present.
1423 std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD);
1424
1425 /// Returns whether the given record has hidden LTO visibility and therefore
1426 /// may participate in (single-module) CFI and whole-program vtable
1427 /// optimization.
1428 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1429
1430 /// Returns whether the given record has public LTO visibility (regardless of
1431 /// -lto-whole-program-visibility) and therefore may not participate in
1432 /// (single-module) CFI and whole-program vtable optimization.
1433 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD);
1434
1435 /// Returns the vcall visibility of the given type. This is the scope in which
1436 /// a virtual function call could be made which ends up being dispatched to a
1437 /// member function of this class. This scope can be wider than the visibility
1438 /// of the class itself when the class has a more-visible dynamic base class.
1439 /// The client should pass in an empty Visited set, which is used to prevent
1440 /// redundant recursive processing.
1441 llvm::GlobalObject::VCallVisibility
1442 GetVCallVisibilityLevel(const CXXRecordDecl *RD,
1443 llvm::DenseSet<const CXXRecordDecl *> &Visited);
1444
1445 /// Emit type metadata for the given vtable using the given layout.
1446 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1447 llvm::GlobalVariable *VTable,
1448 const VTableLayout &VTLayout);
1449
1450 llvm::Type *getVTableComponentType() const;
1451
1452 /// Generate a cross-DSO type identifier for MD.
1453 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1454
1455 /// Generate a KCFI type identifier for T.
1456 llvm::ConstantInt *CreateKCFITypeId(QualType T);
1457
1458 /// Create a metadata identifier for the given type. This may either be an
1459 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1460 /// internal identifiers).
1461 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1462
1463 /// Create a metadata identifier that is intended to be used to check virtual
1464 /// calls via a member function pointer.
1465 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1466
1467 /// Create a metadata identifier for the generalization of the given type.
1468 /// This may either be an MDString (for external identifiers) or a distinct
1469 /// unnamed MDNode (for internal identifiers).
1470 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1471
1472 /// Create and attach type metadata to the given function.
1473 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1474 llvm::Function *F);
1475
1476 /// Set type metadata to the given function.
1477 void setKCFIType(const FunctionDecl *FD, llvm::Function *F);
1478
1479 /// Emit KCFI type identifier constants and remove unused identifiers.
1480 void finalizeKCFITypes();
1481
1482 /// Whether this function's return type has no side effects, and thus may
1483 /// be trivially discarded if it is unused.
1484 bool MayDropFunctionReturn(const ASTContext &Context,
1485 QualType ReturnType) const;
1486
1487 /// Returns whether this module needs the "all-vtables" type identifier.
1488 bool NeedAllVtablesTypeId() const;
1489
1490 /// Create and attach type metadata for the given vtable.
1491 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1492 const CXXRecordDecl *RD);
1493
1494 /// Return a vector of most-base classes for RD. This is used to implement
1495 /// control flow integrity checks for member function pointers.
1496 ///
1497 /// A most-base class of a class C is defined as a recursive base class of C,
1498 /// including C itself, that does not have any bases.
1499 SmallVector<const CXXRecordDecl *, 0>
1500 getMostBaseClasses(const CXXRecordDecl *RD);
1501
1502 /// Get the declaration of std::terminate for the platform.
1503 llvm::FunctionCallee getTerminateFn();
1504
1505 llvm::SanitizerStatReport &getSanStats();
1506
1507 llvm::Value *
1508 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1509
1510 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1511 /// information in the program executable. The argument information stored
1512 /// includes the argument name, its type, the address and access qualifiers
1513 /// used. This helper can be used to generate metadata for source code kernel
1514 /// function as well as generated implicitly kernels. If a kernel is generated
1515 /// implicitly null value has to be passed to the last two parameters,
1516 /// otherwise all parameters must have valid non-null values.
1517 /// \param FN is a pointer to IR function being generated.
1518 /// \param FD is a pointer to function declaration if any.
1519 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1520 void GenKernelArgMetadata(llvm::Function *FN,
1521 const FunctionDecl *FD = nullptr,
1522 CodeGenFunction *CGF = nullptr);
1523
1524 /// Get target specific null pointer.
1525 /// \param T is the LLVM type of the null pointer.
1526 /// \param QT is the clang QualType of the null pointer.
1527 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1528
1529 CharUnits getNaturalTypeAlignment(QualType T,
1530 LValueBaseInfo *BaseInfo = nullptr,
1531 TBAAAccessInfo *TBAAInfo = nullptr,
1532 bool forPointeeType = false);
1533 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1534 LValueBaseInfo *BaseInfo = nullptr,
1535 TBAAAccessInfo *TBAAInfo = nullptr);
1536 bool stopAutoInit();
1537
1538 /// Print the postfix for externalized static variable or kernels for single
1539 /// source offloading languages CUDA and HIP. The unique postfix is created
1540 /// using either the CUID argument, or the file's UniqueID and active macros.
1541 /// The fallback method without a CUID requires that the offloading toolchain
1542 /// does not define separate macros via the -cc1 options.
1543 void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
1544 const Decl *D) const;
1545
1546 /// Move some lazily-emitted states to the NewBuilder. This is especially
1547 /// essential for the incremental parsing environment like Clang Interpreter,
1548 /// because we'll lose all important information after each repl.
1549 void moveLazyEmissionStates(CodeGenModule *NewBuilder);
1550
1551 /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F.
1552 /// If \p MaxThreadsVal is not nullptr, the max threads value is stored in it,
1553 /// if a valid one was found.
1554 void handleCUDALaunchBoundsAttr(llvm::Function *F,
1555 const CUDALaunchBoundsAttr *A,
1556 int32_t *MaxThreadsVal = nullptr,
1557 int32_t *MinBlocksVal = nullptr,
1558 int32_t *MaxClusterRankVal = nullptr);
1559
1560 /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute
1561 /// to \p F. Alternatively, the work group size can be taken from a \p
1562 /// ReqdWGS. If \p MinThreadsVal is not nullptr, the min threads value is
1563 /// stored in it, if a valid one was found. If \p MaxThreadsVal is not
1564 /// nullptr, the max threads value is stored in it, if a valid one was found.
1565 void handleAMDGPUFlatWorkGroupSizeAttr(
1566 llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A,
1567 const ReqdWorkGroupSizeAttr *ReqdWGS = nullptr,
1568 int32_t *MinThreadsVal = nullptr, int32_t *MaxThreadsVal = nullptr);
1569
1570 /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F.
1571 void handleAMDGPUWavesPerEUAttr(llvm::Function *F,
1572 const AMDGPUWavesPerEUAttr *A);
1573
1574 llvm::Constant *
1575 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
1576 const VarDecl *D,
1577 ForDefinition_t IsForDefinition = NotForDefinition);
1578
1579 // FIXME: Hardcoding priority here is gross.
1580 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1581 unsigned LexOrder = ~0U,
1582 llvm::Constant *AssociatedData = nullptr);
1583 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
1584 bool IsDtorAttrFunc = false);
1585
1586private:
1587 llvm::Constant *GetOrCreateLLVMFunction(
1588 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1589 bool DontDefer = false, bool IsThunk = false,
1590 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1591 ForDefinition_t IsForDefinition = NotForDefinition);
1592
1593 // Adds a declaration to the list of multi version functions if not present.
1594 void AddDeferredMultiVersionResolverToEmit(GlobalDecl GD);
1595
1596 // References to multiversion functions are resolved through an implicitly
1597 // defined resolver function. This function is responsible for creating
1598 // the resolver symbol for the provided declaration. The value returned
1599 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
1600 // that feature and for a regular function (llvm::GlobalValue) otherwise.
1601 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD);
1602
1603 // In scenarios where a function is not known to be a multiversion function
1604 // until a later declaration, it is sometimes necessary to change the
1605 // previously created mangled name to align with requirements of whatever
1606 // multiversion function kind the function is now known to be. This function
1607 // is responsible for performing such mangled name updates.
1608 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
1609 StringRef &CurName);
1610
1611 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1612 llvm::AttrBuilder &AttrBuilder,
1613 bool SetTargetFeatures = true);
1614 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1615
1616 /// Set function attributes for a function declaration.
1617 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1618 bool IsIncompleteFunction, bool IsThunk);
1619
1620 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1621
1622 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1623 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1624
1625 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1626 void EmitExternalVarDeclaration(const VarDecl *D);
1627 void EmitAliasDefinition(GlobalDecl GD);
1628 void emitIFuncDefinition(GlobalDecl GD);
1629 void emitCPUDispatchDefinition(GlobalDecl GD);
1630 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1631 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1632
1633 // C++ related functions.
1634
1635 void EmitDeclContext(const DeclContext *DC);
1636 void EmitLinkageSpec(const LinkageSpecDecl *D);
1637 void EmitTopLevelStmt(const TopLevelStmtDecl *D);
1638
1639 /// Emit the function that initializes C++ thread_local variables.
1640 void EmitCXXThreadLocalInitFunc();
1641
1642 /// Emit the function that initializes global variables for a C++ Module.
1643 void EmitCXXModuleInitFunc(clang::Module *Primary);
1644
1645 /// Emit the function that initializes C++ globals.
1646 void EmitCXXGlobalInitFunc();
1647
1648 /// Emit the function that performs cleanup associated with C++ globals.
1649 void EmitCXXGlobalCleanUpFunc();
1650
1651 /// Emit the function that initializes the specified global (if PerformInit is
1652 /// true) and registers its destructor.
1653 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1654 llvm::GlobalVariable *Addr,
1655 bool PerformInit);
1656
1657 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1658 llvm::Function *InitFunc, InitSegAttr *ISA);
1659
1660 /// EmitCtorList - Generates a global array of functions and priorities using
1661 /// the given list and name. This array will have appending linkage and is
1662 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1663 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1664
1665 /// Emit any needed decls for which code generation was deferred.
1666 void EmitDeferred();
1667
1668 /// Try to emit external vtables as available_externally if they have emitted
1669 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1670 /// is not allowed to create new references to things that need to be emitted
1671 /// lazily.
1672 void EmitVTablesOpportunistically();
1673
1674 /// Call replaceAllUsesWith on all pairs in Replacements.
1675 void applyReplacements();
1676
1677 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1678 void applyGlobalValReplacements();
1679
1680 void checkAliases();
1681
1682 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1683
1684 /// Register functions annotated with __attribute__((destructor)) using
1685 /// __cxa_atexit, if it is available, or atexit otherwise.
1686 void registerGlobalDtorsWithAtExit();
1687
1688 // When using sinit and sterm functions, unregister
1689 // __attribute__((destructor)) annotated functions which were previously
1690 // registered by the atexit subroutine using unatexit.
1691 void unregisterGlobalDtorsWithUnAtExit();
1692
1693 /// Emit deferred multiversion function resolvers and associated variants.
1694 void emitMultiVersionFunctions();
1695
1696 /// Emit any vtables which we deferred and still have a use for.
1697 void EmitDeferredVTables();
1698
1699 /// Emit a dummy function that reference a CoreFoundation symbol when
1700 /// @available is used on Darwin.
1701 void emitAtAvailableLinkGuard();
1702
1703 /// Emit the llvm.used and llvm.compiler.used metadata.
1704 void emitLLVMUsed();
1705
1706 /// For C++20 Itanium ABI, emit the initializers for the module.
1707 void EmitModuleInitializers(clang::Module *Primary);
1708
1709 /// Emit the link options introduced by imported modules.
1710 void EmitModuleLinkOptions();
1711
1712 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
1713 /// have a resolver name that matches 'Elem' to instead resolve to the name of
1714 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
1715 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
1716 /// may not reference aliases. Redirection is only performed if 'Elem' is only
1717 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
1718 /// redirection is successful, and 'false' is returned otherwise.
1719 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
1720 llvm::GlobalValue *CppFunc);
1721
1722 /// Emit aliases for internal-linkage declarations inside "C" language
1723 /// linkage specifications, giving them the "expected" name where possible.
1724 void EmitStaticExternCAliases();
1725
1726 void EmitDeclMetadata();
1727
1728 /// Emit the Clang version as llvm.ident metadata.
1729 void EmitVersionIdentMetadata();
1730
1731 /// Emit the Clang commandline as llvm.commandline metadata.
1732 void EmitCommandLineMetadata();
1733
1734 /// Emit the module flag metadata used to pass options controlling the
1735 /// the backend to LLVM.
1736 void EmitBackendOptionsMetadata(const CodeGenOptions &CodeGenOpts);
1737
1738 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1739 void EmitOpenCLMetadata();
1740
1741 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1742 /// .gcda files in a way that persists in .bc files.
1743 void EmitCoverageFile();
1744
1745 /// Determine whether the definition must be emitted; if this returns \c
1746 /// false, the definition can be emitted lazily if it's used.
1747 bool MustBeEmitted(const ValueDecl *D);
1748
1749 /// Determine whether the definition can be emitted eagerly, or should be
1750 /// delayed until the end of the translation unit. This is relevant for
1751 /// definitions whose linkage can change, e.g. implicit function instantions
1752 /// which may later be explicitly instantiated.
1753 bool MayBeEmittedEagerly(const ValueDecl *D);
1754
1755 /// Check whether we can use a "simpler", more core exceptions personality
1756 /// function.
1757 void SimplifyPersonality();
1758
1759 /// Helper function for getDefaultFunctionAttributes. Builds a set of function
1760 /// attributes which can be simply added to a function.
1761 void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1762 bool AttrOnCallSite,
1763 llvm::AttrBuilder &FuncAttrs);
1764
1765 /// Helper function for ConstructAttributeList and
1766 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
1767 /// attributes to add to a function with the given properties.
1768 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1769 bool AttrOnCallSite,
1770 llvm::AttrBuilder &FuncAttrs);
1771
1772 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1773 StringRef Suffix);
1774};
1775
1776} // end namespace CodeGen
1777} // end namespace clang
1778
1779#endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
1780

source code of clang/lib/CodeGen/CodeGenModule.h