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/GlobalDecl.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/SanitizerBlacklist.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 IndexedInstrProfReader;
51 class TargetCodeGenInfo;
57 class ObjCImplementationDecl;
58 class ObjCCategoryImplDecl;
59 class ObjCProtocolDecl;
73 class HeaderSearchOptions;
74 class PreprocessorOptions;
75 class DiagnosticsEngine;
77 class CXXDestructorDecl;
79 class CoverageSourceInfo;
84 class CodeGenFunction;
89 class CGOpenCLRuntime;
90 class CGOpenMPRuntime;
92 class BlockFieldFlags;
93 class FunctionArgList;
94 class CoverageMappingModuleGen;
96 struct OrderGlobalInits {
97 unsigned int priority;
98 unsigned int lex_order;
99 OrderGlobalInits(unsigned int p, unsigned int l)
100 : priority(p), lex_order(l) {}
102 bool operator==(const OrderGlobalInits &RHS) const {
103 return priority == RHS.priority && lex_order == RHS.lex_order;
106 bool operator<(const OrderGlobalInits &RHS) const {
107 return std::tie(priority, lex_order) <
108 std::tie(RHS.priority, RHS.lex_order);
112 struct ObjCEntrypoints {
113 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
115 /// void objc_autoreleasePoolPop(void*);
116 llvm::Constant *objc_autoreleasePoolPop;
118 /// void *objc_autoreleasePoolPush(void);
119 llvm::Constant *objc_autoreleasePoolPush;
121 /// id objc_autorelease(id);
122 llvm::Constant *objc_autorelease;
124 /// id objc_autoreleaseReturnValue(id);
125 llvm::Constant *objc_autoreleaseReturnValue;
127 /// void objc_copyWeak(id *dest, id *src);
128 llvm::Constant *objc_copyWeak;
130 /// void objc_destroyWeak(id*);
131 llvm::Constant *objc_destroyWeak;
133 /// id objc_initWeak(id*, id);
134 llvm::Constant *objc_initWeak;
136 /// id objc_loadWeak(id*);
137 llvm::Constant *objc_loadWeak;
139 /// id objc_loadWeakRetained(id*);
140 llvm::Constant *objc_loadWeakRetained;
142 /// void objc_moveWeak(id *dest, id *src);
143 llvm::Constant *objc_moveWeak;
145 /// id objc_retain(id);
146 llvm::Constant *objc_retain;
148 /// id objc_retainAutorelease(id);
149 llvm::Constant *objc_retainAutorelease;
151 /// id objc_retainAutoreleaseReturnValue(id);
152 llvm::Constant *objc_retainAutoreleaseReturnValue;
154 /// id objc_retainAutoreleasedReturnValue(id);
155 llvm::Constant *objc_retainAutoreleasedReturnValue;
157 /// id objc_retainBlock(id);
158 llvm::Constant *objc_retainBlock;
160 /// void objc_release(id);
161 llvm::Constant *objc_release;
163 /// id objc_storeStrong(id*, id);
164 llvm::Constant *objc_storeStrong;
166 /// id objc_storeWeak(id*, id);
167 llvm::Constant *objc_storeWeak;
169 /// A void(void) inline asm to use to mark that the return value of
170 /// a call will be immediately retain.
171 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
173 /// void clang.arc.use(...);
174 llvm::Constant *clang_arc_use;
177 /// This class records statistics on instrumentation based profiling.
178 class InstrProfStats {
179 uint32_t VisitedInMainFile;
180 uint32_t MissingInMainFile;
187 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
189 /// Record that we've visited a function and whether or not that function was
190 /// in the main source file.
191 void addVisited(bool MainFile) {
196 /// Record that a function we've visited has no profile data.
197 void addMissing(bool MainFile) {
202 /// Record that a function we've visited has mismatched profile data.
203 void addMismatched(bool MainFile) { ++Mismatched; }
204 /// Whether or not the stats we've gathered indicate any potential problems.
205 bool hasDiagnostics() { return Missing || Mismatched; }
206 /// Report potential problems we've found to \c Diags.
207 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
210 /// A pair of helper functions for a __block variable.
211 class BlockByrefHelpers : public llvm::FoldingSetNode {
212 // MSVC requires this type to be complete in order to process this
215 llvm::Constant *CopyHelper;
216 llvm::Constant *DisposeHelper;
218 /// The alignment of the field. This is important because
219 /// different offsets to the field within the byref struct need to
220 /// have different helper functions.
223 BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
224 BlockByrefHelpers(const BlockByrefHelpers &) = default;
225 virtual ~BlockByrefHelpers();
227 void Profile(llvm::FoldingSetNodeID &id) const {
228 id.AddInteger(Alignment.getQuantity());
231 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
233 virtual bool needsCopy() const { return true; }
234 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
236 virtual bool needsDispose() const { return true; }
237 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
240 /// This class organizes the cross-function state that is used while generating
242 class CodeGenModule : public CodeGenTypeCache {
243 CodeGenModule(const CodeGenModule &) = delete;
244 void operator=(const CodeGenModule &) = delete;
248 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
249 Structor(int Priority, llvm::Constant *Initializer,
250 llvm::Constant *AssociatedData)
251 : Priority(Priority), Initializer(Initializer),
252 AssociatedData(AssociatedData) {}
254 llvm::Constant *Initializer;
255 llvm::Constant *AssociatedData;
258 typedef std::vector<Structor> CtorList;
262 const LangOptions &LangOpts;
263 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
264 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
265 const CodeGenOptions &CodeGenOpts;
266 llvm::Module &TheModule;
267 DiagnosticsEngine &Diags;
268 const TargetInfo &Target;
269 std::unique_ptr<CGCXXABI> ABI;
270 llvm::LLVMContext &VMContext;
274 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
276 // This should not be moved earlier, since its initialization depends on some
277 // of the previous reference members being already initialized and also checks
278 // if TheTargetCodeGenInfo is NULL
281 /// Holds information about C++ vtables.
282 CodeGenVTables VTables;
284 CGObjCRuntime* ObjCRuntime;
285 CGOpenCLRuntime* OpenCLRuntime;
286 CGOpenMPRuntime* OpenMPRuntime;
287 CGCUDARuntime* CUDARuntime;
288 CGDebugInfo* DebugInfo;
289 ObjCEntrypoints *ObjCData;
290 llvm::MDNode *NoObjCARCExceptionsMetadata;
291 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
292 InstrProfStats PGOStats;
293 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
295 // A set of references that have only been seen via a weakref so far. This is
296 // used to remove the weak of the reference if we ever see a direct reference
298 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
300 /// This contains all the decls which have definitions but/ which are deferred
301 /// for emission and therefore should only be output if they are actually
302 /// used. If a decl is in this, then it is known to have not been referenced
304 std::map<StringRef, GlobalDecl> DeferredDecls;
306 /// This is a list of deferred decls which we have seen that *are* actually
307 /// referenced. These get code generated when the module is done.
308 struct DeferredGlobal {
309 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
310 llvm::TrackingVH<llvm::GlobalValue> GV;
313 std::vector<DeferredGlobal> DeferredDeclsToEmit;
314 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
315 DeferredDeclsToEmit.emplace_back(GV, GD);
318 /// List of alias we have emitted. Used to make sure that what they point to
319 /// is defined once we get to the end of the of the translation unit.
320 std::vector<GlobalDecl> Aliases;
322 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
323 ReplacementsTy Replacements;
325 /// List of global values to be replaced with something else. Used when we
326 /// want to replace a GlobalValue but can't identify it by its mangled name
327 /// anymore (because the name is already taken).
328 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
329 GlobalValReplacements;
331 /// Set of global decls for which we already diagnosed mangled name conflict.
332 /// Required to not issue a warning (on a mangling conflict) multiple times
333 /// for the same decl.
334 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
336 /// A queue of (optional) vtables to consider emitting.
337 std::vector<const CXXRecordDecl*> DeferredVTables;
339 /// List of global values which are required to be present in the object file;
340 /// bitcast to i8*. This is used for forcing visibility of symbols which may
341 /// otherwise be optimized out.
342 std::vector<llvm::WeakVH> LLVMUsed;
343 std::vector<llvm::WeakVH> LLVMCompilerUsed;
345 /// Store the list of global constructors and their respective priorities to
346 /// be emitted when the translation unit is complete.
347 CtorList GlobalCtors;
349 /// Store the list of global destructors and their respective priorities to be
350 /// emitted when the translation unit is complete.
351 CtorList GlobalDtors;
353 /// An ordered map of canonical GlobalDecls to their mangled names.
354 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
355 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
357 /// Global annotations.
358 std::vector<llvm::Constant*> Annotations;
360 /// Map used to get unique annotation strings.
361 llvm::StringMap<llvm::Constant*> AnnotationStrings;
363 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
365 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
366 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
367 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
368 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
370 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
371 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
373 /// Map used to get unique type descriptor constants for sanitizers.
374 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
376 /// Map used to track internal linkage functions declared within
377 /// extern "C" regions.
378 typedef llvm::MapVector<IdentifierInfo *,
379 llvm::GlobalValue *> StaticExternCMap;
380 StaticExternCMap StaticExternCValues;
382 /// \brief thread_local variables defined or used in this TU.
383 std::vector<const VarDecl *> CXXThreadLocals;
385 /// \brief thread_local variables with initializers that need to run
386 /// before any thread_local variable in this TU is odr-used.
387 std::vector<llvm::Function *> CXXThreadLocalInits;
388 std::vector<const VarDecl *> CXXThreadLocalInitVars;
390 /// Global variables with initializers that need to run before main.
391 std::vector<llvm::Function *> CXXGlobalInits;
393 /// When a C++ decl with an initializer is deferred, null is
394 /// appended to CXXGlobalInits, and the index of that null is placed
395 /// here so that the initializer will be performed in the correct
396 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
397 /// that we don't re-emit the initializer.
398 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
400 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
402 struct GlobalInitPriorityCmp {
403 bool operator()(const GlobalInitData &LHS,
404 const GlobalInitData &RHS) const {
405 return LHS.first.priority < RHS.first.priority;
409 /// Global variables with initializers whose order of initialization is set by
410 /// init_priority attribute.
411 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
413 /// Global destructor functions and arguments that need to run on termination.
414 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
416 /// \brief The complete set of modules that has been imported.
417 llvm::SetVector<clang::Module *> ImportedModules;
419 /// \brief A vector of metadata strings.
420 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
422 /// @name Cache for Objective-C runtime types
425 /// Cached reference to the class for constant strings. This value has type
426 /// int * but is actually an Obj-C class pointer.
427 llvm::WeakVH CFConstantStringClassRef;
429 /// Cached reference to the class for constant strings. This value has type
430 /// int * but is actually an Obj-C class pointer.
431 llvm::WeakVH ConstantStringClassRef;
433 /// \brief The LLVM type corresponding to NSConstantString.
434 llvm::StructType *NSConstantStringType;
436 /// \brief The type used to describe the state of a fast enumeration in
437 /// Objective-C's for..in loop.
438 QualType ObjCFastEnumerationStateType;
442 /// Lazily create the Objective-C runtime
443 void createObjCRuntime();
445 void createOpenCLRuntime();
446 void createOpenMPRuntime();
447 void createCUDARuntime();
449 bool isTriviallyRecursive(const FunctionDecl *F);
450 bool shouldEmitFunction(GlobalDecl GD);
452 /// @name Cache for Blocks Runtime Globals
455 llvm::Constant *NSConcreteGlobalBlock;
456 llvm::Constant *NSConcreteStackBlock;
458 llvm::Constant *BlockObjectAssign;
459 llvm::Constant *BlockObjectDispose;
461 llvm::Type *BlockDescriptorType;
462 llvm::Type *GenericBlockLiteralType;
465 int GlobalUniqueCount;
468 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
469 llvm::Constant *LifetimeStartFn;
471 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
472 llvm::Constant *LifetimeEndFn;
474 GlobalDecl initializedGlobalDecl;
476 std::unique_ptr<SanitizerMetadata> SanitizerMD;
480 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
482 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
484 /// Mapping from canonical types to their metadata identifiers. We need to
485 /// maintain this mapping because identifiers may be formed from distinct
487 llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
490 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
491 const PreprocessorOptions &ppopts,
492 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
493 DiagnosticsEngine &Diags,
494 CoverageSourceInfo *CoverageInfo = nullptr);
500 /// Finalize LLVM code generation.
503 /// Return a reference to the configured Objective-C runtime.
504 CGObjCRuntime &getObjCRuntime() {
505 if (!ObjCRuntime) createObjCRuntime();
509 /// Return true iff an Objective-C runtime has been configured.
510 bool hasObjCRuntime() { return !!ObjCRuntime; }
512 /// Return a reference to the configured OpenCL runtime.
513 CGOpenCLRuntime &getOpenCLRuntime() {
514 assert(OpenCLRuntime != nullptr);
515 return *OpenCLRuntime;
518 /// Return a reference to the configured OpenMP runtime.
519 CGOpenMPRuntime &getOpenMPRuntime() {
520 assert(OpenMPRuntime != nullptr);
521 return *OpenMPRuntime;
524 /// Return a reference to the configured CUDA runtime.
525 CGCUDARuntime &getCUDARuntime() {
526 assert(CUDARuntime != nullptr);
530 ObjCEntrypoints &getObjCEntrypoints() const {
531 assert(ObjCData != nullptr);
535 InstrProfStats &getPGOStats() { return PGOStats; }
536 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
538 CoverageMappingModuleGen *getCoverageMapping() const {
539 return CoverageMapping.get();
542 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
543 return StaticLocalDeclMap[D];
545 void setStaticLocalDeclAddress(const VarDecl *D,
547 StaticLocalDeclMap[D] = C;
551 getOrCreateStaticVarDecl(const VarDecl &D,
552 llvm::GlobalValue::LinkageTypes Linkage);
554 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
555 return StaticLocalDeclGuardMap[D];
557 void setStaticLocalDeclGuardAddress(const VarDecl *D,
558 llvm::GlobalVariable *C) {
559 StaticLocalDeclGuardMap[D] = C;
562 bool lookupRepresentativeDecl(StringRef MangledName,
563 GlobalDecl &Result) const;
565 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
566 return AtomicSetterHelperFnMap[Ty];
568 void setAtomicSetterHelperFnMap(QualType Ty,
569 llvm::Constant *Fn) {
570 AtomicSetterHelperFnMap[Ty] = Fn;
573 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
574 return AtomicGetterHelperFnMap[Ty];
576 void setAtomicGetterHelperFnMap(QualType Ty,
577 llvm::Constant *Fn) {
578 AtomicGetterHelperFnMap[Ty] = Fn;
581 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
582 return TypeDescriptorMap[Ty];
584 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
585 TypeDescriptorMap[Ty] = C;
588 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
590 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
591 if (!NoObjCARCExceptionsMetadata)
592 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
593 return NoObjCARCExceptionsMetadata;
596 ASTContext &getContext() const { return Context; }
597 const LangOptions &getLangOpts() const { return LangOpts; }
598 const HeaderSearchOptions &getHeaderSearchOpts()
599 const { return HeaderSearchOpts; }
600 const PreprocessorOptions &getPreprocessorOpts()
601 const { return PreprocessorOpts; }
602 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
603 llvm::Module &getModule() const { return TheModule; }
604 DiagnosticsEngine &getDiags() const { return Diags; }
605 const llvm::DataLayout &getDataLayout() const {
606 return TheModule.getDataLayout();
608 const TargetInfo &getTarget() const { return Target; }
609 const llvm::Triple &getTriple() const;
610 bool supportsCOMDAT() const;
611 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
613 CGCXXABI &getCXXABI() const { return *ABI; }
614 llvm::LLVMContext &getLLVMContext() { return VMContext; }
616 bool shouldUseTBAA() const { return TBAA != nullptr; }
618 const TargetCodeGenInfo &getTargetCodeGenInfo();
620 CodeGenTypes &getTypes() { return Types; }
622 CodeGenVTables &getVTables() { return VTables; }
624 ItaniumVTableContext &getItaniumVTableContext() {
625 return VTables.getItaniumVTableContext();
628 MicrosoftVTableContext &getMicrosoftVTableContext() {
629 return VTables.getMicrosoftVTableContext();
632 CtorList &getGlobalCtors() { return GlobalCtors; }
633 CtorList &getGlobalDtors() { return GlobalDtors; }
635 llvm::MDNode *getTBAAInfo(QualType QTy);
636 llvm::MDNode *getTBAAInfoForVTablePtr();
637 llvm::MDNode *getTBAAStructInfo(QualType QTy);
638 /// Return the path-aware tag for given base type, access node and offset.
639 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
642 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
644 bool isPaddedAtomicType(QualType type);
645 bool isPaddedAtomicType(const AtomicType *type);
647 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
648 /// is the same as the type. For struct-path aware TBAA, the tag
649 /// is different from the type: base type, access type and offset.
650 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
651 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
652 llvm::MDNode *TBAAInfo,
653 bool ConvertTypeToTag = true);
655 /// Adds !invariant.barrier !tag to instruction
656 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
657 const CXXRecordDecl *RD);
659 /// Emit the given number of characters as a value of type size_t.
660 llvm::ConstantInt *getSize(CharUnits numChars);
662 /// Set the visibility for the given LLVM GlobalValue.
663 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
665 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
666 /// variable declaration D.
667 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
669 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
671 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
672 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
673 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
675 llvm_unreachable("unknown visibility!");
678 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
680 /// Will return a global variable of the given type. If a variable with a
681 /// different type already exists then a new variable with the right type
682 /// will be created and all uses of the old variable will be replaced with a
683 /// bitcast to the new variable.
684 llvm::GlobalVariable *
685 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
686 llvm::GlobalValue::LinkageTypes Linkage);
689 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
690 const CGFunctionInfo &FI,
691 SourceLocation Loc = SourceLocation(),
694 /// Return the address space of the underlying global variable for D, as
695 /// determined by its declaration. Normally this is the same as the address
696 /// space of D's type, but in CUDA, address spaces are associated with
697 /// declarations, not types.
698 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
700 /// Return the llvm::Constant for the address of the given global variable.
701 /// If Ty is non-null and if the global doesn't exist, then it will be created
702 /// with the specified type instead of whatever the normal requested type
703 /// would be. If IsForDefinition is true, it is guranteed that an actual
704 /// global with type Ty will be returned, not conversion of a variable with
705 /// the same mangled name but some other type.
706 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
707 llvm::Type *Ty = nullptr,
708 bool IsForDefinition = false);
710 /// Return the address of the given function. If Ty is non-null, then this
711 /// function will use the specified type if it has to create it.
712 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
713 bool ForVTable = false,
714 bool DontDefer = false,
715 bool IsForDefinition = false);
717 /// Get the address of the RTTI descriptor for the given type.
718 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
720 /// Get the address of a uuid descriptor .
721 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
723 /// Get the address of the thunk for the given global decl.
724 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
726 /// Get a reference to the target of VD.
727 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
729 /// Returns the assumed alignment of an opaque pointer to the given class.
730 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
732 /// Returns the assumed alignment of a virtual base of a class.
733 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
734 const CXXRecordDecl *Derived,
735 const CXXRecordDecl *VBase);
737 /// Given a class pointer with an actual known alignment, and the
738 /// expected alignment of an object at a dynamic offset w.r.t that
739 /// pointer, return the alignment to assume at the offset.
740 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
741 const CXXRecordDecl *Class,
742 CharUnits ExpectedTargetAlign);
745 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
746 CastExpr::path_const_iterator Start,
747 CastExpr::path_const_iterator End);
749 /// Returns the offset from a derived class to a class. Returns null if the
752 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
753 CastExpr::path_const_iterator PathBegin,
754 CastExpr::path_const_iterator PathEnd);
756 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
758 /// Fetches the global unique block count.
759 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
761 /// Fetches the type of a generic block descriptor.
762 llvm::Type *getBlockDescriptorType();
764 /// The type of a generic block literal.
765 llvm::Type *getGenericBlockLiteralType();
767 /// Gets the address of a block which requires no captures.
768 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
770 /// Return a pointer to a constant CFString object for the given string.
771 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
773 /// Return a pointer to a constant NSString object for the given string. Or a
774 /// user defined String object as defined via
775 /// -fconstant-string-class=class_name option.
776 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
778 /// Return a constant array for the given string.
779 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
781 /// Return a pointer to a constant array for the given string literal.
783 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
784 StringRef Name = ".str");
786 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
788 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
790 /// Returns a pointer to a character array containing the literal and a
791 /// terminating '\0' character. The result has pointer to array type.
793 /// \param GlobalName If provided, the name to use for the global (if one is
796 GetAddrOfConstantCString(const std::string &Str,
797 const char *GlobalName = nullptr);
799 /// Returns a pointer to a constant global variable for the given file-scope
800 /// compound literal expression.
801 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
803 /// \brief Returns a pointer to a global variable representing a temporary
804 /// with static or thread storage duration.
805 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
808 /// \brief Retrieve the record type that describes the state of an
809 /// Objective-C fast enumeration loop (for..in).
810 QualType getObjCFastEnumerationStateType();
812 // Produce code for this constructor/destructor. This method doesn't try
813 // to apply any ABI rules about which other constructors/destructors
814 // are needed or if they are alias to each other.
815 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
818 /// Return the address of the constructor/destructor of the given type.
820 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
821 const CGFunctionInfo *FnInfo = nullptr,
822 llvm::FunctionType *FnType = nullptr,
823 bool DontDefer = false, bool IsForDefinition = false);
825 /// Given a builtin id for a function like "__builtin_fabsf", return a
826 /// Function* for "fabsf".
827 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
830 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
832 /// Emit code for a single top level declaration.
833 void EmitTopLevelDecl(Decl *D);
835 /// \brief Stored a deferred empty coverage mapping for an unused
836 /// and thus uninstrumented top level declaration.
837 void AddDeferredUnusedCoverageMapping(Decl *D);
839 /// \brief Remove the deferred empty coverage mapping as this
840 /// declaration is actually instrumented.
841 void ClearUnusedCoverageMapping(const Decl *D);
843 /// \brief Emit all the deferred coverage mappings
844 /// for the uninstrumented functions.
845 void EmitDeferredUnusedCoverageMappings();
847 /// Tell the consumer that this variable has been instantiated.
848 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
850 /// \brief If the declaration has internal linkage but is inside an
851 /// extern "C" linkage specification, prepare to emit an alias for it
852 /// to the expected name.
853 template<typename SomeDecl>
854 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
856 /// Add a global to a list to be added to the llvm.used metadata.
857 void addUsedGlobal(llvm::GlobalValue *GV);
859 /// Add a global to a list to be added to the llvm.compiler.used metadata.
860 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
862 /// Add a destructor and object to add to the C++ global destructor function.
863 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
864 CXXGlobalDtors.emplace_back(DtorFn, Object);
867 /// Create a new runtime function with the specified type and name.
868 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
870 llvm::AttributeSet ExtraAttrs =
871 llvm::AttributeSet());
872 /// Create a new compiler builtin function with the specified type and name.
873 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
875 llvm::AttributeSet ExtraAttrs =
876 llvm::AttributeSet());
877 /// Create a new runtime global variable with the specified type and name.
878 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
881 ///@name Custom Blocks Runtime Interfaces
884 llvm::Constant *getNSConcreteGlobalBlock();
885 llvm::Constant *getNSConcreteStackBlock();
886 llvm::Constant *getBlockObjectAssign();
887 llvm::Constant *getBlockObjectDispose();
891 llvm::Constant *getLLVMLifetimeStartFn();
892 llvm::Constant *getLLVMLifetimeEndFn();
894 // Make sure that this type is translated.
895 void UpdateCompletedType(const TagDecl *TD);
897 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
899 /// Try to emit the initializer for the given declaration as a constant;
900 /// returns 0 if the expression cannot be emitted as a constant.
901 llvm::Constant *EmitConstantInit(const VarDecl &D,
902 CodeGenFunction *CGF = nullptr);
904 /// Try to emit the given expression as a constant; returns 0 if the
905 /// expression cannot be emitted as a constant.
906 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
907 CodeGenFunction *CGF = nullptr);
909 /// Emit the given constant value as a constant, in the type's scalar
911 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
912 CodeGenFunction *CGF = nullptr);
914 /// Emit the given constant value as a constant, in the type's memory
916 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
918 CodeGenFunction *CGF = nullptr);
920 /// \brief Emit type info if type of an expression is a variably modified
921 /// type. Also emit proper debug info for cast types.
922 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
923 CodeGenFunction *CGF = nullptr);
925 /// Return the result of value-initializing the given type, i.e. a null
926 /// expression of the given type. This is usually, but not always, an LLVM
928 llvm::Constant *EmitNullConstant(QualType T);
930 /// Return a null constant appropriate for zero-initializing a base class with
931 /// the given type. This is usually, but not always, an LLVM null constant.
932 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
934 /// Emit a general error that something can't be done.
935 void Error(SourceLocation loc, StringRef error);
937 /// Print out an error that codegen doesn't support the specified stmt yet.
938 void ErrorUnsupported(const Stmt *S, const char *Type);
940 /// Print out an error that codegen doesn't support the specified decl yet.
941 void ErrorUnsupported(const Decl *D, const char *Type);
943 /// Set the attributes on the LLVM function for the given decl and function
944 /// info. This applies attributes necessary for handling the ABI as well as
945 /// user specified attributes like section.
946 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
947 const CGFunctionInfo &FI);
949 /// Set the LLVM function attributes (sext, zext, etc).
950 void SetLLVMFunctionAttributes(const Decl *D,
951 const CGFunctionInfo &Info,
954 /// Set the LLVM function attributes which only apply to a function
956 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
958 /// Return true iff the given type uses 'sret' when used as a return type.
959 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
961 /// Return true iff the given type uses an argument slot when 'sret' is used
962 /// as a return type.
963 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
965 /// Return true iff the given type uses 'fpret' when used as a return type.
966 bool ReturnTypeUsesFPRet(QualType ResultType);
968 /// Return true iff the given type uses 'fp2ret' when used as a return type.
969 bool ReturnTypeUsesFP2Ret(QualType ResultType);
971 /// Get the LLVM attributes and calling convention to use for a particular
974 /// \param Name - The function name.
975 /// \param Info - The function type information.
976 /// \param CalleeInfo - The callee information these attributes are being
977 /// constructed for. If valid, the attributes applied to this decl may
978 /// contribute to the function attributes and calling convention.
979 /// \param PAL [out] - On return, the attribute list to use.
980 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
981 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
982 CGCalleeInfo CalleeInfo, AttributeListType &PAL,
983 unsigned &CallingConv, bool AttrOnCallSite);
985 // Fills in the supplied string map with the set of target features for the
986 // passed in function.
987 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
988 const FunctionDecl *FD);
990 StringRef getMangledName(GlobalDecl GD);
991 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
993 void EmitTentativeDefinition(const VarDecl *D);
995 void EmitVTable(CXXRecordDecl *Class);
997 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
999 /// \brief Appends Opts to the "Linker Options" metadata value.
1000 void AppendLinkerOptions(StringRef Opts);
1002 /// \brief Appends a detect mismatch command to the linker options.
1003 void AddDetectMismatch(StringRef Name, StringRef Value);
1005 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1006 void AddDependentLib(StringRef Lib);
1008 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1010 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1011 F->setLinkage(getFunctionLinkage(GD));
1014 /// Set the DLL storage class on F.
1015 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1017 /// Return the appropriate linkage for the vtable, VTT, and type information
1018 /// of the given class.
1019 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1021 /// Return the store size, in character units, of the given LLVM type.
1022 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1024 /// Returns LLVM linkage for a declarator.
1025 llvm::GlobalValue::LinkageTypes
1026 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1027 bool IsConstantVariable);
1029 /// Returns LLVM linkage for a declarator.
1030 llvm::GlobalValue::LinkageTypes
1031 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1033 /// Emit all the global annotations.
1034 void EmitGlobalAnnotations();
1036 /// Emit an annotation string.
1037 llvm::Constant *EmitAnnotationString(StringRef Str);
1039 /// Emit the annotation's translation unit.
1040 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1042 /// Emit the annotation line number.
1043 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1045 /// Generate the llvm::ConstantStruct which contains the annotation
1046 /// information for a given GlobalValue. The annotation struct is
1047 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1048 /// GlobalValue being annotated. The second field is the constant string
1049 /// created from the AnnotateAttr's annotation. The third field is a constant
1050 /// string containing the name of the translation unit. The fourth field is
1051 /// the line number in the file of the annotated value declaration.
1052 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1053 const AnnotateAttr *AA,
1056 /// Add global annotations that are set on D, for the global GV. Those
1057 /// annotations are emitted during finalization of the LLVM code.
1058 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1060 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1062 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1064 StringRef Category = StringRef()) const;
1066 SanitizerMetadata *getSanitizerMetadata() {
1067 return SanitizerMD.get();
1070 void addDeferredVTable(const CXXRecordDecl *RD) {
1071 DeferredVTables.push_back(RD);
1074 /// Emit code for a singal global function or var decl. Forward declarations
1075 /// are emitted lazily.
1076 void EmitGlobal(GlobalDecl D);
1078 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1080 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1082 /// Set attributes for a global definition.
1083 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1086 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1088 /// Set attributes which are common to any form of a global definition (alias,
1089 /// Objective-C method, function, global variable).
1091 /// NOTE: This should only be called for definitions.
1092 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1094 /// Set attributes which must be preserved by an alias. This includes common
1095 /// attributes (i.e. it includes a call to SetCommonAttributes).
1097 /// NOTE: This should only be called for definitions.
1098 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1100 void addReplacement(StringRef Name, llvm::Constant *C);
1102 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1104 /// \brief Emit a code for threadprivate directive.
1105 /// \param D Threadprivate declaration.
1106 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1108 /// Returns whether the given record is blacklisted from control flow
1109 /// integrity checks.
1110 bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
1112 /// Emit bit set entries for the given vtable using the given layout if
1113 /// vptr CFI is enabled.
1114 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1115 const VTableLayout &VTLayout);
1117 /// Generate a cross-DSO type identifier for type.
1118 llvm::ConstantInt *CreateCfiIdForTypeMetadata(llvm::Metadata *MD);
1120 /// Create a metadata identifier for the given type. This may either be an
1121 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1122 /// internal identifiers).
1123 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1125 /// Create a bitset entry for the given function and add it to BitsetsMD.
1126 void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F);
1128 /// Create a bitset entry for the given vtable and add it to BitsetsMD.
1129 void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
1130 llvm::GlobalVariable *VTable, CharUnits Offset,
1131 const CXXRecordDecl *RD);
1133 /// \breif Get the declaration of std::terminate for the platform.
1134 llvm::Constant *getTerminateFn();
1136 llvm::SanitizerStatReport &getSanStats();
1140 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1141 bool ForVTable, bool DontDefer = false,
1142 bool IsThunk = false,
1143 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
1144 bool IsForDefinition = false);
1146 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1147 llvm::PointerType *PTy,
1149 bool IsForDefinition = false);
1151 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1153 /// Set function attributes for a function declaration.
1154 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1155 bool IsIncompleteFunction, bool IsThunk);
1157 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1159 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1160 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1161 void EmitAliasDefinition(GlobalDecl GD);
1162 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1163 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1165 // C++ related functions.
1167 void EmitNamespace(const NamespaceDecl *D);
1168 void EmitLinkageSpec(const LinkageSpecDecl *D);
1169 void CompleteDIClassType(const CXXMethodDecl* D);
1171 /// \brief Emit the function that initializes C++ thread_local variables.
1172 void EmitCXXThreadLocalInitFunc();
1174 /// Emit the function that initializes C++ globals.
1175 void EmitCXXGlobalInitFunc();
1177 /// Emit the function that destroys C++ globals.
1178 void EmitCXXGlobalDtorFunc();
1180 /// Emit the function that initializes the specified global (if PerformInit is
1181 /// true) and registers its destructor.
1182 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1183 llvm::GlobalVariable *Addr,
1186 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1187 llvm::Function *InitFunc, InitSegAttr *ISA);
1189 // FIXME: Hardcoding priority here is gross.
1190 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1191 llvm::Constant *AssociatedData = nullptr);
1192 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1194 /// Generates a global array of functions and priorities using the given list
1195 /// and name. This array will have appending linkage and is suitable for use
1196 /// as a LLVM constructor or destructor array.
1197 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1199 /// Emit any needed decls for which code generation was deferred.
1200 void EmitDeferred();
1202 /// Call replaceAllUsesWith on all pairs in Replacements.
1203 void applyReplacements();
1205 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1206 void applyGlobalValReplacements();
1208 void checkAliases();
1210 /// Emit any vtables which we deferred and still have a use for.
1211 void EmitDeferredVTables();
1213 /// Emit the llvm.used and llvm.compiler.used metadata.
1214 void emitLLVMUsed();
1216 /// \brief Emit the link options introduced by imported modules.
1217 void EmitModuleLinkOptions();
1219 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1220 /// linkage specifications, giving them the "expected" name where possible.
1221 void EmitStaticExternCAliases();
1223 void EmitDeclMetadata();
1225 /// \brief Emit the Clang version as llvm.ident metadata.
1226 void EmitVersionIdentMetadata();
1228 /// Emits target specific Metadata for global declarations.
1229 void EmitTargetMetadata();
1231 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1232 /// .gcda files in a way that persists in .bc files.
1233 void EmitCoverageFile();
1235 /// Emits the initializer for a uuidof string.
1236 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1238 /// Determine whether the definition must be emitted; if this returns \c
1239 /// false, the definition can be emitted lazily if it's used.
1240 bool MustBeEmitted(const ValueDecl *D);
1242 /// Determine whether the definition can be emitted eagerly, or should be
1243 /// delayed until the end of the translation unit. This is relevant for
1244 /// definitions whose linkage can change, e.g. implicit function instantions
1245 /// which may later be explicitly instantiated.
1246 bool MayBeEmittedEagerly(const ValueDecl *D);
1248 /// Check whether we can use a "simpler", more core exceptions personality
1250 void SimplifyPersonality();
1252 } // end namespace CodeGen
1253 } // end namespace clang
1255 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H