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 "clang/Basic/LangOptions.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
24 #include "CGVTables.h"
25 #include "CodeGenTypes.h"
26 #include "GlobalDecl.h"
28 #include "llvm/Module.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringSet.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/Support/ValueHandle.h"
46 class TargetCodeGenInfo;
51 class ObjCImplementationDecl;
52 class ObjCCategoryImplDecl;
53 class ObjCProtocolDecl;
68 class CXXDestructorDecl;
72 class CodeGenFunction;
78 struct OrderGlobalInits {
79 unsigned int priority;
80 unsigned int lex_order;
81 OrderGlobalInits(unsigned int p, unsigned int l)
82 : priority(p), lex_order(l) {}
84 bool operator==(const OrderGlobalInits &RHS) const {
85 return priority == RHS.priority &&
86 lex_order == RHS.lex_order;
89 bool operator<(const OrderGlobalInits &RHS) const {
90 if (priority < RHS.priority)
93 return priority == RHS.priority && lex_order < RHS.lex_order;
97 /// CodeGenModule - This class organizes the cross-function state that is used
98 /// while generating LLVM code.
99 class CodeGenModule : public BlockModule {
100 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT
101 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
103 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
106 const LangOptions &Features;
107 const CodeGenOptions &CodeGenOpts;
108 llvm::Module &TheModule;
109 const llvm::TargetData &TheTargetData;
110 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
115 /// VTables - Holds information about C++ vtables.
116 CodeGenVTables VTables;
117 friend class CodeGenVTables;
119 CGObjCRuntime* Runtime;
120 CGDebugInfo* DebugInfo;
122 // WeakRefReferences - A set of references that have only been seen via
123 // a weakref so far. This is used to remove the weak of the reference if we ever
124 // see a direct reference or a definition.
125 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
127 /// DeferredDecls - This contains all the decls which have definitions but
128 /// which are deferred for emission and therefore should only be output if
129 /// they are actually used. If a decl is in this, then it is known to have
130 /// not been referenced yet.
131 llvm::StringMap<GlobalDecl> DeferredDecls;
133 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
134 /// that *are* actually referenced. These get code generated when the module
136 std::vector<GlobalDecl> DeferredDeclsToEmit;
138 /// LLVMUsed - List of global values which are required to be
139 /// present in the object file; bitcast to i8*. This is used for
140 /// forcing visibility of symbols which may otherwise be optimized
142 std::vector<llvm::WeakVH> LLVMUsed;
144 /// GlobalCtors - Store the list of global constructors and their respective
145 /// priorities to be emitted when the translation unit is complete.
146 CtorList GlobalCtors;
148 /// GlobalDtors - Store the list of global destructors and their respective
149 /// priorities to be emitted when the translation unit is complete.
150 CtorList GlobalDtors;
152 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
153 llvm::DenseMap<GlobalDecl, llvm::StringRef> MangledDeclNames;
154 llvm::BumpPtrAllocator MangledNamesAllocator;
156 std::vector<llvm::Constant*> Annotations;
158 llvm::StringMap<llvm::Constant*> CFConstantStringMap;
159 llvm::StringMap<llvm::Constant*> ConstantStringMap;
160 llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap;
162 /// CXXGlobalInits - Global variables with initializers that need to run
164 std::vector<llvm::Constant*> CXXGlobalInits;
166 /// When a C++ decl with an initializer is deferred, null is
167 /// appended to CXXGlobalInits, and the index of that null is placed
168 /// here so that the initializer will be performed in the correct
170 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
172 /// - Global variables with initializers whose order of initialization
173 /// is set by init_priority attribute.
175 llvm::SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8>
176 PrioritizedCXXGlobalInits;
178 /// CXXGlobalDtors - Global destructor functions and arguments that need to
179 /// run on termination.
180 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
182 /// CFConstantStringClassRef - Cached reference to the class for constant
183 /// strings. This value has type int * but is actually an Obj-C class pointer.
184 llvm::Constant *CFConstantStringClassRef;
186 /// NSConstantStringClassRef - Cached reference to the class for constant
187 /// strings. This value has type int * but is actually an Obj-C class pointer.
188 llvm::Constant *NSConstantStringClassRef;
190 /// Lazily create the Objective-C runtime
191 void createObjCRuntime();
193 llvm::LLVMContext &VMContext;
195 /// @name Cache for Blocks Runtime Globals
198 const VarDecl *NSConcreteGlobalBlockDecl;
199 const VarDecl *NSConcreteStackBlockDecl;
200 llvm::Constant *NSConcreteGlobalBlock;
201 llvm::Constant *NSConcreteStackBlock;
203 const FunctionDecl *BlockObjectAssignDecl;
204 const FunctionDecl *BlockObjectDisposeDecl;
205 llvm::Constant *BlockObjectAssign;
206 llvm::Constant *BlockObjectDispose;
210 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
211 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
215 /// Release - Finalize LLVM code generation.
218 /// getObjCRuntime() - Return a reference to the configured
219 /// Objective-C runtime.
220 CGObjCRuntime &getObjCRuntime() {
221 if (!Runtime) createObjCRuntime();
225 /// hasObjCRuntime() - Return true iff an Objective-C runtime has
227 bool hasObjCRuntime() { return !!Runtime; }
229 /// getCXXABI() - Return a reference to the configured C++ ABI.
230 CGCXXABI &getCXXABI() { return ABI; }
232 llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) {
233 return StaticLocalDeclMap[VD];
235 void setStaticLocalDeclAddress(const VarDecl *D,
236 llvm::GlobalVariable *GV) {
237 StaticLocalDeclMap[D] = GV;
240 CGDebugInfo *getDebugInfo() { return DebugInfo; }
241 ASTContext &getContext() const { return Context; }
242 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
243 const LangOptions &getLangOptions() const { return Features; }
244 llvm::Module &getModule() const { return TheModule; }
245 CodeGenTypes &getTypes() { return Types; }
246 CodeGenVTables &getVTables() { return VTables; }
247 Diagnostic &getDiags() const { return Diags; }
248 const llvm::TargetData &getTargetData() const { return TheTargetData; }
249 llvm::LLVMContext &getLLVMContext() { return VMContext; }
250 const TargetCodeGenInfo &getTargetCodeGenInfo();
251 bool isTargetDarwin() const;
253 /// getDeclVisibilityMode - Compute the visibility of the decl \arg D.
254 LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const;
256 /// setGlobalVisibility - Set the visibility for the given LLVM
258 void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const;
260 /// setTypeVisibility - Set the visibility for the given global
261 /// value which holds information about a type.
262 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D,
263 bool IsForRTTI) const;
265 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
266 if (isa<CXXConstructorDecl>(GD.getDecl()))
267 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
269 else if (isa<CXXDestructorDecl>(GD.getDecl()))
270 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
272 else if (isa<FunctionDecl>(GD.getDecl()))
273 return GetAddrOfFunction(GD);
275 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
278 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
279 /// given global variable. If Ty is non-null and if the global doesn't exist,
280 /// then it will be greated with the specified type instead of whatever the
281 /// normal requested type would be.
282 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
283 const llvm::Type *Ty = 0);
285 /// GetAddrOfFunction - Return the address of the given function. If Ty is
286 /// non-null, then this function will use the specified type if it has to
288 llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
289 const llvm::Type *Ty = 0);
291 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
292 /// for the given type.
293 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
295 /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
296 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
298 /// GetWeakRefReference - Get a reference to the target of VD.
299 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
301 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
302 /// a class. Returns null if the offset is 0.
304 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
305 CastExpr::path_const_iterator PathBegin,
306 CastExpr::path_const_iterator PathEnd);
308 /// GetStringForStringLiteral - Return the appropriate bytes for a string
309 /// literal, properly padded to match the literal type. If only the address of
310 /// a constant is needed consider using GetAddrOfConstantStringLiteral.
311 std::string GetStringForStringLiteral(const StringLiteral *E);
313 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
314 /// for the given string.
315 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
317 /// GetAddrOfConstantNSString - Return a pointer to a constant NSString object
318 /// for the given string.
319 llvm::Constant *GetAddrOfConstantNSString(const StringLiteral *Literal);
321 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
322 /// for the given string literal.
323 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
325 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
326 /// array for the given ObjCEncodeExpr node.
327 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
329 /// GetAddrOfConstantString - Returns a pointer to a character array
330 /// containing the literal. This contents are exactly that of the given
331 /// string, i.e. it will not be null terminated automatically; see
332 /// GetAddrOfConstantCString. Note that whether the result is actually a
333 /// pointer to an LLVM constant depends on Feature.WriteableStrings.
335 /// The result has pointer to array type.
337 /// \param GlobalName If provided, the name to use for the global
338 /// (if one is created).
339 llvm::Constant *GetAddrOfConstantString(const std::string& str,
340 const char *GlobalName=0);
342 /// GetAddrOfConstantCString - Returns a pointer to a character array
343 /// containing the literal and a terminating '\0' character. The result has
344 /// pointer to array type.
346 /// \param GlobalName If provided, the name to use for the global (if one is
348 llvm::Constant *GetAddrOfConstantCString(const std::string &str,
349 const char *GlobalName=0);
351 /// GetAddrOfCXXConstructor - Return the address of the constructor of the
353 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
356 /// GetAddrOfCXXDestructor - Return the address of the constructor of the
358 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
361 /// getBuiltinLibFunction - Given a builtin id for a function like
362 /// "__builtin_fabsf", return a Function* for "fabsf".
363 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
366 llvm::Function *getMemCpyFn(const llvm::Type *DestType,
367 const llvm::Type *SrcType,
368 const llvm::Type *SizeType);
370 llvm::Function *getMemMoveFn(const llvm::Type *DestType,
371 const llvm::Type *SrcType,
372 const llvm::Type *SizeType);
374 llvm::Function *getMemSetFn(const llvm::Type *DestType,
375 const llvm::Type *SizeType);
377 llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0,
378 unsigned NumTys = 0);
380 /// EmitTopLevelDecl - Emit code for a single top level declaration.
381 void EmitTopLevelDecl(Decl *D);
383 /// AddUsedGlobal - Add a global which should be forced to be
384 /// present in the object file; these are emitted to the llvm.used
386 void AddUsedGlobal(llvm::GlobalValue *GV);
388 void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
390 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
391 /// destructor function.
392 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
393 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
396 /// CreateRuntimeFunction - Create a new runtime function with the specified
398 llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty,
399 llvm::StringRef Name);
400 /// CreateRuntimeVariable - Create a new runtime global variable with the
401 /// specified type and name.
402 llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty,
403 llvm::StringRef Name);
405 ///@name Custom Blocks Runtime Interfaces
408 llvm::Constant *getNSConcreteGlobalBlock();
409 llvm::Constant *getNSConcreteStackBlock();
410 llvm::Constant *getBlockObjectAssign();
411 llvm::Constant *getBlockObjectDispose();
415 void UpdateCompletedType(const TagDecl *TD) {
416 // Make sure that this type is translated.
417 Types.UpdateCompletedType(TD);
420 /// EmitConstantExpr - Try to emit the given expression as a
421 /// constant; returns 0 if the expression cannot be emitted as a
423 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
424 CodeGenFunction *CGF = 0);
426 /// EmitNullConstant - Return the result of value-initializing the given
427 /// type, i.e. a null expression of the given type. This is usually,
428 /// but not always, an LLVM null constant.
429 llvm::Constant *EmitNullConstant(QualType T);
431 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
432 const AnnotateAttr *AA, unsigned LineNo);
434 /// ErrorUnsupported - Print out an error that codegen doesn't support the
435 /// specified stmt yet.
436 /// \param OmitOnError - If true, then this error should only be emitted if no
437 /// other errors have been reported.
438 void ErrorUnsupported(const Stmt *S, const char *Type,
439 bool OmitOnError=false);
441 /// ErrorUnsupported - Print out an error that codegen doesn't support the
442 /// specified decl yet.
443 /// \param OmitOnError - If true, then this error should only be emitted if no
444 /// other errors have been reported.
445 void ErrorUnsupported(const Decl *D, const char *Type,
446 bool OmitOnError=false);
448 /// SetInternalFunctionAttributes - Set the attributes on the LLVM
449 /// function for the given decl and function info. This applies
450 /// attributes necessary for handling the ABI as well as user
451 /// specified attributes like section.
452 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
453 const CGFunctionInfo &FI);
455 /// SetLLVMFunctionAttributes - Set the LLVM function attributes
456 /// (sext, zext, etc).
457 void SetLLVMFunctionAttributes(const Decl *D,
458 const CGFunctionInfo &Info,
461 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
462 /// which only apply to a function definintion.
463 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
465 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used
466 /// as a return type.
467 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
469 /// ReturnTypeUsesSret - Return true iff the given type uses 'fpret' when used
470 /// as a return type.
471 bool ReturnTypeUsesFPRet(QualType ResultType);
473 /// ConstructAttributeList - Get the LLVM attributes and calling convention to
474 /// use for a particular function type.
476 /// \param Info - The function type information.
477 /// \param TargetDecl - The decl these attributes are being constructed
478 /// for. If supplied the attributes applied to this decl may contribute to the
479 /// function attributes and calling convention.
480 /// \param PAL [out] - On return, the attribute list to use.
481 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
482 void ConstructAttributeList(const CGFunctionInfo &Info,
483 const Decl *TargetDecl,
484 AttributeListType &PAL,
485 unsigned &CallingConv);
487 llvm::StringRef getMangledName(GlobalDecl GD);
488 void getMangledName(GlobalDecl GD, MangleBuffer &Buffer, const BlockDecl *BD);
490 void EmitTentativeDefinition(const VarDecl *D);
492 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
494 llvm::GlobalVariable::LinkageTypes
495 getFunctionLinkage(const FunctionDecl *FD);
497 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) {
498 V->setLinkage(getFunctionLinkage(FD));
501 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
502 /// and type information of the given class.
503 static llvm::GlobalVariable::LinkageTypes
504 getVTableLinkage(const CXXRecordDecl *RD);
506 /// GetTargetTypeStoreSize - Return the store size, in character units, of
507 /// the given LLVM type.
508 CharUnits GetTargetTypeStoreSize(const llvm::Type *Ty) const;
510 std::vector<const CXXRecordDecl*> DeferredVTables;
513 llvm::GlobalValue *GetGlobalValue(llvm::StringRef Ref);
515 llvm::Constant *GetOrCreateLLVMFunction(llvm::StringRef MangledName,
516 const llvm::Type *Ty,
518 llvm::Constant *GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
519 const llvm::PointerType *PTy,
522 /// SetCommonAttributes - Set attributes which are common to any
523 /// form of a global definition (alias, Objective-C method,
524 /// function, global variable).
526 /// NOTE: This should only be called for definitions.
527 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
529 /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
530 void SetFunctionDefinitionAttributes(const FunctionDecl *D,
531 llvm::GlobalValue *GV);
533 /// SetFunctionAttributes - Set function attributes for a function
535 void SetFunctionAttributes(GlobalDecl GD,
537 bool IsIncompleteFunction);
539 /// EmitGlobal - Emit code for a singal global function or var decl. Forward
540 /// declarations are emitted lazily.
541 void EmitGlobal(GlobalDecl D);
543 void EmitGlobalDefinition(GlobalDecl D);
545 void EmitGlobalFunctionDefinition(GlobalDecl GD);
546 void EmitGlobalVarDefinition(const VarDecl *D);
547 void EmitAliasDefinition(GlobalDecl GD);
548 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
549 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
551 // C++ related functions.
553 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
554 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
556 void EmitNamespace(const NamespaceDecl *D);
557 void EmitLinkageSpec(const LinkageSpecDecl *D);
559 /// EmitCXXConstructors - Emit constructors (base, complete) from a
560 /// C++ constructor Decl.
561 void EmitCXXConstructors(const CXXConstructorDecl *D);
563 /// EmitCXXConstructor - Emit a single constructor with the given type from
564 /// a C++ constructor Decl.
565 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
567 /// EmitCXXDestructors - Emit destructors (base, complete) from a
568 /// C++ destructor Decl.
569 void EmitCXXDestructors(const CXXDestructorDecl *D);
571 /// EmitCXXDestructor - Emit a single destructor with the given type from
572 /// a C++ destructor Decl.
573 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
575 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
576 void EmitCXXGlobalInitFunc();
578 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
579 void EmitCXXGlobalDtorFunc();
581 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D);
583 // FIXME: Hardcoding priority here is gross.
584 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
585 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
587 /// EmitCtorList - Generates a global array of functions and priorities using
588 /// the given list and name. This array will have appending linkage and is
589 /// suitable for use as a LLVM constructor or destructor array.
590 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
592 void EmitAnnotations(void);
594 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
596 void EmitFundamentalRTTIDescriptor(QualType Type);
598 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
600 void EmitFundamentalRTTIDescriptors();
602 /// EmitDeferred - Emit any needed decls for which code generation
604 void EmitDeferred(void);
606 /// EmitLLVMUsed - Emit the llvm.used metadata used to force
607 /// references to global which may otherwise be optimized out.
608 void EmitLLVMUsed(void);
610 void EmitDeclMetadata();
612 /// MayDeferGeneration - Determine if the given decl can be emitted
613 /// lazily; this is only relevant for definitions. The given decl
614 /// must be either a function or var decl.
615 bool MayDeferGeneration(const ValueDecl *D);
617 } // end namespace CodeGen
618 } // end namespace clang