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 CLANG_CODEGEN_CODEGENMODULE_H
15 #define CLANG_CODEGEN_CODEGENMODULE_H
17 #include "CGVTables.h"
18 #include "CodeGenTypes.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/GlobalDecl.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/Basic/ABI.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/Module.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/ValueHandle.h"
34 #include "llvm/Transforms/Utils/SpecialCaseList.h"
48 class TargetCodeGenInfo;
54 class ObjCImplementationDecl;
55 class ObjCCategoryImplDecl;
56 class ObjCProtocolDecl;
70 class DiagnosticsEngine;
72 class CXXDestructorDecl;
79 class CodeGenFunction;
84 class CGOpenCLRuntime;
86 class BlockFieldFlags;
87 class FunctionArgList;
89 struct OrderGlobalInits {
90 unsigned int priority;
91 unsigned int lex_order;
92 OrderGlobalInits(unsigned int p, unsigned int l)
93 : priority(p), lex_order(l) {}
95 bool operator==(const OrderGlobalInits &RHS) const {
96 return priority == RHS.priority &&
97 lex_order == RHS.lex_order;
100 bool operator<(const OrderGlobalInits &RHS) const {
101 if (priority < RHS.priority)
104 return priority == RHS.priority && lex_order < RHS.lex_order;
108 struct CodeGenTypeCache {
112 /// i8, i16, i32, and i64
113 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
115 llvm::Type *FloatTy, *DoubleTy;
118 llvm::IntegerType *IntTy;
120 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
122 llvm::IntegerType *IntPtrTy;
123 llvm::IntegerType *SizeTy;
124 llvm::IntegerType *PtrDiffTy;
127 /// void* in address space 0
129 llvm::PointerType *VoidPtrTy;
130 llvm::PointerType *Int8PtrTy;
133 /// void** in address space 0
135 llvm::PointerType *VoidPtrPtrTy;
136 llvm::PointerType *Int8PtrPtrTy;
139 /// The width of a pointer into the generic address space.
140 unsigned char PointerWidthInBits;
142 /// The size and alignment of a pointer into the generic address
145 unsigned char PointerAlignInBytes;
146 unsigned char PointerSizeInBytes;
147 unsigned char SizeSizeInBytes; // sizeof(size_t)
150 llvm::CallingConv::ID RuntimeCC;
151 llvm::CallingConv::ID getRuntimeCC() const {
156 struct RREntrypoints {
157 RREntrypoints() { memset(this, 0, sizeof(*this)); }
158 /// void objc_autoreleasePoolPop(void*);
159 llvm::Constant *objc_autoreleasePoolPop;
161 /// void *objc_autoreleasePoolPush(void);
162 llvm::Constant *objc_autoreleasePoolPush;
165 struct ARCEntrypoints {
166 ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
168 /// id objc_autorelease(id);
169 llvm::Constant *objc_autorelease;
171 /// id objc_autoreleaseReturnValue(id);
172 llvm::Constant *objc_autoreleaseReturnValue;
174 /// void objc_copyWeak(id *dest, id *src);
175 llvm::Constant *objc_copyWeak;
177 /// void objc_destroyWeak(id*);
178 llvm::Constant *objc_destroyWeak;
180 /// id objc_initWeak(id*, id);
181 llvm::Constant *objc_initWeak;
183 /// id objc_loadWeak(id*);
184 llvm::Constant *objc_loadWeak;
186 /// id objc_loadWeakRetained(id*);
187 llvm::Constant *objc_loadWeakRetained;
189 /// void objc_moveWeak(id *dest, id *src);
190 llvm::Constant *objc_moveWeak;
192 /// id objc_retain(id);
193 llvm::Constant *objc_retain;
195 /// id objc_retainAutorelease(id);
196 llvm::Constant *objc_retainAutorelease;
198 /// id objc_retainAutoreleaseReturnValue(id);
199 llvm::Constant *objc_retainAutoreleaseReturnValue;
201 /// id objc_retainAutoreleasedReturnValue(id);
202 llvm::Constant *objc_retainAutoreleasedReturnValue;
204 /// id objc_retainBlock(id);
205 llvm::Constant *objc_retainBlock;
207 /// void objc_release(id);
208 llvm::Constant *objc_release;
210 /// id objc_storeStrong(id*, id);
211 llvm::Constant *objc_storeStrong;
213 /// id objc_storeWeak(id*, id);
214 llvm::Constant *objc_storeWeak;
216 /// A void(void) inline asm to use to mark that the return value of
217 /// a call will be immediately retain.
218 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
220 /// void clang.arc.use(...);
221 llvm::Constant *clang_arc_use;
224 /// CodeGenModule - This class organizes the cross-function state that is used
225 /// while generating LLVM code.
226 class CodeGenModule : public CodeGenTypeCache {
227 CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION;
228 void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION;
230 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
233 const LangOptions &LangOpts;
234 const CodeGenOptions &CodeGenOpts;
235 llvm::Module &TheModule;
236 DiagnosticsEngine &Diags;
237 const llvm::DataLayout &TheDataLayout;
238 const TargetInfo &Target;
240 llvm::LLVMContext &VMContext;
244 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
246 // This should not be moved earlier, since its initialization depends on some
247 // of the previous reference members being already initialized and also checks
248 // if TheTargetCodeGenInfo is NULL
251 /// VTables - Holds information about C++ vtables.
252 CodeGenVTables VTables;
254 CGObjCRuntime* ObjCRuntime;
255 CGOpenCLRuntime* OpenCLRuntime;
256 CGCUDARuntime* CUDARuntime;
257 CGDebugInfo* DebugInfo;
258 ARCEntrypoints *ARCData;
259 llvm::MDNode *NoObjCARCExceptionsMetadata;
260 RREntrypoints *RRData;
262 // WeakRefReferences - A set of references that have only been seen via
263 // a weakref so far. This is used to remove the weak of the reference if we
264 // ever see a direct reference or a definition.
265 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
267 /// DeferredDecls - This contains all the decls which have definitions but
268 /// which are deferred for emission and therefore should only be output if
269 /// they are actually used. If a decl is in this, then it is known to have
270 /// not been referenced yet.
271 llvm::StringMap<GlobalDecl> DeferredDecls;
273 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
274 /// that *are* actually referenced. These get code generated when the module
276 std::vector<GlobalDecl> DeferredDeclsToEmit;
278 /// List of alias we have emitted. Used to make sure that what they point to
279 /// is defined once we get to the end of the of the translation unit.
280 std::vector<GlobalDecl> Aliases;
282 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
283 ReplacementsTy Replacements;
285 /// DeferredVTables - A queue of (optional) vtables to consider emitting.
286 std::vector<const CXXRecordDecl*> DeferredVTables;
288 /// LLVMUsed - List of global values which are required to be
289 /// present in the object file; bitcast to i8*. This is used for
290 /// forcing visibility of symbols which may otherwise be optimized
292 std::vector<llvm::WeakVH> LLVMUsed;
294 /// GlobalCtors - Store the list of global constructors and their respective
295 /// priorities to be emitted when the translation unit is complete.
296 CtorList GlobalCtors;
298 /// GlobalDtors - Store the list of global destructors and their respective
299 /// priorities to be emitted when the translation unit is complete.
300 CtorList GlobalDtors;
302 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
303 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames;
304 llvm::BumpPtrAllocator MangledNamesAllocator;
306 /// Global annotations.
307 std::vector<llvm::Constant*> Annotations;
309 /// Map used to get unique annotation strings.
310 llvm::StringMap<llvm::Constant*> AnnotationStrings;
312 llvm::StringMap<llvm::Constant*> CFConstantStringMap;
313 llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap;
314 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
315 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
316 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
318 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
319 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
321 /// Map used to get unique type descriptor constants for sanitizers.
322 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
324 /// Map used to track internal linkage functions declared within
325 /// extern "C" regions.
326 typedef llvm::MapVector<IdentifierInfo *,
327 llvm::GlobalValue *> StaticExternCMap;
328 StaticExternCMap StaticExternCValues;
330 /// \brief thread_local variables defined or used in this TU.
331 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
334 /// \brief thread_local variables with initializers that need to run
335 /// before any thread_local variable in this TU is odr-used.
336 std::vector<llvm::Constant*> CXXThreadLocalInits;
338 /// CXXGlobalInits - Global variables with initializers that need to run
340 std::vector<llvm::Constant*> CXXGlobalInits;
342 /// When a C++ decl with an initializer is deferred, null is
343 /// appended to CXXGlobalInits, and the index of that null is placed
344 /// here so that the initializer will be performed in the correct
346 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
348 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
350 struct GlobalInitPriorityCmp {
351 bool operator()(const GlobalInitData &LHS,
352 const GlobalInitData &RHS) const {
353 return LHS.first.priority < RHS.first.priority;
357 /// - Global variables with initializers whose order of initialization
358 /// is set by init_priority attribute.
359 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
361 /// CXXGlobalDtors - Global destructor functions and arguments that need to
362 /// run on termination.
363 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
365 /// \brief The complete set of modules that has been imported.
366 llvm::SetVector<clang::Module *> ImportedModules;
368 /// \brief A vector of metadata strings.
369 SmallVector<llvm::Value *, 16> LinkerOptionsMetadata;
371 /// @name Cache for Objective-C runtime types
374 /// CFConstantStringClassRef - Cached reference to the class for constant
375 /// strings. This value has type int * but is actually an Obj-C class pointer.
376 llvm::WeakVH CFConstantStringClassRef;
378 /// ConstantStringClassRef - Cached reference to the class for constant
379 /// strings. This value has type int * but is actually an Obj-C class pointer.
380 llvm::WeakVH ConstantStringClassRef;
382 /// \brief The LLVM type corresponding to NSConstantString.
383 llvm::StructType *NSConstantStringType;
385 /// \brief The type used to describe the state of a fast enumeration in
386 /// Objective-C's for..in loop.
387 QualType ObjCFastEnumerationStateType;
391 /// Lazily create the Objective-C runtime
392 void createObjCRuntime();
394 void createOpenCLRuntime();
395 void createCUDARuntime();
397 bool isTriviallyRecursive(const FunctionDecl *F);
398 bool shouldEmitFunction(GlobalDecl GD);
400 /// @name Cache for Blocks Runtime Globals
403 llvm::Constant *NSConcreteGlobalBlock;
404 llvm::Constant *NSConcreteStackBlock;
406 llvm::Constant *BlockObjectAssign;
407 llvm::Constant *BlockObjectDispose;
409 llvm::Type *BlockDescriptorType;
410 llvm::Type *GenericBlockLiteralType;
413 int GlobalUniqueCount;
416 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
417 llvm::Constant *LifetimeStartFn;
419 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
420 llvm::Constant *LifetimeEndFn;
422 GlobalDecl initializedGlobalDecl;
424 llvm::OwningPtr<llvm::SpecialCaseList> SanitizerBlacklist;
426 const SanitizerOptions &SanOpts;
430 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
431 llvm::Module &M, const llvm::DataLayout &TD,
432 DiagnosticsEngine &Diags);
436 /// Release - Finalize LLVM code generation.
439 /// getObjCRuntime() - Return a reference to the configured
440 /// Objective-C runtime.
441 CGObjCRuntime &getObjCRuntime() {
442 if (!ObjCRuntime) createObjCRuntime();
446 /// hasObjCRuntime() - Return true iff an Objective-C runtime has
448 bool hasObjCRuntime() { return !!ObjCRuntime; }
450 /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime.
451 CGOpenCLRuntime &getOpenCLRuntime() {
452 assert(OpenCLRuntime != 0);
453 return *OpenCLRuntime;
456 /// getCUDARuntime() - Return a reference to the configured CUDA runtime.
457 CGCUDARuntime &getCUDARuntime() {
458 assert(CUDARuntime != 0);
462 ARCEntrypoints &getARCEntrypoints() const {
463 assert(getLangOpts().ObjCAutoRefCount && ARCData != 0);
467 RREntrypoints &getRREntrypoints() const {
472 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
473 return StaticLocalDeclMap[D];
475 void setStaticLocalDeclAddress(const VarDecl *D,
477 StaticLocalDeclMap[D] = C;
480 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
481 return StaticLocalDeclGuardMap[D];
483 void setStaticLocalDeclGuardAddress(const VarDecl *D,
484 llvm::GlobalVariable *C) {
485 StaticLocalDeclGuardMap[D] = C;
488 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
489 return AtomicSetterHelperFnMap[Ty];
491 void setAtomicSetterHelperFnMap(QualType Ty,
492 llvm::Constant *Fn) {
493 AtomicSetterHelperFnMap[Ty] = Fn;
496 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
497 return AtomicGetterHelperFnMap[Ty];
499 void setAtomicGetterHelperFnMap(QualType Ty,
500 llvm::Constant *Fn) {
501 AtomicGetterHelperFnMap[Ty] = Fn;
504 llvm::Constant *getTypeDescriptor(QualType Ty) {
505 return TypeDescriptorMap[Ty];
507 void setTypeDescriptor(QualType Ty, llvm::Constant *C) {
508 TypeDescriptorMap[Ty] = C;
511 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
513 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
514 if (!NoObjCARCExceptionsMetadata)
515 NoObjCARCExceptionsMetadata =
516 llvm::MDNode::get(getLLVMContext(),
517 SmallVector<llvm::Value*,1>());
518 return NoObjCARCExceptionsMetadata;
521 ASTContext &getContext() const { return Context; }
522 const LangOptions &getLangOpts() const { return LangOpts; }
523 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
524 llvm::Module &getModule() const { return TheModule; }
525 DiagnosticsEngine &getDiags() const { return Diags; }
526 const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
527 const TargetInfo &getTarget() const { return Target; }
528 CGCXXABI &getCXXABI() { return ABI; }
529 llvm::LLVMContext &getLLVMContext() { return VMContext; }
531 bool shouldUseTBAA() const { return TBAA != 0; }
533 const TargetCodeGenInfo &getTargetCodeGenInfo();
535 CodeGenTypes &getTypes() { return Types; }
537 CodeGenVTables &getVTables() { return VTables; }
539 ItaniumVTableContext &getItaniumVTableContext() {
540 return VTables.getItaniumVTableContext();
543 MicrosoftVTableContext &getMicrosoftVTableContext() {
544 return VTables.getMicrosoftVTableContext();
547 llvm::MDNode *getTBAAInfo(QualType QTy);
548 llvm::MDNode *getTBAAInfoForVTablePtr();
549 llvm::MDNode *getTBAAStructInfo(QualType QTy);
550 /// Return the MDNode in the type DAG for the given struct type.
551 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
552 /// Return the path-aware tag for given base type, access node and offset.
553 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
556 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
558 bool isPaddedAtomicType(QualType type);
559 bool isPaddedAtomicType(const AtomicType *type);
561 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
562 /// is the same as the type. For struct-path aware TBAA, the tag
563 /// is different from the type: base type, access type and offset.
564 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
565 void DecorateInstruction(llvm::Instruction *Inst,
566 llvm::MDNode *TBAAInfo,
567 bool ConvertTypeToTag = true);
569 /// getSize - Emit the given number of characters as a value of type size_t.
570 llvm::ConstantInt *getSize(CharUnits numChars);
572 /// setGlobalVisibility - Set the visibility for the given LLVM
574 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
576 /// setTLSMode - Set the TLS mode for the given LLVM GlobalVariable
577 /// for the thread-local variable declaration D.
578 void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const;
580 /// TypeVisibilityKind - The kind of global variable that is passed to
581 /// setTypeVisibility
582 enum TypeVisibilityKind {
585 TVK_ForConstructionVTable,
590 /// setTypeVisibility - Set the visibility for the given global
591 /// value which holds information about a type.
592 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D,
593 TypeVisibilityKind TVK) const;
595 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
597 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
598 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
599 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
601 llvm_unreachable("unknown visibility!");
604 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
605 if (isa<CXXConstructorDecl>(GD.getDecl()))
606 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
608 else if (isa<CXXDestructorDecl>(GD.getDecl()))
609 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
611 else if (isa<FunctionDecl>(GD.getDecl()))
612 return GetAddrOfFunction(GD);
614 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
617 /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the
618 /// given type. If a variable with a different type already exists then a new
619 /// variable with the right type will be created and all uses of the old
620 /// variable will be replaced with a bitcast to the new variable.
621 llvm::GlobalVariable *
622 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
623 llvm::GlobalValue::LinkageTypes Linkage);
625 /// GetGlobalVarAddressSpace - Return the address space of the underlying
626 /// global variable for D, as determined by its declaration. Normally this
627 /// is the same as the address space of D's type, but in CUDA, address spaces
628 /// are associated with declarations, not types.
629 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
631 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
632 /// given global variable. If Ty is non-null and if the global doesn't exist,
633 /// then it will be greated with the specified type instead of whatever the
634 /// normal requested type would be.
635 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
639 /// GetAddrOfFunction - Return the address of the given function. If Ty is
640 /// non-null, then this function will use the specified type if it has to
642 llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
644 bool ForVTable = false);
646 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
647 /// for the given type.
648 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
650 /// GetAddrOfUuidDescriptor - Get the address of a uuid descriptor .
651 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
653 /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
654 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
656 /// GetWeakRefReference - Get a reference to the target of VD.
657 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
659 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
660 /// a class. Returns null if the offset is 0.
662 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
663 CastExpr::path_const_iterator PathBegin,
664 CastExpr::path_const_iterator PathEnd);
666 /// A pair of helper functions for a __block variable.
667 class ByrefHelpers : public llvm::FoldingSetNode {
669 llvm::Constant *CopyHelper;
670 llvm::Constant *DisposeHelper;
672 /// The alignment of the field. This is important because
673 /// different offsets to the field within the byref struct need to
674 /// have different helper functions.
677 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
678 virtual ~ByrefHelpers();
680 void Profile(llvm::FoldingSetNodeID &id) const {
681 id.AddInteger(Alignment.getQuantity());
684 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
686 virtual bool needsCopy() const { return true; }
687 virtual void emitCopy(CodeGenFunction &CGF,
688 llvm::Value *dest, llvm::Value *src) = 0;
690 virtual bool needsDispose() const { return true; }
691 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
694 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
696 /// getUniqueBlockCount - Fetches the global unique block count.
697 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
699 /// getBlockDescriptorType - Fetches the type of a generic block
701 llvm::Type *getBlockDescriptorType();
703 /// getGenericBlockLiteralType - The type of a generic block literal.
704 llvm::Type *getGenericBlockLiteralType();
706 /// GetAddrOfGlobalBlock - Gets the address of a block which
707 /// requires no captures.
708 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
710 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
711 /// for the given string.
712 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
714 /// GetAddrOfConstantString - Return a pointer to a constant NSString object
715 /// for the given string. Or a user defined String object as defined via
716 /// -fconstant-string-class=class_name option.
717 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
719 /// GetConstantArrayFromStringLiteral - Return a constant array for the given
721 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
723 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
724 /// for the given string literal.
725 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
727 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
728 /// array for the given ObjCEncodeExpr node.
729 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
731 /// GetAddrOfConstantString - Returns a pointer to a character array
732 /// containing the literal. This contents are exactly that of the given
733 /// string, i.e. it will not be null terminated automatically; see
734 /// GetAddrOfConstantCString. Note that whether the result is actually a
735 /// pointer to an LLVM constant depends on Feature.WriteableStrings.
737 /// The result has pointer to array type.
739 /// \param GlobalName If provided, the name to use for the global
740 /// (if one is created).
741 llvm::Constant *GetAddrOfConstantString(StringRef Str,
742 const char *GlobalName=0,
743 unsigned Alignment=0);
745 /// GetAddrOfConstantCString - Returns a pointer to a character array
746 /// containing the literal and a terminating '\0' character. The result has
747 /// pointer to array type.
749 /// \param GlobalName If provided, the name to use for the global (if one is
751 llvm::Constant *GetAddrOfConstantCString(const std::string &str,
752 const char *GlobalName=0,
753 unsigned Alignment=0);
755 /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global
756 /// variable for the given file-scope compound literal expression.
757 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
759 /// \brief Returns a pointer to a global variable representing a temporary
760 /// with static or thread storage duration.
761 llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
764 /// \brief Retrieve the record type that describes the state of an
765 /// Objective-C fast enumeration loop (for..in).
766 QualType getObjCFastEnumerationStateType();
768 /// GetAddrOfCXXConstructor - Return the address of the constructor of the
770 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
771 CXXCtorType ctorType,
772 const CGFunctionInfo *fnInfo = 0);
774 /// GetAddrOfCXXDestructor - Return the address of the constructor of the
776 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
777 CXXDtorType dtorType,
778 const CGFunctionInfo *fnInfo = 0,
779 llvm::FunctionType *fnType = 0);
781 /// getBuiltinLibFunction - Given a builtin id for a function like
782 /// "__builtin_fabsf", return a Function* for "fabsf".
783 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
786 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
788 /// EmitTopLevelDecl - Emit code for a single top level declaration.
789 void EmitTopLevelDecl(Decl *D);
791 /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this
792 // variable has been instantiated.
793 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
795 /// \brief If the declaration has internal linkage but is inside an
796 /// extern "C" linkage specification, prepare to emit an alias for it
797 /// to the expected name.
798 template<typename SomeDecl>
799 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
801 /// AddUsedGlobal - Add a global which should be forced to be
802 /// present in the object file; these are emitted to the llvm.used
804 void AddUsedGlobal(llvm::GlobalValue *GV);
806 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
807 /// destructor function.
808 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
809 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
812 /// CreateRuntimeFunction - Create a new runtime function with the specified
814 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
816 llvm::AttributeSet ExtraAttrs =
817 llvm::AttributeSet());
818 /// CreateRuntimeVariable - Create a new runtime global variable with the
819 /// specified type and name.
820 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
823 ///@name Custom Blocks Runtime Interfaces
826 llvm::Constant *getNSConcreteGlobalBlock();
827 llvm::Constant *getNSConcreteStackBlock();
828 llvm::Constant *getBlockObjectAssign();
829 llvm::Constant *getBlockObjectDispose();
833 llvm::Constant *getLLVMLifetimeStartFn();
834 llvm::Constant *getLLVMLifetimeEndFn();
836 // UpdateCompleteType - Make sure that this type is translated.
837 void UpdateCompletedType(const TagDecl *TD);
839 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
841 /// EmitConstantInit - Try to emit the initializer for the given declaration
842 /// as a constant; returns 0 if the expression cannot be emitted as a
844 llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF = 0);
846 /// EmitConstantExpr - Try to emit the given expression as a
847 /// constant; returns 0 if the expression cannot be emitted as a
849 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
850 CodeGenFunction *CGF = 0);
852 /// EmitConstantValue - Emit the given constant value as a constant, in the
853 /// type's scalar representation.
854 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
855 CodeGenFunction *CGF = 0);
857 /// EmitConstantValueForMemory - Emit the given constant value as a constant,
858 /// in the type's memory representation.
859 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
861 CodeGenFunction *CGF = 0);
863 /// EmitNullConstant - Return the result of value-initializing the given
864 /// type, i.e. a null expression of the given type. This is usually,
865 /// but not always, an LLVM null constant.
866 llvm::Constant *EmitNullConstant(QualType T);
868 /// EmitNullConstantForBase - Return a null constant appropriate for
869 /// zero-initializing a base class with the given type. This is usually,
870 /// but not always, an LLVM null constant.
871 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
873 /// Error - Emit a general error that something can't be done.
874 void Error(SourceLocation loc, StringRef error);
876 /// ErrorUnsupported - Print out an error that codegen doesn't support the
877 /// specified stmt yet.
878 void ErrorUnsupported(const Stmt *S, const char *Type);
880 /// ErrorUnsupported - Print out an error that codegen doesn't support the
881 /// specified decl yet.
882 void ErrorUnsupported(const Decl *D, const char *Type);
884 /// SetInternalFunctionAttributes - Set the attributes on the LLVM
885 /// function for the given decl and function info. This applies
886 /// attributes necessary for handling the ABI as well as user
887 /// specified attributes like section.
888 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
889 const CGFunctionInfo &FI);
891 /// SetLLVMFunctionAttributes - Set the LLVM function attributes
892 /// (sext, zext, etc).
893 void SetLLVMFunctionAttributes(const Decl *D,
894 const CGFunctionInfo &Info,
897 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
898 /// which only apply to a function definintion.
899 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
901 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used
902 /// as a return type.
903 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
905 /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when
906 /// used as a return type.
907 bool ReturnTypeUsesFPRet(QualType ResultType);
909 /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when
910 /// used as a return type.
911 bool ReturnTypeUsesFP2Ret(QualType ResultType);
913 /// ConstructAttributeList - Get the LLVM attributes and calling convention to
914 /// use for a particular function type.
916 /// \param Info - The function type information.
917 /// \param TargetDecl - The decl these attributes are being constructed
918 /// for. If supplied the attributes applied to this decl may contribute to the
919 /// function attributes and calling convention.
920 /// \param PAL [out] - On return, the attribute list to use.
921 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
922 void ConstructAttributeList(const CGFunctionInfo &Info,
923 const Decl *TargetDecl,
924 AttributeListType &PAL,
925 unsigned &CallingConv,
926 bool AttrOnCallSite);
928 StringRef getMangledName(GlobalDecl GD);
929 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
930 const BlockDecl *BD);
932 void EmitTentativeDefinition(const VarDecl *D);
934 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
936 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
938 void EmitFundamentalRTTIDescriptors();
940 /// \brief Appends Opts to the "Linker Options" metadata value.
941 void AppendLinkerOptions(StringRef Opts);
943 /// \brief Appends a detect mismatch command to the linker options.
944 void AddDetectMismatch(StringRef Name, StringRef Value);
946 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
947 void AddDependentLib(StringRef Lib);
949 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
951 void setFunctionLinkage(GlobalDecl GD, llvm::GlobalValue *V) {
952 V->setLinkage(getFunctionLinkage(GD));
955 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
956 /// and type information of the given class.
957 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
959 /// GetTargetTypeStoreSize - Return the store size, in character units, of
960 /// the given LLVM type.
961 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
963 /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global
965 llvm::GlobalValue::LinkageTypes
966 GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant);
968 /// Emit all the global annotations.
969 void EmitGlobalAnnotations();
971 /// Emit an annotation string.
972 llvm::Constant *EmitAnnotationString(StringRef Str);
974 /// Emit the annotation's translation unit.
975 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
977 /// Emit the annotation line number.
978 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
980 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
981 /// annotation information for a given GlobalValue. The annotation struct is
982 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
983 /// GlobalValue being annotated. The second field is the constant string
984 /// created from the AnnotateAttr's annotation. The third field is a constant
985 /// string containing the name of the translation unit. The fourth field is
986 /// the line number in the file of the annotated value declaration.
987 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
988 const AnnotateAttr *AA,
991 /// Add global annotations that are set on D, for the global GV. Those
992 /// annotations are emitted during finalization of the LLVM code.
993 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
995 const llvm::SpecialCaseList &getSanitizerBlacklist() const {
996 return *SanitizerBlacklist;
999 const SanitizerOptions &getSanOpts() const { return SanOpts; }
1001 void addDeferredVTable(const CXXRecordDecl *RD) {
1002 DeferredVTables.push_back(RD);
1005 /// EmitGlobal - Emit code for a singal global function or var decl. Forward
1006 /// declarations are emitted lazily.
1007 void EmitGlobal(GlobalDecl D);
1010 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1012 llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName,
1016 llvm::AttributeSet ExtraAttrs =
1017 llvm::AttributeSet());
1018 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1019 llvm::PointerType *PTy,
1021 bool UnnamedAddr = false);
1023 /// SetCommonAttributes - Set attributes which are common to any
1024 /// form of a global definition (alias, Objective-C method,
1025 /// function, global variable).
1027 /// NOTE: This should only be called for definitions.
1028 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1030 /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
1031 void SetFunctionDefinitionAttributes(const FunctionDecl *D,
1032 llvm::GlobalValue *GV);
1034 /// SetFunctionAttributes - Set function attributes for a function
1036 void SetFunctionAttributes(GlobalDecl GD,
1038 bool IsIncompleteFunction);
1040 void EmitGlobalDefinition(GlobalDecl D);
1042 void EmitGlobalFunctionDefinition(GlobalDecl GD);
1043 void EmitGlobalVarDefinition(const VarDecl *D);
1044 void EmitAliasDefinition(GlobalDecl GD);
1045 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1046 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1048 // C++ related functions.
1050 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1052 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1054 void EmitNamespace(const NamespaceDecl *D);
1055 void EmitLinkageSpec(const LinkageSpecDecl *D);
1056 void CompleteDIClassType(const CXXMethodDecl* D);
1058 /// EmitCXXConstructor - Emit a single constructor with the given type from
1059 /// a C++ constructor Decl.
1060 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
1062 /// EmitCXXDestructor - Emit a single destructor with the given type from
1063 /// a C++ destructor Decl.
1064 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
1066 /// \brief Emit the function that initializes C++ thread_local variables.
1067 void EmitCXXThreadLocalInitFunc();
1069 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
1070 void EmitCXXGlobalInitFunc();
1072 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
1073 void EmitCXXGlobalDtorFunc();
1075 /// EmitCXXGlobalVarDeclInitFunc - Emit the function that initializes the
1076 /// specified global (if PerformInit is true) and registers its destructor.
1077 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1078 llvm::GlobalVariable *Addr,
1081 // FIXME: Hardcoding priority here is gross.
1082 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
1083 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
1085 /// EmitCtorList - Generates a global array of functions and priorities using
1086 /// the given list and name. This array will have appending linkage and is
1087 /// suitable for use as a LLVM constructor or destructor array.
1088 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1090 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
1092 void EmitFundamentalRTTIDescriptor(QualType Type);
1094 /// EmitDeferred - Emit any needed decls for which code generation
1096 void EmitDeferred();
1098 /// Call replaceAllUsesWith on all pairs in Replacements.
1099 void applyReplacements();
1101 void checkAliases();
1103 /// EmitDeferredVTables - Emit any vtables which we deferred and
1104 /// still have a use for.
1105 void EmitDeferredVTables();
1107 /// EmitLLVMUsed - Emit the llvm.used metadata used to force
1108 /// references to global which may otherwise be optimized out.
1109 void EmitLLVMUsed();
1111 /// \brief Emit the link options introduced by imported modules.
1112 void EmitModuleLinkOptions();
1114 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1115 /// linkage specifications, giving them the "expected" name where possible.
1116 void EmitStaticExternCAliases();
1118 void EmitDeclMetadata();
1120 /// \brief Emit the Clang version as llvm.ident metadata.
1121 void EmitVersionIdentMetadata();
1123 /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where
1124 /// to emit the .gcno and .gcda files in a way that persists in .bc files.
1125 void EmitCoverageFile();
1127 /// Emits the initializer for a uuidof string.
1128 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType);
1130 /// MayDeferGeneration - Determine if the given decl can be emitted
1131 /// lazily; this is only relevant for definitions. The given decl
1132 /// must be either a function or var decl.
1133 bool MayDeferGeneration(const ValueDecl *D);
1135 /// SimplifyPersonality - Check whether we can use a "simpler", more
1136 /// core exceptions personality function.
1137 void SimplifyPersonality();
1139 } // end namespace CodeGen
1140 } // end namespace clang