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 "clang/AST/DeclObjC.h"
21 #include "CGBlocks.h"
22 #include "CGCall.h"
23 #include "CGCXX.h"
24 #include "CGVTables.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/ADT/SmallPtrSet.h"
33 #include "llvm/Support/ValueHandle.h"
34 
35 namespace llvm {
36   class Module;
37   class Constant;
38   class Function;
39   class GlobalValue;
40   class TargetData;
41   class FunctionType;
42   class LLVMContext;
43 }
44 
45 namespace 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 
70 namespace CodeGen {
71 
72   class CodeGenFunction;
73   class CGDebugInfo;
74   class CGObjCRuntime;
75   class MangleBuffer;
76 
77 /// CodeGenModule - This class organizes the cross-function state that is used
78 /// while generating LLVM code.
79 class 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   /// VTables - Holds information about C++ vtables.
96   CodeGenVTables VTables;
97   friend class CodeGenVTables;
98 
99   CGObjCRuntime* Runtime;
100   CGDebugInfo* DebugInfo;
101 
102   // WeakRefReferences - A set of references that have only been seen via
103   // a weakref so far. This is used to remove the weak of the reference if we ever
104   // see a direct reference or a definition.
105   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
106 
107   /// DeferredDecls - This contains all the decls which have definitions but
108   /// which are deferred for emission and therefore should only be output if
109   /// they are actually used.  If a decl is in this, then it is known to have
110   /// not been referenced yet.
111   llvm::StringMap<GlobalDecl> DeferredDecls;
112 
113   /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
114   /// that *are* actually referenced.  These get code generated when the module
115   /// is done.
116   std::vector<GlobalDecl> DeferredDeclsToEmit;
117 
118   /// LLVMUsed - List of global values which are required to be
119   /// present in the object file; bitcast to i8*. This is used for
120   /// forcing visibility of symbols which may otherwise be optimized
121   /// out.
122   std::vector<llvm::WeakVH> LLVMUsed;
123 
124   /// GlobalCtors - Store the list of global constructors and their respective
125   /// priorities to be emitted when the translation unit is complete.
126   CtorList GlobalCtors;
127 
128   /// GlobalDtors - Store the list of global destructors and their respective
129   /// priorities to be emitted when the translation unit is complete.
130   CtorList GlobalDtors;
131 
132   std::vector<llvm::Constant*> Annotations;
133 
134   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
135   llvm::StringMap<llvm::Constant*> ConstantStringMap;
136   llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap;
137 
138   /// CXXGlobalInits - Global variables with initializers that need to run
139   /// before main.
140   std::vector<llvm::Constant*> CXXGlobalInits;
141 
142   /// CXXGlobalDtors - Global destructor functions and arguments that need to
143   /// run on termination.
144   std::vector<std::pair<llvm::Constant*,llvm::Constant*> > CXXGlobalDtors;
145 
146   /// CFConstantStringClassRef - Cached reference to the class for constant
147   /// strings. This value has type int * but is actually an Obj-C class pointer.
148   llvm::Constant *CFConstantStringClassRef;
149 
150   /// NSConstantStringClassRef - Cached reference to the class for constant
151   /// strings. This value has type int * but is actually an Obj-C class pointer.
152   llvm::Constant *NSConstantStringClassRef;
153 
154   /// Lazily create the Objective-C runtime
155   void createObjCRuntime();
156 
157   llvm::LLVMContext &VMContext;
158 public:
159   CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
160                 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
161 
162   ~CodeGenModule();
163 
164   /// Release - Finalize LLVM code generation.
165   void Release();
166 
167   /// getObjCRuntime() - Return a reference to the configured
168   /// Objective-C runtime.
169   CGObjCRuntime &getObjCRuntime() {
170     if (!Runtime) createObjCRuntime();
171     return *Runtime;
172   }
173 
174   /// hasObjCRuntime() - Return true iff an Objective-C runtime has
175   /// been configured.
176   bool hasObjCRuntime() { return !!Runtime; }
177 
178   llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) {
179     return StaticLocalDeclMap[VD];
180   }
181   void setStaticLocalDeclAddress(const VarDecl *D,
182                              llvm::GlobalVariable *GV) {
183     StaticLocalDeclMap[D] = GV;
184   }
185 
186   CGDebugInfo *getDebugInfo() { return DebugInfo; }
187   ASTContext &getContext() const { return Context; }
188   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
189   const LangOptions &getLangOptions() const { return Features; }
190   llvm::Module &getModule() const { return TheModule; }
191   CodeGenTypes &getTypes() { return Types; }
192   MangleContext &getMangleContext() { return MangleCtx; }
193   CodeGenVTables &getVTables() { return VTables; }
194   Diagnostic &getDiags() const { return Diags; }
195   const llvm::TargetData &getTargetData() const { return TheTargetData; }
196   llvm::LLVMContext &getLLVMContext() { return VMContext; }
197   const TargetCodeGenInfo &getTargetCodeGenInfo() const;
198   bool isTargetDarwin() const;
199 
200   /// getDeclVisibilityMode - Compute the visibility of the decl \arg D.
201   LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const;
202 
203   /// setGlobalVisibility - Set the visibility for the given LLVM
204   /// GlobalValue.
205   void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const;
206 
207   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
208     if (isa<CXXConstructorDecl>(GD.getDecl()))
209       return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
210                                      GD.getCtorType());
211     else if (isa<CXXDestructorDecl>(GD.getDecl()))
212       return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
213                                      GD.getDtorType());
214     else if (isa<FunctionDecl>(GD.getDecl()))
215       return GetAddrOfFunction(GD);
216     else
217       return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
218   }
219 
220   /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
221   /// given global variable.  If Ty is non-null and if the global doesn't exist,
222   /// then it will be greated with the specified type instead of whatever the
223   /// normal requested type would be.
224   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
225                                      const llvm::Type *Ty = 0);
226 
227   /// GetAddrOfFunction - Return the address of the given function.  If Ty is
228   /// non-null, then this function will use the specified type if it has to
229   /// create it.
230   llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
231                                     const llvm::Type *Ty = 0);
232 
233   /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
234   /// for the given type.
235   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
236 
237   /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
238   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
239 
240   /// GetWeakRefReference - Get a reference to the target of VD.
241   llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
242 
243   /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
244   /// a class. Returns null if the offset is 0.
245   llvm::Constant *
246   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
247                                const CXXBaseSpecifierArray &BasePath);
248 
249   /// GetStringForStringLiteral - Return the appropriate bytes for a string
250   /// literal, properly padded to match the literal type. If only the address of
251   /// a constant is needed consider using GetAddrOfConstantStringLiteral.
252   std::string GetStringForStringLiteral(const StringLiteral *E);
253 
254   /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
255   /// for the given string.
256   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
257 
258   /// GetAddrOfConstantNSString - Return a pointer to a constant NSString object
259   /// for the given string.
260   llvm::Constant *GetAddrOfConstantNSString(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::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
295                                              CXXCtorType Type);
296 
297   /// GetAddrOfCXXDestructor - Return the address of the constructor of the
298   /// given type.
299   llvm::GlobalValue *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(const llvm::Type *DestType,
308                               const llvm::Type *SrcType,
309                               const llvm::Type *SizeType);
310 
311   llvm::Function *getMemMoveFn(const llvm::Type *DestType,
312                                const llvm::Type *SrcType,
313                                const llvm::Type *SizeType);
314 
315   llvm::Function *getMemSetFn(const llvm::Type *DestType,
316                               const llvm::Type *SizeType);
317 
318   llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0,
319                                unsigned NumTys = 0);
320 
321   /// EmitTopLevelDecl - Emit code for a single top level declaration.
322   void EmitTopLevelDecl(Decl *D);
323 
324   /// AddUsedGlobal - Add a global which should be forced to be
325   /// present in the object file; these are emitted to the llvm.used
326   /// metadata global.
327   void AddUsedGlobal(llvm::GlobalValue *GV);
328 
329   void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
330 
331   /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
332   /// destructor function.
333   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object);
334 
335   /// CreateRuntimeFunction - Create a new runtime function with the specified
336   /// type and name.
337   llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty,
338                                         llvm::StringRef Name);
339   /// CreateRuntimeVariable - Create a new runtime global variable with the
340   /// specified type and name.
341   llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty,
342                                         llvm::StringRef Name);
343 
344   void UpdateCompletedType(const TagDecl *TD) {
345     // Make sure that this type is translated.
346     Types.UpdateCompletedType(TD);
347   }
348 
349   /// EmitConstantExpr - Try to emit the given expression as a
350   /// constant; returns 0 if the expression cannot be emitted as a
351   /// constant.
352   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
353                                    CodeGenFunction *CGF = 0);
354 
355   /// EmitNullConstant - Return the result of value-initializing the given
356   /// type, i.e. a null expression of the given type.  This is usually,
357   /// but not always, an LLVM null constant.
358   llvm::Constant *EmitNullConstant(QualType T);
359 
360   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
361                                    const AnnotateAttr *AA, unsigned LineNo);
362 
363   llvm::Constant *EmitPointerToDataMember(const FieldDecl *FD);
364 
365   /// ErrorUnsupported - Print out an error that codegen doesn't support the
366   /// specified stmt yet.
367   /// \param OmitOnError - If true, then this error should only be emitted if no
368   /// other errors have been reported.
369   void ErrorUnsupported(const Stmt *S, const char *Type,
370                         bool OmitOnError=false);
371 
372   /// ErrorUnsupported - Print out an error that codegen doesn't support the
373   /// specified decl yet.
374   /// \param OmitOnError - If true, then this error should only be emitted if no
375   /// other errors have been reported.
376   void ErrorUnsupported(const Decl *D, const char *Type,
377                         bool OmitOnError=false);
378 
379   /// SetInternalFunctionAttributes - Set the attributes on the LLVM
380   /// function for the given decl and function info. This applies
381   /// attributes necessary for handling the ABI as well as user
382   /// specified attributes like section.
383   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
384                                      const CGFunctionInfo &FI);
385 
386   /// SetLLVMFunctionAttributes - Set the LLVM function attributes
387   /// (sext, zext, etc).
388   void SetLLVMFunctionAttributes(const Decl *D,
389                                  const CGFunctionInfo &Info,
390                                  llvm::Function *F);
391 
392   /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
393   /// which only apply to a function definintion.
394   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
395 
396   /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used
397   /// as a return type.
398   bool ReturnTypeUsesSret(const CGFunctionInfo &FI);
399 
400   /// ConstructAttributeList - Get the LLVM attributes and calling convention to
401   /// use for a particular function type.
402   ///
403   /// \param Info - The function type information.
404   /// \param TargetDecl - The decl these attributes are being constructed
405   /// for. If supplied the attributes applied to this decl may contribute to the
406   /// function attributes and calling convention.
407   /// \param PAL [out] - On return, the attribute list to use.
408   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
409   void ConstructAttributeList(const CGFunctionInfo &Info,
410                               const Decl *TargetDecl,
411                               AttributeListType &PAL,
412                               unsigned &CallingConv);
413 
414   void getMangledName(MangleBuffer &Buffer, GlobalDecl D);
415   void getMangledName(MangleBuffer &Buffer, const NamedDecl *ND);
416   void getMangledCXXCtorName(MangleBuffer &Buffer,
417                              const CXXConstructorDecl *D,
418                              CXXCtorType Type);
419   void getMangledCXXDtorName(MangleBuffer &Buffer,
420                              const CXXDestructorDecl *D,
421                              CXXDtorType Type);
422 
423   void EmitTentativeDefinition(const VarDecl *D);
424 
425   enum GVALinkage {
426     GVA_Internal,
427     GVA_C99Inline,
428     GVA_CXXInline,
429     GVA_StrongExternal,
430     GVA_TemplateInstantiation,
431     GVA_ExplicitTemplateInstantiation
432   };
433 
434   llvm::GlobalVariable::LinkageTypes
435   getFunctionLinkage(const FunctionDecl *FD);
436 
437   /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
438   /// and type information of the given class.
439   static llvm::GlobalVariable::LinkageTypes
440   getVTableLinkage(const CXXRecordDecl *RD);
441 
442   /// GetTargetTypeStoreSize - Return the store size, in character units, of
443   /// the given LLVM type.
444   CharUnits GetTargetTypeStoreSize(const llvm::Type *Ty) const;
445 
446   std::vector<const CXXRecordDecl*> DeferredVTables;
447 
448 private:
449   llvm::GlobalValue *GetGlobalValue(llvm::StringRef Ref);
450 
451   llvm::Constant *GetOrCreateLLVMFunction(llvm::StringRef MangledName,
452                                           const llvm::Type *Ty,
453                                           GlobalDecl D);
454   llvm::Constant *GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
455                                         const llvm::PointerType *PTy,
456                                         const VarDecl *D);
457 
458   /// SetCommonAttributes - Set attributes which are common to any
459   /// form of a global definition (alias, Objective-C method,
460   /// function, global variable).
461   ///
462   /// NOTE: This should only be called for definitions.
463   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
464 
465   /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
466   void SetFunctionDefinitionAttributes(const FunctionDecl *D,
467                                        llvm::GlobalValue *GV);
468 
469   /// SetFunctionAttributes - Set function attributes for a function
470   /// declaration.
471   void SetFunctionAttributes(GlobalDecl GD,
472                              llvm::Function *F,
473                              bool IsIncompleteFunction);
474 
475   /// EmitGlobal - Emit code for a singal global function or var decl. Forward
476   /// declarations are emitted lazily.
477   void EmitGlobal(GlobalDecl D);
478 
479   void EmitGlobalDefinition(GlobalDecl D);
480 
481   void EmitGlobalFunctionDefinition(GlobalDecl GD);
482   void EmitGlobalVarDefinition(const VarDecl *D);
483   void EmitAliasDefinition(GlobalDecl GD);
484   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
485   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
486 
487   // C++ related functions.
488 
489   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
490   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
491 
492   void EmitNamespace(const NamespaceDecl *D);
493   void EmitLinkageSpec(const LinkageSpecDecl *D);
494 
495   /// EmitCXXConstructors - Emit constructors (base, complete) from a
496   /// C++ constructor Decl.
497   void EmitCXXConstructors(const CXXConstructorDecl *D);
498 
499   /// EmitCXXConstructor - Emit a single constructor with the given type from
500   /// a C++ constructor Decl.
501   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
502 
503   /// EmitCXXDestructors - Emit destructors (base, complete) from a
504   /// C++ destructor Decl.
505   void EmitCXXDestructors(const CXXDestructorDecl *D);
506 
507   /// EmitCXXDestructor - Emit a single destructor with the given type from
508   /// a C++ destructor Decl.
509   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
510 
511   /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
512   void EmitCXXGlobalInitFunc();
513 
514   /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
515   void EmitCXXGlobalDtorFunc();
516 
517   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D);
518 
519   // FIXME: Hardcoding priority here is gross.
520   void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
521   void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
522 
523   /// EmitCtorList - Generates a global array of functions and priorities using
524   /// the given list and name. This array will have appending linkage and is
525   /// suitable for use as a LLVM constructor or destructor array.
526   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
527 
528   void EmitAnnotations(void);
529 
530   /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
531   /// given type.
532   void EmitFundamentalRTTIDescriptor(QualType Type);
533 
534   /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
535   /// builtin types.
536   void EmitFundamentalRTTIDescriptors();
537 
538   /// EmitDeferred - Emit any needed decls for which code generation
539   /// was deferred.
540   void EmitDeferred(void);
541 
542   /// EmitLLVMUsed - Emit the llvm.used metadata used to force
543   /// references to global which may otherwise be optimized out.
544   void EmitLLVMUsed(void);
545 
546   /// MayDeferGeneration - Determine if the given decl can be emitted
547   /// lazily; this is only relevant for definitions. The given decl
548   /// must be either a function or var decl.
549   bool MayDeferGeneration(const ValueDecl *D);
550 };
551 }  // end namespace CodeGen
552 }  // end namespace clang
553 
554 #endif
555