1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the internal per-translation-unit state used for llvm translation.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
17 #include "CGVTables.h"
18 #include "CodeGenTypeCache.h"
19 #include "CodeGenTypes.h"
20 #include "SanitizerMetadata.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/GlobalDecl.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/Module.h"
30 #include "clang/Basic/SanitizerBlacklist.h"
31 #include "clang/Basic/XRayLists.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;
58 class ObjCImplementationDecl;
59 class ObjCCategoryImplDecl;
60 class ObjCProtocolDecl;
74 class HeaderSearchOptions;
75 class PreprocessorOptions;
76 class DiagnosticsEngine;
78 class CXXDestructorDecl;
80 class CoverageSourceInfo;
85 class CodeGenFunction;
90 class CGOpenCLRuntime;
91 class CGOpenMPRuntime;
93 class BlockFieldFlags;
94 class FunctionArgList;
95 class CoverageMappingModuleGen;
96 class TargetCodeGenInfo;
98 enum ForDefinition_t : bool {
99 NotForDefinition = false,
103 struct OrderGlobalInits {
104 unsigned int priority;
105 unsigned int lex_order;
106 OrderGlobalInits(unsigned int p, unsigned int l)
107 : priority(p), lex_order(l) {}
109 bool operator==(const OrderGlobalInits &RHS) const {
110 return priority == RHS.priority && lex_order == RHS.lex_order;
113 bool operator<(const OrderGlobalInits &RHS) const {
114 return std::tie(priority, lex_order) <
115 std::tie(RHS.priority, RHS.lex_order);
119 struct ObjCEntrypoints {
120 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
122 /// void objc_autoreleasePoolPop(void*);
123 llvm::Constant *objc_autoreleasePoolPop;
125 /// void *objc_autoreleasePoolPush(void);
126 llvm::Constant *objc_autoreleasePoolPush;
128 /// id objc_autorelease(id);
129 llvm::Constant *objc_autorelease;
131 /// id objc_autoreleaseReturnValue(id);
132 llvm::Constant *objc_autoreleaseReturnValue;
134 /// void objc_copyWeak(id *dest, id *src);
135 llvm::Constant *objc_copyWeak;
137 /// void objc_destroyWeak(id*);
138 llvm::Constant *objc_destroyWeak;
140 /// id objc_initWeak(id*, id);
141 llvm::Constant *objc_initWeak;
143 /// id objc_loadWeak(id*);
144 llvm::Constant *objc_loadWeak;
146 /// id objc_loadWeakRetained(id*);
147 llvm::Constant *objc_loadWeakRetained;
149 /// void objc_moveWeak(id *dest, id *src);
150 llvm::Constant *objc_moveWeak;
152 /// id objc_retain(id);
153 llvm::Constant *objc_retain;
155 /// id objc_retainAutorelease(id);
156 llvm::Constant *objc_retainAutorelease;
158 /// id objc_retainAutoreleaseReturnValue(id);
159 llvm::Constant *objc_retainAutoreleaseReturnValue;
161 /// id objc_retainAutoreleasedReturnValue(id);
162 llvm::Constant *objc_retainAutoreleasedReturnValue;
164 /// id objc_retainBlock(id);
165 llvm::Constant *objc_retainBlock;
167 /// void objc_release(id);
168 llvm::Constant *objc_release;
170 /// void objc_storeStrong(id*, id);
171 llvm::Constant *objc_storeStrong;
173 /// id objc_storeWeak(id*, id);
174 llvm::Constant *objc_storeWeak;
176 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
177 llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
179 /// A void(void) inline asm to use to mark that the return value of
180 /// a call will be immediately retain.
181 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
183 /// void clang.arc.use(...);
184 llvm::Constant *clang_arc_use;
187 /// This class records statistics on instrumentation based profiling.
188 class InstrProfStats {
189 uint32_t VisitedInMainFile;
190 uint32_t MissingInMainFile;
197 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
199 /// Record that we've visited a function and whether or not that function was
200 /// in the main source file.
201 void addVisited(bool MainFile) {
206 /// Record that a function we've visited has no profile data.
207 void addMissing(bool MainFile) {
212 /// Record that a function we've visited has mismatched profile data.
213 void addMismatched(bool MainFile) { ++Mismatched; }
214 /// Whether or not the stats we've gathered indicate any potential problems.
215 bool hasDiagnostics() { return Missing || Mismatched; }
216 /// Report potential problems we've found to \c Diags.
217 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
220 /// A pair of helper functions for a __block variable.
221 class BlockByrefHelpers : public llvm::FoldingSetNode {
222 // MSVC requires this type to be complete in order to process this
225 llvm::Constant *CopyHelper;
226 llvm::Constant *DisposeHelper;
228 /// The alignment of the field. This is important because
229 /// different offsets to the field within the byref struct need to
230 /// have different helper functions.
233 BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
234 BlockByrefHelpers(const BlockByrefHelpers &) = default;
235 virtual ~BlockByrefHelpers();
237 void Profile(llvm::FoldingSetNodeID &id) const {
238 id.AddInteger(Alignment.getQuantity());
241 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
243 virtual bool needsCopy() const { return true; }
244 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
246 virtual bool needsDispose() const { return true; }
247 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
250 /// This class organizes the cross-function state that is used while generating
252 class CodeGenModule : public CodeGenTypeCache {
253 CodeGenModule(const CodeGenModule &) = delete;
254 void operator=(const CodeGenModule &) = delete;
258 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
259 Structor(int Priority, llvm::Constant *Initializer,
260 llvm::Constant *AssociatedData)
261 : Priority(Priority), Initializer(Initializer),
262 AssociatedData(AssociatedData) {}
264 llvm::Constant *Initializer;
265 llvm::Constant *AssociatedData;
268 typedef std::vector<Structor> CtorList;
272 const LangOptions &LangOpts;
273 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
274 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
275 const CodeGenOptions &CodeGenOpts;
276 llvm::Module &TheModule;
277 DiagnosticsEngine &Diags;
278 const TargetInfo &Target;
279 std::unique_ptr<CGCXXABI> ABI;
280 llvm::LLVMContext &VMContext;
282 std::unique_ptr<CodeGenTBAA> TBAA;
284 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
286 // This should not be moved earlier, since its initialization depends on some
287 // of the previous reference members being already initialized and also checks
288 // if TheTargetCodeGenInfo is NULL
291 /// Holds information about C++ vtables.
292 CodeGenVTables VTables;
294 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
295 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
296 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
297 std::unique_ptr<CGCUDARuntime> CUDARuntime;
298 std::unique_ptr<CGDebugInfo> DebugInfo;
299 std::unique_ptr<ObjCEntrypoints> ObjCData;
300 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
301 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
302 InstrProfStats PGOStats;
303 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
305 // A set of references that have only been seen via a weakref so far. This is
306 // used to remove the weak of the reference if we ever see a direct reference
308 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
310 /// This contains all the decls which have definitions but/ which are deferred
311 /// for emission and therefore should only be output if they are actually
312 /// used. If a decl is in this, then it is known to have not been referenced
314 std::map<StringRef, GlobalDecl> DeferredDecls;
316 /// This is a list of deferred decls which we have seen that *are* actually
317 /// referenced. These get code generated when the module is done.
318 std::vector<GlobalDecl> DeferredDeclsToEmit;
319 void addDeferredDeclToEmit(GlobalDecl GD) {
320 DeferredDeclsToEmit.emplace_back(GD);
323 /// List of alias we have emitted. Used to make sure that what they point to
324 /// is defined once we get to the end of the of the translation unit.
325 std::vector<GlobalDecl> Aliases;
327 /// List of multiversion functions that have to be emitted. Used to make sure
328 /// we properly emit the iFunc.
329 std::vector<GlobalDecl> MultiVersionFuncs;
331 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
332 ReplacementsTy Replacements;
334 /// List of global values to be replaced with something else. Used when we
335 /// want to replace a GlobalValue but can't identify it by its mangled name
336 /// anymore (because the name is already taken).
337 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
338 GlobalValReplacements;
340 /// Set of global decls for which we already diagnosed mangled name conflict.
341 /// Required to not issue a warning (on a mangling conflict) multiple times
342 /// for the same decl.
343 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
345 /// A queue of (optional) vtables to consider emitting.
346 std::vector<const CXXRecordDecl*> DeferredVTables;
348 /// A queue of (optional) vtables that may be emitted opportunistically.
349 std::vector<const CXXRecordDecl *> OpportunisticVTables;
351 /// List of global values which are required to be present in the object file;
352 /// bitcast to i8*. This is used for forcing visibility of symbols which may
353 /// otherwise be optimized out.
354 std::vector<llvm::WeakTrackingVH> LLVMUsed;
355 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
357 /// Store the list of global constructors and their respective priorities to
358 /// be emitted when the translation unit is complete.
359 CtorList GlobalCtors;
361 /// Store the list of global destructors and their respective priorities to be
362 /// emitted when the translation unit is complete.
363 CtorList GlobalDtors;
365 /// An ordered map of canonical GlobalDecls to their mangled names.
366 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
367 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
369 // An ordered map of canonical GlobalDecls paired with the cpu-index for
370 // cpu-specific name manglings.
371 llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef>
372 CPUSpecificMangledDeclNames;
373 llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator>
374 CPUSpecificManglings;
376 /// Global annotations.
377 std::vector<llvm::Constant*> Annotations;
379 /// Map used to get unique annotation strings.
380 llvm::StringMap<llvm::Constant*> AnnotationStrings;
382 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
384 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
385 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
386 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
387 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
389 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
390 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
392 /// Map used to get unique type descriptor constants for sanitizers.
393 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
395 /// Map used to track internal linkage functions declared within
396 /// extern "C" regions.
397 typedef llvm::MapVector<IdentifierInfo *,
398 llvm::GlobalValue *> StaticExternCMap;
399 StaticExternCMap StaticExternCValues;
401 /// thread_local variables defined or used in this TU.
402 std::vector<const VarDecl *> CXXThreadLocals;
404 /// thread_local variables with initializers that need to run
405 /// before any thread_local variable in this TU is odr-used.
406 std::vector<llvm::Function *> CXXThreadLocalInits;
407 std::vector<const VarDecl *> CXXThreadLocalInitVars;
409 /// Global variables with initializers that need to run before main.
410 std::vector<llvm::Function *> CXXGlobalInits;
412 /// When a C++ decl with an initializer is deferred, null is
413 /// appended to CXXGlobalInits, and the index of that null is placed
414 /// here so that the initializer will be performed in the correct
415 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
416 /// that we don't re-emit the initializer.
417 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
419 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
421 struct GlobalInitPriorityCmp {
422 bool operator()(const GlobalInitData &LHS,
423 const GlobalInitData &RHS) const {
424 return LHS.first.priority < RHS.first.priority;
428 /// Global variables with initializers whose order of initialization is set by
429 /// init_priority attribute.
430 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
432 /// Global destructor functions and arguments that need to run on termination.
433 std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>> CXXGlobalDtors;
435 /// The complete set of modules that has been imported.
436 llvm::SetVector<clang::Module *> ImportedModules;
438 /// The set of modules for which the module initializers
439 /// have been emitted.
440 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
442 /// A vector of metadata strings.
443 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
445 /// @name Cache for Objective-C runtime types
448 /// Cached reference to the class for constant strings. This value has type
449 /// int * but is actually an Obj-C class pointer.
450 llvm::WeakTrackingVH CFConstantStringClassRef;
452 /// The type used to describe the state of a fast enumeration in
453 /// Objective-C's for..in loop.
454 QualType ObjCFastEnumerationStateType;
458 /// Lazily create the Objective-C runtime
459 void createObjCRuntime();
461 void createOpenCLRuntime();
462 void createOpenMPRuntime();
463 void createCUDARuntime();
465 bool isTriviallyRecursive(const FunctionDecl *F);
466 bool shouldEmitFunction(GlobalDecl GD);
467 bool shouldOpportunisticallyEmitVTables();
468 /// Map used to be sure we don't emit the same CompoundLiteral twice.
469 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
470 EmittedCompoundLiterals;
472 /// Map of the global blocks we've emitted, so that we don't have to re-emit
473 /// them if the constexpr evaluator gets aggressive.
474 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
476 /// @name Cache for Blocks Runtime Globals
479 llvm::Constant *NSConcreteGlobalBlock = nullptr;
480 llvm::Constant *NSConcreteStackBlock = nullptr;
482 llvm::Constant *BlockObjectAssign = nullptr;
483 llvm::Constant *BlockObjectDispose = nullptr;
485 llvm::Type *BlockDescriptorType = nullptr;
486 llvm::Type *GenericBlockLiteralType = nullptr;
489 int GlobalUniqueCount;
492 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
493 llvm::Constant *LifetimeStartFn = nullptr;
495 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
496 llvm::Constant *LifetimeEndFn = nullptr;
498 GlobalDecl initializedGlobalDecl;
500 std::unique_ptr<SanitizerMetadata> SanitizerMD;
504 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
506 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
508 /// Mapping from canonical types to their metadata identifiers. We need to
509 /// maintain this mapping because identifiers may be formed from distinct
511 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
512 MetadataTypeMap MetadataIdMap;
513 MetadataTypeMap VirtualMetadataIdMap;
514 MetadataTypeMap GeneralizedMetadataIdMap;
517 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
518 const PreprocessorOptions &ppopts,
519 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
520 DiagnosticsEngine &Diags,
521 CoverageSourceInfo *CoverageInfo = nullptr);
527 /// Finalize LLVM code generation.
530 /// Return true if we should emit location information for expressions.
531 bool getExpressionLocationsEnabled() const;
533 /// Return a reference to the configured Objective-C runtime.
534 CGObjCRuntime &getObjCRuntime() {
535 if (!ObjCRuntime) createObjCRuntime();
539 /// Return true iff an Objective-C runtime has been configured.
540 bool hasObjCRuntime() { return !!ObjCRuntime; }
542 /// Return a reference to the configured OpenCL runtime.
543 CGOpenCLRuntime &getOpenCLRuntime() {
544 assert(OpenCLRuntime != nullptr);
545 return *OpenCLRuntime;
548 /// Return a reference to the configured OpenMP runtime.
549 CGOpenMPRuntime &getOpenMPRuntime() {
550 assert(OpenMPRuntime != nullptr);
551 return *OpenMPRuntime;
554 /// Return a reference to the configured CUDA runtime.
555 CGCUDARuntime &getCUDARuntime() {
556 assert(CUDARuntime != nullptr);
560 ObjCEntrypoints &getObjCEntrypoints() const {
561 assert(ObjCData != nullptr);
565 // Version checking function, used to implement ObjC's @available:
566 // i32 @__isOSVersionAtLeast(i32, i32, i32)
567 llvm::Constant *IsOSVersionAtLeastFn = nullptr;
569 InstrProfStats &getPGOStats() { return PGOStats; }
570 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
572 CoverageMappingModuleGen *getCoverageMapping() const {
573 return CoverageMapping.get();
576 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
577 return StaticLocalDeclMap[D];
579 void setStaticLocalDeclAddress(const VarDecl *D,
581 StaticLocalDeclMap[D] = C;
585 getOrCreateStaticVarDecl(const VarDecl &D,
586 llvm::GlobalValue::LinkageTypes Linkage);
588 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
589 return StaticLocalDeclGuardMap[D];
591 void setStaticLocalDeclGuardAddress(const VarDecl *D,
592 llvm::GlobalVariable *C) {
593 StaticLocalDeclGuardMap[D] = C;
596 bool lookupRepresentativeDecl(StringRef MangledName,
597 GlobalDecl &Result) const;
599 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
600 return AtomicSetterHelperFnMap[Ty];
602 void setAtomicSetterHelperFnMap(QualType Ty,
603 llvm::Constant *Fn) {
604 AtomicSetterHelperFnMap[Ty] = Fn;
607 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
608 return AtomicGetterHelperFnMap[Ty];
610 void setAtomicGetterHelperFnMap(QualType Ty,
611 llvm::Constant *Fn) {
612 AtomicGetterHelperFnMap[Ty] = Fn;
615 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
616 return TypeDescriptorMap[Ty];
618 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
619 TypeDescriptorMap[Ty] = C;
622 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
624 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
625 if (!NoObjCARCExceptionsMetadata)
626 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
627 return NoObjCARCExceptionsMetadata;
630 ASTContext &getContext() const { return Context; }
631 const LangOptions &getLangOpts() const { return LangOpts; }
632 const HeaderSearchOptions &getHeaderSearchOpts()
633 const { return HeaderSearchOpts; }
634 const PreprocessorOptions &getPreprocessorOpts()
635 const { return PreprocessorOpts; }
636 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
637 llvm::Module &getModule() const { return TheModule; }
638 DiagnosticsEngine &getDiags() const { return Diags; }
639 const llvm::DataLayout &getDataLayout() const {
640 return TheModule.getDataLayout();
642 const TargetInfo &getTarget() const { return Target; }
643 const llvm::Triple &getTriple() const { return Target.getTriple(); }
644 bool supportsCOMDAT() const;
645 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
647 CGCXXABI &getCXXABI() const { return *ABI; }
648 llvm::LLVMContext &getLLVMContext() { return VMContext; }
650 bool shouldUseTBAA() const { return TBAA != nullptr; }
652 const TargetCodeGenInfo &getTargetCodeGenInfo();
654 CodeGenTypes &getTypes() { return Types; }
656 CodeGenVTables &getVTables() { return VTables; }
658 ItaniumVTableContext &getItaniumVTableContext() {
659 return VTables.getItaniumVTableContext();
662 MicrosoftVTableContext &getMicrosoftVTableContext() {
663 return VTables.getMicrosoftVTableContext();
666 CtorList &getGlobalCtors() { return GlobalCtors; }
667 CtorList &getGlobalDtors() { return GlobalDtors; }
669 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
671 llvm::MDNode *getTBAATypeInfo(QualType QTy);
673 /// getTBAAAccessInfo - Get TBAA information that describes an access to
674 /// an object of the given type.
675 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
677 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
678 /// access to a virtual table pointer.
679 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
681 llvm::MDNode *getTBAAStructInfo(QualType QTy);
683 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
684 /// type. Return null if the type is not suitable for use in TBAA access tags.
685 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
687 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
688 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
690 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
692 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
693 TBAAAccessInfo TargetInfo);
695 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
696 /// purposes of conditional operator.
697 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
698 TBAAAccessInfo InfoB);
700 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
701 /// purposes of memory transfer calls.
702 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
703 TBAAAccessInfo SrcInfo);
705 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
707 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
708 if (Base.getTBAAInfo().isMayAlias())
709 return TBAAAccessInfo::getMayAliasInfo();
710 return getTBAAAccessInfo(AccessType);
713 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
715 bool isPaddedAtomicType(QualType type);
716 bool isPaddedAtomicType(const AtomicType *type);
718 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
719 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
720 TBAAAccessInfo TBAAInfo);
722 /// Adds !invariant.barrier !tag to instruction
723 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
724 const CXXRecordDecl *RD);
726 /// Emit the given number of characters as a value of type size_t.
727 llvm::ConstantInt *getSize(CharUnits numChars);
729 /// Set the visibility for the given LLVM GlobalValue.
730 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
732 void setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
733 const NamedDecl *D) const;
735 void setDSOLocal(llvm::GlobalValue *GV) const;
737 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
738 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
739 /// Set visibility, dllimport/dllexport and dso_local.
740 /// This must be called after dllimport/dllexport is set.
741 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
742 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
744 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
745 /// variable declaration D.
746 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
748 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
750 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
751 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
752 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
754 llvm_unreachable("unknown visibility!");
757 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
758 ForDefinition_t IsForDefinition
761 /// Will return a global variable of the given type. If a variable with a
762 /// different type already exists then a new variable with the right type
763 /// will be created and all uses of the old variable will be replaced with a
764 /// bitcast to the new variable.
765 llvm::GlobalVariable *
766 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
767 llvm::GlobalValue::LinkageTypes Linkage);
770 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
771 const CGFunctionInfo &FI,
772 SourceLocation Loc = SourceLocation(),
775 /// Return the AST address space of the underlying global variable for D, as
776 /// determined by its declaration. Normally this is the same as the address
777 /// space of D's type, but in CUDA, address spaces are associated with
778 /// declarations, not types. If D is nullptr, return the default address
779 /// space for global variable.
781 /// For languages without explicit address spaces, if D has default address
782 /// space, target-specific global or constant address space may be returned.
783 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
785 /// Return the llvm::Constant for the address of the given global variable.
786 /// If Ty is non-null and if the global doesn't exist, then it will be created
787 /// with the specified type instead of whatever the normal requested type
788 /// would be. If IsForDefinition is true, it is guaranteed that an actual
789 /// global with type Ty will be returned, not conversion of a variable with
790 /// the same mangled name but some other type.
791 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
792 llvm::Type *Ty = nullptr,
793 ForDefinition_t IsForDefinition
796 /// Return the AST address space of string literal, which is used to emit
797 /// the string literal as global variable in LLVM IR.
798 /// Note: This is not necessarily the address space of the string literal
799 /// in AST. For address space agnostic language, e.g. C++, string literal
800 /// in AST is always in default address space.
801 LangAS getStringLiteralAddressSpace() const;
803 /// Return the address of the given function. If Ty is non-null, then this
804 /// function will use the specified type if it has to create it.
805 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
806 bool ForVTable = false,
807 bool DontDefer = false,
808 ForDefinition_t IsForDefinition
811 /// Get the address of the RTTI descriptor for the given type.
812 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
814 /// Get the address of a uuid descriptor .
815 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
817 /// Get the address of the thunk for the given global decl.
818 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
821 /// Get a reference to the target of VD.
822 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
824 /// Returns the assumed alignment of an opaque pointer to the given class.
825 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
827 /// Returns the assumed alignment of a virtual base of a class.
828 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
829 const CXXRecordDecl *Derived,
830 const CXXRecordDecl *VBase);
832 /// Given a class pointer with an actual known alignment, and the
833 /// expected alignment of an object at a dynamic offset w.r.t that
834 /// pointer, return the alignment to assume at the offset.
835 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
836 const CXXRecordDecl *Class,
837 CharUnits ExpectedTargetAlign);
840 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
841 CastExpr::path_const_iterator Start,
842 CastExpr::path_const_iterator End);
844 /// Returns the offset from a derived class to a class. Returns null if the
847 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
848 CastExpr::path_const_iterator PathBegin,
849 CastExpr::path_const_iterator PathEnd);
851 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
853 /// Fetches the global unique block count.
854 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
856 /// Fetches the type of a generic block descriptor.
857 llvm::Type *getBlockDescriptorType();
859 /// The type of a generic block literal.
860 llvm::Type *getGenericBlockLiteralType();
862 /// Gets the address of a block which requires no captures.
863 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
865 /// Returns the address of a block which requires no caputres, or null if
866 /// we've yet to emit the block for BE.
867 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
868 return EmittedGlobalBlocks.lookup(BE);
871 /// Notes that BE's global block is available via Addr. Asserts that BE
872 /// isn't already emitted.
873 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
875 /// Return a pointer to a constant CFString object for the given string.
876 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
878 /// Return a pointer to a constant NSString object for the given string. Or a
879 /// user defined String object as defined via
880 /// -fconstant-string-class=class_name option.
881 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
883 /// Return a constant array for the given string.
884 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
886 /// Return a pointer to a constant array for the given string literal.
888 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
889 StringRef Name = ".str");
891 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
893 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
895 /// Returns a pointer to a character array containing the literal and a
896 /// terminating '\0' character. The result has pointer to array type.
898 /// \param GlobalName If provided, the name to use for the global (if one is
901 GetAddrOfConstantCString(const std::string &Str,
902 const char *GlobalName = nullptr);
904 /// Returns a pointer to a constant global variable for the given file-scope
905 /// compound literal expression.
906 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
908 /// If it's been emitted already, returns the GlobalVariable corresponding to
909 /// a compound literal. Otherwise, returns null.
910 llvm::GlobalVariable *
911 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
913 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
915 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
916 llvm::GlobalVariable *GV);
918 /// Returns a pointer to a global variable representing a temporary
919 /// with static or thread storage duration.
920 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
923 /// Retrieve the record type that describes the state of an
924 /// Objective-C fast enumeration loop (for..in).
925 QualType getObjCFastEnumerationStateType();
927 // Produce code for this constructor/destructor. This method doesn't try
928 // to apply any ABI rules about which other constructors/destructors
929 // are needed or if they are alias to each other.
930 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
933 /// Return the address of the constructor/destructor of the given type.
935 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
936 const CGFunctionInfo *FnInfo = nullptr,
937 llvm::FunctionType *FnType = nullptr,
938 bool DontDefer = false,
939 ForDefinition_t IsForDefinition = NotForDefinition);
941 /// Given a builtin id for a function like "__builtin_fabsf", return a
942 /// Function* for "fabsf".
943 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
946 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
948 /// Emit code for a single top level declaration.
949 void EmitTopLevelDecl(Decl *D);
951 /// Stored a deferred empty coverage mapping for an unused
952 /// and thus uninstrumented top level declaration.
953 void AddDeferredUnusedCoverageMapping(Decl *D);
955 /// Remove the deferred empty coverage mapping as this
956 /// declaration is actually instrumented.
957 void ClearUnusedCoverageMapping(const Decl *D);
959 /// Emit all the deferred coverage mappings
960 /// for the uninstrumented functions.
961 void EmitDeferredUnusedCoverageMappings();
963 /// Tell the consumer that this variable has been instantiated.
964 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
966 /// If the declaration has internal linkage but is inside an
967 /// extern "C" linkage specification, prepare to emit an alias for it
968 /// to the expected name.
969 template<typename SomeDecl>
970 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
972 /// Add a global to a list to be added to the llvm.used metadata.
973 void addUsedGlobal(llvm::GlobalValue *GV);
975 /// Add a global to a list to be added to the llvm.compiler.used metadata.
976 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
978 /// Add a destructor and object to add to the C++ global destructor function.
979 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
980 CXXGlobalDtors.emplace_back(DtorFn, Object);
983 /// Create a new runtime function with the specified type and name.
985 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
986 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
989 /// Create a new compiler builtin function with the specified type and name.
991 CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name,
992 llvm::AttributeList ExtraAttrs = llvm::AttributeList());
993 /// Create a new runtime global variable with the specified type and name.
994 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
997 ///@name Custom Blocks Runtime Interfaces
1000 llvm::Constant *getNSConcreteGlobalBlock();
1001 llvm::Constant *getNSConcreteStackBlock();
1002 llvm::Constant *getBlockObjectAssign();
1003 llvm::Constant *getBlockObjectDispose();
1007 llvm::Constant *getLLVMLifetimeStartFn();
1008 llvm::Constant *getLLVMLifetimeEndFn();
1010 // Make sure that this type is translated.
1011 void UpdateCompletedType(const TagDecl *TD);
1013 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1015 /// Emit type info if type of an expression is a variably modified
1016 /// type. Also emit proper debug info for cast types.
1017 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1018 CodeGenFunction *CGF = nullptr);
1020 /// Return the result of value-initializing the given type, i.e. a null
1021 /// expression of the given type. This is usually, but not always, an LLVM
1023 llvm::Constant *EmitNullConstant(QualType T);
1025 /// Return a null constant appropriate for zero-initializing a base class with
1026 /// the given type. This is usually, but not always, an LLVM null constant.
1027 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1029 /// Emit a general error that something can't be done.
1030 void Error(SourceLocation loc, StringRef error);
1032 /// Print out an error that codegen doesn't support the specified stmt yet.
1033 void ErrorUnsupported(const Stmt *S, const char *Type);
1035 /// Print out an error that codegen doesn't support the specified decl yet.
1036 void ErrorUnsupported(const Decl *D, const char *Type);
1038 /// Set the attributes on the LLVM function for the given decl and function
1039 /// info. This applies attributes necessary for handling the ABI as well as
1040 /// user specified attributes like section.
1041 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1042 const CGFunctionInfo &FI);
1044 /// Set the LLVM function attributes (sext, zext, etc).
1045 void SetLLVMFunctionAttributes(const Decl *D,
1046 const CGFunctionInfo &Info,
1049 /// Set the LLVM function attributes which only apply to a function
1051 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1053 /// Return true iff the given type uses 'sret' when used as a return type.
1054 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1056 /// Return true iff the given type uses an argument slot when 'sret' is used
1057 /// as a return type.
1058 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1060 /// Return true iff the given type uses 'fpret' when used as a return type.
1061 bool ReturnTypeUsesFPRet(QualType ResultType);
1063 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1064 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1066 /// Get the LLVM attributes and calling convention to use for a particular
1069 /// \param Name - The function name.
1070 /// \param Info - The function type information.
1071 /// \param CalleeInfo - The callee information these attributes are being
1072 /// constructed for. If valid, the attributes applied to this decl may
1073 /// contribute to the function attributes and calling convention.
1074 /// \param Attrs [out] - On return, the attribute list to use.
1075 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1076 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1077 CGCalleeInfo CalleeInfo,
1078 llvm::AttributeList &Attrs, unsigned &CallingConv,
1079 bool AttrOnCallSite);
1081 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1082 /// though we had emitted it ourselves. We remove any attributes on F that
1083 /// conflict with the attributes we add here.
1085 /// This is useful for adding attrs to bitcode modules that you want to link
1086 /// with but don't control, such as CUDA's libdevice. When linking with such
1087 /// a bitcode library, you might want to set e.g. its functions'
1088 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1089 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1090 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1091 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1092 /// function in the bitcode library!
1094 /// With the exception of fast-math attrs, this will only make the attributes
1095 /// on the function more conservative. But it's unsafe to call this on a
1096 /// function which relies on particular fast-math attributes for correctness.
1097 /// It's up to you to ensure that this is safe.
1098 void AddDefaultFnAttrs(llvm::Function &F);
1100 /// Parses the target attributes passed in, and returns only the ones that are
1101 /// valid feature names.
1102 TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD);
1104 // Fills in the supplied string map with the set of target features for the
1105 // passed in function.
1106 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
1107 const FunctionDecl *FD);
1109 StringRef getMangledName(GlobalDecl GD);
1110 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1112 void EmitTentativeDefinition(const VarDecl *D);
1114 void EmitVTable(CXXRecordDecl *Class);
1116 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1118 /// Appends Opts to the "llvm.linker.options" metadata value.
1119 void AppendLinkerOptions(StringRef Opts);
1121 /// Appends a detect mismatch command to the linker options.
1122 void AddDetectMismatch(StringRef Name, StringRef Value);
1124 /// Appends a dependent lib to the "llvm.linker.options" metadata
1126 void AddDependentLib(StringRef Lib);
1128 void AddELFLibDirective(StringRef Lib);
1130 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1132 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1133 F->setLinkage(getFunctionLinkage(GD));
1136 /// Return the appropriate linkage for the vtable, VTT, and type information
1137 /// of the given class.
1138 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1140 /// Return the store size, in character units, of the given LLVM type.
1141 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1143 /// Returns LLVM linkage for a declarator.
1144 llvm::GlobalValue::LinkageTypes
1145 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1146 bool IsConstantVariable);
1148 /// Returns LLVM linkage for a declarator.
1149 llvm::GlobalValue::LinkageTypes
1150 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1152 /// Emit all the global annotations.
1153 void EmitGlobalAnnotations();
1155 /// Emit an annotation string.
1156 llvm::Constant *EmitAnnotationString(StringRef Str);
1158 /// Emit the annotation's translation unit.
1159 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1161 /// Emit the annotation line number.
1162 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1164 /// Generate the llvm::ConstantStruct which contains the annotation
1165 /// information for a given GlobalValue. The annotation struct is
1166 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1167 /// GlobalValue being annotated. The second field is the constant string
1168 /// created from the AnnotateAttr's annotation. The third field is a constant
1169 /// string containing the name of the translation unit. The fourth field is
1170 /// the line number in the file of the annotated value declaration.
1171 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1172 const AnnotateAttr *AA,
1175 /// Add global annotations that are set on D, for the global GV. Those
1176 /// annotations are emitted during finalization of the LLVM code.
1177 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1179 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn,
1180 SourceLocation Loc) const;
1182 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1184 StringRef Category = StringRef()) const;
1186 /// Imbue XRay attributes to a function, applying the always/never attribute
1187 /// lists in the process. Returns true if we did imbue attributes this way,
1188 /// false otherwise.
1189 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1190 StringRef Category = StringRef()) const;
1192 SanitizerMetadata *getSanitizerMetadata() {
1193 return SanitizerMD.get();
1196 void addDeferredVTable(const CXXRecordDecl *RD) {
1197 DeferredVTables.push_back(RD);
1200 /// Emit code for a single global function or var decl. Forward declarations
1201 /// are emitted lazily.
1202 void EmitGlobal(GlobalDecl D);
1204 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1206 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1208 /// Set attributes which are common to any form of a global definition (alias,
1209 /// Objective-C method, function, global variable).
1211 /// NOTE: This should only be called for definitions.
1212 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1214 void addReplacement(StringRef Name, llvm::Constant *C);
1216 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1218 /// Emit a code for threadprivate directive.
1219 /// \param D Threadprivate declaration.
1220 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1222 /// Emit a code for declare reduction construct.
1223 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1224 CodeGenFunction *CGF = nullptr);
1226 /// Returns whether the given record has hidden LTO visibility and therefore
1227 /// may participate in (single-module) CFI and whole-program vtable
1229 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1231 /// Emit type metadata for the given vtable using the given layout.
1232 void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1233 const VTableLayout &VTLayout);
1235 /// Generate a cross-DSO type identifier for MD.
1236 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1238 /// Create a metadata identifier for the given type. This may either be an
1239 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1240 /// internal identifiers).
1241 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1243 /// Create a metadata identifier that is intended to be used to check virtual
1244 /// calls via a member function pointer.
1245 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1247 /// Create a metadata identifier for the generalization of the given type.
1248 /// This may either be an MDString (for external identifiers) or a distinct
1249 /// unnamed MDNode (for internal identifiers).
1250 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1252 /// Create and attach type metadata to the given function.
1253 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1256 /// Returns whether this module needs the "all-vtables" type identifier.
1257 bool NeedAllVtablesTypeId() const;
1259 /// Create and attach type metadata for the given vtable.
1260 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1261 const CXXRecordDecl *RD);
1263 /// Return a vector of most-base classes for RD. This is used to implement
1264 /// control flow integrity checks for member function pointers.
1266 /// A most-base class of a class C is defined as a recursive base class of C,
1267 /// including C itself, that does not have any bases.
1268 std::vector<const CXXRecordDecl *>
1269 getMostBaseClasses(const CXXRecordDecl *RD);
1271 /// Get the declaration of std::terminate for the platform.
1272 llvm::Constant *getTerminateFn();
1274 llvm::SanitizerStatReport &getSanStats();
1277 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1279 /// Get target specific null pointer.
1280 /// \param T is the LLVM type of the null pointer.
1281 /// \param QT is the clang QualType of the null pointer.
1282 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1285 llvm::Constant *GetOrCreateLLVMFunction(
1286 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1287 bool DontDefer = false, bool IsThunk = false,
1288 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1289 ForDefinition_t IsForDefinition = NotForDefinition);
1291 llvm::Constant *GetOrCreateMultiVersionIFunc(GlobalDecl GD,
1293 const FunctionDecl *FD);
1294 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD);
1296 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1297 llvm::PointerType *PTy,
1299 ForDefinition_t IsForDefinition
1300 = NotForDefinition);
1302 bool GetCPUAndFeaturesAttributes(const Decl *D,
1303 llvm::AttrBuilder &AttrBuilder);
1304 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1306 /// Set function attributes for a function declaration.
1307 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1308 bool IsIncompleteFunction, bool IsThunk);
1310 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1312 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1313 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1314 void EmitAliasDefinition(GlobalDecl GD);
1315 void emitIFuncDefinition(GlobalDecl GD);
1316 void emitCPUDispatchDefinition(GlobalDecl GD);
1317 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1318 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1320 // C++ related functions.
1322 void EmitDeclContext(const DeclContext *DC);
1323 void EmitLinkageSpec(const LinkageSpecDecl *D);
1325 /// Emit the function that initializes C++ thread_local variables.
1326 void EmitCXXThreadLocalInitFunc();
1328 /// Emit the function that initializes C++ globals.
1329 void EmitCXXGlobalInitFunc();
1331 /// Emit the function that destroys C++ globals.
1332 void EmitCXXGlobalDtorFunc();
1334 /// Emit the function that initializes the specified global (if PerformInit is
1335 /// true) and registers its destructor.
1336 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1337 llvm::GlobalVariable *Addr,
1340 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1341 llvm::Function *InitFunc, InitSegAttr *ISA);
1343 // FIXME: Hardcoding priority here is gross.
1344 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1345 llvm::Constant *AssociatedData = nullptr);
1346 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1348 /// EmitCtorList - Generates a global array of functions and priorities using
1349 /// the given list and name. This array will have appending linkage and is
1350 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1351 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1353 /// Emit any needed decls for which code generation was deferred.
1354 void EmitDeferred();
1356 /// Try to emit external vtables as available_externally if they have emitted
1357 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1358 /// is not allowed to create new references to things that need to be emitted
1360 void EmitVTablesOpportunistically();
1362 /// Call replaceAllUsesWith on all pairs in Replacements.
1363 void applyReplacements();
1365 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1366 void applyGlobalValReplacements();
1368 void checkAliases();
1370 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1372 /// Register functions annotated with __attribute__((destructor)) using
1373 /// __cxa_atexit, if it is available, or atexit otherwise.
1374 void registerGlobalDtorsWithAtExit();
1376 void emitMultiVersionFunctions();
1378 /// Emit any vtables which we deferred and still have a use for.
1379 void EmitDeferredVTables();
1381 /// Emit a dummy function that reference a CoreFoundation symbol when
1382 /// @available is used on Darwin.
1383 void emitAtAvailableLinkGuard();
1385 /// Emit the llvm.used and llvm.compiler.used metadata.
1386 void emitLLVMUsed();
1388 /// Emit the link options introduced by imported modules.
1389 void EmitModuleLinkOptions();
1391 /// Emit aliases for internal-linkage declarations inside "C" language
1392 /// linkage specifications, giving them the "expected" name where possible.
1393 void EmitStaticExternCAliases();
1395 void EmitDeclMetadata();
1397 /// Emit the Clang version as llvm.ident metadata.
1398 void EmitVersionIdentMetadata();
1400 /// Emits target specific Metadata for global declarations.
1401 void EmitTargetMetadata();
1403 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1404 void EmitOpenCLMetadata();
1406 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1407 /// .gcda files in a way that persists in .bc files.
1408 void EmitCoverageFile();
1410 /// Emits the initializer for a uuidof string.
1411 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1413 /// Determine whether the definition must be emitted; if this returns \c
1414 /// false, the definition can be emitted lazily if it's used.
1415 bool MustBeEmitted(const ValueDecl *D);
1417 /// Determine whether the definition can be emitted eagerly, or should be
1418 /// delayed until the end of the translation unit. This is relevant for
1419 /// definitions whose linkage can change, e.g. implicit function instantions
1420 /// which may later be explicitly instantiated.
1421 bool MayBeEmittedEagerly(const ValueDecl *D);
1423 /// Check whether we can use a "simpler", more core exceptions personality
1425 void SimplifyPersonality();
1427 /// Helper function for ConstructAttributeList and AddDefaultFnAttrs.
1428 /// Constructs an AttrList for a function with the given properties.
1429 void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1430 bool AttrOnCallSite,
1431 llvm::AttrBuilder &FuncAttrs);
1433 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1437 } // end namespace CodeGen
1438 } // end namespace clang
1440 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H