blob: 8280766c7035366750380e095fb124b80da2623a [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is the internal per-translation-unit state used for llvm translation.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef CLANG_CODEGEN_CODEGENMODULE_H
15#define CLANG_CODEGEN_CODEGENMODULE_H
16
17#include "clang/Basic/LangOptions.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "CGBlocks.h"
22#include "CGCall.h"
23#include "CGCXX.h"
24#include "CGVtable.h"
25#include "CodeGenTypes.h"
26#include "GlobalDecl.h"
27#include "Mangle.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/Support/ValueHandle.h"
33#include <list>
34
35namespace llvm {
36 class Module;
37 class Constant;
38 class Function;
39 class GlobalValue;
40 class TargetData;
41 class FunctionType;
42 class LLVMContext;
43}
44
45namespace clang {
46 class TargetCodeGenInfo;
47 class ASTContext;
48 class FunctionDecl;
49 class IdentifierInfo;
50 class ObjCMethodDecl;
51 class ObjCImplementationDecl;
52 class ObjCCategoryImplDecl;
53 class ObjCProtocolDecl;
54 class ObjCEncodeExpr;
55 class BlockExpr;
56 class CharUnits;
57 class Decl;
58 class Expr;
59 class Stmt;
60 class StringLiteral;
61 class NamedDecl;
62 class ValueDecl;
63 class VarDecl;
64 class LangOptions;
65 class CodeGenOptions;
66 class Diagnostic;
67 class AnnotateAttr;
68 class CXXDestructorDecl;
69
70namespace CodeGen {
71
72 class CodeGenFunction;
73 class CGDebugInfo;
74 class CGObjCRuntime;
75
76
77/// CodeGenModule - This class organizes the cross-function state that is used
78/// while generating LLVM code.
79class CodeGenModule : public BlockModule {
80 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT
81 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
82
83 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
84
85 ASTContext &Context;
86 const LangOptions &Features;
87 const CodeGenOptions &CodeGenOpts;
88 llvm::Module &TheModule;
89 const llvm::TargetData &TheTargetData;
90 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
91 Diagnostic &Diags;
92 CodeGenTypes Types;
93 MangleContext MangleCtx;
94
95 /// VtableInfo - Holds information about C++ vtables.
96 CGVtableInfo VtableInfo;
97
98 CGObjCRuntime* Runtime;
99 CGDebugInfo* DebugInfo;
100
101 llvm::Function *MemCpyFn;
102 llvm::Function *MemMoveFn;
103 llvm::Function *MemSetFn;
104
105 /// GlobalDeclMap - Mapping of decl names (represented as unique
106 /// character pointers from either the identifier table or the set
107 /// of mangled names) to global variables we have already
108 /// emitted. Note that the entries in this map are the actual
109 /// globals and therefore may not be of the same type as the decl,
110 /// they should be bitcasted on retrieval. Also note that the
111 /// globals are keyed on their source mangled name, not the global name
112 /// (which may change with attributes such as asm-labels). The key
113 /// to this map should be generated using getMangledName().
114 ///
115 /// Note that this map always lines up exactly with the contents of the LLVM
116 /// IR symbol table, but this is quicker to query since it is doing uniqued
117 /// pointer lookups instead of full string lookups.
118 llvm::DenseMap<const char*, llvm::GlobalValue*> GlobalDeclMap;
119
120 /// \brief Contains the strings used for mangled names.
121 ///
122 /// FIXME: Eventually, this should map from the semantic/canonical
123 /// declaration for each global entity to its mangled name (if it
124 /// has one).
125 llvm::StringSet<> MangledNames;
126
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. The key to this map is a uniqued mangled name.
131 llvm::DenseMap<const char*, GlobalDecl> DeferredDecls;
132
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
135 /// is done.
136 std::vector<GlobalDecl> DeferredDeclsToEmit;
137
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
141 /// out.
142 std::vector<llvm::WeakVH> LLVMUsed;
143
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;
147
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;
151
152 std::vector<llvm::Constant*> Annotations;
153
154 llvm::StringMap<llvm::Constant*> CFConstantStringMap;
155 llvm::StringMap<llvm::Constant*> ConstantStringMap;
156
157 /// CXXGlobalInits - Variables with global initializers that need to run
158 /// before main.
159 std::vector<llvm::Constant*> CXXGlobalInits;
160
161 /// CFConstantStringClassRef - Cached reference to the class for constant
162 /// strings. This value has type int * but is actually an Obj-C class pointer.
163 llvm::Constant *CFConstantStringClassRef;
164
165 /// Lazily create the Objective-C runtime
166 void createObjCRuntime();
167
168 llvm::LLVMContext &VMContext;
169public:
170 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
171 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
172
173 ~CodeGenModule();
174
175 /// Release - Finalize LLVM code generation.
176 void Release();
177
178 /// getObjCRuntime() - Return a reference to the configured
179 /// Objective-C runtime.
180 CGObjCRuntime &getObjCRuntime() {
181 if (!Runtime) createObjCRuntime();
182 return *Runtime;
183 }
184
185 /// hasObjCRuntime() - Return true iff an Objective-C runtime has
186 /// been configured.
187 bool hasObjCRuntime() { return !!Runtime; }
188
189 CGDebugInfo *getDebugInfo() { return DebugInfo; }
190 ASTContext &getContext() const { return Context; }
191 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
192 const LangOptions &getLangOptions() const { return Features; }
193 llvm::Module &getModule() const { return TheModule; }
194 CodeGenTypes &getTypes() { return Types; }
195 MangleContext &getMangleContext() { return MangleCtx; }
196 CGVtableInfo &getVtableInfo() { return VtableInfo; }
197 Diagnostic &getDiags() const { return Diags; }
198 const llvm::TargetData &getTargetData() const { return TheTargetData; }
199 llvm::LLVMContext &getLLVMContext() { return VMContext; }
200 const TargetCodeGenInfo &getTargetCodeGenInfo() const;
201
202 /// getDeclVisibilityMode - Compute the visibility of the decl \arg D.
203 LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const;
204
205 /// setGlobalVisibility - Set the visibility for the given LLVM
206 /// GlobalValue.
207 void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const;
208
209 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
210 /// given global variable. If Ty is non-null and if the global doesn't exist,
211 /// then it will be greated with the specified type instead of whatever the
212 /// normal requested type would be.
213 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
214 const llvm::Type *Ty = 0);
215
216 /// GetAddrOfFunction - Return the address of the given function. If Ty is
217 /// non-null, then this function will use the specified type if it has to
218 /// create it.
219 llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
220 const llvm::Type *Ty = 0);
221
222 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
223 /// for the given type.
224 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty);
225
226 llvm::Constant *GetAddrOfThunk(GlobalDecl GD,
227 const ThunkAdjustment &ThisAdjustment);
228 llvm::Constant *GetAddrOfCovariantThunk(GlobalDecl GD,
229 const CovariantThunkAdjustment &ThisAdjustment);
230 void BuildThunksForVirtual(GlobalDecl GD);
231 void BuildThunksForVirtualRecursive(GlobalDecl GD, GlobalDecl BaseOGD);
232
233 /// BuildThunk - Build a thunk for the given method.
234 llvm::Constant *BuildThunk(GlobalDecl GD, bool Extern,
235 const ThunkAdjustment &ThisAdjustment);
236
237 /// BuildCoVariantThunk - Build a thunk for the given method
238 llvm::Constant *
239 BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
240 const CovariantThunkAdjustment &Adjustment);
241
242 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
243 /// its base class. Returns null if the offset is 0.
244 llvm::Constant *
245 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
246 const CXXRecordDecl *BaseClassDecl);
247
248 /// ComputeThunkAdjustment - Returns the two parts required to compute the
249 /// offset for an object.
250 ThunkAdjustment ComputeThunkAdjustment(const CXXRecordDecl *ClassDecl,
251 const CXXRecordDecl *BaseClassDecl);
252
253 /// GetStringForStringLiteral - Return the appropriate bytes for a string
254 /// literal, properly padded to match the literal type. If only the address of
255 /// a constant is needed consider using GetAddrOfConstantStringLiteral.
256 std::string GetStringForStringLiteral(const StringLiteral *E);
257
258 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
259 /// for the given string.
260 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
261
262 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
263 /// for the given string literal.
264 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
265
266 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
267 /// array for the given ObjCEncodeExpr node.
268 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
269
270 /// GetAddrOfConstantString - Returns a pointer to a character array
271 /// containing the literal. This contents are exactly that of the given
272 /// string, i.e. it will not be null terminated automatically; see
273 /// GetAddrOfConstantCString. Note that whether the result is actually a
274 /// pointer to an LLVM constant depends on Feature.WriteableStrings.
275 ///
276 /// The result has pointer to array type.
277 ///
278 /// \param GlobalName If provided, the name to use for the global
279 /// (if one is created).
280 llvm::Constant *GetAddrOfConstantString(const std::string& str,
281 const char *GlobalName=0);
282
283 /// GetAddrOfConstantCString - Returns a pointer to a character array
284 /// containing the literal and a terminating '\0' character. The result has
285 /// pointer to array type.
286 ///
287 /// \param GlobalName If provided, the name to use for the global (if one is
288 /// created).
289 llvm::Constant *GetAddrOfConstantCString(const std::string &str,
290 const char *GlobalName=0);
291
292 /// GetAddrOfCXXConstructor - Return the address of the constructor of the
293 /// given type.
294 llvm::Function *GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
295 CXXCtorType Type);
296
297 /// GetAddrOfCXXDestructor - Return the address of the constructor of the
298 /// given type.
299 llvm::Function *GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
300 CXXDtorType Type);
301
302 /// getBuiltinLibFunction - Given a builtin id for a function like
303 /// "__builtin_fabsf", return a Function* for "fabsf".
304 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
305 unsigned BuiltinID);
306
307 llvm::Function *getMemCpyFn();
308 llvm::Function *getMemMoveFn();
309 llvm::Function *getMemSetFn();
310 llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0,
311 unsigned NumTys = 0);
312
313 /// EmitTopLevelDecl - Emit code for a single top level declaration.
314 void EmitTopLevelDecl(Decl *D);
315
316 /// AddUsedGlobal - Add a global which should be forced to be
317 /// present in the object file; these are emitted to the llvm.used
318 /// metadata global.
319 void AddUsedGlobal(llvm::GlobalValue *GV);
320
321 void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
322
323 /// CreateRuntimeFunction - Create a new runtime function with the specified
324 /// type and name.
325 llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty,
326 const char *Name);
327 /// CreateRuntimeVariable - Create a new runtime global variable with the
328 /// specified type and name.
329 llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty,
330 const char *Name);
331
332 void UpdateCompletedType(const TagDecl *TD) {
333 // Make sure that this type is translated.
334 Types.UpdateCompletedType(TD);
335 }
336
337 /// EmitConstantExpr - Try to emit the given expression as a
338 /// constant; returns 0 if the expression cannot be emitted as a
339 /// constant.
340 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
341 CodeGenFunction *CGF = 0);
342
343 /// EmitNullConstant - Return the result of value-initializing the given
344 /// type, i.e. a null expression of the given type. This is usually,
345 /// but not always, an LLVM null constant.
346 llvm::Constant *EmitNullConstant(QualType T);
347
348 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
349 const AnnotateAttr *AA, unsigned LineNo);
350
351 llvm::Constant *EmitPointerToDataMember(const FieldDecl *FD);
352
353 /// ErrorUnsupported - Print out an error that codegen doesn't support the
354 /// specified stmt yet.
355 /// \param OmitOnError - If true, then this error should only be emitted if no
356 /// other errors have been reported.
357 void ErrorUnsupported(const Stmt *S, const char *Type,
358 bool OmitOnError=false);
359
360 /// ErrorUnsupported - Print out an error that codegen doesn't support the
361 /// specified decl yet.
362 /// \param OmitOnError - If true, then this error should only be emitted if no
363 /// other errors have been reported.
364 void ErrorUnsupported(const Decl *D, const char *Type,
365 bool OmitOnError=false);
366
367 /// SetInternalFunctionAttributes - Set the attributes on the LLVM
368 /// function for the given decl and function info. This applies
369 /// attributes necessary for handling the ABI as well as user
370 /// specified attributes like section.
371 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
372 const CGFunctionInfo &FI);
373
374 /// SetLLVMFunctionAttributes - Set the LLVM function attributes
375 /// (sext, zext, etc).
376 void SetLLVMFunctionAttributes(const Decl *D,
377 const CGFunctionInfo &Info,
378 llvm::Function *F);
379
380 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
381 /// which only apply to a function definintion.
382 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
383
384 /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used
385 /// as a return type.
386 bool ReturnTypeUsesSret(const CGFunctionInfo &FI);
387
388 /// ConstructAttributeList - Get the LLVM attributes and calling convention to
389 /// use for a particular function type.
390 ///
391 /// \param Info - The function type information.
392 /// \param TargetDecl - The decl these attributes are being constructed
393 /// for. If supplied the attributes applied to this decl may contribute to the
394 /// function attributes and calling convention.
395 /// \param PAL [out] - On return, the attribute list to use.
396 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
397 void ConstructAttributeList(const CGFunctionInfo &Info,
398 const Decl *TargetDecl,
399 AttributeListType &PAL,
400 unsigned &CallingConv);
401
402 const char *getMangledName(const GlobalDecl &D);
403
404 const char *getMangledName(const NamedDecl *ND);
405 const char *getMangledCXXCtorName(const CXXConstructorDecl *D,
406 CXXCtorType Type);
407 const char *getMangledCXXDtorName(const CXXDestructorDecl *D,
408 CXXDtorType Type);
409
410 void EmitTentativeDefinition(const VarDecl *D);
411
412 enum GVALinkage {
413 GVA_Internal,
414 GVA_C99Inline,
415 GVA_CXXInline,
416 GVA_StrongExternal,
417 GVA_TemplateInstantiation
418 };
419
420 /// getVtableLinkage - Return the appropriate linkage for the vtable, VTT,
421 /// and type information of the given class.
422 static llvm::GlobalVariable::LinkageTypes
423 getVtableLinkage(const CXXRecordDecl *RD);
424
425 /// GetTargetTypeStoreSize - Return the store size, in character units, of
426 /// the given LLVM type.
427 CharUnits GetTargetTypeStoreSize(const llvm::Type *Ty) const;
428
429private:
430 /// UniqueMangledName - Unique a name by (if necessary) inserting it into the
431 /// MangledNames string map.
432 const char *UniqueMangledName(const char *NameStart, const char *NameEnd);
433
434 llvm::Constant *GetOrCreateLLVMFunction(const char *MangledName,
435 const llvm::Type *Ty,
436 GlobalDecl D);
437 llvm::Constant *GetOrCreateLLVMGlobal(const char *MangledName,
438 const llvm::PointerType *PTy,
439 const VarDecl *D);
440
441 /// SetCommonAttributes - Set attributes which are common to any
442 /// form of a global definition (alias, Objective-C method,
443 /// function, global variable).
444 ///
445 /// NOTE: This should only be called for definitions.
446 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
447
448 /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
449 void SetFunctionDefinitionAttributes(const FunctionDecl *D,
450 llvm::GlobalValue *GV);
451
452 /// SetFunctionAttributes - Set function attributes for a function
453 /// declaration.
454 void SetFunctionAttributes(GlobalDecl GD,
455 llvm::Function *F,
456 bool IsIncompleteFunction);
457
458 /// EmitGlobal - Emit code for a singal global function or var decl. Forward
459 /// declarations are emitted lazily.
460 void EmitGlobal(GlobalDecl D);
461
462 void EmitGlobalDefinition(GlobalDecl D);
463
464 void EmitGlobalFunctionDefinition(GlobalDecl GD);
465 void EmitGlobalVarDefinition(const VarDecl *D);
466 void EmitAliasDefinition(const ValueDecl *D);
467 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
468
469 // C++ related functions.
470
471 void EmitNamespace(const NamespaceDecl *D);
472 void EmitLinkageSpec(const LinkageSpecDecl *D);
473
474 /// EmitCXXConstructors - Emit constructors (base, complete) from a
475 /// C++ constructor Decl.
476 void EmitCXXConstructors(const CXXConstructorDecl *D);
477
478 /// EmitCXXConstructor - Emit a single constructor with the given type from
479 /// a C++ constructor Decl.
480 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
481
482 /// EmitCXXDestructors - Emit destructors (base, complete) from a
483 /// C++ destructor Decl.
484 void EmitCXXDestructors(const CXXDestructorDecl *D);
485
486 /// EmitCXXDestructor - Emit a single destructor with the given type from
487 /// a C++ destructor Decl.
488 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
489
490 /// EmitCXXGlobalInitFunc - Emit a function that initializes C++ globals.
491 void EmitCXXGlobalInitFunc();
492
493 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D);
494
495 // FIXME: Hardcoding priority here is gross.
496 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
497 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
498
499 /// EmitCtorList - Generates a global array of functions and priorities using
500 /// the given list and name. This array will have appending linkage and is
501 /// suitable for use as a LLVM constructor or destructor array.
502 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
503
504 void EmitAnnotations(void);
505
506 /// EmitDeferred - Emit any needed decls for which code generation
507 /// was deferred.
508 void EmitDeferred(void);
509
510 /// EmitLLVMUsed - Emit the llvm.used metadata used to force
511 /// references to global which may otherwise be optimized out.
512 void EmitLLVMUsed(void);
513
514 /// MayDeferGeneration - Determine if the given decl can be emitted
515 /// lazily; this is only relevant for definitions. The given decl
516 /// must be either a function or var decl.
517 bool MayDeferGeneration(const ValueDecl *D);
518};
519} // end namespace CodeGen
520} // end namespace clang
521
522#endif