1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This is the internal per-translation-unit state used for llvm translation.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
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/TargetInfo.h"
30 #include "clang/Basic/XRayLists.h"
31 #include "clang/Lex/PreprocessorOptions.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
49 class IndexedInstrProfReader;
57 class ObjCImplementationDecl;
70 class HeaderSearchOptions;
71 class DiagnosticsEngine;
73 class CXXDestructorDecl;
75 class CoverageSourceInfo;
80 class CodeGenFunction;
85 class CGOpenCLRuntime;
86 class CGOpenMPRuntime;
88 class CoverageMappingModuleGen;
89 class TargetCodeGenInfo;
91 enum ForDefinition_t : bool {
92 NotForDefinition = false,
96 struct OrderGlobalInitsOrStermFinalizers {
97 unsigned int priority;
98 unsigned int lex_order;
99 OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l)
100 : priority(p), lex_order(l) {}
102 bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
103 return priority == RHS.priority && lex_order == RHS.lex_order;
106 bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const {
107 return std::tie(priority, lex_order) <
108 std::tie(RHS.priority, RHS.lex_order);
112 struct ObjCEntrypoints {
113 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
115 /// void objc_alloc(id);
116 llvm::FunctionCallee objc_alloc;
118 /// void objc_allocWithZone(id);
119 llvm::FunctionCallee objc_allocWithZone;
121 /// void objc_alloc_init(id);
122 llvm::FunctionCallee objc_alloc_init;
124 /// void objc_autoreleasePoolPop(void*);
125 llvm::FunctionCallee objc_autoreleasePoolPop;
127 /// void objc_autoreleasePoolPop(void*);
128 /// Note this method is used when we are using exception handling
129 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
131 /// void *objc_autoreleasePoolPush(void);
132 llvm::Function *objc_autoreleasePoolPush;
134 /// id objc_autorelease(id);
135 llvm::Function *objc_autorelease;
137 /// id objc_autorelease(id);
138 /// Note this is the runtime method not the intrinsic.
139 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
141 /// id objc_autoreleaseReturnValue(id);
142 llvm::Function *objc_autoreleaseReturnValue;
144 /// void objc_copyWeak(id *dest, id *src);
145 llvm::Function *objc_copyWeak;
147 /// void objc_destroyWeak(id*);
148 llvm::Function *objc_destroyWeak;
150 /// id objc_initWeak(id*, id);
151 llvm::Function *objc_initWeak;
153 /// id objc_loadWeak(id*);
154 llvm::Function *objc_loadWeak;
156 /// id objc_loadWeakRetained(id*);
157 llvm::Function *objc_loadWeakRetained;
159 /// void objc_moveWeak(id *dest, id *src);
160 llvm::Function *objc_moveWeak;
162 /// id objc_retain(id);
163 llvm::Function *objc_retain;
165 /// id objc_retain(id);
166 /// Note this is the runtime method not the intrinsic.
167 llvm::FunctionCallee objc_retainRuntimeFunction;
169 /// id objc_retainAutorelease(id);
170 llvm::Function *objc_retainAutorelease;
172 /// id objc_retainAutoreleaseReturnValue(id);
173 llvm::Function *objc_retainAutoreleaseReturnValue;
175 /// id objc_retainAutoreleasedReturnValue(id);
176 llvm::Function *objc_retainAutoreleasedReturnValue;
178 /// id objc_retainBlock(id);
179 llvm::Function *objc_retainBlock;
181 /// void objc_release(id);
182 llvm::Function *objc_release;
184 /// void objc_release(id);
185 /// Note this is the runtime method not the intrinsic.
186 llvm::FunctionCallee objc_releaseRuntimeFunction;
188 /// void objc_storeStrong(id*, id);
189 llvm::Function *objc_storeStrong;
191 /// id objc_storeWeak(id*, id);
192 llvm::Function *objc_storeWeak;
194 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
195 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
197 /// A void(void) inline asm to use to mark that the return value of
198 /// a call will be immediately retain.
199 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
201 /// void clang.arc.use(...);
202 llvm::Function *clang_arc_use;
204 /// void clang.arc.noop.use(...);
205 llvm::Function *clang_arc_noop_use;
208 /// This class records statistics on instrumentation based profiling.
209 class InstrProfStats {
210 uint32_t VisitedInMainFile;
211 uint32_t MissingInMainFile;
218 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
220 /// Record that we've visited a function and whether or not that function was
221 /// in the main source file.
222 void addVisited(bool MainFile) {
227 /// Record that a function we've visited has no profile data.
228 void addMissing(bool MainFile) {
233 /// Record that a function we've visited has mismatched profile data.
234 void addMismatched(bool MainFile) { ++Mismatched; }
235 /// Whether or not the stats we've gathered indicate any potential problems.
236 bool hasDiagnostics() { return Missing || Mismatched; }
237 /// Report potential problems we've found to \c Diags.
238 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
241 /// A pair of helper functions for a __block variable.
242 class BlockByrefHelpers : public llvm::FoldingSetNode {
243 // MSVC requires this type to be complete in order to process this
246 llvm::Constant *CopyHelper;
247 llvm::Constant *DisposeHelper;
249 /// The alignment of the field. This is important because
250 /// different offsets to the field within the byref struct need to
251 /// have different helper functions.
254 BlockByrefHelpers(CharUnits alignment)
255 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
256 BlockByrefHelpers(const BlockByrefHelpers &) = default;
257 virtual ~BlockByrefHelpers();
259 void Profile(llvm::FoldingSetNodeID &id) const {
260 id.AddInteger(Alignment.getQuantity());
263 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
265 virtual bool needsCopy() const { return true; }
266 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
268 virtual bool needsDispose() const { return true; }
269 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
272 /// This class organizes the cross-function state that is used while generating
274 class CodeGenModule : public CodeGenTypeCache {
275 CodeGenModule(const CodeGenModule &) = delete;
276 void operator=(const CodeGenModule &) = delete;
280 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
281 Structor(int Priority, llvm::Constant *Initializer,
282 llvm::Constant *AssociatedData)
283 : Priority(Priority), Initializer(Initializer),
284 AssociatedData(AssociatedData) {}
286 llvm::Constant *Initializer;
287 llvm::Constant *AssociatedData;
290 typedef std::vector<Structor> CtorList;
294 const LangOptions &LangOpts;
295 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
296 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
297 const CodeGenOptions &CodeGenOpts;
298 unsigned NumAutoVarInit = 0;
299 llvm::Module &TheModule;
300 DiagnosticsEngine &Diags;
301 const TargetInfo &Target;
302 std::unique_ptr<CGCXXABI> ABI;
303 llvm::LLVMContext &VMContext;
304 std::string ModuleNameHash;
306 std::unique_ptr<CodeGenTBAA> TBAA;
308 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
310 // This should not be moved earlier, since its initialization depends on some
311 // of the previous reference members being already initialized and also checks
312 // if TheTargetCodeGenInfo is NULL
315 /// Holds information about C++ vtables.
316 CodeGenVTables VTables;
318 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
319 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
320 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
321 std::unique_ptr<CGCUDARuntime> CUDARuntime;
322 std::unique_ptr<CGDebugInfo> DebugInfo;
323 std::unique_ptr<ObjCEntrypoints> ObjCData;
324 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
325 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
326 InstrProfStats PGOStats;
327 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
329 // A set of references that have only been seen via a weakref so far. This is
330 // used to remove the weak of the reference if we ever see a direct reference
332 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
334 /// This contains all the decls which have definitions but/ which are deferred
335 /// for emission and therefore should only be output if they are actually
336 /// used. If a decl is in this, then it is known to have not been referenced
338 llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
340 /// This is a list of deferred decls which we have seen that *are* actually
341 /// referenced. These get code generated when the module is done.
342 std::vector<GlobalDecl> DeferredDeclsToEmit;
343 void addDeferredDeclToEmit(GlobalDecl GD) {
344 DeferredDeclsToEmit.emplace_back(GD);
347 /// List of alias we have emitted. Used to make sure that what they point to
348 /// is defined once we get to the end of the of the translation unit.
349 std::vector<GlobalDecl> Aliases;
351 /// List of multiversion functions that have to be emitted. Used to make sure
352 /// we properly emit the iFunc.
353 std::vector<GlobalDecl> MultiVersionFuncs;
355 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
356 ReplacementsTy Replacements;
358 /// List of global values to be replaced with something else. Used when we
359 /// want to replace a GlobalValue but can't identify it by its mangled name
360 /// anymore (because the name is already taken).
361 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
362 GlobalValReplacements;
364 /// Variables for which we've emitted globals containing their constant
365 /// values along with the corresponding globals, for opportunistic reuse.
366 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
368 /// Set of global decls for which we already diagnosed mangled name conflict.
369 /// Required to not issue a warning (on a mangling conflict) multiple times
370 /// for the same decl.
371 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
373 /// A queue of (optional) vtables to consider emitting.
374 std::vector<const CXXRecordDecl*> DeferredVTables;
376 /// A queue of (optional) vtables that may be emitted opportunistically.
377 std::vector<const CXXRecordDecl *> OpportunisticVTables;
379 /// List of global values which are required to be present in the object file;
380 /// bitcast to i8*. This is used for forcing visibility of symbols which may
381 /// otherwise be optimized out.
382 std::vector<llvm::WeakTrackingVH> LLVMUsed;
383 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
385 /// Store the list of global constructors and their respective priorities to
386 /// be emitted when the translation unit is complete.
387 CtorList GlobalCtors;
389 /// Store the list of global destructors and their respective priorities to be
390 /// emitted when the translation unit is complete.
391 CtorList GlobalDtors;
393 /// An ordered map of canonical GlobalDecls to their mangled names.
394 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
395 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
397 /// Global annotations.
398 std::vector<llvm::Constant*> Annotations;
400 /// Map used to get unique annotation strings.
401 llvm::StringMap<llvm::Constant*> AnnotationStrings;
403 /// Used for uniquing of annotation arguments.
404 llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
406 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
408 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
409 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
410 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
411 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
413 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
414 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
416 /// Map used to get unique type descriptor constants for sanitizers.
417 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
419 /// Map used to track internal linkage functions declared within
420 /// extern "C" regions.
421 typedef llvm::MapVector<IdentifierInfo *,
422 llvm::GlobalValue *> StaticExternCMap;
423 StaticExternCMap StaticExternCValues;
425 /// thread_local variables defined or used in this TU.
426 std::vector<const VarDecl *> CXXThreadLocals;
428 /// thread_local variables with initializers that need to run
429 /// before any thread_local variable in this TU is odr-used.
430 std::vector<llvm::Function *> CXXThreadLocalInits;
431 std::vector<const VarDecl *> CXXThreadLocalInitVars;
433 /// Global variables with initializers that need to run before main.
434 std::vector<llvm::Function *> CXXGlobalInits;
436 /// When a C++ decl with an initializer is deferred, null is
437 /// appended to CXXGlobalInits, and the index of that null is placed
438 /// here so that the initializer will be performed in the correct
439 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
440 /// that we don't re-emit the initializer.
441 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
443 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
446 struct GlobalInitPriorityCmp {
447 bool operator()(const GlobalInitData &LHS,
448 const GlobalInitData &RHS) const {
449 return LHS.first.priority < RHS.first.priority;
453 /// Global variables with initializers whose order of initialization is set by
454 /// init_priority attribute.
455 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
457 /// Global destructor functions and arguments that need to run on termination.
458 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
459 /// functions, which also run on unloading a shared library.
460 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
462 CXXGlobalDtorsOrStermFinalizer_t;
463 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
464 CXXGlobalDtorsOrStermFinalizers;
466 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
469 struct StermFinalizerPriorityCmp {
470 bool operator()(const StermFinalizerData &LHS,
471 const StermFinalizerData &RHS) const {
472 return LHS.first.priority < RHS.first.priority;
476 /// Global variables with sterm finalizers whose order of initialization is
477 /// set by init_priority attribute.
478 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
480 /// The complete set of modules that has been imported.
481 llvm::SetVector<clang::Module *> ImportedModules;
483 /// The set of modules for which the module initializers
484 /// have been emitted.
485 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
487 /// A vector of metadata strings for linker options.
488 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
490 /// A vector of metadata strings for dependent libraries for ELF.
491 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
493 /// @name Cache for Objective-C runtime types
496 /// Cached reference to the class for constant strings. This value has type
497 /// int * but is actually an Obj-C class pointer.
498 llvm::WeakTrackingVH CFConstantStringClassRef;
500 /// The type used to describe the state of a fast enumeration in
501 /// Objective-C's for..in loop.
502 QualType ObjCFastEnumerationStateType;
506 /// Lazily create the Objective-C runtime
507 void createObjCRuntime();
509 void createOpenCLRuntime();
510 void createOpenMPRuntime();
511 void createCUDARuntime();
513 bool isTriviallyRecursive(const FunctionDecl *F);
514 bool shouldEmitFunction(GlobalDecl GD);
515 bool shouldOpportunisticallyEmitVTables();
516 /// Map used to be sure we don't emit the same CompoundLiteral twice.
517 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
518 EmittedCompoundLiterals;
520 /// Map of the global blocks we've emitted, so that we don't have to re-emit
521 /// them if the constexpr evaluator gets aggressive.
522 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
524 /// @name Cache for Blocks Runtime Globals
527 llvm::Constant *NSConcreteGlobalBlock = nullptr;
528 llvm::Constant *NSConcreteStackBlock = nullptr;
530 llvm::FunctionCallee BlockObjectAssign = nullptr;
531 llvm::FunctionCallee BlockObjectDispose = nullptr;
533 llvm::Type *BlockDescriptorType = nullptr;
534 llvm::Type *GenericBlockLiteralType = nullptr;
537 int GlobalUniqueCount;
540 GlobalDecl initializedGlobalDecl;
544 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
545 llvm::Function *LifetimeStartFn = nullptr;
547 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
548 llvm::Function *LifetimeEndFn = nullptr;
550 std::unique_ptr<SanitizerMetadata> SanitizerMD;
552 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
554 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
556 /// Mapping from canonical types to their metadata identifiers. We need to
557 /// maintain this mapping because identifiers may be formed from distinct
559 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
560 MetadataTypeMap MetadataIdMap;
561 MetadataTypeMap VirtualMetadataIdMap;
562 MetadataTypeMap GeneralizedMetadataIdMap;
565 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
566 const PreprocessorOptions &ppopts,
567 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
568 DiagnosticsEngine &Diags,
569 CoverageSourceInfo *CoverageInfo = nullptr);
575 /// Finalize LLVM code generation.
578 /// Return true if we should emit location information for expressions.
579 bool getExpressionLocationsEnabled() const;
581 /// Return a reference to the configured Objective-C runtime.
582 CGObjCRuntime &getObjCRuntime() {
583 if (!ObjCRuntime) createObjCRuntime();
587 /// Return true iff an Objective-C runtime has been configured.
588 bool hasObjCRuntime() { return !!ObjCRuntime; }
590 const std::string &getModuleNameHash() const { return ModuleNameHash; }
592 /// Return a reference to the configured OpenCL runtime.
593 CGOpenCLRuntime &getOpenCLRuntime() {
594 assert(OpenCLRuntime != nullptr);
595 return *OpenCLRuntime;
598 /// Return a reference to the configured OpenMP runtime.
599 CGOpenMPRuntime &getOpenMPRuntime() {
600 assert(OpenMPRuntime != nullptr);
601 return *OpenMPRuntime;
604 /// Return a reference to the configured CUDA runtime.
605 CGCUDARuntime &getCUDARuntime() {
606 assert(CUDARuntime != nullptr);
610 ObjCEntrypoints &getObjCEntrypoints() const {
611 assert(ObjCData != nullptr);
615 // Version checking functions, used to implement ObjC's @available:
616 // i32 @__isOSVersionAtLeast(i32, i32, i32)
617 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
618 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
619 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
621 InstrProfStats &getPGOStats() { return PGOStats; }
622 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
624 CoverageMappingModuleGen *getCoverageMapping() const {
625 return CoverageMapping.get();
628 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
629 return StaticLocalDeclMap[D];
631 void setStaticLocalDeclAddress(const VarDecl *D,
633 StaticLocalDeclMap[D] = C;
637 getOrCreateStaticVarDecl(const VarDecl &D,
638 llvm::GlobalValue::LinkageTypes Linkage);
640 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
641 return StaticLocalDeclGuardMap[D];
643 void setStaticLocalDeclGuardAddress(const VarDecl *D,
644 llvm::GlobalVariable *C) {
645 StaticLocalDeclGuardMap[D] = C;
648 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
651 bool lookupRepresentativeDecl(StringRef MangledName,
652 GlobalDecl &Result) const;
654 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
655 return AtomicSetterHelperFnMap[Ty];
657 void setAtomicSetterHelperFnMap(QualType Ty,
658 llvm::Constant *Fn) {
659 AtomicSetterHelperFnMap[Ty] = Fn;
662 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
663 return AtomicGetterHelperFnMap[Ty];
665 void setAtomicGetterHelperFnMap(QualType Ty,
666 llvm::Constant *Fn) {
667 AtomicGetterHelperFnMap[Ty] = Fn;
670 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
671 return TypeDescriptorMap[Ty];
673 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
674 TypeDescriptorMap[Ty] = C;
677 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
679 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
680 if (!NoObjCARCExceptionsMetadata)
681 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
682 return NoObjCARCExceptionsMetadata;
685 ASTContext &getContext() const { return Context; }
686 const LangOptions &getLangOpts() const { return LangOpts; }
687 const HeaderSearchOptions &getHeaderSearchOpts()
688 const { return HeaderSearchOpts; }
689 const PreprocessorOptions &getPreprocessorOpts()
690 const { return PreprocessorOpts; }
691 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
692 llvm::Module &getModule() const { return TheModule; }
693 DiagnosticsEngine &getDiags() const { return Diags; }
694 const llvm::DataLayout &getDataLayout() const {
695 return TheModule.getDataLayout();
697 const TargetInfo &getTarget() const { return Target; }
698 const llvm::Triple &getTriple() const { return Target.getTriple(); }
699 bool supportsCOMDAT() const;
700 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
702 CGCXXABI &getCXXABI() const { return *ABI; }
703 llvm::LLVMContext &getLLVMContext() { return VMContext; }
705 bool shouldUseTBAA() const { return TBAA != nullptr; }
707 const TargetCodeGenInfo &getTargetCodeGenInfo();
709 CodeGenTypes &getTypes() { return Types; }
711 CodeGenVTables &getVTables() { return VTables; }
713 ItaniumVTableContext &getItaniumVTableContext() {
714 return VTables.getItaniumVTableContext();
717 MicrosoftVTableContext &getMicrosoftVTableContext() {
718 return VTables.getMicrosoftVTableContext();
721 CtorList &getGlobalCtors() { return GlobalCtors; }
722 CtorList &getGlobalDtors() { return GlobalDtors; }
724 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
726 llvm::MDNode *getTBAATypeInfo(QualType QTy);
728 /// getTBAAAccessInfo - Get TBAA information that describes an access to
729 /// an object of the given type.
730 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
732 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
733 /// access to a virtual table pointer.
734 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
736 llvm::MDNode *getTBAAStructInfo(QualType QTy);
738 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
739 /// type. Return null if the type is not suitable for use in TBAA access tags.
740 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
742 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
743 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
745 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
747 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
748 TBAAAccessInfo TargetInfo);
750 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
751 /// purposes of conditional operator.
752 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
753 TBAAAccessInfo InfoB);
755 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
756 /// purposes of memory transfer calls.
757 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
758 TBAAAccessInfo SrcInfo);
760 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
762 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
763 if (Base.getTBAAInfo().isMayAlias())
764 return TBAAAccessInfo::getMayAliasInfo();
765 return getTBAAAccessInfo(AccessType);
768 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
770 bool isPaddedAtomicType(QualType type);
771 bool isPaddedAtomicType(const AtomicType *type);
773 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
774 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
775 TBAAAccessInfo TBAAInfo);
777 /// Adds !invariant.barrier !tag to instruction
778 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
779 const CXXRecordDecl *RD);
781 /// Emit the given number of characters as a value of type size_t.
782 llvm::ConstantInt *getSize(CharUnits numChars);
784 /// Set the visibility for the given LLVM GlobalValue.
785 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
787 void setDSOLocal(llvm::GlobalValue *GV) const;
789 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
790 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
791 /// Set visibility, dllimport/dllexport and dso_local.
792 /// This must be called after dllimport/dllexport is set.
793 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
794 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
796 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
798 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
799 /// variable declaration D.
800 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
802 /// Get LLVM TLS mode from CodeGenOptions.
803 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
805 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
807 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
808 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
809 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
811 llvm_unreachable("unknown visibility!");
814 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
815 ForDefinition_t IsForDefinition
818 /// Will return a global variable of the given type. If a variable with a
819 /// different type already exists then a new variable with the right type
820 /// will be created and all uses of the old variable will be replaced with a
821 /// bitcast to the new variable.
822 llvm::GlobalVariable *
823 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
824 llvm::GlobalValue::LinkageTypes Linkage,
827 llvm::Function *CreateGlobalInitOrCleanUpFunction(
828 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
829 SourceLocation Loc = SourceLocation(), bool TLS = false);
831 /// Return the AST address space of the underlying global variable for D, as
832 /// determined by its declaration. Normally this is the same as the address
833 /// space of D's type, but in CUDA, address spaces are associated with
834 /// declarations, not types. If D is nullptr, return the default address
835 /// space for global variable.
837 /// For languages without explicit address spaces, if D has default address
838 /// space, target-specific global or constant address space may be returned.
839 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
841 /// Return the AST address space of constant literal, which is used to emit
842 /// the constant literal as global variable in LLVM IR.
843 /// Note: This is not necessarily the address space of the constant literal
844 /// in AST. For address space agnostic language, e.g. C++, constant literal
845 /// in AST is always in default address space.
846 LangAS GetGlobalConstantAddressSpace() const;
848 /// Return the llvm::Constant for the address of the given global variable.
849 /// If Ty is non-null and if the global doesn't exist, then it will be created
850 /// with the specified type instead of whatever the normal requested type
851 /// would be. If IsForDefinition is true, it is guaranteed that an actual
852 /// global with type Ty will be returned, not conversion of a variable with
853 /// the same mangled name but some other type.
854 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
855 llvm::Type *Ty = nullptr,
856 ForDefinition_t IsForDefinition
859 /// Return the address of the given function. If Ty is non-null, then this
860 /// function will use the specified type if it has to create it.
861 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
862 bool ForVTable = false,
863 bool DontDefer = false,
864 ForDefinition_t IsForDefinition
867 // Return the function body address of the given function.
868 llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
870 /// Get the address of the RTTI descriptor for the given type.
871 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
873 /// Get the address of a GUID.
874 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
876 /// Get the address of a template parameter object.
878 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
880 /// Get the address of the thunk for the given global decl.
881 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
884 /// Get a reference to the target of VD.
885 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
887 /// Returns the assumed alignment of an opaque pointer to the given class.
888 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
890 /// Returns the minimum object size for an object of the given class type
891 /// (or a class derived from it).
892 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
894 /// Returns the minimum object size for an object of the given type.
895 CharUnits getMinimumObjectSize(QualType Ty) {
896 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
897 return getMinimumClassObjectSize(RD);
898 return getContext().getTypeSizeInChars(Ty);
901 /// Returns the assumed alignment of a virtual base of a class.
902 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
903 const CXXRecordDecl *Derived,
904 const CXXRecordDecl *VBase);
906 /// Given a class pointer with an actual known alignment, and the
907 /// expected alignment of an object at a dynamic offset w.r.t that
908 /// pointer, return the alignment to assume at the offset.
909 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
910 const CXXRecordDecl *Class,
911 CharUnits ExpectedTargetAlign);
914 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
915 CastExpr::path_const_iterator Start,
916 CastExpr::path_const_iterator End);
918 /// Returns the offset from a derived class to a class. Returns null if the
921 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
922 CastExpr::path_const_iterator PathBegin,
923 CastExpr::path_const_iterator PathEnd);
925 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
927 /// Fetches the global unique block count.
928 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
930 /// Fetches the type of a generic block descriptor.
931 llvm::Type *getBlockDescriptorType();
933 /// The type of a generic block literal.
934 llvm::Type *getGenericBlockLiteralType();
936 /// Gets the address of a block which requires no captures.
937 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
939 /// Returns the address of a block which requires no caputres, or null if
940 /// we've yet to emit the block for BE.
941 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
942 return EmittedGlobalBlocks.lookup(BE);
945 /// Notes that BE's global block is available via Addr. Asserts that BE
946 /// isn't already emitted.
947 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
949 /// Return a pointer to a constant CFString object for the given string.
950 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
952 /// Return a pointer to a constant NSString object for the given string. Or a
953 /// user defined String object as defined via
954 /// -fconstant-string-class=class_name option.
955 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
957 /// Return a constant array for the given string.
958 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
960 /// Return a pointer to a constant array for the given string literal.
962 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
963 StringRef Name = ".str");
965 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
967 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
969 /// Returns a pointer to a character array containing the literal and a
970 /// terminating '\0' character. The result has pointer to array type.
972 /// \param GlobalName If provided, the name to use for the global (if one is
975 GetAddrOfConstantCString(const std::string &Str,
976 const char *GlobalName = nullptr);
978 /// Returns a pointer to a constant global variable for the given file-scope
979 /// compound literal expression.
980 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
982 /// If it's been emitted already, returns the GlobalVariable corresponding to
983 /// a compound literal. Otherwise, returns null.
984 llvm::GlobalVariable *
985 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
987 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
989 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
990 llvm::GlobalVariable *GV);
992 /// Returns a pointer to a global variable representing a temporary
993 /// with static or thread storage duration.
994 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
997 /// Retrieve the record type that describes the state of an
998 /// Objective-C fast enumeration loop (for..in).
999 QualType getObjCFastEnumerationStateType();
1001 // Produce code for this constructor/destructor. This method doesn't try
1002 // to apply any ABI rules about which other constructors/destructors
1003 // are needed or if they are alias to each other.
1004 llvm::Function *codegenCXXStructor(GlobalDecl GD);
1006 /// Return the address of the constructor/destructor of the given type.
1008 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1009 llvm::FunctionType *FnType = nullptr,
1010 bool DontDefer = false,
1011 ForDefinition_t IsForDefinition = NotForDefinition) {
1012 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1018 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1019 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1020 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1021 ForDefinition_t IsForDefinition = NotForDefinition);
1023 /// Given a builtin id for a function like "__builtin_fabsf", return a
1024 /// Function* for "fabsf".
1025 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1026 unsigned BuiltinID);
1028 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
1030 /// Emit code for a single top level declaration.
1031 void EmitTopLevelDecl(Decl *D);
1033 /// Stored a deferred empty coverage mapping for an unused
1034 /// and thus uninstrumented top level declaration.
1035 void AddDeferredUnusedCoverageMapping(Decl *D);
1037 /// Remove the deferred empty coverage mapping as this
1038 /// declaration is actually instrumented.
1039 void ClearUnusedCoverageMapping(const Decl *D);
1041 /// Emit all the deferred coverage mappings
1042 /// for the uninstrumented functions.
1043 void EmitDeferredUnusedCoverageMappings();
1045 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1046 void EmitMainVoidAlias();
1048 /// Tell the consumer that this variable has been instantiated.
1049 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1051 /// If the declaration has internal linkage but is inside an
1052 /// extern "C" linkage specification, prepare to emit an alias for it
1053 /// to the expected name.
1054 template<typename SomeDecl>
1055 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1057 /// Add a global to a list to be added to the llvm.used metadata.
1058 void addUsedGlobal(llvm::GlobalValue *GV);
1060 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1061 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1063 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1064 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
1066 /// Add a destructor and object to add to the C++ global destructor function.
1067 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1068 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1069 DtorFn.getCallee(), Object);
1072 /// Add an sterm finalizer to the C++ global cleanup function.
1073 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1074 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1075 DtorFn.getCallee(), nullptr);
1078 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1079 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
1081 AddGlobalDtor(StermFinalizer, Priority);
1084 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
1086 OrderGlobalInitsOrStermFinalizers Key(Priority,
1087 PrioritizedCXXStermFinalizers.size());
1088 PrioritizedCXXStermFinalizers.push_back(
1089 std::make_pair(Key, StermFinalizer));
1092 /// Create or return a runtime function declaration with the specified type
1093 /// and name. If \p AssumeConvergent is true, the call will have the
1094 /// convergent attribute added.
1095 llvm::FunctionCallee
1096 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1097 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1098 bool Local = false, bool AssumeConvergent = false);
1100 /// Create a new runtime global variable with the specified type and name.
1101 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1104 ///@name Custom Blocks Runtime Interfaces
1107 llvm::Constant *getNSConcreteGlobalBlock();
1108 llvm::Constant *getNSConcreteStackBlock();
1109 llvm::FunctionCallee getBlockObjectAssign();
1110 llvm::FunctionCallee getBlockObjectDispose();
1114 llvm::Function *getLLVMLifetimeStartFn();
1115 llvm::Function *getLLVMLifetimeEndFn();
1117 // Make sure that this type is translated.
1118 void UpdateCompletedType(const TagDecl *TD);
1120 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1122 /// Emit type info if type of an expression is a variably modified
1123 /// type. Also emit proper debug info for cast types.
1124 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1125 CodeGenFunction *CGF = nullptr);
1127 /// Return the result of value-initializing the given type, i.e. a null
1128 /// expression of the given type. This is usually, but not always, an LLVM
1130 llvm::Constant *EmitNullConstant(QualType T);
1132 /// Return a null constant appropriate for zero-initializing a base class with
1133 /// the given type. This is usually, but not always, an LLVM null constant.
1134 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1136 /// Emit a general error that something can't be done.
1137 void Error(SourceLocation loc, StringRef error);
1139 /// Print out an error that codegen doesn't support the specified stmt yet.
1140 void ErrorUnsupported(const Stmt *S, const char *Type);
1142 /// Print out an error that codegen doesn't support the specified decl yet.
1143 void ErrorUnsupported(const Decl *D, const char *Type);
1145 /// Set the attributes on the LLVM function for the given decl and function
1146 /// info. This applies attributes necessary for handling the ABI as well as
1147 /// user specified attributes like section.
1148 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1149 const CGFunctionInfo &FI);
1151 /// Set the LLVM function attributes (sext, zext, etc).
1152 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1153 llvm::Function *F, bool IsThunk);
1155 /// Set the LLVM function attributes which only apply to a function
1157 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1159 /// Set the LLVM function attributes that represent floating point
1161 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
1163 /// Return true iff the given type uses 'sret' when used as a return type.
1164 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1166 /// Return true iff the given type uses an argument slot when 'sret' is used
1167 /// as a return type.
1168 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1170 /// Return true iff the given type uses 'fpret' when used as a return type.
1171 bool ReturnTypeUsesFPRet(QualType ResultType);
1173 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1174 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1176 /// Get the LLVM attributes and calling convention to use for a particular
1179 /// \param Name - The function name.
1180 /// \param Info - The function type information.
1181 /// \param CalleeInfo - The callee information these attributes are being
1182 /// constructed for. If valid, the attributes applied to this decl may
1183 /// contribute to the function attributes and calling convention.
1184 /// \param Attrs [out] - On return, the attribute list to use.
1185 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1186 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1187 CGCalleeInfo CalleeInfo,
1188 llvm::AttributeList &Attrs, unsigned &CallingConv,
1189 bool AttrOnCallSite, bool IsThunk);
1191 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1192 /// though we had emitted it ourselves. We remove any attributes on F that
1193 /// conflict with the attributes we add here.
1195 /// This is useful for adding attrs to bitcode modules that you want to link
1196 /// with but don't control, such as CUDA's libdevice. When linking with such
1197 /// a bitcode library, you might want to set e.g. its functions'
1198 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1199 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1200 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1201 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1202 /// function in the bitcode library!
1204 /// With the exception of fast-math attrs, this will only make the attributes
1205 /// on the function more conservative. But it's unsafe to call this on a
1206 /// function which relies on particular fast-math attributes for correctness.
1207 /// It's up to you to ensure that this is safe.
1208 void addDefaultFunctionDefinitionAttributes(llvm::Function &F);
1210 /// Like the overload taking a `Function &`, but intended specifically
1211 /// for frontends that want to build on Clang's target-configuration logic.
1212 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1214 StringRef getMangledName(GlobalDecl GD);
1215 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1217 void EmitTentativeDefinition(const VarDecl *D);
1219 void EmitExternalDeclaration(const VarDecl *D);
1221 void EmitVTable(CXXRecordDecl *Class);
1223 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1225 /// Appends Opts to the "llvm.linker.options" metadata value.
1226 void AppendLinkerOptions(StringRef Opts);
1228 /// Appends a detect mismatch command to the linker options.
1229 void AddDetectMismatch(StringRef Name, StringRef Value);
1231 /// Appends a dependent lib to the appropriate metadata value.
1232 void AddDependentLib(StringRef Lib);
1235 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1237 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1238 F->setLinkage(getFunctionLinkage(GD));
1241 /// Return the appropriate linkage for the vtable, VTT, and type information
1242 /// of the given class.
1243 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1245 /// Return the store size, in character units, of the given LLVM type.
1246 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1248 /// Returns LLVM linkage for a declarator.
1249 llvm::GlobalValue::LinkageTypes
1250 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1251 bool IsConstantVariable);
1253 /// Returns LLVM linkage for a declarator.
1254 llvm::GlobalValue::LinkageTypes
1255 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1257 /// Emit all the global annotations.
1258 void EmitGlobalAnnotations();
1260 /// Emit an annotation string.
1261 llvm::Constant *EmitAnnotationString(StringRef Str);
1263 /// Emit the annotation's translation unit.
1264 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1266 /// Emit the annotation line number.
1267 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1269 /// Emit additional args of the annotation.
1270 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
1272 /// Generate the llvm::ConstantStruct which contains the annotation
1273 /// information for a given GlobalValue. The annotation struct is
1274 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1275 /// GlobalValue being annotated. The second field is the constant string
1276 /// created from the AnnotateAttr's annotation. The third field is a constant
1277 /// string containing the name of the translation unit. The fourth field is
1278 /// the line number in the file of the annotated value declaration.
1279 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1280 const AnnotateAttr *AA,
1283 /// Add global annotations that are set on D, for the global GV. Those
1284 /// annotations are emitted during finalization of the LLVM code.
1285 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1287 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
1288 SourceLocation Loc) const;
1290 bool isInNoSanitizeList(llvm::GlobalVariable *GV, SourceLocation Loc,
1291 QualType Ty, StringRef Category = StringRef()) const;
1293 /// Imbue XRay attributes to a function, applying the always/never attribute
1294 /// lists in the process. Returns true if we did imbue attributes this way,
1295 /// false otherwise.
1296 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1297 StringRef Category = StringRef()) const;
1299 /// Returns true if function at the given location should be excluded from
1300 /// profile instrumentation.
1301 bool isProfileInstrExcluded(llvm::Function *Fn, SourceLocation Loc) const;
1303 SanitizerMetadata *getSanitizerMetadata() {
1304 return SanitizerMD.get();
1307 void addDeferredVTable(const CXXRecordDecl *RD) {
1308 DeferredVTables.push_back(RD);
1311 /// Emit code for a single global function or var decl. Forward declarations
1312 /// are emitted lazily.
1313 void EmitGlobal(GlobalDecl D);
1315 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1317 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1319 /// Set attributes which are common to any form of a global definition (alias,
1320 /// Objective-C method, function, global variable).
1322 /// NOTE: This should only be called for definitions.
1323 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1325 void addReplacement(StringRef Name, llvm::Constant *C);
1327 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1329 /// Emit a code for threadprivate directive.
1330 /// \param D Threadprivate declaration.
1331 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1333 /// Emit a code for declare reduction construct.
1334 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1335 CodeGenFunction *CGF = nullptr);
1337 /// Emit a code for declare mapper construct.
1338 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1339 CodeGenFunction *CGF = nullptr);
1341 /// Emit a code for requires directive.
1342 /// \param D Requires declaration
1343 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1345 /// Emit a code for the allocate directive.
1346 /// \param D The allocate declaration
1347 void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
1349 /// Returns whether the given record has hidden LTO visibility and therefore
1350 /// may participate in (single-module) CFI and whole-program vtable
1352 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1354 /// Returns whether the given record has public std LTO visibility
1355 /// and therefore may not participate in (single-module) CFI and whole-program
1356 /// vtable optimization.
1357 bool HasLTOVisibilityPublicStd(const CXXRecordDecl *RD);
1359 /// Returns the vcall visibility of the given type. This is the scope in which
1360 /// a virtual function call could be made which ends up being dispatched to a
1361 /// member function of this class. This scope can be wider than the visibility
1362 /// of the class itself when the class has a more-visible dynamic base class.
1363 /// The client should pass in an empty Visited set, which is used to prevent
1364 /// redundant recursive processing.
1365 llvm::GlobalObject::VCallVisibility
1366 GetVCallVisibilityLevel(const CXXRecordDecl *RD,
1367 llvm::DenseSet<const CXXRecordDecl *> &Visited);
1369 /// Emit type metadata for the given vtable using the given layout.
1370 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1371 llvm::GlobalVariable *VTable,
1372 const VTableLayout &VTLayout);
1374 /// Generate a cross-DSO type identifier for MD.
1375 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1377 /// Create a metadata identifier for the given type. This may either be an
1378 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1379 /// internal identifiers).
1380 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1382 /// Create a metadata identifier that is intended to be used to check virtual
1383 /// calls via a member function pointer.
1384 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1386 /// Create a metadata identifier for the generalization of the given type.
1387 /// This may either be an MDString (for external identifiers) or a distinct
1388 /// unnamed MDNode (for internal identifiers).
1389 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1391 /// Create and attach type metadata to the given function.
1392 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1395 /// Whether this function's return type has no side effects, and thus may
1396 /// be trivially discarded if it is unused.
1397 bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType);
1399 /// Returns whether this module needs the "all-vtables" type identifier.
1400 bool NeedAllVtablesTypeId() const;
1402 /// Create and attach type metadata for the given vtable.
1403 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1404 const CXXRecordDecl *RD);
1406 /// Return a vector of most-base classes for RD. This is used to implement
1407 /// control flow integrity checks for member function pointers.
1409 /// A most-base class of a class C is defined as a recursive base class of C,
1410 /// including C itself, that does not have any bases.
1411 std::vector<const CXXRecordDecl *>
1412 getMostBaseClasses(const CXXRecordDecl *RD);
1414 /// Get the declaration of std::terminate for the platform.
1415 llvm::FunctionCallee getTerminateFn();
1417 llvm::SanitizerStatReport &getSanStats();
1420 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1422 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1423 /// information in the program executable. The argument information stored
1424 /// includes the argument name, its type, the address and access qualifiers
1425 /// used. This helper can be used to generate metadata for source code kernel
1426 /// function as well as generated implicitly kernels. If a kernel is generated
1427 /// implicitly null value has to be passed to the last two parameters,
1428 /// otherwise all parameters must have valid non-null values.
1429 /// \param FN is a pointer to IR function being generated.
1430 /// \param FD is a pointer to function declaration if any.
1431 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1432 void GenOpenCLArgMetadata(llvm::Function *FN,
1433 const FunctionDecl *FD = nullptr,
1434 CodeGenFunction *CGF = nullptr);
1436 /// Get target specific null pointer.
1437 /// \param T is the LLVM type of the null pointer.
1438 /// \param QT is the clang QualType of the null pointer.
1439 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1441 CharUnits getNaturalTypeAlignment(QualType T,
1442 LValueBaseInfo *BaseInfo = nullptr,
1443 TBAAAccessInfo *TBAAInfo = nullptr,
1444 bool forPointeeType = false);
1445 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1446 LValueBaseInfo *BaseInfo = nullptr,
1447 TBAAAccessInfo *TBAAInfo = nullptr);
1448 bool stopAutoInit();
1450 /// Print the postfix for externalized static variable for single source
1451 /// offloading languages CUDA and HIP.
1452 void printPostfixForExternalizedStaticVar(llvm::raw_ostream &OS) const;
1455 llvm::Constant *GetOrCreateLLVMFunction(
1456 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1457 bool DontDefer = false, bool IsThunk = false,
1458 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1459 ForDefinition_t IsForDefinition = NotForDefinition);
1461 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD,
1463 const FunctionDecl *FD);
1464 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
1465 StringRef &CurName);
1468 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
1470 ForDefinition_t IsForDefinition = NotForDefinition);
1472 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1473 llvm::AttrBuilder &AttrBuilder);
1474 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1476 /// Set function attributes for a function declaration.
1477 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1478 bool IsIncompleteFunction, bool IsThunk);
1480 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1482 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1483 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1485 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1486 void EmitExternalVarDeclaration(const VarDecl *D);
1487 void EmitAliasDefinition(GlobalDecl GD);
1488 void emitIFuncDefinition(GlobalDecl GD);
1489 void emitCPUDispatchDefinition(GlobalDecl GD);
1490 void EmitTargetClonesResolver(GlobalDecl GD);
1491 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1492 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1494 // C++ related functions.
1496 void EmitDeclContext(const DeclContext *DC);
1497 void EmitLinkageSpec(const LinkageSpecDecl *D);
1499 /// Emit the function that initializes C++ thread_local variables.
1500 void EmitCXXThreadLocalInitFunc();
1502 /// Emit the function that initializes C++ globals.
1503 void EmitCXXGlobalInitFunc();
1505 /// Emit the function that performs cleanup associated with C++ globals.
1506 void EmitCXXGlobalCleanUpFunc();
1508 /// Emit the function that initializes the specified global (if PerformInit is
1509 /// true) and registers its destructor.
1510 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1511 llvm::GlobalVariable *Addr,
1514 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1515 llvm::Function *InitFunc, InitSegAttr *ISA);
1517 // FIXME: Hardcoding priority here is gross.
1518 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1519 llvm::Constant *AssociatedData = nullptr);
1520 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
1521 bool IsDtorAttrFunc = false);
1523 /// EmitCtorList - Generates a global array of functions and priorities using
1524 /// the given list and name. This array will have appending linkage and is
1525 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1526 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1528 /// Emit any needed decls for which code generation was deferred.
1529 void EmitDeferred();
1531 /// Try to emit external vtables as available_externally if they have emitted
1532 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1533 /// is not allowed to create new references to things that need to be emitted
1535 void EmitVTablesOpportunistically();
1537 /// Call replaceAllUsesWith on all pairs in Replacements.
1538 void applyReplacements();
1540 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1541 void applyGlobalValReplacements();
1543 void checkAliases();
1545 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1547 /// Register functions annotated with __attribute__((destructor)) using
1548 /// __cxa_atexit, if it is available, or atexit otherwise.
1549 void registerGlobalDtorsWithAtExit();
1551 // When using sinit and sterm functions, unregister
1552 // __attribute__((destructor)) annotated functions which were previously
1553 // registered by the atexit subroutine using unatexit.
1554 void unregisterGlobalDtorsWithUnAtExit();
1556 void emitMultiVersionFunctions();
1558 /// Emit any vtables which we deferred and still have a use for.
1559 void EmitDeferredVTables();
1561 /// Emit a dummy function that reference a CoreFoundation symbol when
1562 /// @available is used on Darwin.
1563 void emitAtAvailableLinkGuard();
1565 /// Emit the llvm.used and llvm.compiler.used metadata.
1566 void emitLLVMUsed();
1568 /// Emit the link options introduced by imported modules.
1569 void EmitModuleLinkOptions();
1571 /// Emit aliases for internal-linkage declarations inside "C" language
1572 /// linkage specifications, giving them the "expected" name where possible.
1573 void EmitStaticExternCAliases();
1575 void EmitDeclMetadata();
1577 /// Emit the Clang version as llvm.ident metadata.
1578 void EmitVersionIdentMetadata();
1580 /// Emit the Clang commandline as llvm.commandline metadata.
1581 void EmitCommandLineMetadata();
1583 /// Emit the module flag metadata used to pass options controlling the
1584 /// the backend to LLVM.
1585 void EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts);
1587 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1588 void EmitOpenCLMetadata();
1590 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1591 /// .gcda files in a way that persists in .bc files.
1592 void EmitCoverageFile();
1594 /// Determine whether the definition must be emitted; if this returns \c
1595 /// false, the definition can be emitted lazily if it's used.
1596 bool MustBeEmitted(const ValueDecl *D);
1598 /// Determine whether the definition can be emitted eagerly, or should be
1599 /// delayed until the end of the translation unit. This is relevant for
1600 /// definitions whose linkage can change, e.g. implicit function instantions
1601 /// which may later be explicitly instantiated.
1602 bool MayBeEmittedEagerly(const ValueDecl *D);
1604 /// Check whether we can use a "simpler", more core exceptions personality
1606 void SimplifyPersonality();
1608 /// Helper function for ConstructAttributeList and
1609 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
1610 /// attributes to add to a function with the given properties.
1611 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1612 bool AttrOnCallSite,
1613 llvm::AttrBuilder &FuncAttrs);
1615 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1619 } // end namespace CodeGen
1620 } // end namespace clang
1622 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H