1 //===--- 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 "CGBlocks.h"
21 #include "CGCall.h"
22 #include "CGCXX.h"
23 #include "CodeGenTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include <list>
30 
31 namespace llvm {
32   class Module;
33   class Constant;
34   class Function;
35   class GlobalValue;
36   class TargetData;
37   class FunctionType;
38   class LLVMContext;
39 }
40 
41 namespace clang {
42   class ASTContext;
43   class FunctionDecl;
44   class IdentifierInfo;
45   class ObjCMethodDecl;
46   class ObjCImplementationDecl;
47   class ObjCCategoryImplDecl;
48   class ObjCProtocolDecl;
49   class ObjCEncodeExpr;
50   class BlockExpr;
51   class Decl;
52   class Expr;
53   class Stmt;
54   class StringLiteral;
55   class NamedDecl;
56   class ValueDecl;
57   class VarDecl;
58   class LangOptions;
59   class CompileOptions;
60   class Diagnostic;
61   class AnnotateAttr;
62   class CXXDestructorDecl;
63 
64 namespace CodeGen {
65 
66   class CodeGenFunction;
67   class CGDebugInfo;
68   class CGObjCRuntime;
69 
70 /// GlobalDecl - represents a global declaration. This can either be a
71 /// CXXConstructorDecl and the constructor type (Base, Complete).
72 /// a CXXDestructorDecl and the destructor type (Base, Complete) or
73 // a regular VarDecl or a FunctionDecl.
74 class GlobalDecl {
75   llvm::PointerIntPair<const ValueDecl*, 2> Value;
76 
77 public:
78   GlobalDecl() {}
79 
80   explicit GlobalDecl(const ValueDecl *VD) : Value(VD, 0) {
81     assert(!isa<CXXConstructorDecl>(VD) && "Use other ctor with ctor decls!");
82     assert(!isa<CXXDestructorDecl>(VD) && "Use other ctor with dtor decls!");
83   }
84   GlobalDecl(const CXXConstructorDecl *D, CXXCtorType Type)
85   : Value(D, Type) {}
86   GlobalDecl(const CXXDestructorDecl *D, CXXDtorType Type)
87   : Value(D, Type) {}
88 
89   const ValueDecl *getDecl() const { return Value.getPointer(); }
90 
91   CXXCtorType getCtorType() const {
92     assert(isa<CXXConstructorDecl>(getDecl()) && "Decl is not a ctor!");
93     return static_cast<CXXCtorType>(Value.getInt());
94   }
95 
96   CXXDtorType getDtorType() const {
97     assert(isa<CXXDestructorDecl>(getDecl()) && "Decl is not a dtor!");
98     return static_cast<CXXDtorType>(Value.getInt());
99   }
100 };
101 
102 /// CodeGenModule - This class organizes the cross-function state that is used
103 /// while generating LLVM code.
104 class CodeGenModule : public BlockModule {
105   CodeGenModule(const CodeGenModule&);  // DO NOT IMPLEMENT
106   void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
107 
108   typedef std::vector< std::pair<llvm::Constant*, int> > CtorList;
109 
110   ASTContext &Context;
111   const LangOptions &Features;
112   const CompileOptions &CompileOpts;
113   llvm::Module &TheModule;
114   const llvm::TargetData &TheTargetData;
115   Diagnostic &Diags;
116   CodeGenTypes Types;
117   CGObjCRuntime* Runtime;
118   CGDebugInfo* DebugInfo;
119 
120   llvm::Function *MemCpyFn;
121   llvm::Function *MemMoveFn;
122   llvm::Function *MemSetFn;
123 
124   /// GlobalDeclMap - Mapping of decl names (represented as unique
125   /// character pointers from either the identifier table or the set
126   /// of mangled names) to global variables we have already
127   /// emitted. Note that the entries in this map are the actual
128   /// globals and therefore may not be of the same type as the decl,
129   /// they should be bitcasted on retrieval. Also note that the
130   /// globals are keyed on their source mangled name, not the global name
131   /// (which may change with attributes such as asm-labels).  The key
132   /// to this map should be generated using getMangledName().
133   ///
134   /// Note that this map always lines up exactly with the contents of the LLVM
135   /// IR symbol table, but this is quicker to query since it is doing uniqued
136   /// pointer lookups instead of full string lookups.
137   llvm::DenseMap<const char*, llvm::GlobalValue*> GlobalDeclMap;
138 
139   /// \brief Contains the strings used for mangled names.
140   ///
141   /// FIXME: Eventually, this should map from the semantic/canonical
142   /// declaration for each global entity to its mangled name (if it
143   /// has one).
144   llvm::StringSet<> MangledNames;
145 
146   /// DeferredDecls - This contains all the decls which have definitions but
147   /// which are deferred for emission and therefore should only be output if
148   /// they are actually used.  If a decl is in this, then it is known to have
149   /// not been referenced yet.  The key to this map is a uniqued mangled name.
150   llvm::DenseMap<const char*, GlobalDecl> DeferredDecls;
151 
152   /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
153   /// that *are* actually referenced.  These get code generated when the module
154   /// is done.
155   std::vector<GlobalDecl> DeferredDeclsToEmit;
156 
157   /// LLVMUsed - List of global values which are required to be
158   /// present in the object file; bitcast to i8*. This is used for
159   /// forcing visibility of symbols which may otherwise be optimized
160   /// out.
161   std::vector<llvm::WeakVH> LLVMUsed;
162 
163   /// GlobalCtors - Store the list of global constructors and their respective
164   /// priorities to be emitted when the translation unit is complete.
165   CtorList GlobalCtors;
166 
167   /// GlobalDtors - Store the list of global destructors and their respective
168   /// priorities to be emitted when the translation unit is complete.
169   CtorList GlobalDtors;
170 
171   std::vector<llvm::Constant*> Annotations;
172 
173   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
174   llvm::StringMap<llvm::Constant*> ConstantStringMap;
175 
176   /// CFConstantStringClassRef - Cached reference to the class for constant
177   /// strings. This value has type int * but is actually an Obj-C class pointer.
178   llvm::Constant *CFConstantStringClassRef;
179 
180   llvm::LLVMContext &VMContext;
181 public:
182   CodeGenModule(ASTContext &C, const CompileOptions &CompileOpts,
183                 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
184 
185   ~CodeGenModule();
186 
187   /// Release - Finalize LLVM code generation.
188   void Release();
189 
190   /// getObjCRuntime() - Return a reference to the configured
191   /// Objective-C runtime.
192   CGObjCRuntime &getObjCRuntime() {
193     assert(Runtime && "No Objective-C runtime has been configured.");
194     return *Runtime;
195   }
196 
197   /// hasObjCRuntime() - Return true iff an Objective-C runtime has
198   /// been configured.
199   bool hasObjCRuntime() { return !!Runtime; }
200 
201   CGDebugInfo *getDebugInfo() { return DebugInfo; }
202   ASTContext &getContext() const { return Context; }
203   const CompileOptions &getCompileOpts() const { return CompileOpts; }
204   const LangOptions &getLangOptions() const { return Features; }
205   llvm::Module &getModule() const { return TheModule; }
206   CodeGenTypes &getTypes() { return Types; }
207   Diagnostic &getDiags() const { return Diags; }
208   const llvm::TargetData &getTargetData() const { return TheTargetData; }
209   llvm::LLVMContext &getLLVMContext() { return VMContext; }
210 
211   /// getDeclVisibilityMode - Compute the visibility of the decl \arg D.
212   LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const;
213 
214   /// setGlobalVisibility - Set the visibility for the given LLVM
215   /// GlobalValue.
216   void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const;
217 
218   /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
219   /// given global variable.  If Ty is non-null and if the global doesn't exist,
220   /// then it will be greated with the specified type instead of whatever the
221   /// normal requested type would be.
222   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
223                                      const llvm::Type *Ty = 0);
224 
225   /// GetAddrOfFunction - Return the address of the given function.  If Ty is
226   /// non-null, then this function will use the specified type if it has to
227   /// create it.
228   llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
229                                     const llvm::Type *Ty = 0);
230 
231   /// GetStringForStringLiteral - Return the appropriate bytes for a string
232   /// literal, properly padded to match the literal type. If only the address of
233   /// a constant is needed consider using GetAddrOfConstantStringLiteral.
234   std::string GetStringForStringLiteral(const StringLiteral *E);
235 
236   /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
237   /// for the given string.
238   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
239 
240   /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
241   /// for the given string literal.
242   llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
243 
244   /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
245   /// array for the given ObjCEncodeExpr node.
246   llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
247 
248   /// GetAddrOfConstantString - Returns a pointer to a character array
249   /// containing the literal. This contents are exactly that of the given
250   /// string, i.e. it will not be null terminated automatically; see
251   /// GetAddrOfConstantCString. Note that whether the result is actually a
252   /// pointer to an LLVM constant depends on Feature.WriteableStrings.
253   ///
254   /// The result has pointer to array type.
255   ///
256   /// \param GlobalName If provided, the name to use for the global
257   /// (if one is created).
258   llvm::Constant *GetAddrOfConstantString(const std::string& str,
259                                           const char *GlobalName=0);
260 
261   /// GetAddrOfConstantCString - Returns a pointer to a character array
262   /// containing the literal and a terminating '\0' character. The result has
263   /// pointer to array type.
264   ///
265   /// \param GlobalName If provided, the name to use for the global (if one is
266   /// created).
267   llvm::Constant *GetAddrOfConstantCString(const std::string &str,
268                                            const char *GlobalName=0);
269 
270   /// GetAddrOfCXXConstructor - Return the address of the constructor of the
271   /// given type.
272   llvm::Function *GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
273                                           CXXCtorType Type);
274 
275   /// GetAddrOfCXXDestructor - Return the address of the constructor of the
276   /// given type.
277   llvm::Function *GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
278                                          CXXDtorType Type);
279 
280   /// getBuiltinLibFunction - Given a builtin id for a function like
281   /// "__builtin_fabsf", return a Function* for "fabsf".
282   llvm::Value *getBuiltinLibFunction(unsigned BuiltinID);
283 
284   llvm::Function *getMemCpyFn();
285   llvm::Function *getMemMoveFn();
286   llvm::Function *getMemSetFn();
287   llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0,
288                                unsigned NumTys = 0);
289 
290   /// EmitTopLevelDecl - Emit code for a single top level declaration.
291   void EmitTopLevelDecl(Decl *D);
292 
293   /// AddUsedGlobal - Add a global which should be forced to be
294   /// present in the object file; these are emitted to the llvm.used
295   /// metadata global.
296   void AddUsedGlobal(llvm::GlobalValue *GV);
297 
298   void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
299 
300   /// CreateRuntimeFunction - Create a new runtime function with the specified
301   /// type and name.
302   llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty,
303                                         const char *Name);
304   /// CreateRuntimeVariable - Create a new runtime global variable with the
305   /// specified type and name.
306   llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty,
307                                         const char *Name);
308 
309   void UpdateCompletedType(const TagDecl *TD) {
310     // Make sure that this type is translated.
311     Types.UpdateCompletedType(TD);
312   }
313 
314   /// EmitConstantExpr - Try to emit the given expression as a
315   /// constant; returns 0 if the expression cannot be emitted as a
316   /// constant.
317   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
318                                    CodeGenFunction *CGF = 0);
319 
320   /// EmitNullConstant - Return the result of value-initializing the given
321   /// type, i.e. a null expression of the given type.  This is usually,
322   /// but not always, an LLVM null constant.
323   llvm::Constant *EmitNullConstant(QualType T);
324 
325   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
326                                    const AnnotateAttr *AA, unsigned LineNo);
327 
328   /// ErrorUnsupported - Print out an error that codegen doesn't support the
329   /// specified stmt yet.
330   /// \param OmitOnError - If true, then this error should only be emitted if no
331   /// other errors have been reported.
332   void ErrorUnsupported(const Stmt *S, const char *Type,
333                         bool OmitOnError=false);
334 
335   /// ErrorUnsupported - Print out an error that codegen doesn't support the
336   /// specified decl yet.
337   /// \param OmitOnError - If true, then this error should only be emitted if no
338   /// other errors have been reported.
339   void ErrorUnsupported(const Decl *D, const char *Type,
340                         bool OmitOnError=false);
341 
342   /// SetInternalFunctionAttributes - Set the attributes on the LLVM
343   /// function for the given decl and function info. This applies
344   /// attributes necessary for handling the ABI as well as user
345   /// specified attributes like section.
346   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
347                                      const CGFunctionInfo &FI);
348 
349   /// SetLLVMFunctionAttributes - Set the LLVM function attributes
350   /// (sext, zext, etc).
351   void SetLLVMFunctionAttributes(const Decl *D,
352                                  const CGFunctionInfo &Info,
353                                  llvm::Function *F);
354 
355   /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
356   /// which only apply to a function definintion.
357   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
358 
359   /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used
360   /// as a return type.
361   bool ReturnTypeUsesSret(const CGFunctionInfo &FI);
362 
363   void ConstructAttributeList(const CGFunctionInfo &Info,
364                               const Decl *TargetDecl,
365                               AttributeListType &PAL);
366 
367   const char *getMangledName(const GlobalDecl &D);
368 
369   const char *getMangledName(const NamedDecl *ND);
370   const char *getMangledCXXCtorName(const CXXConstructorDecl *D,
371                                     CXXCtorType Type);
372   const char *getMangledCXXDtorName(const CXXDestructorDecl *D,
373                                     CXXDtorType Type);
374 
375   void EmitTentativeDefinition(const VarDecl *D);
376 
377   enum GVALinkage {
378     GVA_Internal,
379     GVA_C99Inline,
380     GVA_CXXInline,
381     GVA_StrongExternal,
382     GVA_TemplateInstantiation
383   };
384 
385 private:
386   /// UniqueMangledName - Unique a name by (if necessary) inserting it into the
387   /// MangledNames string map.
388   const char *UniqueMangledName(const char *NameStart, const char *NameEnd);
389 
390   llvm::Constant *GetOrCreateLLVMFunction(const char *MangledName,
391                                           const llvm::Type *Ty,
392                                           GlobalDecl D);
393   llvm::Constant *GetOrCreateLLVMGlobal(const char *MangledName,
394                                         const llvm::PointerType *PTy,
395                                         const VarDecl *D);
396 
397   /// SetCommonAttributes - Set attributes which are common to any
398   /// form of a global definition (alias, Objective-C method,
399   /// function, global variable).
400   ///
401   /// NOTE: This should only be called for definitions.
402   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
403 
404   /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
405   void SetFunctionDefinitionAttributes(const FunctionDecl *D,
406                                        llvm::GlobalValue *GV);
407 
408   /// SetFunctionAttributes - Set function attributes for a function
409   /// declaration.
410   void SetFunctionAttributes(const FunctionDecl *FD,
411                              llvm::Function *F,
412                              bool IsIncompleteFunction);
413 
414   /// EmitGlobal - Emit code for a singal global function or var decl. Forward
415   /// declarations are emitted lazily.
416   void EmitGlobal(GlobalDecl D);
417 
418   void EmitGlobalDefinition(GlobalDecl D);
419 
420   void EmitGlobalFunctionDefinition(GlobalDecl GD);
421   void EmitGlobalVarDefinition(const VarDecl *D);
422   void EmitAliasDefinition(const ValueDecl *D);
423   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
424 
425   // C++ related functions.
426 
427   void EmitNamespace(const NamespaceDecl *D);
428   void EmitLinkageSpec(const LinkageSpecDecl *D);
429 
430   /// EmitCXXConstructors - Emit constructors (base, complete) from a
431   /// C++ constructor Decl.
432   void EmitCXXConstructors(const CXXConstructorDecl *D);
433 
434   /// EmitCXXConstructor - Emit a single constructor with the given type from
435   /// a C++ constructor Decl.
436   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
437 
438   /// EmitCXXDestructors - Emit destructors (base, complete) from a
439   /// C++ destructor Decl.
440   void EmitCXXDestructors(const CXXDestructorDecl *D);
441 
442   /// EmitCXXDestructor - Emit a single destructor with the given type from
443   /// a C++ destructor Decl.
444   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
445 
446   // FIXME: Hardcoding priority here is gross.
447   void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
448   void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
449 
450   /// EmitCtorList - Generates a global array of functions and priorities using
451   /// the given list and name. This array will have appending linkage and is
452   /// suitable for use as a LLVM constructor or destructor array.
453   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
454 
455   void EmitAnnotations(void);
456 
457   /// EmitDeferred - Emit any needed decls for which code generation
458   /// was deferred.
459   void EmitDeferred(void);
460 
461   /// EmitLLVMUsed - Emit the llvm.used metadata used to force
462   /// references to global which may otherwise be optimized out.
463   void EmitLLVMUsed(void);
464 
465   /// MayDeferGeneration - Determine if the given decl can be emitted
466   /// lazily; this is only relevant for definitions. The given decl
467   /// must be either a function or var decl.
468   bool MayDeferGeneration(const ValueDecl *D);
469 };
470 }  // end namespace CodeGen
471 }  // end namespace clang
472 
473 #endif
474