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 "CodeGenTypes.h"
19 #include "SanitizerMetadata.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/GlobalDecl.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/Basic/ABI.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/SanitizerBlacklist.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ValueHandle.h"
46 class IndexedInstrProfReader;
50 class TargetCodeGenInfo;
56 class ObjCImplementationDecl;
57 class ObjCCategoryImplDecl;
58 class ObjCProtocolDecl;
72 class HeaderSearchOptions;
73 class PreprocessorOptions;
74 class DiagnosticsEngine;
76 class CXXDestructorDecl;
78 class CoverageSourceInfo;
83 class CodeGenFunction;
88 class CGOpenCLRuntime;
89 class CGOpenMPRuntime;
91 class BlockFieldFlags;
92 class FunctionArgList;
93 class CoverageMappingModuleGen;
95 struct OrderGlobalInits {
96 unsigned int priority;
97 unsigned int lex_order;
98 OrderGlobalInits(unsigned int p, unsigned int l)
99 : priority(p), lex_order(l) {}
101 bool operator==(const OrderGlobalInits &RHS) const {
102 return priority == RHS.priority && lex_order == RHS.lex_order;
105 bool operator<(const OrderGlobalInits &RHS) const {
106 return std::tie(priority, lex_order) <
107 std::tie(RHS.priority, RHS.lex_order);
111 struct CodeGenTypeCache {
115 /// i8, i16, i32, and i64
116 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
118 llvm::Type *FloatTy, *DoubleTy;
121 llvm::IntegerType *IntTy;
123 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
125 llvm::IntegerType *IntPtrTy;
126 llvm::IntegerType *SizeTy;
127 llvm::IntegerType *PtrDiffTy;
130 /// void* in address space 0
132 llvm::PointerType *VoidPtrTy;
133 llvm::PointerType *Int8PtrTy;
136 /// void** in address space 0
138 llvm::PointerType *VoidPtrPtrTy;
139 llvm::PointerType *Int8PtrPtrTy;
142 /// The width of a pointer into the generic address space.
143 unsigned char PointerWidthInBits;
145 /// The size and alignment of a pointer into the generic address
148 unsigned char PointerAlignInBytes;
149 unsigned char PointerSizeInBytes;
150 unsigned char SizeSizeInBytes; // sizeof(size_t)
153 llvm::CallingConv::ID RuntimeCC;
154 llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
155 llvm::CallingConv::ID BuiltinCC;
156 llvm::CallingConv::ID getBuiltinCC() const { return BuiltinCC; }
159 struct RREntrypoints {
160 RREntrypoints() { memset(this, 0, sizeof(*this)); }
161 /// void objc_autoreleasePoolPop(void*);
162 llvm::Constant *objc_autoreleasePoolPop;
164 /// void *objc_autoreleasePoolPush(void);
165 llvm::Constant *objc_autoreleasePoolPush;
168 struct ARCEntrypoints {
169 ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
171 /// id objc_autorelease(id);
172 llvm::Constant *objc_autorelease;
174 /// id objc_autoreleaseReturnValue(id);
175 llvm::Constant *objc_autoreleaseReturnValue;
177 /// void objc_copyWeak(id *dest, id *src);
178 llvm::Constant *objc_copyWeak;
180 /// void objc_destroyWeak(id*);
181 llvm::Constant *objc_destroyWeak;
183 /// id objc_initWeak(id*, id);
184 llvm::Constant *objc_initWeak;
186 /// id objc_loadWeak(id*);
187 llvm::Constant *objc_loadWeak;
189 /// id objc_loadWeakRetained(id*);
190 llvm::Constant *objc_loadWeakRetained;
192 /// void objc_moveWeak(id *dest, id *src);
193 llvm::Constant *objc_moveWeak;
195 /// id objc_retain(id);
196 llvm::Constant *objc_retain;
198 /// id objc_retainAutorelease(id);
199 llvm::Constant *objc_retainAutorelease;
201 /// id objc_retainAutoreleaseReturnValue(id);
202 llvm::Constant *objc_retainAutoreleaseReturnValue;
204 /// id objc_retainAutoreleasedReturnValue(id);
205 llvm::Constant *objc_retainAutoreleasedReturnValue;
207 /// id objc_retainBlock(id);
208 llvm::Constant *objc_retainBlock;
210 /// void objc_release(id);
211 llvm::Constant *objc_release;
213 /// id objc_storeStrong(id*, id);
214 llvm::Constant *objc_storeStrong;
216 /// id objc_storeWeak(id*, id);
217 llvm::Constant *objc_storeWeak;
219 /// A void(void) inline asm to use to mark that the return value of
220 /// a call will be immediately retain.
221 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
223 /// void clang.arc.use(...);
224 llvm::Constant *clang_arc_use;
227 /// This class records statistics on instrumentation based profiling.
228 class InstrProfStats {
229 uint32_t VisitedInMainFile;
230 uint32_t MissingInMainFile;
237 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
239 /// Record that we've visited a function and whether or not that function was
240 /// in the main source file.
241 void addVisited(bool MainFile) {
246 /// Record that a function we've visited has no profile data.
247 void addMissing(bool MainFile) {
252 /// Record that a function we've visited has mismatched profile data.
253 void addMismatched(bool MainFile) { ++Mismatched; }
254 /// Whether or not the stats we've gathered indicate any potential problems.
255 bool hasDiagnostics() { return Missing || Mismatched; }
256 /// Report potential problems we've found to \c Diags.
257 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
260 /// This class organizes the cross-function state that is used while generating
262 class CodeGenModule : public CodeGenTypeCache {
263 CodeGenModule(const CodeGenModule &) = delete;
264 void operator=(const CodeGenModule &) = delete;
268 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
269 Structor(int Priority, llvm::Constant *Initializer,
270 llvm::Constant *AssociatedData)
271 : Priority(Priority), Initializer(Initializer),
272 AssociatedData(AssociatedData) {}
274 llvm::Constant *Initializer;
275 llvm::Constant *AssociatedData;
278 typedef std::vector<Structor> CtorList;
282 const LangOptions &LangOpts;
283 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
284 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
285 const CodeGenOptions &CodeGenOpts;
286 llvm::Module &TheModule;
287 DiagnosticsEngine &Diags;
288 const llvm::DataLayout &TheDataLayout;
289 const TargetInfo &Target;
290 std::unique_ptr<CGCXXABI> ABI;
291 llvm::LLVMContext &VMContext;
295 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
297 // This should not be moved earlier, since its initialization depends on some
298 // of the previous reference members being already initialized and also checks
299 // if TheTargetCodeGenInfo is NULL
302 /// Holds information about C++ vtables.
303 CodeGenVTables VTables;
305 CGObjCRuntime* ObjCRuntime;
306 CGOpenCLRuntime* OpenCLRuntime;
307 CGOpenMPRuntime* OpenMPRuntime;
308 CGCUDARuntime* CUDARuntime;
309 CGDebugInfo* DebugInfo;
310 ARCEntrypoints *ARCData;
311 llvm::MDNode *NoObjCARCExceptionsMetadata;
312 RREntrypoints *RRData;
313 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
314 InstrProfStats PGOStats;
316 // A set of references that have only been seen via a weakref so far. This is
317 // used to remove the weak of the reference if we ever see a direct reference
319 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
321 /// This contains all the decls which have definitions but/ which are deferred
322 /// for emission and therefore should only be output if they are actually
323 /// used. If a decl is in this, then it is known to have not been referenced
325 std::map<StringRef, GlobalDecl> DeferredDecls;
327 /// This is a list of deferred decls which we have seen that *are* actually
328 /// referenced. These get code generated when the module is done.
329 struct DeferredGlobal {
330 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
331 llvm::TrackingVH<llvm::GlobalValue> GV;
334 std::vector<DeferredGlobal> DeferredDeclsToEmit;
335 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
336 DeferredDeclsToEmit.emplace_back(GV, GD);
339 /// List of alias we have emitted. Used to make sure that what they point to
340 /// is defined once we get to the end of the of the translation unit.
341 std::vector<GlobalDecl> Aliases;
343 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
344 ReplacementsTy Replacements;
346 /// A queue of (optional) vtables to consider emitting.
347 std::vector<const CXXRecordDecl*> DeferredVTables;
349 /// List of global values which are required to be present in the object file;
350 /// bitcast to i8*. This is used for forcing visibility of symbols which may
351 /// otherwise be optimized out.
352 std::vector<llvm::WeakVH> LLVMUsed;
353 std::vector<llvm::WeakVH> LLVMCompilerUsed;
355 /// Store the list of global constructors and their respective priorities to
356 /// be emitted when the translation unit is complete.
357 CtorList GlobalCtors;
359 /// Store the list of global destructors and their respective priorities to be
360 /// emitted when the translation unit is complete.
361 CtorList GlobalDtors;
363 /// An ordered map of canonical GlobalDecls to their mangled names.
364 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
365 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
367 /// Global annotations.
368 std::vector<llvm::Constant*> Annotations;
370 /// Map used to get unique annotation strings.
371 llvm::StringMap<llvm::Constant*> AnnotationStrings;
373 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
375 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
376 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
377 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
378 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
380 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
381 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
383 /// Map used to get unique type descriptor constants for sanitizers.
384 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
386 /// Map used to track internal linkage functions declared within
387 /// extern "C" regions.
388 typedef llvm::MapVector<IdentifierInfo *,
389 llvm::GlobalValue *> StaticExternCMap;
390 StaticExternCMap StaticExternCValues;
392 /// \brief thread_local variables defined or used in this TU.
393 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
396 /// \brief thread_local variables with initializers that need to run
397 /// before any thread_local variable in this TU is odr-used.
398 std::vector<llvm::Function *> CXXThreadLocalInits;
399 std::vector<llvm::GlobalVariable *> CXXThreadLocalInitVars;
401 /// Global variables with initializers that need to run before main.
402 std::vector<llvm::Function *> CXXGlobalInits;
404 /// When a C++ decl with an initializer is deferred, null is
405 /// appended to CXXGlobalInits, and the index of that null is placed
406 /// here so that the initializer will be performed in the correct
407 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
408 /// that we don't re-emit the initializer.
409 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
411 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
413 struct GlobalInitPriorityCmp {
414 bool operator()(const GlobalInitData &LHS,
415 const GlobalInitData &RHS) const {
416 return LHS.first.priority < RHS.first.priority;
420 /// Global variables with initializers whose order of initialization is set by
421 /// init_priority attribute.
422 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
424 /// Global destructor functions and arguments that need to run on termination.
425 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
427 /// \brief The complete set of modules that has been imported.
428 llvm::SetVector<clang::Module *> ImportedModules;
430 /// \brief A vector of metadata strings.
431 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
433 /// @name Cache for Objective-C runtime types
436 /// Cached reference to the class for constant strings. This value has type
437 /// int * but is actually an Obj-C class pointer.
438 llvm::WeakVH CFConstantStringClassRef;
440 /// Cached reference to the class for constant strings. This value has type
441 /// int * but is actually an Obj-C class pointer.
442 llvm::WeakVH ConstantStringClassRef;
444 /// \brief The LLVM type corresponding to NSConstantString.
445 llvm::StructType *NSConstantStringType;
447 /// \brief The type used to describe the state of a fast enumeration in
448 /// Objective-C's for..in loop.
449 QualType ObjCFastEnumerationStateType;
453 /// Lazily create the Objective-C runtime
454 void createObjCRuntime();
456 void createOpenCLRuntime();
457 void createOpenMPRuntime();
458 void createCUDARuntime();
460 bool isTriviallyRecursive(const FunctionDecl *F);
461 bool shouldEmitFunction(GlobalDecl GD);
463 /// @name Cache for Blocks Runtime Globals
466 llvm::Constant *NSConcreteGlobalBlock;
467 llvm::Constant *NSConcreteStackBlock;
469 llvm::Constant *BlockObjectAssign;
470 llvm::Constant *BlockObjectDispose;
472 llvm::Type *BlockDescriptorType;
473 llvm::Type *GenericBlockLiteralType;
476 int GlobalUniqueCount;
479 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
480 llvm::Constant *LifetimeStartFn;
482 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
483 llvm::Constant *LifetimeEndFn;
485 GlobalDecl initializedGlobalDecl;
487 std::unique_ptr<SanitizerMetadata> SanitizerMD;
491 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
493 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
495 CodeGenModule(ASTContext &C,
496 const HeaderSearchOptions &headersearchopts,
497 const PreprocessorOptions &ppopts,
498 const CodeGenOptions &CodeGenOpts,
499 llvm::Module &M, const llvm::DataLayout &TD,
500 DiagnosticsEngine &Diags,
501 CoverageSourceInfo *CoverageInfo = nullptr);
507 /// Finalize LLVM code generation.
510 /// Return a reference to the configured Objective-C runtime.
511 CGObjCRuntime &getObjCRuntime() {
512 if (!ObjCRuntime) createObjCRuntime();
516 /// Return true iff an Objective-C runtime has been configured.
517 bool hasObjCRuntime() { return !!ObjCRuntime; }
519 /// Return a reference to the configured OpenCL runtime.
520 CGOpenCLRuntime &getOpenCLRuntime() {
521 assert(OpenCLRuntime != nullptr);
522 return *OpenCLRuntime;
525 /// Return a reference to the configured OpenMP runtime.
526 CGOpenMPRuntime &getOpenMPRuntime() {
527 assert(OpenMPRuntime != nullptr);
528 return *OpenMPRuntime;
531 /// Return a reference to the configured CUDA runtime.
532 CGCUDARuntime &getCUDARuntime() {
533 assert(CUDARuntime != nullptr);
537 ARCEntrypoints &getARCEntrypoints() const {
538 assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
542 RREntrypoints &getRREntrypoints() const {
543 assert(RRData != nullptr);
547 InstrProfStats &getPGOStats() { return PGOStats; }
548 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
550 CoverageMappingModuleGen *getCoverageMapping() const {
551 return CoverageMapping.get();
554 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
555 return StaticLocalDeclMap[D];
557 void setStaticLocalDeclAddress(const VarDecl *D,
559 StaticLocalDeclMap[D] = C;
563 getOrCreateStaticVarDecl(const VarDecl &D,
564 llvm::GlobalValue::LinkageTypes Linkage);
566 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
567 return StaticLocalDeclGuardMap[D];
569 void setStaticLocalDeclGuardAddress(const VarDecl *D,
570 llvm::GlobalVariable *C) {
571 StaticLocalDeclGuardMap[D] = C;
574 bool lookupRepresentativeDecl(StringRef MangledName,
575 GlobalDecl &Result) const;
577 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
578 return AtomicSetterHelperFnMap[Ty];
580 void setAtomicSetterHelperFnMap(QualType Ty,
581 llvm::Constant *Fn) {
582 AtomicSetterHelperFnMap[Ty] = Fn;
585 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
586 return AtomicGetterHelperFnMap[Ty];
588 void setAtomicGetterHelperFnMap(QualType Ty,
589 llvm::Constant *Fn) {
590 AtomicGetterHelperFnMap[Ty] = Fn;
593 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
594 return TypeDescriptorMap[Ty];
596 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
597 TypeDescriptorMap[Ty] = C;
600 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
602 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
603 if (!NoObjCARCExceptionsMetadata)
604 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
605 return NoObjCARCExceptionsMetadata;
608 ASTContext &getContext() const { return Context; }
609 const LangOptions &getLangOpts() const { return LangOpts; }
610 const HeaderSearchOptions &getHeaderSearchOpts()
611 const { return HeaderSearchOpts; }
612 const PreprocessorOptions &getPreprocessorOpts()
613 const { return PreprocessorOpts; }
614 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
615 llvm::Module &getModule() const { return TheModule; }
616 DiagnosticsEngine &getDiags() const { return Diags; }
617 const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
618 const TargetInfo &getTarget() const { return Target; }
619 const llvm::Triple &getTriple() const;
620 bool supportsCOMDAT() const;
621 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
623 CGCXXABI &getCXXABI() const { return *ABI; }
624 llvm::LLVMContext &getLLVMContext() { return VMContext; }
626 bool shouldUseTBAA() const { return TBAA != nullptr; }
628 const TargetCodeGenInfo &getTargetCodeGenInfo();
630 CodeGenTypes &getTypes() { return Types; }
632 CodeGenVTables &getVTables() { return VTables; }
634 ItaniumVTableContext &getItaniumVTableContext() {
635 return VTables.getItaniumVTableContext();
638 MicrosoftVTableContext &getMicrosoftVTableContext() {
639 return VTables.getMicrosoftVTableContext();
642 CtorList &getGlobalCtors() { return GlobalCtors; }
643 CtorList &getGlobalDtors() { return GlobalDtors; }
645 llvm::MDNode *getTBAAInfo(QualType QTy);
646 llvm::MDNode *getTBAAInfoForVTablePtr();
647 llvm::MDNode *getTBAAStructInfo(QualType QTy);
648 /// Return the MDNode in the type DAG for the given struct type.
649 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
650 /// Return the path-aware tag for given base type, access node and offset.
651 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
654 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
656 bool isPaddedAtomicType(QualType type);
657 bool isPaddedAtomicType(const AtomicType *type);
659 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
660 /// is the same as the type. For struct-path aware TBAA, the tag
661 /// is different from the type: base type, access type and offset.
662 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
663 void DecorateInstruction(llvm::Instruction *Inst,
664 llvm::MDNode *TBAAInfo,
665 bool ConvertTypeToTag = true);
667 /// Emit the given number of characters as a value of type size_t.
668 llvm::ConstantInt *getSize(CharUnits numChars);
670 /// Set the visibility for the given LLVM GlobalValue.
671 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
673 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
674 /// variable declaration D.
675 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
677 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
679 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
680 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
681 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
683 llvm_unreachable("unknown visibility!");
686 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
687 if (isa<CXXConstructorDecl>(GD.getDecl()))
688 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
689 getFromCtorType(GD.getCtorType()));
690 else if (isa<CXXDestructorDecl>(GD.getDecl()))
691 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
692 getFromDtorType(GD.getDtorType()));
693 else if (isa<FunctionDecl>(GD.getDecl()))
694 return GetAddrOfFunction(GD);
696 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
699 /// Will return a global variable of the given type. If a variable with a
700 /// different type already exists then a new variable with the right type
701 /// will be created and all uses of the old variable will be replaced with a
702 /// bitcast to the new variable.
703 llvm::GlobalVariable *
704 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
705 llvm::GlobalValue::LinkageTypes Linkage);
708 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
709 SourceLocation Loc = SourceLocation(),
712 /// Return the address space of the underlying global variable for D, as
713 /// determined by its declaration. Normally this is the same as the address
714 /// space of D's type, but in CUDA, address spaces are associated with
715 /// declarations, not types.
716 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
718 /// Return the llvm::Constant for the address of the given global variable.
719 /// If Ty is non-null and if the global doesn't exist, then it will be greated
720 /// with the specified type instead of whatever the normal requested type
722 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
723 llvm::Type *Ty = nullptr);
725 /// Return the address of the given function. If Ty is non-null, then this
726 /// function will use the specified type if it has to create it.
727 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
728 bool ForVTable = false,
729 bool DontDefer = false);
731 /// Get the address of the RTTI descriptor for the given type.
732 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
734 llvm::Constant *getAddrOfCXXCatchHandlerType(QualType Ty,
735 QualType CatchHandlerType);
737 /// Get the address of a uuid descriptor .
738 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
740 /// Get the address of the thunk for the given global decl.
741 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
743 /// Get a reference to the target of VD.
744 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
747 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
748 CastExpr::path_const_iterator Start,
749 CastExpr::path_const_iterator End);
751 /// Returns the offset from a derived class to a class. Returns null if the
754 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
755 CastExpr::path_const_iterator PathBegin,
756 CastExpr::path_const_iterator PathEnd);
758 /// A pair of helper functions for a __block variable.
759 class ByrefHelpers : public llvm::FoldingSetNode {
761 llvm::Constant *CopyHelper;
762 llvm::Constant *DisposeHelper;
764 /// The alignment of the field. This is important because
765 /// different offsets to the field within the byref struct need to
766 /// have different helper functions.
769 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
770 virtual ~ByrefHelpers();
772 void Profile(llvm::FoldingSetNodeID &id) const {
773 id.AddInteger(Alignment.getQuantity());
776 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
778 virtual bool needsCopy() const { return true; }
779 virtual void emitCopy(CodeGenFunction &CGF,
780 llvm::Value *dest, llvm::Value *src) = 0;
782 virtual bool needsDispose() const { return true; }
783 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
786 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
788 /// Fetches the global unique block count.
789 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
791 /// Fetches the type of a generic block descriptor.
792 llvm::Type *getBlockDescriptorType();
794 /// The type of a generic block literal.
795 llvm::Type *getGenericBlockLiteralType();
797 /// Gets the address of a block which requires no captures.
798 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
800 /// Return a pointer to a constant CFString object for the given string.
801 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
803 /// Return a pointer to a constant NSString object for the given string. Or a
804 /// user defined String object as defined via
805 /// -fconstant-string-class=class_name option.
806 llvm::GlobalVariable *GetAddrOfConstantString(const StringLiteral *Literal);
808 /// Return a constant array for the given string.
809 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
811 /// Return a pointer to a constant array for the given string literal.
812 llvm::GlobalVariable *
813 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
814 StringRef Name = ".str");
816 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
817 llvm::GlobalVariable *
818 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
820 /// Returns a pointer to a character array containing the literal and a
821 /// terminating '\0' character. The result has pointer to array type.
823 /// \param GlobalName If provided, the name to use for the global (if one is
825 llvm::GlobalVariable *
826 GetAddrOfConstantCString(const std::string &Str,
827 const char *GlobalName = nullptr,
828 unsigned Alignment = 0);
830 /// Returns a pointer to a constant global variable for the given file-scope
831 /// compound literal expression.
832 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
834 /// \brief Returns a pointer to a global variable representing a temporary
835 /// with static or thread storage duration.
836 llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
839 /// \brief Retrieve the record type that describes the state of an
840 /// Objective-C fast enumeration loop (for..in).
841 QualType getObjCFastEnumerationStateType();
843 // Produce code for this constructor/destructor. This method doesn't try
844 // to apply any ABI rules about which other constructors/destructors
845 // are needed or if they are alias to each other.
846 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
849 /// Return the address of the constructor/destructor of the given type.
851 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
852 const CGFunctionInfo *FnInfo = nullptr,
853 llvm::FunctionType *FnType = nullptr,
854 bool DontDefer = false);
856 /// Given a builtin id for a function like "__builtin_fabsf", return a
857 /// Function* for "fabsf".
858 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
861 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
863 /// Emit code for a single top level declaration.
864 void EmitTopLevelDecl(Decl *D);
866 /// \brief Stored a deferred empty coverage mapping for an unused
867 /// and thus uninstrumented top level declaration.
868 void AddDeferredUnusedCoverageMapping(Decl *D);
870 /// \brief Remove the deferred empty coverage mapping as this
871 /// declaration is actually instrumented.
872 void ClearUnusedCoverageMapping(const Decl *D);
874 /// \brief Emit all the deferred coverage mappings
875 /// for the uninstrumented functions.
876 void EmitDeferredUnusedCoverageMappings();
878 /// Tell the consumer that this variable has been instantiated.
879 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
881 /// \brief If the declaration has internal linkage but is inside an
882 /// extern "C" linkage specification, prepare to emit an alias for it
883 /// to the expected name.
884 template<typename SomeDecl>
885 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
887 /// Add a global to a list to be added to the llvm.used metadata.
888 void addUsedGlobal(llvm::GlobalValue *GV);
890 /// Add a global to a list to be added to the llvm.compiler.used metadata.
891 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
893 /// Add a destructor and object to add to the C++ global destructor function.
894 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
895 CXXGlobalDtors.emplace_back(DtorFn, Object);
898 /// Create a new runtime function with the specified type and name.
899 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
901 llvm::AttributeSet ExtraAttrs =
902 llvm::AttributeSet());
903 /// Create a new compiler builtin function with the specified type and name.
904 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
906 llvm::AttributeSet ExtraAttrs =
907 llvm::AttributeSet());
908 /// Create a new runtime global variable with the specified type and name.
909 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
912 ///@name Custom Blocks Runtime Interfaces
915 llvm::Constant *getNSConcreteGlobalBlock();
916 llvm::Constant *getNSConcreteStackBlock();
917 llvm::Constant *getBlockObjectAssign();
918 llvm::Constant *getBlockObjectDispose();
922 llvm::Constant *getLLVMLifetimeStartFn();
923 llvm::Constant *getLLVMLifetimeEndFn();
925 // Make sure that this type is translated.
926 void UpdateCompletedType(const TagDecl *TD);
928 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
930 /// Try to emit the initializer for the given declaration as a constant;
931 /// returns 0 if the expression cannot be emitted as a constant.
932 llvm::Constant *EmitConstantInit(const VarDecl &D,
933 CodeGenFunction *CGF = nullptr);
935 /// Try to emit the given expression as a constant; returns 0 if the
936 /// expression cannot be emitted as a constant.
937 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
938 CodeGenFunction *CGF = nullptr);
940 /// Emit the given constant value as a constant, in the type's scalar
942 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
943 CodeGenFunction *CGF = nullptr);
945 /// Emit the given constant value as a constant, in the type's memory
947 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
949 CodeGenFunction *CGF = nullptr);
951 /// Return the result of value-initializing the given type, i.e. a null
952 /// expression of the given type. This is usually, but not always, an LLVM
954 llvm::Constant *EmitNullConstant(QualType T);
956 /// Return a null constant appropriate for zero-initializing a base class with
957 /// the given type. This is usually, but not always, an LLVM null constant.
958 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
960 /// Emit a general error that something can't be done.
961 void Error(SourceLocation loc, StringRef error);
963 /// Print out an error that codegen doesn't support the specified stmt yet.
964 void ErrorUnsupported(const Stmt *S, const char *Type);
966 /// Print out an error that codegen doesn't support the specified decl yet.
967 void ErrorUnsupported(const Decl *D, const char *Type);
969 /// Set the attributes on the LLVM function for the given decl and function
970 /// info. This applies attributes necessary for handling the ABI as well as
971 /// user specified attributes like section.
972 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
973 const CGFunctionInfo &FI);
975 /// Set the LLVM function attributes (sext, zext, etc).
976 void SetLLVMFunctionAttributes(const Decl *D,
977 const CGFunctionInfo &Info,
980 /// Set the LLVM function attributes which only apply to a function
982 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
984 /// Return true iff the given type uses 'sret' when used as a return type.
985 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
987 /// Return true iff the given type uses an argument slot when 'sret' is used
988 /// as a return type.
989 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
991 /// Return true iff the given type uses 'fpret' when used as a return type.
992 bool ReturnTypeUsesFPRet(QualType ResultType);
994 /// Return true iff the given type uses 'fp2ret' when used as a return type.
995 bool ReturnTypeUsesFP2Ret(QualType ResultType);
997 /// Get the LLVM attributes and calling convention to use for a particular
1000 /// \param Info - The function type information.
1001 /// \param TargetDecl - The decl these attributes are being constructed
1002 /// for. If supplied the attributes applied to this decl may contribute to the
1003 /// function attributes and calling convention.
1004 /// \param PAL [out] - On return, the attribute list to use.
1005 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1006 void ConstructAttributeList(const CGFunctionInfo &Info,
1007 const Decl *TargetDecl,
1008 AttributeListType &PAL,
1009 unsigned &CallingConv,
1010 bool AttrOnCallSite);
1012 StringRef getMangledName(GlobalDecl GD);
1013 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1015 void EmitTentativeDefinition(const VarDecl *D);
1017 void EmitVTable(CXXRecordDecl *Class);
1019 /// Emit the RTTI descriptors for the builtin types.
1020 void EmitFundamentalRTTIDescriptors();
1022 /// \brief Appends Opts to the "Linker Options" metadata value.
1023 void AppendLinkerOptions(StringRef Opts);
1025 /// \brief Appends a detect mismatch command to the linker options.
1026 void AddDetectMismatch(StringRef Name, StringRef Value);
1028 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1029 void AddDependentLib(StringRef Lib);
1031 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1033 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1034 F->setLinkage(getFunctionLinkage(GD));
1037 /// Set the DLL storage class on F.
1038 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1040 /// Return the appropriate linkage for the vtable, VTT, and type information
1041 /// of the given class.
1042 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1044 /// Return the store size, in character units, of the given LLVM type.
1045 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1047 /// Returns LLVM linkage for a declarator.
1048 llvm::GlobalValue::LinkageTypes
1049 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1050 bool IsConstantVariable);
1052 /// Returns LLVM linkage for a declarator.
1053 llvm::GlobalValue::LinkageTypes
1054 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1056 /// Emit all the global annotations.
1057 void EmitGlobalAnnotations();
1059 /// Emit an annotation string.
1060 llvm::Constant *EmitAnnotationString(StringRef Str);
1062 /// Emit the annotation's translation unit.
1063 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1065 /// Emit the annotation line number.
1066 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1068 /// Generate the llvm::ConstantStruct which contains the annotation
1069 /// information for a given GlobalValue. The annotation struct is
1070 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1071 /// GlobalValue being annotated. The second field is the constant string
1072 /// created from the AnnotateAttr's annotation. The third field is a constant
1073 /// string containing the name of the translation unit. The fourth field is
1074 /// the line number in the file of the annotated value declaration.
1075 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1076 const AnnotateAttr *AA,
1079 /// Add global annotations that are set on D, for the global GV. Those
1080 /// annotations are emitted during finalization of the LLVM code.
1081 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1083 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1085 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1087 StringRef Category = StringRef()) const;
1089 SanitizerMetadata *getSanitizerMetadata() {
1090 return SanitizerMD.get();
1093 void addDeferredVTable(const CXXRecordDecl *RD) {
1094 DeferredVTables.push_back(RD);
1097 /// Emit code for a singal global function or var decl. Forward declarations
1098 /// are emitted lazily.
1099 void EmitGlobal(GlobalDecl D);
1101 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1103 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1105 /// Set attributes for a global definition.
1106 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1109 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1111 /// Set attributes which are common to any form of a global definition (alias,
1112 /// Objective-C method, function, global variable).
1114 /// NOTE: This should only be called for definitions.
1115 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1117 /// Set attributes which must be preserved by an alias. This includes common
1118 /// attributes (i.e. it includes a call to SetCommonAttributes).
1120 /// NOTE: This should only be called for definitions.
1121 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1123 void addReplacement(StringRef Name, llvm::Constant *C);
1125 /// \brief Emit a code for threadprivate directive.
1126 /// \param D Threadprivate declaration.
1127 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1129 /// Returns whether the given record is blacklisted from control flow
1130 /// integrity checks.
1131 bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
1133 /// Emit bit set entries for the given vtable using the given layout if
1134 /// vptr CFI is enabled.
1135 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1136 const VTableLayout &VTLayout);
1138 /// Create a bitset entry for the given vtable.
1139 llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
1141 const CXXRecordDecl *RD);
1143 /// \breif Get the declaration of std::terminate for the platform.
1144 llvm::Constant *getTerminateFn();
1148 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1149 bool ForVTable, bool DontDefer = false,
1150 bool IsThunk = false,
1151 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
1153 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1154 llvm::PointerType *PTy,
1157 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1159 /// Set function attributes for a function declaration.
1160 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1161 bool IsIncompleteFunction, bool IsThunk);
1163 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1165 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1166 void EmitGlobalVarDefinition(const VarDecl *D);
1167 void EmitAliasDefinition(GlobalDecl GD);
1168 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1169 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1171 // C++ related functions.
1173 void EmitNamespace(const NamespaceDecl *D);
1174 void EmitLinkageSpec(const LinkageSpecDecl *D);
1175 void CompleteDIClassType(const CXXMethodDecl* D);
1177 /// \brief Emit the function that initializes C++ thread_local variables.
1178 void EmitCXXThreadLocalInitFunc();
1180 /// Emit the function that initializes C++ globals.
1181 void EmitCXXGlobalInitFunc();
1183 /// Emit the function that destroys C++ globals.
1184 void EmitCXXGlobalDtorFunc();
1186 /// Emit the function that initializes the specified global (if PerformInit is
1187 /// true) and registers its destructor.
1188 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1189 llvm::GlobalVariable *Addr,
1192 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1193 llvm::Function *InitFunc, InitSegAttr *ISA);
1195 // FIXME: Hardcoding priority here is gross.
1196 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1197 llvm::Constant *AssociatedData = 0);
1198 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1200 /// Generates a global array of functions and priorities using the given list
1201 /// and name. This array will have appending linkage and is suitable for use
1202 /// as a LLVM constructor or destructor array.
1203 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1205 /// Emit the RTTI descriptors for the given type.
1206 void EmitFundamentalRTTIDescriptor(QualType Type);
1208 /// Emit any needed decls for which code generation was deferred.
1209 void EmitDeferred();
1211 /// Call replaceAllUsesWith on all pairs in Replacements.
1212 void applyReplacements();
1214 void checkAliases();
1216 /// Emit any vtables which we deferred and still have a use for.
1217 void EmitDeferredVTables();
1219 /// Emit the llvm.used and llvm.compiler.used metadata.
1220 void emitLLVMUsed();
1222 /// \brief Emit the link options introduced by imported modules.
1223 void EmitModuleLinkOptions();
1225 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1226 /// linkage specifications, giving them the "expected" name where possible.
1227 void EmitStaticExternCAliases();
1229 void EmitDeclMetadata();
1231 /// \brief Emit the Clang version as llvm.ident metadata.
1232 void EmitVersionIdentMetadata();
1234 /// Emits target specific Metadata for global declarations.
1235 void EmitTargetMetadata();
1237 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1238 /// .gcda files in a way that persists in .bc files.
1239 void EmitCoverageFile();
1241 /// Emits the initializer for a uuidof string.
1242 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1244 /// Determine whether the definition must be emitted; if this returns \c
1245 /// false, the definition can be emitted lazily if it's used.
1246 bool MustBeEmitted(const ValueDecl *D);
1248 /// Determine whether the definition can be emitted eagerly, or should be
1249 /// delayed until the end of the translation unit. This is relevant for
1250 /// definitions whose linkage can change, e.g. implicit function instantions
1251 /// which may later be explicitly instantiated.
1252 bool MayBeEmittedEagerly(const ValueDecl *D);
1254 /// Check whether we can use a "simpler", more core exceptions personality
1256 void SimplifyPersonality();
1258 } // end namespace CodeGen
1259 } // end namespace clang