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/SanitizerBlacklist.h"
29 #include "clang/Basic/XRayLists.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/Transforms/Utils/SanitizerStats.h"
47 class OpenMPIRBuilder;
48 class IndexedInstrProfReader;
57 class ObjCImplementationDecl;
58 class ObjCCategoryImplDecl;
59 class ObjCProtocolDecl;
73 class HeaderSearchOptions;
74 class PreprocessorOptions;
75 class DiagnosticsEngine;
77 class CXXDestructorDecl;
79 class CoverageSourceInfo;
82 struct ParsedTargetAttr;
87 class CodeGenFunction;
92 class CGOpenCLRuntime;
93 class CGOpenMPRuntime;
95 class BlockFieldFlags;
96 class FunctionArgList;
97 class CoverageMappingModuleGen;
98 class TargetCodeGenInfo;
100 enum ForDefinition_t : bool {
101 NotForDefinition = false,
105 struct OrderGlobalInits {
106 unsigned int priority;
107 unsigned int lex_order;
108 OrderGlobalInits(unsigned int p, unsigned int l)
109 : priority(p), lex_order(l) {}
111 bool operator==(const OrderGlobalInits &RHS) const {
112 return priority == RHS.priority && lex_order == RHS.lex_order;
115 bool operator<(const OrderGlobalInits &RHS) const {
116 return std::tie(priority, lex_order) <
117 std::tie(RHS.priority, RHS.lex_order);
121 struct ObjCEntrypoints {
122 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
124 /// void objc_alloc(id);
125 llvm::FunctionCallee objc_alloc;
127 /// void objc_allocWithZone(id);
128 llvm::FunctionCallee objc_allocWithZone;
130 /// void objc_alloc_init(id);
131 llvm::FunctionCallee objc_alloc_init;
133 /// void objc_autoreleasePoolPop(void*);
134 llvm::FunctionCallee objc_autoreleasePoolPop;
136 /// void objc_autoreleasePoolPop(void*);
137 /// Note this method is used when we are using exception handling
138 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
140 /// void *objc_autoreleasePoolPush(void);
141 llvm::Function *objc_autoreleasePoolPush;
143 /// id objc_autorelease(id);
144 llvm::Function *objc_autorelease;
146 /// id objc_autorelease(id);
147 /// Note this is the runtime method not the intrinsic.
148 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
150 /// id objc_autoreleaseReturnValue(id);
151 llvm::Function *objc_autoreleaseReturnValue;
153 /// void objc_copyWeak(id *dest, id *src);
154 llvm::Function *objc_copyWeak;
156 /// void objc_destroyWeak(id*);
157 llvm::Function *objc_destroyWeak;
159 /// id objc_initWeak(id*, id);
160 llvm::Function *objc_initWeak;
162 /// id objc_loadWeak(id*);
163 llvm::Function *objc_loadWeak;
165 /// id objc_loadWeakRetained(id*);
166 llvm::Function *objc_loadWeakRetained;
168 /// void objc_moveWeak(id *dest, id *src);
169 llvm::Function *objc_moveWeak;
171 /// id objc_retain(id);
172 llvm::Function *objc_retain;
174 /// id objc_retain(id);
175 /// Note this is the runtime method not the intrinsic.
176 llvm::FunctionCallee objc_retainRuntimeFunction;
178 /// id objc_retainAutorelease(id);
179 llvm::Function *objc_retainAutorelease;
181 /// id objc_retainAutoreleaseReturnValue(id);
182 llvm::Function *objc_retainAutoreleaseReturnValue;
184 /// id objc_retainAutoreleasedReturnValue(id);
185 llvm::Function *objc_retainAutoreleasedReturnValue;
187 /// id objc_retainBlock(id);
188 llvm::Function *objc_retainBlock;
190 /// void objc_release(id);
191 llvm::Function *objc_release;
193 /// void objc_release(id);
194 /// Note this is the runtime method not the intrinsic.
195 llvm::FunctionCallee objc_releaseRuntimeFunction;
197 /// void objc_storeStrong(id*, id);
198 llvm::Function *objc_storeStrong;
200 /// id objc_storeWeak(id*, id);
201 llvm::Function *objc_storeWeak;
203 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
204 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
206 /// A void(void) inline asm to use to mark that the return value of
207 /// a call will be immediately retain.
208 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
210 /// void clang.arc.use(...);
211 llvm::Function *clang_arc_use;
214 /// This class records statistics on instrumentation based profiling.
215 class InstrProfStats {
216 uint32_t VisitedInMainFile;
217 uint32_t MissingInMainFile;
224 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
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) {
233 /// Record that a function we've visited has no profile data.
234 void addMissing(bool MainFile) {
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);
247 /// A pair of helper functions for a __block variable.
248 class BlockByrefHelpers : public llvm::FoldingSetNode {
249 // MSVC requires this type to be complete in order to process this
252 llvm::Constant *CopyHelper;
253 llvm::Constant *DisposeHelper;
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.
260 BlockByrefHelpers(CharUnits alignment)
261 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
262 BlockByrefHelpers(const BlockByrefHelpers &) = default;
263 virtual ~BlockByrefHelpers();
265 void Profile(llvm::FoldingSetNodeID &id) const {
266 id.AddInteger(Alignment.getQuantity());
269 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
271 virtual bool needsCopy() const { return true; }
272 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
274 virtual bool needsDispose() const { return true; }
275 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
278 /// This class organizes the cross-function state that is used while generating
280 class CodeGenModule : public CodeGenTypeCache {
281 CodeGenModule(const CodeGenModule &) = delete;
282 void operator=(const CodeGenModule &) = delete;
286 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
287 Structor(int Priority, llvm::Constant *Initializer,
288 llvm::Constant *AssociatedData)
289 : Priority(Priority), Initializer(Initializer),
290 AssociatedData(AssociatedData) {}
292 llvm::Constant *Initializer;
293 llvm::Constant *AssociatedData;
296 typedef std::vector<Structor> CtorList;
300 const LangOptions &LangOpts;
301 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
302 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
303 const CodeGenOptions &CodeGenOpts;
304 llvm::Module &TheModule;
305 DiagnosticsEngine &Diags;
306 const TargetInfo &Target;
307 std::unique_ptr<CGCXXABI> ABI;
308 llvm::LLVMContext &VMContext;
310 std::unique_ptr<CodeGenTBAA> TBAA;
312 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
314 // This should not be moved earlier, since its initialization depends on some
315 // of the previous reference members being already initialized and also checks
316 // if TheTargetCodeGenInfo is NULL
319 /// Holds information about C++ vtables.
320 CodeGenVTables VTables;
322 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
323 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
324 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
325 std::unique_ptr<llvm::OpenMPIRBuilder> OMPBuilder;
326 std::unique_ptr<CGCUDARuntime> CUDARuntime;
327 std::unique_ptr<CGDebugInfo> DebugInfo;
328 std::unique_ptr<ObjCEntrypoints> ObjCData;
329 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
330 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
331 InstrProfStats PGOStats;
332 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
334 // A set of references that have only been seen via a weakref so far. This is
335 // used to remove the weak of the reference if we ever see a direct reference
337 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
339 /// This contains all the decls which have definitions but/ which are deferred
340 /// for emission and therefore should only be output if they are actually
341 /// used. If a decl is in this, then it is known to have not been referenced
343 std::map<StringRef, GlobalDecl> DeferredDecls;
345 /// This is a list of deferred decls which we have seen that *are* actually
346 /// referenced. These get code generated when the module is done.
347 std::vector<GlobalDecl> DeferredDeclsToEmit;
348 void addDeferredDeclToEmit(GlobalDecl GD) {
349 DeferredDeclsToEmit.emplace_back(GD);
352 /// List of alias we have emitted. Used to make sure that what they point to
353 /// is defined once we get to the end of the of the translation unit.
354 std::vector<GlobalDecl> Aliases;
356 /// List of multiversion functions that have to be emitted. Used to make sure
357 /// we properly emit the iFunc.
358 std::vector<GlobalDecl> MultiVersionFuncs;
360 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
361 ReplacementsTy Replacements;
363 /// List of global values to be replaced with something else. Used when we
364 /// want to replace a GlobalValue but can't identify it by its mangled name
365 /// anymore (because the name is already taken).
366 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
367 GlobalValReplacements;
369 /// Variables for which we've emitted globals containing their constant
370 /// values along with the corresponding globals, for opportunistic reuse.
371 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
373 /// Set of global decls for which we already diagnosed mangled name conflict.
374 /// Required to not issue a warning (on a mangling conflict) multiple times
375 /// for the same decl.
376 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
378 /// A queue of (optional) vtables to consider emitting.
379 std::vector<const CXXRecordDecl*> DeferredVTables;
381 /// A queue of (optional) vtables that may be emitted opportunistically.
382 std::vector<const CXXRecordDecl *> OpportunisticVTables;
384 /// List of global values which are required to be present in the object file;
385 /// bitcast to i8*. This is used for forcing visibility of symbols which may
386 /// otherwise be optimized out.
387 std::vector<llvm::WeakTrackingVH> LLVMUsed;
388 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
390 /// Store the list of global constructors and their respective priorities to
391 /// be emitted when the translation unit is complete.
392 CtorList GlobalCtors;
394 /// Store the list of global destructors and their respective priorities to be
395 /// emitted when the translation unit is complete.
396 CtorList GlobalDtors;
398 /// An ordered map of canonical GlobalDecls to their mangled names.
399 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
400 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
402 // An ordered map of canonical GlobalDecls paired with the cpu-index for
403 // cpu-specific name manglings.
404 llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef>
405 CPUSpecificMangledDeclNames;
406 llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator>
407 CPUSpecificManglings;
409 /// Global annotations.
410 std::vector<llvm::Constant*> Annotations;
412 /// Map used to get unique annotation strings.
413 llvm::StringMap<llvm::Constant*> AnnotationStrings;
415 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
417 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
418 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
419 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
420 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
422 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
423 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
425 /// Map used to get unique type descriptor constants for sanitizers.
426 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
428 /// Map used to track internal linkage functions declared within
429 /// extern "C" regions.
430 typedef llvm::MapVector<IdentifierInfo *,
431 llvm::GlobalValue *> StaticExternCMap;
432 StaticExternCMap StaticExternCValues;
434 /// thread_local variables defined or used in this TU.
435 std::vector<const VarDecl *> CXXThreadLocals;
437 /// thread_local variables with initializers that need to run
438 /// before any thread_local variable in this TU is odr-used.
439 std::vector<llvm::Function *> CXXThreadLocalInits;
440 std::vector<const VarDecl *> CXXThreadLocalInitVars;
442 /// Global variables with initializers that need to run before main.
443 std::vector<llvm::Function *> CXXGlobalInits;
445 /// When a C++ decl with an initializer is deferred, null is
446 /// appended to CXXGlobalInits, and the index of that null is placed
447 /// here so that the initializer will be performed in the correct
448 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
449 /// that we don't re-emit the initializer.
450 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
452 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
454 struct GlobalInitPriorityCmp {
455 bool operator()(const GlobalInitData &LHS,
456 const GlobalInitData &RHS) const {
457 return LHS.first.priority < RHS.first.priority;
461 /// Global variables with initializers whose order of initialization is set by
462 /// init_priority attribute.
463 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
465 /// Global destructor functions and arguments that need to run on termination.
467 std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant *>>
470 /// The complete set of modules that has been imported.
471 llvm::SetVector<clang::Module *> ImportedModules;
473 /// The set of modules for which the module initializers
474 /// have been emitted.
475 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
477 /// A vector of metadata strings for linker options.
478 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
480 /// A vector of metadata strings for dependent libraries for ELF.
481 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
483 /// @name Cache for Objective-C runtime types
486 /// Cached reference to the class for constant strings. This value has type
487 /// int * but is actually an Obj-C class pointer.
488 llvm::WeakTrackingVH CFConstantStringClassRef;
490 /// The type used to describe the state of a fast enumeration in
491 /// Objective-C's for..in loop.
492 QualType ObjCFastEnumerationStateType;
496 /// Lazily create the Objective-C runtime
497 void createObjCRuntime();
499 void createOpenCLRuntime();
500 void createOpenMPRuntime();
501 void createCUDARuntime();
503 bool isTriviallyRecursive(const FunctionDecl *F);
504 bool shouldEmitFunction(GlobalDecl GD);
505 bool shouldOpportunisticallyEmitVTables();
506 /// Map used to be sure we don't emit the same CompoundLiteral twice.
507 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
508 EmittedCompoundLiterals;
510 /// Map of the global blocks we've emitted, so that we don't have to re-emit
511 /// them if the constexpr evaluator gets aggressive.
512 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
514 /// @name Cache for Blocks Runtime Globals
517 llvm::Constant *NSConcreteGlobalBlock = nullptr;
518 llvm::Constant *NSConcreteStackBlock = nullptr;
520 llvm::FunctionCallee BlockObjectAssign = nullptr;
521 llvm::FunctionCallee BlockObjectDispose = nullptr;
523 llvm::Type *BlockDescriptorType = nullptr;
524 llvm::Type *GenericBlockLiteralType = nullptr;
527 int GlobalUniqueCount;
530 GlobalDecl initializedGlobalDecl;
534 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
535 llvm::Function *LifetimeStartFn = nullptr;
537 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
538 llvm::Function *LifetimeEndFn = nullptr;
540 std::unique_ptr<SanitizerMetadata> SanitizerMD;
542 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
544 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
546 /// Mapping from canonical types to their metadata identifiers. We need to
547 /// maintain this mapping because identifiers may be formed from distinct
549 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
550 MetadataTypeMap MetadataIdMap;
551 MetadataTypeMap VirtualMetadataIdMap;
552 MetadataTypeMap GeneralizedMetadataIdMap;
555 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
556 const PreprocessorOptions &ppopts,
557 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
558 DiagnosticsEngine &Diags,
559 CoverageSourceInfo *CoverageInfo = nullptr);
565 /// Finalize LLVM code generation.
568 /// Return true if we should emit location information for expressions.
569 bool getExpressionLocationsEnabled() const;
571 /// Return a reference to the configured Objective-C runtime.
572 CGObjCRuntime &getObjCRuntime() {
573 if (!ObjCRuntime) createObjCRuntime();
577 /// Return true iff an Objective-C runtime has been configured.
578 bool hasObjCRuntime() { return !!ObjCRuntime; }
580 /// Return a reference to the configured OpenCL runtime.
581 CGOpenCLRuntime &getOpenCLRuntime() {
582 assert(OpenCLRuntime != nullptr);
583 return *OpenCLRuntime;
586 /// Return a reference to the configured OpenMP runtime.
587 CGOpenMPRuntime &getOpenMPRuntime() {
588 assert(OpenMPRuntime != nullptr);
589 return *OpenMPRuntime;
592 /// Return a pointer to the configured OpenMPIRBuilder, if any.
593 llvm::OpenMPIRBuilder *getOpenMPIRBuilder() { return OMPBuilder.get(); }
595 /// Return a reference to the configured CUDA runtime.
596 CGCUDARuntime &getCUDARuntime() {
597 assert(CUDARuntime != nullptr);
601 ObjCEntrypoints &getObjCEntrypoints() const {
602 assert(ObjCData != nullptr);
606 // Version checking function, used to implement ObjC's @available:
607 // i32 @__isOSVersionAtLeast(i32, i32, i32)
608 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
610 InstrProfStats &getPGOStats() { return PGOStats; }
611 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
613 CoverageMappingModuleGen *getCoverageMapping() const {
614 return CoverageMapping.get();
617 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
618 return StaticLocalDeclMap[D];
620 void setStaticLocalDeclAddress(const VarDecl *D,
622 StaticLocalDeclMap[D] = C;
626 getOrCreateStaticVarDecl(const VarDecl &D,
627 llvm::GlobalValue::LinkageTypes Linkage);
629 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
630 return StaticLocalDeclGuardMap[D];
632 void setStaticLocalDeclGuardAddress(const VarDecl *D,
633 llvm::GlobalVariable *C) {
634 StaticLocalDeclGuardMap[D] = C;
637 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
640 bool lookupRepresentativeDecl(StringRef MangledName,
641 GlobalDecl &Result) const;
643 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
644 return AtomicSetterHelperFnMap[Ty];
646 void setAtomicSetterHelperFnMap(QualType Ty,
647 llvm::Constant *Fn) {
648 AtomicSetterHelperFnMap[Ty] = Fn;
651 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
652 return AtomicGetterHelperFnMap[Ty];
654 void setAtomicGetterHelperFnMap(QualType Ty,
655 llvm::Constant *Fn) {
656 AtomicGetterHelperFnMap[Ty] = Fn;
659 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
660 return TypeDescriptorMap[Ty];
662 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
663 TypeDescriptorMap[Ty] = C;
666 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
668 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
669 if (!NoObjCARCExceptionsMetadata)
670 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
671 return NoObjCARCExceptionsMetadata;
674 ASTContext &getContext() const { return Context; }
675 const LangOptions &getLangOpts() const { return LangOpts; }
676 const HeaderSearchOptions &getHeaderSearchOpts()
677 const { return HeaderSearchOpts; }
678 const PreprocessorOptions &getPreprocessorOpts()
679 const { return PreprocessorOpts; }
680 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
681 llvm::Module &getModule() const { return TheModule; }
682 DiagnosticsEngine &getDiags() const { return Diags; }
683 const llvm::DataLayout &getDataLayout() const {
684 return TheModule.getDataLayout();
686 const TargetInfo &getTarget() const { return Target; }
687 const llvm::Triple &getTriple() const { return Target.getTriple(); }
688 bool supportsCOMDAT() const;
689 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
691 CGCXXABI &getCXXABI() const { return *ABI; }
692 llvm::LLVMContext &getLLVMContext() { return VMContext; }
694 bool shouldUseTBAA() const { return TBAA != nullptr; }
696 const TargetCodeGenInfo &getTargetCodeGenInfo();
698 CodeGenTypes &getTypes() { return Types; }
700 CodeGenVTables &getVTables() { return VTables; }
702 ItaniumVTableContext &getItaniumVTableContext() {
703 return VTables.getItaniumVTableContext();
706 MicrosoftVTableContext &getMicrosoftVTableContext() {
707 return VTables.getMicrosoftVTableContext();
710 CtorList &getGlobalCtors() { return GlobalCtors; }
711 CtorList &getGlobalDtors() { return GlobalDtors; }
713 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
715 llvm::MDNode *getTBAATypeInfo(QualType QTy);
717 /// getTBAAAccessInfo - Get TBAA information that describes an access to
718 /// an object of the given type.
719 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
721 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
722 /// access to a virtual table pointer.
723 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
725 llvm::MDNode *getTBAAStructInfo(QualType QTy);
727 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
728 /// type. Return null if the type is not suitable for use in TBAA access tags.
729 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
731 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
732 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
734 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
736 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
737 TBAAAccessInfo TargetInfo);
739 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
740 /// purposes of conditional operator.
741 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
742 TBAAAccessInfo InfoB);
744 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
745 /// purposes of memory transfer calls.
746 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
747 TBAAAccessInfo SrcInfo);
749 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
751 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
752 if (Base.getTBAAInfo().isMayAlias())
753 return TBAAAccessInfo::getMayAliasInfo();
754 return getTBAAAccessInfo(AccessType);
757 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
759 bool isPaddedAtomicType(QualType type);
760 bool isPaddedAtomicType(const AtomicType *type);
762 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
763 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
764 TBAAAccessInfo TBAAInfo);
766 /// Adds !invariant.barrier !tag to instruction
767 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
768 const CXXRecordDecl *RD);
770 /// Emit the given number of characters as a value of type size_t.
771 llvm::ConstantInt *getSize(CharUnits numChars);
773 /// Set the visibility for the given LLVM GlobalValue.
774 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
776 void setDSOLocal(llvm::GlobalValue *GV) const;
778 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
779 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
780 /// Set visibility, dllimport/dllexport and dso_local.
781 /// This must be called after dllimport/dllexport is set.
782 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
783 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
785 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
787 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
788 /// variable declaration D.
789 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
791 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
793 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
794 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
795 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
797 llvm_unreachable("unknown visibility!");
800 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
801 ForDefinition_t IsForDefinition
804 /// Will return a global variable of the given type. If a variable with a
805 /// different type already exists then a new variable with the right type
806 /// will be created and all uses of the old variable will be replaced with a
807 /// bitcast to the new variable.
808 llvm::GlobalVariable *
809 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
810 llvm::GlobalValue::LinkageTypes Linkage,
814 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
815 const CGFunctionInfo &FI,
816 SourceLocation Loc = SourceLocation(),
819 /// Return the AST address space of the underlying global variable for D, as
820 /// determined by its declaration. Normally this is the same as the address
821 /// space of D's type, but in CUDA, address spaces are associated with
822 /// declarations, not types. If D is nullptr, return the default address
823 /// space for global variable.
825 /// For languages without explicit address spaces, if D has default address
826 /// space, target-specific global or constant address space may be returned.
827 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
829 /// Return the llvm::Constant for the address of the given global variable.
830 /// If Ty is non-null and if the global doesn't exist, then it will be created
831 /// with the specified type instead of whatever the normal requested type
832 /// would be. If IsForDefinition is true, it is guaranteed that an actual
833 /// global with type Ty will be returned, not conversion of a variable with
834 /// the same mangled name but some other type.
835 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
836 llvm::Type *Ty = nullptr,
837 ForDefinition_t IsForDefinition
840 /// Return the AST address space of string literal, which is used to emit
841 /// the string literal as global variable in LLVM IR.
842 /// Note: This is not necessarily the address space of the string literal
843 /// in AST. For address space agnostic language, e.g. C++, string literal
844 /// in AST is always in default address space.
845 LangAS getStringLiteralAddressSpace() const;
847 /// Return the address of the given function. If Ty is non-null, then this
848 /// function will use the specified type if it has to create it.
849 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
850 bool ForVTable = false,
851 bool DontDefer = false,
852 ForDefinition_t IsForDefinition
855 /// Get the address of the RTTI descriptor for the given type.
856 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
858 /// Get the address of a uuid descriptor .
859 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
861 /// Get the address of the thunk for the given global decl.
862 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
865 /// Get a reference to the target of VD.
866 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
868 /// Returns the assumed alignment of an opaque pointer to the given class.
869 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
871 /// Returns the assumed alignment of a virtual base of a class.
872 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
873 const CXXRecordDecl *Derived,
874 const CXXRecordDecl *VBase);
876 /// Given a class pointer with an actual known alignment, and the
877 /// expected alignment of an object at a dynamic offset w.r.t that
878 /// pointer, return the alignment to assume at the offset.
879 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
880 const CXXRecordDecl *Class,
881 CharUnits ExpectedTargetAlign);
884 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
885 CastExpr::path_const_iterator Start,
886 CastExpr::path_const_iterator End);
888 /// Returns the offset from a derived class to a class. Returns null if the
891 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
892 CastExpr::path_const_iterator PathBegin,
893 CastExpr::path_const_iterator PathEnd);
895 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
897 /// Fetches the global unique block count.
898 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
900 /// Fetches the type of a generic block descriptor.
901 llvm::Type *getBlockDescriptorType();
903 /// The type of a generic block literal.
904 llvm::Type *getGenericBlockLiteralType();
906 /// Gets the address of a block which requires no captures.
907 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
909 /// Returns the address of a block which requires no caputres, or null if
910 /// we've yet to emit the block for BE.
911 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
912 return EmittedGlobalBlocks.lookup(BE);
915 /// Notes that BE's global block is available via Addr. Asserts that BE
916 /// isn't already emitted.
917 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
919 /// Return a pointer to a constant CFString object for the given string.
920 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
922 /// Return a pointer to a constant NSString object for the given string. Or a
923 /// user defined String object as defined via
924 /// -fconstant-string-class=class_name option.
925 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
927 /// Return a constant array for the given string.
928 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
930 /// Return a pointer to a constant array for the given string literal.
932 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
933 StringRef Name = ".str");
935 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
937 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
939 /// Returns a pointer to a character array containing the literal and a
940 /// terminating '\0' character. The result has pointer to array type.
942 /// \param GlobalName If provided, the name to use for the global (if one is
945 GetAddrOfConstantCString(const std::string &Str,
946 const char *GlobalName = nullptr);
948 /// Returns a pointer to a constant global variable for the given file-scope
949 /// compound literal expression.
950 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
952 /// If it's been emitted already, returns the GlobalVariable corresponding to
953 /// a compound literal. Otherwise, returns null.
954 llvm::GlobalVariable *
955 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
957 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
959 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
960 llvm::GlobalVariable *GV);
962 /// Returns a pointer to a global variable representing a temporary
963 /// with static or thread storage duration.
964 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
967 /// Retrieve the record type that describes the state of an
968 /// Objective-C fast enumeration loop (for..in).
969 QualType getObjCFastEnumerationStateType();
971 // Produce code for this constructor/destructor. This method doesn't try
972 // to apply any ABI rules about which other constructors/destructors
973 // are needed or if they are alias to each other.
974 llvm::Function *codegenCXXStructor(GlobalDecl GD);
976 /// Return the address of the constructor/destructor of the given type.
978 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
979 llvm::FunctionType *FnType = nullptr,
980 bool DontDefer = false,
981 ForDefinition_t IsForDefinition = NotForDefinition) {
982 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
988 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
989 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
990 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
991 ForDefinition_t IsForDefinition = NotForDefinition);
993 /// Given a builtin id for a function like "__builtin_fabsf", return a
994 /// Function* for "fabsf".
995 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
998 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
1000 /// Emit code for a single top level declaration.
1001 void EmitTopLevelDecl(Decl *D);
1003 /// Stored a deferred empty coverage mapping for an unused
1004 /// and thus uninstrumented top level declaration.
1005 void AddDeferredUnusedCoverageMapping(Decl *D);
1007 /// Remove the deferred empty coverage mapping as this
1008 /// declaration is actually instrumented.
1009 void ClearUnusedCoverageMapping(const Decl *D);
1011 /// Emit all the deferred coverage mappings
1012 /// for the uninstrumented functions.
1013 void EmitDeferredUnusedCoverageMappings();
1015 /// Tell the consumer that this variable has been instantiated.
1016 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1018 /// If the declaration has internal linkage but is inside an
1019 /// extern "C" linkage specification, prepare to emit an alias for it
1020 /// to the expected name.
1021 template<typename SomeDecl>
1022 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1024 /// Add a global to a list to be added to the llvm.used metadata.
1025 void addUsedGlobal(llvm::GlobalValue *GV);
1027 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1028 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1030 /// Add a destructor and object to add to the C++ global destructor function.
1031 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1032 CXXGlobalDtors.emplace_back(DtorFn.getFunctionType(), DtorFn.getCallee(),
1036 /// Create or return a runtime function declaration with the specified type
1037 /// and name. If \p AssumeConvergent is true, the call will have the
1038 /// convergent attribute added.
1039 llvm::FunctionCallee
1040 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1041 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1042 bool Local = false, bool AssumeConvergent = false);
1044 /// Create or return a runtime function declaration with the specified type
1045 /// and name. This will automatically add the convergent attribute to the
1046 /// function declaration.
1047 llvm::FunctionCallee CreateConvergentRuntimeFunction(
1048 llvm::FunctionType *Ty, StringRef Name,
1049 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1050 bool Local = false) {
1051 return CreateRuntimeFunction(Ty, Name, ExtraAttrs, Local, true);
1054 /// Create a new runtime global variable with the specified type and name.
1055 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1058 ///@name Custom Blocks Runtime Interfaces
1061 llvm::Constant *getNSConcreteGlobalBlock();
1062 llvm::Constant *getNSConcreteStackBlock();
1063 llvm::FunctionCallee getBlockObjectAssign();
1064 llvm::FunctionCallee getBlockObjectDispose();
1068 llvm::Function *getLLVMLifetimeStartFn();
1069 llvm::Function *getLLVMLifetimeEndFn();
1071 // Make sure that this type is translated.
1072 void UpdateCompletedType(const TagDecl *TD);
1074 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1076 /// Emit type info if type of an expression is a variably modified
1077 /// type. Also emit proper debug info for cast types.
1078 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1079 CodeGenFunction *CGF = nullptr);
1081 /// Return the result of value-initializing the given type, i.e. a null
1082 /// expression of the given type. This is usually, but not always, an LLVM
1084 llvm::Constant *EmitNullConstant(QualType T);
1086 /// Return a null constant appropriate for zero-initializing a base class with
1087 /// the given type. This is usually, but not always, an LLVM null constant.
1088 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1090 /// Emit a general error that something can't be done.
1091 void Error(SourceLocation loc, StringRef error);
1093 /// Print out an error that codegen doesn't support the specified stmt yet.
1094 void ErrorUnsupported(const Stmt *S, const char *Type);
1096 /// Print out an error that codegen doesn't support the specified decl yet.
1097 void ErrorUnsupported(const Decl *D, const char *Type);
1099 /// Set the attributes on the LLVM function for the given decl and function
1100 /// info. This applies attributes necessary for handling the ABI as well as
1101 /// user specified attributes like section.
1102 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1103 const CGFunctionInfo &FI);
1105 /// Set the LLVM function attributes (sext, zext, etc).
1106 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1109 /// Set the LLVM function attributes which only apply to a function
1111 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1113 /// Return true iff the given type uses 'sret' when used as a return type.
1114 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1116 /// Return true iff the given type uses an argument slot when 'sret' is used
1117 /// as a return type.
1118 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1120 /// Return true iff the given type uses 'fpret' when used as a return type.
1121 bool ReturnTypeUsesFPRet(QualType ResultType);
1123 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1124 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1126 /// Get the LLVM attributes and calling convention to use for a particular
1129 /// \param Name - The function name.
1130 /// \param Info - The function type information.
1131 /// \param CalleeInfo - The callee information these attributes are being
1132 /// constructed for. If valid, the attributes applied to this decl may
1133 /// contribute to the function attributes and calling convention.
1134 /// \param Attrs [out] - On return, the attribute list to use.
1135 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1136 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1137 CGCalleeInfo CalleeInfo,
1138 llvm::AttributeList &Attrs, unsigned &CallingConv,
1139 bool AttrOnCallSite);
1141 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1142 /// though we had emitted it ourselves. We remove any attributes on F that
1143 /// conflict with the attributes we add here.
1145 /// This is useful for adding attrs to bitcode modules that you want to link
1146 /// with but don't control, such as CUDA's libdevice. When linking with such
1147 /// a bitcode library, you might want to set e.g. its functions'
1148 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1149 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1150 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1151 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1152 /// function in the bitcode library!
1154 /// With the exception of fast-math attrs, this will only make the attributes
1155 /// on the function more conservative. But it's unsafe to call this on a
1156 /// function which relies on particular fast-math attributes for correctness.
1157 /// It's up to you to ensure that this is safe.
1158 void AddDefaultFnAttrs(llvm::Function &F);
1160 StringRef getMangledName(GlobalDecl GD);
1161 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1163 void EmitTentativeDefinition(const VarDecl *D);
1165 void EmitExternalDeclaration(const VarDecl *D);
1167 void EmitVTable(CXXRecordDecl *Class);
1169 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1171 /// Appends Opts to the "llvm.linker.options" metadata value.
1172 void AppendLinkerOptions(StringRef Opts);
1174 /// Appends a detect mismatch command to the linker options.
1175 void AddDetectMismatch(StringRef Name, StringRef Value);
1177 /// Appends a dependent lib to the appropriate metadata value.
1178 void AddDependentLib(StringRef Lib);
1181 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1183 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1184 F->setLinkage(getFunctionLinkage(GD));
1187 /// Return the appropriate linkage for the vtable, VTT, and type information
1188 /// of the given class.
1189 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1191 /// Return the store size, in character units, of the given LLVM type.
1192 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1194 /// Returns LLVM linkage for a declarator.
1195 llvm::GlobalValue::LinkageTypes
1196 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1197 bool IsConstantVariable);
1199 /// Returns LLVM linkage for a declarator.
1200 llvm::GlobalValue::LinkageTypes
1201 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1203 /// Emit all the global annotations.
1204 void EmitGlobalAnnotations();
1206 /// Emit an annotation string.
1207 llvm::Constant *EmitAnnotationString(StringRef Str);
1209 /// Emit the annotation's translation unit.
1210 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1212 /// Emit the annotation line number.
1213 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1215 /// Generate the llvm::ConstantStruct which contains the annotation
1216 /// information for a given GlobalValue. The annotation struct is
1217 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1218 /// GlobalValue being annotated. The second field is the constant string
1219 /// created from the AnnotateAttr's annotation. The third field is a constant
1220 /// string containing the name of the translation unit. The fourth field is
1221 /// the line number in the file of the annotated value declaration.
1222 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1223 const AnnotateAttr *AA,
1226 /// Add global annotations that are set on D, for the global GV. Those
1227 /// annotations are emitted during finalization of the LLVM code.
1228 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1230 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn,
1231 SourceLocation Loc) const;
1233 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1235 StringRef Category = StringRef()) const;
1237 /// Imbue XRay attributes to a function, applying the always/never attribute
1238 /// lists in the process. Returns true if we did imbue attributes this way,
1239 /// false otherwise.
1240 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1241 StringRef Category = StringRef()) const;
1243 SanitizerMetadata *getSanitizerMetadata() {
1244 return SanitizerMD.get();
1247 void addDeferredVTable(const CXXRecordDecl *RD) {
1248 DeferredVTables.push_back(RD);
1251 /// Emit code for a single global function or var decl. Forward declarations
1252 /// are emitted lazily.
1253 void EmitGlobal(GlobalDecl D);
1255 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1257 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1259 /// Set attributes which are common to any form of a global definition (alias,
1260 /// Objective-C method, function, global variable).
1262 /// NOTE: This should only be called for definitions.
1263 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1265 void addReplacement(StringRef Name, llvm::Constant *C);
1267 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1269 /// Emit a code for threadprivate directive.
1270 /// \param D Threadprivate declaration.
1271 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1273 /// Emit a code for declare reduction construct.
1274 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1275 CodeGenFunction *CGF = nullptr);
1277 /// Emit a code for declare mapper construct.
1278 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1279 CodeGenFunction *CGF = nullptr);
1281 /// Emit a code for requires directive.
1282 /// \param D Requires declaration
1283 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1285 /// Emits the definition of \p OldGD function with body from \p NewGD.
1286 /// Required for proper handling of declare variant directive on the GPU.
1287 void emitOpenMPDeviceFunctionRedefinition(GlobalDecl OldGD, GlobalDecl NewGD,
1288 llvm::GlobalValue *GV);
1290 /// Returns whether the given record has hidden LTO visibility and therefore
1291 /// may participate in (single-module) CFI and whole-program vtable
1293 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1295 /// Returns the vcall visibility of the given type. This is the scope in which
1296 /// a virtual function call could be made which ends up being dispatched to a
1297 /// member function of this class. This scope can be wider than the visibility
1298 /// of the class itself when the class has a more-visible dynamic base class.
1299 llvm::GlobalObject::VCallVisibility
1300 GetVCallVisibilityLevel(const CXXRecordDecl *RD);
1302 /// Emit type metadata for the given vtable using the given layout.
1303 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1304 llvm::GlobalVariable *VTable,
1305 const VTableLayout &VTLayout);
1307 /// Generate a cross-DSO type identifier for MD.
1308 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1310 /// Create a metadata identifier for the given type. This may either be an
1311 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1312 /// internal identifiers).
1313 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1315 /// Create a metadata identifier that is intended to be used to check virtual
1316 /// calls via a member function pointer.
1317 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1319 /// Create a metadata identifier for the generalization of the given type.
1320 /// This may either be an MDString (for external identifiers) or a distinct
1321 /// unnamed MDNode (for internal identifiers).
1322 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1324 /// Create and attach type metadata to the given function.
1325 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1328 /// Returns whether this module needs the "all-vtables" type identifier.
1329 bool NeedAllVtablesTypeId() const;
1331 /// Create and attach type metadata for the given vtable.
1332 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1333 const CXXRecordDecl *RD);
1335 /// Return a vector of most-base classes for RD. This is used to implement
1336 /// control flow integrity checks for member function pointers.
1338 /// A most-base class of a class C is defined as a recursive base class of C,
1339 /// including C itself, that does not have any bases.
1340 std::vector<const CXXRecordDecl *>
1341 getMostBaseClasses(const CXXRecordDecl *RD);
1343 /// Get the declaration of std::terminate for the platform.
1344 llvm::FunctionCallee getTerminateFn();
1346 llvm::SanitizerStatReport &getSanStats();
1349 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1351 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1352 /// information in the program executable. The argument information stored
1353 /// includes the argument name, its type, the address and access qualifiers
1354 /// used. This helper can be used to generate metadata for source code kernel
1355 /// function as well as generated implicitly kernels. If a kernel is generated
1356 /// implicitly null value has to be passed to the last two parameters,
1357 /// otherwise all parameters must have valid non-null values.
1358 /// \param FN is a pointer to IR function being generated.
1359 /// \param FD is a pointer to function declaration if any.
1360 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1361 void GenOpenCLArgMetadata(llvm::Function *FN,
1362 const FunctionDecl *FD = nullptr,
1363 CodeGenFunction *CGF = nullptr);
1365 /// Get target specific null pointer.
1366 /// \param T is the LLVM type of the null pointer.
1367 /// \param QT is the clang QualType of the null pointer.
1368 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1371 llvm::Constant *GetOrCreateLLVMFunction(
1372 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1373 bool DontDefer = false, bool IsThunk = false,
1374 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1375 ForDefinition_t IsForDefinition = NotForDefinition);
1377 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD,
1379 const FunctionDecl *FD);
1380 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD);
1382 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1383 llvm::PointerType *PTy,
1385 ForDefinition_t IsForDefinition
1386 = NotForDefinition);
1388 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1389 llvm::AttrBuilder &AttrBuilder);
1390 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1392 /// Set function attributes for a function declaration.
1393 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1394 bool IsIncompleteFunction, bool IsThunk);
1396 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1398 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1399 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1401 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1402 void EmitExternalVarDeclaration(const VarDecl *D);
1403 void EmitAliasDefinition(GlobalDecl GD);
1404 void emitIFuncDefinition(GlobalDecl GD);
1405 void emitCPUDispatchDefinition(GlobalDecl GD);
1406 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1407 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1409 // C++ related functions.
1411 void EmitDeclContext(const DeclContext *DC);
1412 void EmitLinkageSpec(const LinkageSpecDecl *D);
1414 /// Emit the function that initializes C++ thread_local variables.
1415 void EmitCXXThreadLocalInitFunc();
1417 /// Emit the function that initializes C++ globals.
1418 void EmitCXXGlobalInitFunc();
1420 /// Emit the function that destroys C++ globals.
1421 void EmitCXXGlobalDtorFunc();
1423 /// Emit the function that initializes the specified global (if PerformInit is
1424 /// true) and registers its destructor.
1425 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1426 llvm::GlobalVariable *Addr,
1429 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1430 llvm::Function *InitFunc, InitSegAttr *ISA);
1432 // FIXME: Hardcoding priority here is gross.
1433 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1434 llvm::Constant *AssociatedData = nullptr);
1435 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1437 /// EmitCtorList - Generates a global array of functions and priorities using
1438 /// the given list and name. This array will have appending linkage and is
1439 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1440 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1442 /// Emit any needed decls for which code generation was deferred.
1443 void EmitDeferred();
1445 /// Try to emit external vtables as available_externally if they have emitted
1446 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1447 /// is not allowed to create new references to things that need to be emitted
1449 void EmitVTablesOpportunistically();
1451 /// Call replaceAllUsesWith on all pairs in Replacements.
1452 void applyReplacements();
1454 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1455 void applyGlobalValReplacements();
1457 void checkAliases();
1459 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1461 /// Register functions annotated with __attribute__((destructor)) using
1462 /// __cxa_atexit, if it is available, or atexit otherwise.
1463 void registerGlobalDtorsWithAtExit();
1465 void emitMultiVersionFunctions();
1467 /// Emit any vtables which we deferred and still have a use for.
1468 void EmitDeferredVTables();
1470 /// Emit a dummy function that reference a CoreFoundation symbol when
1471 /// @available is used on Darwin.
1472 void emitAtAvailableLinkGuard();
1474 /// Emit the llvm.used and llvm.compiler.used metadata.
1475 void emitLLVMUsed();
1477 /// Emit the link options introduced by imported modules.
1478 void EmitModuleLinkOptions();
1480 /// Emit aliases for internal-linkage declarations inside "C" language
1481 /// linkage specifications, giving them the "expected" name where possible.
1482 void EmitStaticExternCAliases();
1484 void EmitDeclMetadata();
1486 /// Emit the Clang version as llvm.ident metadata.
1487 void EmitVersionIdentMetadata();
1489 /// Emit the Clang commandline as llvm.commandline metadata.
1490 void EmitCommandLineMetadata();
1492 /// Emits target specific Metadata for global declarations.
1493 void EmitTargetMetadata();
1495 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1496 void EmitOpenCLMetadata();
1498 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1499 /// .gcda files in a way that persists in .bc files.
1500 void EmitCoverageFile();
1502 /// Emits the initializer for a uuidof string.
1503 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1505 /// Determine whether the definition must be emitted; if this returns \c
1506 /// false, the definition can be emitted lazily if it's used.
1507 bool MustBeEmitted(const ValueDecl *D);
1509 /// Determine whether the definition can be emitted eagerly, or should be
1510 /// delayed until the end of the translation unit. This is relevant for
1511 /// definitions whose linkage can change, e.g. implicit function instantions
1512 /// which may later be explicitly instantiated.
1513 bool MayBeEmittedEagerly(const ValueDecl *D);
1515 /// Check whether we can use a "simpler", more core exceptions personality
1517 void SimplifyPersonality();
1519 /// Helper function for ConstructAttributeList and AddDefaultFnAttrs.
1520 /// Constructs an AttrList for a function with the given properties.
1521 void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1522 bool AttrOnCallSite,
1523 llvm::AttrBuilder &FuncAttrs);
1525 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1529 } // end namespace CodeGen
1530 } // end namespace clang
1532 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H