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/BlackList.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;
253 friend class CodeGenVTables;
255 CGObjCRuntime* ObjCRuntime;
256 CGOpenCLRuntime* OpenCLRuntime;
257 CGCUDARuntime* CUDARuntime;
258 CGDebugInfo* DebugInfo;
259 ARCEntrypoints *ARCData;
260 llvm::MDNode *NoObjCARCExceptionsMetadata;
261 RREntrypoints *RRData;
263 // WeakRefReferences - A set of references that have only been seen via
264 // a weakref so far. This is used to remove the weak of the reference if we
265 // ever see a direct reference or a definition.
266 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
268 /// DeferredDecls - This contains all the decls which have definitions but
269 /// which are deferred for emission and therefore should only be output if
270 /// they are actually used. If a decl is in this, then it is known to have
271 /// not been referenced yet.
272 llvm::StringMap<GlobalDecl> DeferredDecls;
274 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
275 /// that *are* actually referenced. These get code generated when the module
277 std::vector<GlobalDecl> DeferredDeclsToEmit;
279 /// DeferredVTables - A queue of (optional) vtables to consider emitting.
280 std::vector<const CXXRecordDecl*> DeferredVTables;
282 /// LLVMUsed - List of global values which are required to be
283 /// present in the object file; bitcast to i8*. This is used for
284 /// forcing visibility of symbols which may otherwise be optimized
286 std::vector<llvm::WeakVH> LLVMUsed;
288 /// GlobalCtors - Store the list of global constructors and their respective
289 /// priorities to be emitted when the translation unit is complete.
290 CtorList GlobalCtors;
292 /// GlobalDtors - Store the list of global destructors and their respective
293 /// priorities to be emitted when the translation unit is complete.
294 CtorList GlobalDtors;
296 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
297 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames;
298 llvm::BumpPtrAllocator MangledNamesAllocator;
300 /// Global annotations.
301 std::vector<llvm::Constant*> Annotations;
303 /// Map used to get unique annotation strings.
304 llvm::StringMap<llvm::Constant*> AnnotationStrings;
306 llvm::StringMap<llvm::Constant*> CFConstantStringMap;
307 llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap;
308 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
309 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
311 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
312 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
314 /// Map used to track internal linkage functions declared within
315 /// extern "C" regions.
316 typedef llvm::MapVector<IdentifierInfo *,
317 llvm::GlobalValue *> StaticExternCMap;
318 StaticExternCMap StaticExternCValues;
320 /// \brief thread_local variables defined or used in this TU.
321 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
324 /// \brief thread_local variables with initializers that need to run
325 /// before any thread_local variable in this TU is odr-used.
326 std::vector<llvm::Constant*> CXXThreadLocalInits;
328 /// CXXGlobalInits - Global variables with initializers that need to run
330 std::vector<llvm::Constant*> CXXGlobalInits;
332 /// When a C++ decl with an initializer is deferred, null is
333 /// appended to CXXGlobalInits, and the index of that null is placed
334 /// here so that the initializer will be performed in the correct
336 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
338 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
340 struct GlobalInitPriorityCmp {
341 bool operator()(const GlobalInitData &LHS,
342 const GlobalInitData &RHS) const {
343 return LHS.first.priority < RHS.first.priority;
347 /// - Global variables with initializers whose order of initialization
348 /// is set by init_priority attribute.
349 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
351 /// CXXGlobalDtors - Global destructor functions and arguments that need to
352 /// run on termination.
353 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
355 /// \brief The complete set of modules that has been imported.
356 llvm::SetVector<clang::Module *> ImportedModules;
358 /// @name Cache for Objective-C runtime types
361 /// CFConstantStringClassRef - Cached reference to the class for constant
362 /// strings. This value has type int * but is actually an Obj-C class pointer.
363 llvm::WeakVH CFConstantStringClassRef;
365 /// ConstantStringClassRef - Cached reference to the class for constant
366 /// strings. This value has type int * but is actually an Obj-C class pointer.
367 llvm::WeakVH ConstantStringClassRef;
369 /// \brief The LLVM type corresponding to NSConstantString.
370 llvm::StructType *NSConstantStringType;
372 /// \brief The type used to describe the state of a fast enumeration in
373 /// Objective-C's for..in loop.
374 QualType ObjCFastEnumerationStateType;
378 /// Lazily create the Objective-C runtime
379 void createObjCRuntime();
381 void createOpenCLRuntime();
382 void createCUDARuntime();
384 bool isTriviallyRecursive(const FunctionDecl *F);
385 bool shouldEmitFunction(const FunctionDecl *F);
387 /// @name Cache for Blocks Runtime Globals
390 llvm::Constant *NSConcreteGlobalBlock;
391 llvm::Constant *NSConcreteStackBlock;
393 llvm::Constant *BlockObjectAssign;
394 llvm::Constant *BlockObjectDispose;
396 llvm::Type *BlockDescriptorType;
397 llvm::Type *GenericBlockLiteralType;
400 int GlobalUniqueCount;
403 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
404 llvm::Constant *LifetimeStartFn;
406 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
407 llvm::Constant *LifetimeEndFn;
409 GlobalDecl initializedGlobalDecl;
411 llvm::BlackList SanitizerBlacklist;
413 const SanitizerOptions &SanOpts;
417 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
418 llvm::Module &M, const llvm::DataLayout &TD,
419 DiagnosticsEngine &Diags);
423 /// Release - Finalize LLVM code generation.
426 /// getObjCRuntime() - Return a reference to the configured
427 /// Objective-C runtime.
428 CGObjCRuntime &getObjCRuntime() {
429 if (!ObjCRuntime) createObjCRuntime();
433 /// hasObjCRuntime() - Return true iff an Objective-C runtime has
435 bool hasObjCRuntime() { return !!ObjCRuntime; }
437 /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime.
438 CGOpenCLRuntime &getOpenCLRuntime() {
439 assert(OpenCLRuntime != 0);
440 return *OpenCLRuntime;
443 /// getCUDARuntime() - Return a reference to the configured CUDA runtime.
444 CGCUDARuntime &getCUDARuntime() {
445 assert(CUDARuntime != 0);
449 ARCEntrypoints &getARCEntrypoints() const {
450 assert(getLangOpts().ObjCAutoRefCount && ARCData != 0);
454 RREntrypoints &getRREntrypoints() const {
459 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
460 return StaticLocalDeclMap[D];
462 void setStaticLocalDeclAddress(const VarDecl *D,
464 StaticLocalDeclMap[D] = C;
467 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
468 return StaticLocalDeclGuardMap[D];
470 void setStaticLocalDeclGuardAddress(const VarDecl *D,
471 llvm::GlobalVariable *C) {
472 StaticLocalDeclGuardMap[D] = C;
475 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
476 return AtomicSetterHelperFnMap[Ty];
478 void setAtomicSetterHelperFnMap(QualType Ty,
479 llvm::Constant *Fn) {
480 AtomicSetterHelperFnMap[Ty] = Fn;
483 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
484 return AtomicGetterHelperFnMap[Ty];
486 void setAtomicGetterHelperFnMap(QualType Ty,
487 llvm::Constant *Fn) {
488 AtomicGetterHelperFnMap[Ty] = Fn;
491 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
493 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
494 if (!NoObjCARCExceptionsMetadata)
495 NoObjCARCExceptionsMetadata =
496 llvm::MDNode::get(getLLVMContext(),
497 SmallVector<llvm::Value*,1>());
498 return NoObjCARCExceptionsMetadata;
501 ASTContext &getContext() const { return Context; }
502 const LangOptions &getLangOpts() const { return LangOpts; }
503 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
504 llvm::Module &getModule() const { return TheModule; }
505 DiagnosticsEngine &getDiags() const { return Diags; }
506 const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
507 const TargetInfo &getTarget() const { return Target; }
508 CGCXXABI &getCXXABI() { return ABI; }
509 llvm::LLVMContext &getLLVMContext() { return VMContext; }
511 bool shouldUseTBAA() const { return TBAA != 0; }
513 const TargetCodeGenInfo &getTargetCodeGenInfo();
515 CodeGenTypes &getTypes() { return Types; }
517 CodeGenVTables &getVTables() { return VTables; }
518 VTableContext &getVTableContext() { return VTables.getVTableContext(); }
520 llvm::MDNode *getTBAAInfo(QualType QTy);
521 llvm::MDNode *getTBAAInfoForVTablePtr();
522 llvm::MDNode *getTBAAStructInfo(QualType QTy);
523 /// Return the MDNode in the type DAG for the given struct type.
524 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
525 /// Return the path-aware tag for given base type, access node and offset.
526 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
529 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
531 bool isPaddedAtomicType(QualType type);
532 bool isPaddedAtomicType(const AtomicType *type);
534 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
535 /// is the same as the type. For struct-path aware TBAA, the tag
536 /// is different from the type: base type, access type and offset.
537 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
538 void DecorateInstruction(llvm::Instruction *Inst,
539 llvm::MDNode *TBAAInfo,
540 bool ConvertTypeToTag = true);
542 /// getSize - Emit the given number of characters as a value of type size_t.
543 llvm::ConstantInt *getSize(CharUnits numChars);
545 /// setGlobalVisibility - Set the visibility for the given LLVM
547 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
549 /// setTLSMode - Set the TLS mode for the given LLVM GlobalVariable
550 /// for the thread-local variable declaration D.
551 void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const;
553 /// TypeVisibilityKind - The kind of global variable that is passed to
554 /// setTypeVisibility
555 enum TypeVisibilityKind {
558 TVK_ForConstructionVTable,
563 /// setTypeVisibility - Set the visibility for the given global
564 /// value which holds information about a type.
565 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D,
566 TypeVisibilityKind TVK) const;
568 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
570 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
571 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
572 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
574 llvm_unreachable("unknown visibility!");
577 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
578 if (isa<CXXConstructorDecl>(GD.getDecl()))
579 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
581 else if (isa<CXXDestructorDecl>(GD.getDecl()))
582 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
584 else if (isa<FunctionDecl>(GD.getDecl()))
585 return GetAddrOfFunction(GD);
587 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
590 /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the
591 /// given type. If a variable with a different type already exists then a new
592 /// variable with the right type will be created and all uses of the old
593 /// variable will be replaced with a bitcast to the new variable.
594 llvm::GlobalVariable *
595 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
596 llvm::GlobalValue::LinkageTypes Linkage);
598 /// GetGlobalVarAddressSpace - Return the address space of the underlying
599 /// global variable for D, as determined by its declaration. Normally this
600 /// is the same as the address space of D's type, but in CUDA, address spaces
601 /// are associated with declarations, not types.
602 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
604 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
605 /// given global variable. If Ty is non-null and if the global doesn't exist,
606 /// then it will be greated with the specified type instead of whatever the
607 /// normal requested type would be.
608 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
612 /// GetAddrOfFunction - Return the address of the given function. If Ty is
613 /// non-null, then this function will use the specified type if it has to
615 llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
617 bool ForVTable = false);
619 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
620 /// for the given type.
621 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
623 /// GetAddrOfUuidDescriptor - Get the address of a uuid descriptor .
624 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
626 /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
627 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
629 /// GetWeakRefReference - Get a reference to the target of VD.
630 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
632 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
633 /// a class. Returns null if the offset is 0.
635 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
636 CastExpr::path_const_iterator PathBegin,
637 CastExpr::path_const_iterator PathEnd);
639 /// A pair of helper functions for a __block variable.
640 class ByrefHelpers : public llvm::FoldingSetNode {
642 llvm::Constant *CopyHelper;
643 llvm::Constant *DisposeHelper;
645 /// The alignment of the field. This is important because
646 /// different offsets to the field within the byref struct need to
647 /// have different helper functions.
650 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
651 virtual ~ByrefHelpers();
653 void Profile(llvm::FoldingSetNodeID &id) const {
654 id.AddInteger(Alignment.getQuantity());
657 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
659 virtual bool needsCopy() const { return true; }
660 virtual void emitCopy(CodeGenFunction &CGF,
661 llvm::Value *dest, llvm::Value *src) = 0;
663 virtual bool needsDispose() const { return true; }
664 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
667 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
669 /// getUniqueBlockCount - Fetches the global unique block count.
670 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
672 /// getBlockDescriptorType - Fetches the type of a generic block
674 llvm::Type *getBlockDescriptorType();
676 /// getGenericBlockLiteralType - The type of a generic block literal.
677 llvm::Type *getGenericBlockLiteralType();
679 /// GetAddrOfGlobalBlock - Gets the address of a block which
680 /// requires no captures.
681 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
683 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
684 /// for the given string.
685 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
687 /// GetAddrOfConstantString - Return a pointer to a constant NSString object
688 /// for the given string. Or a user defined String object as defined via
689 /// -fconstant-string-class=class_name option.
690 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
692 /// GetConstantArrayFromStringLiteral - Return a constant array for the given
694 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
696 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
697 /// for the given string literal.
698 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
700 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
701 /// array for the given ObjCEncodeExpr node.
702 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
704 /// GetAddrOfConstantString - Returns a pointer to a character array
705 /// containing the literal. This contents are exactly that of the given
706 /// string, i.e. it will not be null terminated automatically; see
707 /// GetAddrOfConstantCString. Note that whether the result is actually a
708 /// pointer to an LLVM constant depends on Feature.WriteableStrings.
710 /// The result has pointer to array type.
712 /// \param GlobalName If provided, the name to use for the global
713 /// (if one is created).
714 llvm::Constant *GetAddrOfConstantString(StringRef Str,
715 const char *GlobalName=0,
716 unsigned Alignment=0);
718 /// GetAddrOfConstantCString - Returns a pointer to a character array
719 /// containing the literal and a terminating '\0' character. The result has
720 /// pointer to array type.
722 /// \param GlobalName If provided, the name to use for the global (if one is
724 llvm::Constant *GetAddrOfConstantCString(const std::string &str,
725 const char *GlobalName=0,
726 unsigned Alignment=0);
728 /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global
729 /// variable for the given file-scope compound literal expression.
730 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
732 /// \brief Retrieve the record type that describes the state of an
733 /// Objective-C fast enumeration loop (for..in).
734 QualType getObjCFastEnumerationStateType();
736 /// GetAddrOfCXXConstructor - Return the address of the constructor of the
738 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
739 CXXCtorType ctorType,
740 const CGFunctionInfo *fnInfo = 0);
742 /// GetAddrOfCXXDestructor - Return the address of the constructor of the
744 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
745 CXXDtorType dtorType,
746 const CGFunctionInfo *fnInfo = 0);
748 /// getBuiltinLibFunction - Given a builtin id for a function like
749 /// "__builtin_fabsf", return a Function* for "fabsf".
750 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
753 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
755 /// EmitTopLevelDecl - Emit code for a single top level declaration.
756 void EmitTopLevelDecl(Decl *D);
758 /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this
759 // variable has been instantiated.
760 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
762 /// \brief If the declaration has internal linkage but is inside an
763 /// extern "C" linkage specification, prepare to emit an alias for it
764 /// to the expected name.
765 template<typename SomeDecl>
766 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
768 /// AddUsedGlobal - Add a global which should be forced to be
769 /// present in the object file; these are emitted to the llvm.used
771 void AddUsedGlobal(llvm::GlobalValue *GV);
773 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
774 /// destructor function.
775 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
776 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
779 /// CreateRuntimeFunction - Create a new runtime function with the specified
781 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
783 llvm::AttributeSet ExtraAttrs =
784 llvm::AttributeSet());
785 /// CreateRuntimeVariable - Create a new runtime global variable with the
786 /// specified type and name.
787 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
790 ///@name Custom Blocks Runtime Interfaces
793 llvm::Constant *getNSConcreteGlobalBlock();
794 llvm::Constant *getNSConcreteStackBlock();
795 llvm::Constant *getBlockObjectAssign();
796 llvm::Constant *getBlockObjectDispose();
800 llvm::Constant *getLLVMLifetimeStartFn();
801 llvm::Constant *getLLVMLifetimeEndFn();
803 // UpdateCompleteType - Make sure that this type is translated.
804 void UpdateCompletedType(const TagDecl *TD);
806 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
808 /// EmitConstantInit - Try to emit the initializer for the given declaration
809 /// as a constant; returns 0 if the expression cannot be emitted as a
811 llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF = 0);
813 /// EmitConstantExpr - Try to emit the given expression as a
814 /// constant; returns 0 if the expression cannot be emitted as a
816 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
817 CodeGenFunction *CGF = 0);
819 /// EmitConstantValue - Emit the given constant value as a constant, in the
820 /// type's scalar representation.
821 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
822 CodeGenFunction *CGF = 0);
824 /// EmitConstantValueForMemory - Emit the given constant value as a constant,
825 /// in the type's memory representation.
826 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
828 CodeGenFunction *CGF = 0);
830 /// EmitNullConstant - Return the result of value-initializing the given
831 /// type, i.e. a null expression of the given type. This is usually,
832 /// but not always, an LLVM null constant.
833 llvm::Constant *EmitNullConstant(QualType T);
835 /// EmitNullConstantForBase - Return a null constant appropriate for
836 /// zero-initializing a base class with the given type. This is usually,
837 /// but not always, an LLVM null constant.
838 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
840 /// Error - Emit a general error that something can't be done.
841 void Error(SourceLocation loc, StringRef error);
843 /// ErrorUnsupported - Print out an error that codegen doesn't support the
844 /// specified stmt yet.
845 /// \param OmitOnError - If true, then this error should only be emitted if no
846 /// other errors have been reported.
847 void ErrorUnsupported(const Stmt *S, const char *Type,
848 bool OmitOnError=false);
850 /// ErrorUnsupported - Print out an error that codegen doesn't support the
851 /// specified decl yet.
852 /// \param OmitOnError - If true, then this error should only be emitted if no
853 /// other errors have been reported.
854 void ErrorUnsupported(const Decl *D, const char *Type,
855 bool OmitOnError=false);
857 /// SetInternalFunctionAttributes - Set the attributes on the LLVM
858 /// function for the given decl and function info. This applies
859 /// attributes necessary for handling the ABI as well as user
860 /// specified attributes like section.
861 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
862 const CGFunctionInfo &FI);
864 /// SetLLVMFunctionAttributes - Set the LLVM function attributes
865 /// (sext, zext, etc).
866 void SetLLVMFunctionAttributes(const Decl *D,
867 const CGFunctionInfo &Info,
870 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
871 /// which only apply to a function definintion.
872 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
874 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used
875 /// as a return type.
876 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
878 /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when
879 /// used as a return type.
880 bool ReturnTypeUsesFPRet(QualType ResultType);
882 /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when
883 /// used as a return type.
884 bool ReturnTypeUsesFP2Ret(QualType ResultType);
886 /// ConstructAttributeList - Get the LLVM attributes and calling convention to
887 /// use for a particular function type.
889 /// \param Info - The function type information.
890 /// \param TargetDecl - The decl these attributes are being constructed
891 /// for. If supplied the attributes applied to this decl may contribute to the
892 /// function attributes and calling convention.
893 /// \param PAL [out] - On return, the attribute list to use.
894 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
895 void ConstructAttributeList(const CGFunctionInfo &Info,
896 const Decl *TargetDecl,
897 AttributeListType &PAL,
898 unsigned &CallingConv,
899 bool AttrOnCallSite);
901 StringRef getMangledName(GlobalDecl GD);
902 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
903 const BlockDecl *BD);
905 void EmitTentativeDefinition(const VarDecl *D);
907 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
909 llvm::GlobalVariable::LinkageTypes
910 getFunctionLinkage(const FunctionDecl *FD);
912 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) {
913 V->setLinkage(getFunctionLinkage(FD));
916 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
917 /// and type information of the given class.
918 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
920 /// GetTargetTypeStoreSize - Return the store size, in character units, of
921 /// the given LLVM type.
922 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
924 /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global
926 llvm::GlobalValue::LinkageTypes
927 GetLLVMLinkageVarDefinition(const VarDecl *D,
928 llvm::GlobalVariable *GV);
930 /// Emit all the global annotations.
931 void EmitGlobalAnnotations();
933 /// Emit an annotation string.
934 llvm::Constant *EmitAnnotationString(StringRef Str);
936 /// Emit the annotation's translation unit.
937 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
939 /// Emit the annotation line number.
940 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
942 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
943 /// annotation information for a given GlobalValue. The annotation struct is
944 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
945 /// GlobalValue being annotated. The second field is the constant string
946 /// created from the AnnotateAttr's annotation. The third field is a constant
947 /// string containing the name of the translation unit. The fourth field is
948 /// the line number in the file of the annotated value declaration.
949 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
950 const AnnotateAttr *AA,
953 /// Add global annotations that are set on D, for the global GV. Those
954 /// annotations are emitted during finalization of the LLVM code.
955 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
957 const llvm::BlackList &getSanitizerBlacklist() const {
958 return SanitizerBlacklist;
961 const SanitizerOptions &getSanOpts() const { return SanOpts; }
963 void addDeferredVTable(const CXXRecordDecl *RD) {
964 DeferredVTables.push_back(RD);
968 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
970 llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName,
974 llvm::AttributeSet ExtraAttrs =
975 llvm::AttributeSet());
976 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
977 llvm::PointerType *PTy,
979 bool UnnamedAddr = false);
981 /// SetCommonAttributes - Set attributes which are common to any
982 /// form of a global definition (alias, Objective-C method,
983 /// function, global variable).
985 /// NOTE: This should only be called for definitions.
986 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
988 /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
989 void SetFunctionDefinitionAttributes(const FunctionDecl *D,
990 llvm::GlobalValue *GV);
992 /// SetFunctionAttributes - Set function attributes for a function
994 void SetFunctionAttributes(GlobalDecl GD,
996 bool IsIncompleteFunction);
998 /// EmitGlobal - Emit code for a singal global function or var decl. Forward
999 /// declarations are emitted lazily.
1000 void EmitGlobal(GlobalDecl D);
1002 void EmitGlobalDefinition(GlobalDecl D);
1004 void EmitGlobalFunctionDefinition(GlobalDecl GD);
1005 void EmitGlobalVarDefinition(const VarDecl *D);
1006 llvm::Constant *MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1008 void EmitAliasDefinition(GlobalDecl GD);
1009 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1010 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1012 // C++ related functions.
1014 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
1015 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1017 void EmitNamespace(const NamespaceDecl *D);
1018 void EmitLinkageSpec(const LinkageSpecDecl *D);
1020 /// EmitCXXConstructors - Emit constructors (base, complete) from a
1021 /// C++ constructor Decl.
1022 void EmitCXXConstructors(const CXXConstructorDecl *D);
1024 /// EmitCXXConstructor - Emit a single constructor with the given type from
1025 /// a C++ constructor Decl.
1026 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
1028 /// EmitCXXDestructors - Emit destructors (base, complete) from a
1029 /// C++ destructor Decl.
1030 void EmitCXXDestructors(const CXXDestructorDecl *D);
1032 /// EmitCXXDestructor - Emit a single destructor with the given type from
1033 /// a C++ destructor Decl.
1034 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
1036 /// \brief Emit the function that initializes C++ thread_local variables.
1037 void EmitCXXThreadLocalInitFunc();
1039 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
1040 void EmitCXXGlobalInitFunc();
1042 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
1043 void EmitCXXGlobalDtorFunc();
1045 /// EmitCXXGlobalVarDeclInitFunc - Emit the function that initializes the
1046 /// specified global (if PerformInit is true) and registers its destructor.
1047 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1048 llvm::GlobalVariable *Addr,
1051 // FIXME: Hardcoding priority here is gross.
1052 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
1053 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
1055 /// EmitCtorList - Generates a global array of functions and priorities using
1056 /// the given list and name. This array will have appending linkage and is
1057 /// suitable for use as a LLVM constructor or destructor array.
1058 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1060 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
1062 void EmitFundamentalRTTIDescriptor(QualType Type);
1064 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
1066 void EmitFundamentalRTTIDescriptors();
1068 /// EmitDeferred - Emit any needed decls for which code generation
1070 void EmitDeferred();
1072 /// EmitDeferredVTables - Emit any vtables which we deferred and
1073 /// still have a use for.
1074 void EmitDeferredVTables();
1076 /// EmitLLVMUsed - Emit the llvm.used metadata used to force
1077 /// references to global which may otherwise be optimized out.
1078 void EmitLLVMUsed();
1080 /// \brief Emit the link options introduced by imported modules.
1081 void EmitModuleLinkOptions();
1083 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1084 /// linkage specifications, giving them the "expected" name where possible.
1085 void EmitStaticExternCAliases();
1087 void EmitDeclMetadata();
1089 /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where
1090 /// to emit the .gcno and .gcda files in a way that persists in .bc files.
1091 void EmitCoverageFile();
1093 /// Emits the initializer for a uuidof string.
1094 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType);
1096 /// MayDeferGeneration - Determine if the given decl can be emitted
1097 /// lazily; this is only relevant for definitions. The given decl
1098 /// must be either a function or var decl.
1099 bool MayDeferGeneration(const ValueDecl *D);
1101 /// SimplifyPersonality - Check whether we can use a "simpler", more
1102 /// core exceptions personality function.
1103 void SimplifyPersonality();
1105 } // end namespace CodeGen
1106 } // end namespace clang