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 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
170 llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
172 /// A void(void) inline asm to use to mark that the return value of
173 /// a call will be immediately retain.
174 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
176 /// void clang.arc.use(...);
177 llvm::Constant *clang_arc_use;
180 /// This class records statistics on instrumentation based profiling.
181 class InstrProfStats {
182 uint32_t VisitedInMainFile;
183 uint32_t MissingInMainFile;
190 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
192 /// Record that we've visited a function and whether or not that function was
193 /// in the main source file.
194 void addVisited(bool MainFile) {
199 /// Record that a function we've visited has no profile data.
200 void addMissing(bool MainFile) {
205 /// Record that a function we've visited has mismatched profile data.
206 void addMismatched(bool MainFile) { ++Mismatched; }
207 /// Whether or not the stats we've gathered indicate any potential problems.
208 bool hasDiagnostics() { return Missing || Mismatched; }
209 /// Report potential problems we've found to \c Diags.
210 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
213 /// A pair of helper functions for a __block variable.
214 class BlockByrefHelpers : public llvm::FoldingSetNode {
215 // MSVC requires this type to be complete in order to process this
218 llvm::Constant *CopyHelper;
219 llvm::Constant *DisposeHelper;
221 /// The alignment of the field. This is important because
222 /// different offsets to the field within the byref struct need to
223 /// have different helper functions.
226 BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
227 BlockByrefHelpers(const BlockByrefHelpers &) = default;
228 virtual ~BlockByrefHelpers();
230 void Profile(llvm::FoldingSetNodeID &id) const {
231 id.AddInteger(Alignment.getQuantity());
234 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
236 virtual bool needsCopy() const { return true; }
237 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
239 virtual bool needsDispose() const { return true; }
240 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
243 /// This class organizes the cross-function state that is used while generating
245 class CodeGenModule : public CodeGenTypeCache {
246 CodeGenModule(const CodeGenModule &) = delete;
247 void operator=(const CodeGenModule &) = delete;
251 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
252 Structor(int Priority, llvm::Constant *Initializer,
253 llvm::Constant *AssociatedData)
254 : Priority(Priority), Initializer(Initializer),
255 AssociatedData(AssociatedData) {}
257 llvm::Constant *Initializer;
258 llvm::Constant *AssociatedData;
261 typedef std::vector<Structor> CtorList;
265 const LangOptions &LangOpts;
266 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
267 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
268 const CodeGenOptions &CodeGenOpts;
269 llvm::Module &TheModule;
270 DiagnosticsEngine &Diags;
271 const TargetInfo &Target;
272 std::unique_ptr<CGCXXABI> ABI;
273 llvm::LLVMContext &VMContext;
277 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
279 // This should not be moved earlier, since its initialization depends on some
280 // of the previous reference members being already initialized and also checks
281 // if TheTargetCodeGenInfo is NULL
284 /// Holds information about C++ vtables.
285 CodeGenVTables VTables;
287 CGObjCRuntime* ObjCRuntime;
288 CGOpenCLRuntime* OpenCLRuntime;
289 CGOpenMPRuntime* OpenMPRuntime;
290 CGCUDARuntime* CUDARuntime;
291 CGDebugInfo* DebugInfo;
292 ObjCEntrypoints *ObjCData;
293 llvm::MDNode *NoObjCARCExceptionsMetadata;
294 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
295 InstrProfStats PGOStats;
296 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
298 // A set of references that have only been seen via a weakref so far. This is
299 // used to remove the weak of the reference if we ever see a direct reference
301 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
303 /// This contains all the decls which have definitions but/ which are deferred
304 /// for emission and therefore should only be output if they are actually
305 /// used. If a decl is in this, then it is known to have not been referenced
307 std::map<StringRef, GlobalDecl> DeferredDecls;
309 /// This is a list of deferred decls which we have seen that *are* actually
310 /// referenced. These get code generated when the module is done.
311 struct DeferredGlobal {
312 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
313 llvm::TrackingVH<llvm::GlobalValue> GV;
316 std::vector<DeferredGlobal> DeferredDeclsToEmit;
317 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
318 DeferredDeclsToEmit.emplace_back(GV, GD);
321 /// List of alias we have emitted. Used to make sure that what they point to
322 /// is defined once we get to the end of the of the translation unit.
323 std::vector<GlobalDecl> Aliases;
325 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
326 ReplacementsTy Replacements;
328 /// List of global values to be replaced with something else. Used when we
329 /// want to replace a GlobalValue but can't identify it by its mangled name
330 /// anymore (because the name is already taken).
331 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
332 GlobalValReplacements;
334 /// Set of global decls for which we already diagnosed mangled name conflict.
335 /// Required to not issue a warning (on a mangling conflict) multiple times
336 /// for the same decl.
337 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
339 /// A queue of (optional) vtables to consider emitting.
340 std::vector<const CXXRecordDecl*> DeferredVTables;
342 /// List of global values which are required to be present in the object file;
343 /// bitcast to i8*. This is used for forcing visibility of symbols which may
344 /// otherwise be optimized out.
345 std::vector<llvm::WeakVH> LLVMUsed;
346 std::vector<llvm::WeakVH> LLVMCompilerUsed;
348 /// Store the list of global constructors and their respective priorities to
349 /// be emitted when the translation unit is complete.
350 CtorList GlobalCtors;
352 /// Store the list of global destructors and their respective priorities to be
353 /// emitted when the translation unit is complete.
354 CtorList GlobalDtors;
356 /// An ordered map of canonical GlobalDecls to their mangled names.
357 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
358 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
360 /// Global annotations.
361 std::vector<llvm::Constant*> Annotations;
363 /// Map used to get unique annotation strings.
364 llvm::StringMap<llvm::Constant*> AnnotationStrings;
366 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
368 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
369 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
370 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
371 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
373 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
374 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
376 /// Map used to get unique type descriptor constants for sanitizers.
377 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
379 /// Map used to track internal linkage functions declared within
380 /// extern "C" regions.
381 typedef llvm::MapVector<IdentifierInfo *,
382 llvm::GlobalValue *> StaticExternCMap;
383 StaticExternCMap StaticExternCValues;
385 /// \brief thread_local variables defined or used in this TU.
386 std::vector<const VarDecl *> CXXThreadLocals;
388 /// \brief thread_local variables with initializers that need to run
389 /// before any thread_local variable in this TU is odr-used.
390 std::vector<llvm::Function *> CXXThreadLocalInits;
391 std::vector<const VarDecl *> CXXThreadLocalInitVars;
393 /// Global variables with initializers that need to run before main.
394 std::vector<llvm::Function *> CXXGlobalInits;
396 /// When a C++ decl with an initializer is deferred, null is
397 /// appended to CXXGlobalInits, and the index of that null is placed
398 /// here so that the initializer will be performed in the correct
399 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
400 /// that we don't re-emit the initializer.
401 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
403 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
405 struct GlobalInitPriorityCmp {
406 bool operator()(const GlobalInitData &LHS,
407 const GlobalInitData &RHS) const {
408 return LHS.first.priority < RHS.first.priority;
412 /// Global variables with initializers whose order of initialization is set by
413 /// init_priority attribute.
414 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
416 /// Global destructor functions and arguments that need to run on termination.
417 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
419 /// \brief The complete set of modules that has been imported.
420 llvm::SetVector<clang::Module *> ImportedModules;
422 /// \brief A vector of metadata strings.
423 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
425 /// @name Cache for Objective-C runtime types
428 /// Cached reference to the class for constant strings. This value has type
429 /// int * but is actually an Obj-C class pointer.
430 llvm::WeakVH CFConstantStringClassRef;
432 /// Cached reference to the class for constant strings. This value has type
433 /// int * but is actually an Obj-C class pointer.
434 llvm::WeakVH ConstantStringClassRef;
436 /// \brief The LLVM type corresponding to NSConstantString.
437 llvm::StructType *NSConstantStringType;
439 /// \brief The type used to describe the state of a fast enumeration in
440 /// Objective-C's for..in loop.
441 QualType ObjCFastEnumerationStateType;
445 /// Lazily create the Objective-C runtime
446 void createObjCRuntime();
448 void createOpenCLRuntime();
449 void createOpenMPRuntime();
450 void createCUDARuntime();
452 bool isTriviallyRecursive(const FunctionDecl *F);
453 bool shouldEmitFunction(GlobalDecl GD);
455 /// @name Cache for Blocks Runtime Globals
458 llvm::Constant *NSConcreteGlobalBlock;
459 llvm::Constant *NSConcreteStackBlock;
461 llvm::Constant *BlockObjectAssign;
462 llvm::Constant *BlockObjectDispose;
464 llvm::Type *BlockDescriptorType;
465 llvm::Type *GenericBlockLiteralType;
468 int GlobalUniqueCount;
471 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
472 llvm::Constant *LifetimeStartFn;
474 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
475 llvm::Constant *LifetimeEndFn;
477 GlobalDecl initializedGlobalDecl;
479 std::unique_ptr<SanitizerMetadata> SanitizerMD;
483 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
485 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
487 /// Mapping from canonical types to their metadata identifiers. We need to
488 /// maintain this mapping because identifiers may be formed from distinct
490 llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
492 SanitizerBlacklist WholeProgramVTablesBlacklist;
495 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
496 const PreprocessorOptions &ppopts,
497 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
498 DiagnosticsEngine &Diags,
499 CoverageSourceInfo *CoverageInfo = nullptr);
505 /// Finalize LLVM code generation.
508 /// Return a reference to the configured Objective-C runtime.
509 CGObjCRuntime &getObjCRuntime() {
510 if (!ObjCRuntime) createObjCRuntime();
514 /// Return true iff an Objective-C runtime has been configured.
515 bool hasObjCRuntime() { return !!ObjCRuntime; }
517 /// Return a reference to the configured OpenCL runtime.
518 CGOpenCLRuntime &getOpenCLRuntime() {
519 assert(OpenCLRuntime != nullptr);
520 return *OpenCLRuntime;
523 /// Return a reference to the configured OpenMP runtime.
524 CGOpenMPRuntime &getOpenMPRuntime() {
525 assert(OpenMPRuntime != nullptr);
526 return *OpenMPRuntime;
529 /// Return a reference to the configured CUDA runtime.
530 CGCUDARuntime &getCUDARuntime() {
531 assert(CUDARuntime != nullptr);
535 ObjCEntrypoints &getObjCEntrypoints() const {
536 assert(ObjCData != nullptr);
540 InstrProfStats &getPGOStats() { return PGOStats; }
541 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
543 CoverageMappingModuleGen *getCoverageMapping() const {
544 return CoverageMapping.get();
547 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
548 return StaticLocalDeclMap[D];
550 void setStaticLocalDeclAddress(const VarDecl *D,
552 StaticLocalDeclMap[D] = C;
556 getOrCreateStaticVarDecl(const VarDecl &D,
557 llvm::GlobalValue::LinkageTypes Linkage);
559 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
560 return StaticLocalDeclGuardMap[D];
562 void setStaticLocalDeclGuardAddress(const VarDecl *D,
563 llvm::GlobalVariable *C) {
564 StaticLocalDeclGuardMap[D] = C;
567 bool lookupRepresentativeDecl(StringRef MangledName,
568 GlobalDecl &Result) const;
570 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
571 return AtomicSetterHelperFnMap[Ty];
573 void setAtomicSetterHelperFnMap(QualType Ty,
574 llvm::Constant *Fn) {
575 AtomicSetterHelperFnMap[Ty] = Fn;
578 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
579 return AtomicGetterHelperFnMap[Ty];
581 void setAtomicGetterHelperFnMap(QualType Ty,
582 llvm::Constant *Fn) {
583 AtomicGetterHelperFnMap[Ty] = Fn;
586 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
587 return TypeDescriptorMap[Ty];
589 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
590 TypeDescriptorMap[Ty] = C;
593 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
595 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
596 if (!NoObjCARCExceptionsMetadata)
597 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
598 return NoObjCARCExceptionsMetadata;
601 ASTContext &getContext() const { return Context; }
602 const LangOptions &getLangOpts() const { return LangOpts; }
603 const HeaderSearchOptions &getHeaderSearchOpts()
604 const { return HeaderSearchOpts; }
605 const PreprocessorOptions &getPreprocessorOpts()
606 const { return PreprocessorOpts; }
607 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
608 llvm::Module &getModule() const { return TheModule; }
609 DiagnosticsEngine &getDiags() const { return Diags; }
610 const llvm::DataLayout &getDataLayout() const {
611 return TheModule.getDataLayout();
613 const TargetInfo &getTarget() const { return Target; }
614 const llvm::Triple &getTriple() const;
615 bool supportsCOMDAT() const;
616 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
618 CGCXXABI &getCXXABI() const { return *ABI; }
619 llvm::LLVMContext &getLLVMContext() { return VMContext; }
621 bool shouldUseTBAA() const { return TBAA != nullptr; }
623 const TargetCodeGenInfo &getTargetCodeGenInfo();
625 CodeGenTypes &getTypes() { return Types; }
627 CodeGenVTables &getVTables() { return VTables; }
629 ItaniumVTableContext &getItaniumVTableContext() {
630 return VTables.getItaniumVTableContext();
633 MicrosoftVTableContext &getMicrosoftVTableContext() {
634 return VTables.getMicrosoftVTableContext();
637 CtorList &getGlobalCtors() { return GlobalCtors; }
638 CtorList &getGlobalDtors() { return GlobalDtors; }
640 llvm::MDNode *getTBAAInfo(QualType QTy);
641 llvm::MDNode *getTBAAInfoForVTablePtr();
642 llvm::MDNode *getTBAAStructInfo(QualType QTy);
643 /// Return the path-aware tag for given base type, access node and offset.
644 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
647 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
649 bool isPaddedAtomicType(QualType type);
650 bool isPaddedAtomicType(const AtomicType *type);
652 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
653 /// is the same as the type. For struct-path aware TBAA, the tag
654 /// is different from the type: base type, access type and offset.
655 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
656 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
657 llvm::MDNode *TBAAInfo,
658 bool ConvertTypeToTag = true);
660 /// Adds !invariant.barrier !tag to instruction
661 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
662 const CXXRecordDecl *RD);
664 /// Emit the given number of characters as a value of type size_t.
665 llvm::ConstantInt *getSize(CharUnits numChars);
667 /// Set the visibility for the given LLVM GlobalValue.
668 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
670 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
671 /// variable declaration D.
672 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
674 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
676 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
677 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
678 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
680 llvm_unreachable("unknown visibility!");
683 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
685 /// Will return a global variable of the given type. If a variable with a
686 /// different type already exists then a new variable with the right type
687 /// will be created and all uses of the old variable will be replaced with a
688 /// bitcast to the new variable.
689 llvm::GlobalVariable *
690 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
691 llvm::GlobalValue::LinkageTypes Linkage);
694 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
695 const CGFunctionInfo &FI,
696 SourceLocation Loc = SourceLocation(),
699 /// Return the address space of the underlying global variable for D, as
700 /// determined by its declaration. Normally this is the same as the address
701 /// space of D's type, but in CUDA, address spaces are associated with
702 /// declarations, not types.
703 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
705 /// Return the llvm::Constant for the address of the given global variable.
706 /// If Ty is non-null and if the global doesn't exist, then it will be created
707 /// with the specified type instead of whatever the normal requested type
708 /// would be. If IsForDefinition is true, it is guranteed that an actual
709 /// global with type Ty will be returned, not conversion of a variable with
710 /// the same mangled name but some other type.
711 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
712 llvm::Type *Ty = nullptr,
713 bool IsForDefinition = false);
715 /// Return the address of the given function. If Ty is non-null, then this
716 /// function will use the specified type if it has to create it.
717 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
718 bool ForVTable = false,
719 bool DontDefer = false,
720 bool IsForDefinition = false);
722 /// Get the address of the RTTI descriptor for the given type.
723 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
725 /// Get the address of a uuid descriptor .
726 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
728 /// Get the address of the thunk for the given global decl.
729 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
731 /// Get a reference to the target of VD.
732 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
734 /// Returns the assumed alignment of an opaque pointer to the given class.
735 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
737 /// Returns the assumed alignment of a virtual base of a class.
738 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
739 const CXXRecordDecl *Derived,
740 const CXXRecordDecl *VBase);
742 /// Given a class pointer with an actual known alignment, and the
743 /// expected alignment of an object at a dynamic offset w.r.t that
744 /// pointer, return the alignment to assume at the offset.
745 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
746 const CXXRecordDecl *Class,
747 CharUnits ExpectedTargetAlign);
750 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
751 CastExpr::path_const_iterator Start,
752 CastExpr::path_const_iterator End);
754 /// Returns the offset from a derived class to a class. Returns null if the
757 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
758 CastExpr::path_const_iterator PathBegin,
759 CastExpr::path_const_iterator PathEnd);
761 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
763 /// Fetches the global unique block count.
764 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
766 /// Fetches the type of a generic block descriptor.
767 llvm::Type *getBlockDescriptorType();
769 /// The type of a generic block literal.
770 llvm::Type *getGenericBlockLiteralType();
772 /// Gets the address of a block which requires no captures.
773 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
775 /// Return a pointer to a constant CFString object for the given string.
776 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
778 /// Return a pointer to a constant NSString object for the given string. Or a
779 /// user defined String object as defined via
780 /// -fconstant-string-class=class_name option.
781 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
783 /// Return a constant array for the given string.
784 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
786 /// Return a pointer to a constant array for the given string literal.
788 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
789 StringRef Name = ".str");
791 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
793 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
795 /// Returns a pointer to a character array containing the literal and a
796 /// terminating '\0' character. The result has pointer to array type.
798 /// \param GlobalName If provided, the name to use for the global (if one is
801 GetAddrOfConstantCString(const std::string &Str,
802 const char *GlobalName = nullptr);
804 /// Returns a pointer to a constant global variable for the given file-scope
805 /// compound literal expression.
806 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
808 /// \brief Returns a pointer to a global variable representing a temporary
809 /// with static or thread storage duration.
810 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
813 /// \brief Retrieve the record type that describes the state of an
814 /// Objective-C fast enumeration loop (for..in).
815 QualType getObjCFastEnumerationStateType();
817 // Produce code for this constructor/destructor. This method doesn't try
818 // to apply any ABI rules about which other constructors/destructors
819 // are needed or if they are alias to each other.
820 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
823 /// Return the address of the constructor/destructor of the given type.
825 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
826 const CGFunctionInfo *FnInfo = nullptr,
827 llvm::FunctionType *FnType = nullptr,
828 bool DontDefer = false, bool IsForDefinition = false);
830 /// Given a builtin id for a function like "__builtin_fabsf", return a
831 /// Function* for "fabsf".
832 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
835 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
837 /// Emit code for a single top level declaration.
838 void EmitTopLevelDecl(Decl *D);
840 /// \brief Stored a deferred empty coverage mapping for an unused
841 /// and thus uninstrumented top level declaration.
842 void AddDeferredUnusedCoverageMapping(Decl *D);
844 /// \brief Remove the deferred empty coverage mapping as this
845 /// declaration is actually instrumented.
846 void ClearUnusedCoverageMapping(const Decl *D);
848 /// \brief Emit all the deferred coverage mappings
849 /// for the uninstrumented functions.
850 void EmitDeferredUnusedCoverageMappings();
852 /// Tell the consumer that this variable has been instantiated.
853 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
855 /// \brief If the declaration has internal linkage but is inside an
856 /// extern "C" linkage specification, prepare to emit an alias for it
857 /// to the expected name.
858 template<typename SomeDecl>
859 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
861 /// Add a global to a list to be added to the llvm.used metadata.
862 void addUsedGlobal(llvm::GlobalValue *GV);
864 /// Add a global to a list to be added to the llvm.compiler.used metadata.
865 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
867 /// Add a destructor and object to add to the C++ global destructor function.
868 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
869 CXXGlobalDtors.emplace_back(DtorFn, Object);
872 /// Create a new runtime function with the specified type and name.
873 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
875 llvm::AttributeSet ExtraAttrs =
876 llvm::AttributeSet());
877 /// Create a new compiler builtin function with the specified type and name.
878 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
880 llvm::AttributeSet ExtraAttrs =
881 llvm::AttributeSet());
882 /// Create a new runtime global variable with the specified type and name.
883 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
886 ///@name Custom Blocks Runtime Interfaces
889 llvm::Constant *getNSConcreteGlobalBlock();
890 llvm::Constant *getNSConcreteStackBlock();
891 llvm::Constant *getBlockObjectAssign();
892 llvm::Constant *getBlockObjectDispose();
896 llvm::Constant *getLLVMLifetimeStartFn();
897 llvm::Constant *getLLVMLifetimeEndFn();
899 // Make sure that this type is translated.
900 void UpdateCompletedType(const TagDecl *TD);
902 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
904 /// Try to emit the initializer for the given declaration as a constant;
905 /// returns 0 if the expression cannot be emitted as a constant.
906 llvm::Constant *EmitConstantInit(const VarDecl &D,
907 CodeGenFunction *CGF = nullptr);
909 /// Try to emit the given expression as a constant; returns 0 if the
910 /// expression cannot be emitted as a constant.
911 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
912 CodeGenFunction *CGF = nullptr);
914 /// Emit the given constant value as a constant, in the type's scalar
916 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
917 CodeGenFunction *CGF = nullptr);
919 /// Emit the given constant value as a constant, in the type's memory
921 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
923 CodeGenFunction *CGF = nullptr);
925 /// \brief Emit type info if type of an expression is a variably modified
926 /// type. Also emit proper debug info for cast types.
927 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
928 CodeGenFunction *CGF = nullptr);
930 /// Return the result of value-initializing the given type, i.e. a null
931 /// expression of the given type. This is usually, but not always, an LLVM
933 llvm::Constant *EmitNullConstant(QualType T);
935 /// Return a null constant appropriate for zero-initializing a base class with
936 /// the given type. This is usually, but not always, an LLVM null constant.
937 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
939 /// Emit a general error that something can't be done.
940 void Error(SourceLocation loc, StringRef error);
942 /// Print out an error that codegen doesn't support the specified stmt yet.
943 void ErrorUnsupported(const Stmt *S, const char *Type);
945 /// Print out an error that codegen doesn't support the specified decl yet.
946 void ErrorUnsupported(const Decl *D, const char *Type);
948 /// Set the attributes on the LLVM function for the given decl and function
949 /// info. This applies attributes necessary for handling the ABI as well as
950 /// user specified attributes like section.
951 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
952 const CGFunctionInfo &FI);
954 /// Set the LLVM function attributes (sext, zext, etc).
955 void SetLLVMFunctionAttributes(const Decl *D,
956 const CGFunctionInfo &Info,
959 /// Set the LLVM function attributes which only apply to a function
961 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
963 /// Return true iff the given type uses 'sret' when used as a return type.
964 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
966 /// Return true iff the given type uses an argument slot when 'sret' is used
967 /// as a return type.
968 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
970 /// Return true iff the given type uses 'fpret' when used as a return type.
971 bool ReturnTypeUsesFPRet(QualType ResultType);
973 /// Return true iff the given type uses 'fp2ret' when used as a return type.
974 bool ReturnTypeUsesFP2Ret(QualType ResultType);
976 /// Get the LLVM attributes and calling convention to use for a particular
979 /// \param Name - The function name.
980 /// \param Info - The function type information.
981 /// \param CalleeInfo - The callee information these attributes are being
982 /// constructed for. If valid, the attributes applied to this decl may
983 /// contribute to the function attributes and calling convention.
984 /// \param PAL [out] - On return, the attribute list to use.
985 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
986 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
987 CGCalleeInfo CalleeInfo, AttributeListType &PAL,
988 unsigned &CallingConv, bool AttrOnCallSite);
990 // Fills in the supplied string map with the set of target features for the
991 // passed in function.
992 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
993 const FunctionDecl *FD);
995 StringRef getMangledName(GlobalDecl GD);
996 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
998 void EmitTentativeDefinition(const VarDecl *D);
1000 void EmitVTable(CXXRecordDecl *Class);
1002 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1004 /// \brief Appends Opts to the "Linker Options" metadata value.
1005 void AppendLinkerOptions(StringRef Opts);
1007 /// \brief Appends a detect mismatch command to the linker options.
1008 void AddDetectMismatch(StringRef Name, StringRef Value);
1010 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1011 void AddDependentLib(StringRef Lib);
1013 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1015 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1016 F->setLinkage(getFunctionLinkage(GD));
1019 /// Set the DLL storage class on F.
1020 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1022 /// Return the appropriate linkage for the vtable, VTT, and type information
1023 /// of the given class.
1024 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1026 /// Return the store size, in character units, of the given LLVM type.
1027 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1029 /// Returns LLVM linkage for a declarator.
1030 llvm::GlobalValue::LinkageTypes
1031 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1032 bool IsConstantVariable);
1034 /// Returns LLVM linkage for a declarator.
1035 llvm::GlobalValue::LinkageTypes
1036 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1038 /// Emit all the global annotations.
1039 void EmitGlobalAnnotations();
1041 /// Emit an annotation string.
1042 llvm::Constant *EmitAnnotationString(StringRef Str);
1044 /// Emit the annotation's translation unit.
1045 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1047 /// Emit the annotation line number.
1048 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1050 /// Generate the llvm::ConstantStruct which contains the annotation
1051 /// information for a given GlobalValue. The annotation struct is
1052 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1053 /// GlobalValue being annotated. The second field is the constant string
1054 /// created from the AnnotateAttr's annotation. The third field is a constant
1055 /// string containing the name of the translation unit. The fourth field is
1056 /// the line number in the file of the annotated value declaration.
1057 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1058 const AnnotateAttr *AA,
1061 /// Add global annotations that are set on D, for the global GV. Those
1062 /// annotations are emitted during finalization of the LLVM code.
1063 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1065 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1067 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1069 StringRef Category = StringRef()) const;
1071 SanitizerMetadata *getSanitizerMetadata() {
1072 return SanitizerMD.get();
1075 void addDeferredVTable(const CXXRecordDecl *RD) {
1076 DeferredVTables.push_back(RD);
1079 /// Emit code for a singal global function or var decl. Forward declarations
1080 /// are emitted lazily.
1081 void EmitGlobal(GlobalDecl D);
1083 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1085 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1087 /// Set attributes for a global definition.
1088 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1091 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1093 /// Set attributes which are common to any form of a global definition (alias,
1094 /// Objective-C method, function, global variable).
1096 /// NOTE: This should only be called for definitions.
1097 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1099 /// Set attributes which must be preserved by an alias. This includes common
1100 /// attributes (i.e. it includes a call to SetCommonAttributes).
1102 /// NOTE: This should only be called for definitions.
1103 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1105 void addReplacement(StringRef Name, llvm::Constant *C);
1107 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1109 /// \brief Emit a code for threadprivate directive.
1110 /// \param D Threadprivate declaration.
1111 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1113 /// Returns whether we need bit sets attached to vtables.
1114 bool NeedVTableBitSets();
1116 /// Returns whether the given record is blacklisted from whole-program
1117 /// transformations (i.e. CFI or whole-program vtable optimization).
1118 bool IsBitSetBlacklistedRecord(const CXXRecordDecl *RD);
1120 /// Emit bit set entries for the given vtable using the given layout if
1121 /// vptr CFI is enabled.
1122 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1123 const VTableLayout &VTLayout);
1125 /// Generate a cross-DSO type identifier for type.
1126 llvm::ConstantInt *CreateCfiIdForTypeMetadata(llvm::Metadata *MD);
1128 /// Create a metadata identifier for the given type. This may either be an
1129 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1130 /// internal identifiers).
1131 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1133 /// Create a bitset entry for the given function and add it to BitsetsMD.
1134 void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F);
1136 /// Returns whether this module needs the "all-vtables" bitset.
1137 bool NeedAllVtablesBitSet() const;
1139 /// Create a bitset entry for the given vtable and add it to BitsetsMD.
1140 void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
1141 llvm::GlobalVariable *VTable, CharUnits Offset,
1142 const CXXRecordDecl *RD);
1144 /// \breif Get the declaration of std::terminate for the platform.
1145 llvm::Constant *getTerminateFn();
1147 llvm::SanitizerStatReport &getSanStats();
1151 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1152 bool ForVTable, bool DontDefer = false,
1153 bool IsThunk = false,
1154 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
1155 bool IsForDefinition = false);
1157 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1158 llvm::PointerType *PTy,
1160 bool IsForDefinition = false);
1162 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1164 /// Set function attributes for a function declaration.
1165 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1166 bool IsIncompleteFunction, bool IsThunk);
1168 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1170 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1171 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1172 void EmitAliasDefinition(GlobalDecl GD);
1173 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1174 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1176 // C++ related functions.
1178 void EmitNamespace(const NamespaceDecl *D);
1179 void EmitLinkageSpec(const LinkageSpecDecl *D);
1180 void CompleteDIClassType(const CXXMethodDecl* D);
1182 /// \brief Emit the function that initializes C++ thread_local variables.
1183 void EmitCXXThreadLocalInitFunc();
1185 /// Emit the function that initializes C++ globals.
1186 void EmitCXXGlobalInitFunc();
1188 /// Emit the function that destroys C++ globals.
1189 void EmitCXXGlobalDtorFunc();
1191 /// Emit the function that initializes the specified global (if PerformInit is
1192 /// true) and registers its destructor.
1193 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1194 llvm::GlobalVariable *Addr,
1197 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1198 llvm::Function *InitFunc, InitSegAttr *ISA);
1200 // FIXME: Hardcoding priority here is gross.
1201 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1202 llvm::Constant *AssociatedData = nullptr);
1203 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1205 /// Generates a global array of functions and priorities using the given list
1206 /// and name. This array will have appending linkage and is suitable for use
1207 /// as a LLVM constructor or destructor array.
1208 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1210 /// Emit any needed decls for which code generation was deferred.
1211 void EmitDeferred();
1213 /// Call replaceAllUsesWith on all pairs in Replacements.
1214 void applyReplacements();
1216 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1217 void applyGlobalValReplacements();
1219 void checkAliases();
1221 /// Emit any vtables which we deferred and still have a use for.
1222 void EmitDeferredVTables();
1224 /// Emit the llvm.used and llvm.compiler.used metadata.
1225 void emitLLVMUsed();
1227 /// \brief Emit the link options introduced by imported modules.
1228 void EmitModuleLinkOptions();
1230 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1231 /// linkage specifications, giving them the "expected" name where possible.
1232 void EmitStaticExternCAliases();
1234 void EmitDeclMetadata();
1236 /// \brief Emit the Clang version as llvm.ident metadata.
1237 void EmitVersionIdentMetadata();
1239 /// Emits target specific Metadata for global declarations.
1240 void EmitTargetMetadata();
1242 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1243 /// .gcda files in a way that persists in .bc files.
1244 void EmitCoverageFile();
1246 /// Emits the initializer for a uuidof string.
1247 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1249 /// Determine whether the definition must be emitted; if this returns \c
1250 /// false, the definition can be emitted lazily if it's used.
1251 bool MustBeEmitted(const ValueDecl *D);
1253 /// Determine whether the definition can be emitted eagerly, or should be
1254 /// delayed until the end of the translation unit. This is relevant for
1255 /// definitions whose linkage can change, e.g. implicit function instantions
1256 /// which may later be explicitly instantiated.
1257 bool MayBeEmittedEagerly(const ValueDecl *D);
1259 /// Check whether we can use a "simpler", more core exceptions personality
1261 void SimplifyPersonality();
1263 } // end namespace CodeGen
1264 } // end namespace clang
1266 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H