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 "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 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 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 /// 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; 169 public: 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 /// GetCXXBaseClassOffset - Returns the offset from a derived class to its 243 /// base class. Returns null if the offset is 0. 244 llvm::Constant *GetCXXBaseClassOffset(const CXXRecordDecl *ClassDecl, 245 const CXXRecordDecl *BaseClassDecl); 246 247 /// ComputeThunkAdjustment - Returns the two parts required to compute the 248 /// offset for an object. 249 ThunkAdjustment ComputeThunkAdjustment(const CXXRecordDecl *ClassDecl, 250 const CXXRecordDecl *BaseClassDecl); 251 252 /// GetStringForStringLiteral - Return the appropriate bytes for a string 253 /// literal, properly padded to match the literal type. If only the address of 254 /// a constant is needed consider using GetAddrOfConstantStringLiteral. 255 std::string GetStringForStringLiteral(const StringLiteral *E); 256 257 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object 258 /// for the given string. 259 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 260 261 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array 262 /// for the given string literal. 263 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 264 265 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 266 /// array for the given ObjCEncodeExpr node. 267 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 268 269 /// GetAddrOfConstantString - Returns a pointer to a character array 270 /// containing the literal. This contents are exactly that of the given 271 /// string, i.e. it will not be null terminated automatically; see 272 /// GetAddrOfConstantCString. Note that whether the result is actually a 273 /// pointer to an LLVM constant depends on Feature.WriteableStrings. 274 /// 275 /// The result has pointer to array type. 276 /// 277 /// \param GlobalName If provided, the name to use for the global 278 /// (if one is created). 279 llvm::Constant *GetAddrOfConstantString(const std::string& str, 280 const char *GlobalName=0); 281 282 /// GetAddrOfConstantCString - Returns a pointer to a character array 283 /// containing the literal and a terminating '\0' character. The result has 284 /// pointer to array type. 285 /// 286 /// \param GlobalName If provided, the name to use for the global (if one is 287 /// created). 288 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 289 const char *GlobalName=0); 290 291 /// GetAddrOfCXXConstructor - Return the address of the constructor of the 292 /// given type. 293 llvm::Function *GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 294 CXXCtorType Type); 295 296 /// GetAddrOfCXXDestructor - Return the address of the constructor of the 297 /// given type. 298 llvm::Function *GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 299 CXXDtorType Type); 300 301 /// getBuiltinLibFunction - Given a builtin id for a function like 302 /// "__builtin_fabsf", return a Function* for "fabsf". 303 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 304 unsigned BuiltinID); 305 306 llvm::Function *getMemCpyFn(); 307 llvm::Function *getMemMoveFn(); 308 llvm::Function *getMemSetFn(); 309 llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0, 310 unsigned NumTys = 0); 311 312 /// EmitTopLevelDecl - Emit code for a single top level declaration. 313 void EmitTopLevelDecl(Decl *D); 314 315 /// AddUsedGlobal - Add a global which should be forced to be 316 /// present in the object file; these are emitted to the llvm.used 317 /// metadata global. 318 void AddUsedGlobal(llvm::GlobalValue *GV); 319 320 void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); } 321 322 /// CreateRuntimeFunction - Create a new runtime function with the specified 323 /// type and name. 324 llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty, 325 const char *Name); 326 /// CreateRuntimeVariable - Create a new runtime global variable with the 327 /// specified type and name. 328 llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty, 329 const char *Name); 330 331 void UpdateCompletedType(const TagDecl *TD) { 332 // Make sure that this type is translated. 333 Types.UpdateCompletedType(TD); 334 } 335 336 /// EmitConstantExpr - Try to emit the given expression as a 337 /// constant; returns 0 if the expression cannot be emitted as a 338 /// constant. 339 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 340 CodeGenFunction *CGF = 0); 341 342 /// EmitNullConstant - Return the result of value-initializing the given 343 /// type, i.e. a null expression of the given type. This is usually, 344 /// but not always, an LLVM null constant. 345 llvm::Constant *EmitNullConstant(QualType T); 346 347 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 348 const AnnotateAttr *AA, unsigned LineNo); 349 350 /// ErrorUnsupported - Print out an error that codegen doesn't support the 351 /// specified stmt yet. 352 /// \param OmitOnError - If true, then this error should only be emitted if no 353 /// other errors have been reported. 354 void ErrorUnsupported(const Stmt *S, const char *Type, 355 bool OmitOnError=false); 356 357 /// ErrorUnsupported - Print out an error that codegen doesn't support the 358 /// specified decl yet. 359 /// \param OmitOnError - If true, then this error should only be emitted if no 360 /// other errors have been reported. 361 void ErrorUnsupported(const Decl *D, const char *Type, 362 bool OmitOnError=false); 363 364 /// SetInternalFunctionAttributes - Set the attributes on the LLVM 365 /// function for the given decl and function info. This applies 366 /// attributes necessary for handling the ABI as well as user 367 /// specified attributes like section. 368 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 369 const CGFunctionInfo &FI); 370 371 /// SetLLVMFunctionAttributes - Set the LLVM function attributes 372 /// (sext, zext, etc). 373 void SetLLVMFunctionAttributes(const Decl *D, 374 const CGFunctionInfo &Info, 375 llvm::Function *F); 376 377 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes 378 /// which only apply to a function definintion. 379 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 380 381 /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used 382 /// as a return type. 383 bool ReturnTypeUsesSret(const CGFunctionInfo &FI); 384 385 /// ConstructAttributeList - Get the LLVM attributes and calling convention to 386 /// use for a particular function type. 387 /// 388 /// \param Info - The function type information. 389 /// \param TargetDecl - The decl these attributes are being constructed 390 /// for. If supplied the attributes applied to this decl may contribute to the 391 /// function attributes and calling convention. 392 /// \param PAL [out] - On return, the attribute list to use. 393 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 394 void ConstructAttributeList(const CGFunctionInfo &Info, 395 const Decl *TargetDecl, 396 AttributeListType &PAL, 397 unsigned &CallingConv); 398 399 const char *getMangledName(const GlobalDecl &D); 400 401 const char *getMangledName(const NamedDecl *ND); 402 const char *getMangledCXXCtorName(const CXXConstructorDecl *D, 403 CXXCtorType Type); 404 const char *getMangledCXXDtorName(const CXXDestructorDecl *D, 405 CXXDtorType Type); 406 407 void EmitTentativeDefinition(const VarDecl *D); 408 409 enum GVALinkage { 410 GVA_Internal, 411 GVA_C99Inline, 412 GVA_CXXInline, 413 GVA_StrongExternal, 414 GVA_TemplateInstantiation 415 }; 416 417 /// getVtableLinkage - Return the appropriate linkage for the vtable, VTT, 418 /// and type information of the given class. 419 static llvm::GlobalVariable::LinkageTypes 420 getVtableLinkage(const CXXRecordDecl *RD); 421 422 /// GetTargetTypeStoreSize - Return the store size, in character units, of 423 /// the given LLVM type. 424 CharUnits GetTargetTypeStoreSize(const llvm::Type *Ty) const; 425 426 private: 427 /// UniqueMangledName - Unique a name by (if necessary) inserting it into the 428 /// MangledNames string map. 429 const char *UniqueMangledName(const char *NameStart, const char *NameEnd); 430 431 llvm::Constant *GetOrCreateLLVMFunction(const char *MangledName, 432 const llvm::Type *Ty, 433 GlobalDecl D); 434 llvm::Constant *GetOrCreateLLVMGlobal(const char *MangledName, 435 const llvm::PointerType *PTy, 436 const VarDecl *D); 437 438 /// SetCommonAttributes - Set attributes which are common to any 439 /// form of a global definition (alias, Objective-C method, 440 /// function, global variable). 441 /// 442 /// NOTE: This should only be called for definitions. 443 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 444 445 /// SetFunctionDefinitionAttributes - Set attributes for a global definition. 446 void SetFunctionDefinitionAttributes(const FunctionDecl *D, 447 llvm::GlobalValue *GV); 448 449 /// SetFunctionAttributes - Set function attributes for a function 450 /// declaration. 451 void SetFunctionAttributes(const FunctionDecl *FD, 452 llvm::Function *F, 453 bool IsIncompleteFunction); 454 455 /// EmitGlobal - Emit code for a singal global function or var decl. Forward 456 /// declarations are emitted lazily. 457 void EmitGlobal(GlobalDecl D); 458 459 void EmitGlobalDefinition(GlobalDecl D); 460 461 void EmitGlobalFunctionDefinition(GlobalDecl GD); 462 void EmitGlobalVarDefinition(const VarDecl *D); 463 void EmitAliasDefinition(const ValueDecl *D); 464 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 465 466 // C++ related functions. 467 468 void EmitNamespace(const NamespaceDecl *D); 469 void EmitLinkageSpec(const LinkageSpecDecl *D); 470 471 /// EmitCXXConstructors - Emit constructors (base, complete) from a 472 /// C++ constructor Decl. 473 void EmitCXXConstructors(const CXXConstructorDecl *D); 474 475 /// EmitCXXConstructor - Emit a single constructor with the given type from 476 /// a C++ constructor Decl. 477 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 478 479 /// EmitCXXDestructors - Emit destructors (base, complete) from a 480 /// C++ destructor Decl. 481 void EmitCXXDestructors(const CXXDestructorDecl *D); 482 483 /// EmitCXXDestructor - Emit a single destructor with the given type from 484 /// a C++ destructor Decl. 485 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 486 487 /// EmitCXXGlobalInitFunc - Emit a function that initializes C++ globals. 488 void EmitCXXGlobalInitFunc(); 489 490 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D); 491 492 // FIXME: Hardcoding priority here is gross. 493 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); 494 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); 495 496 /// EmitCtorList - Generates a global array of functions and priorities using 497 /// the given list and name. This array will have appending linkage and is 498 /// suitable for use as a LLVM constructor or destructor array. 499 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 500 501 void EmitAnnotations(void); 502 503 /// EmitDeferred - Emit any needed decls for which code generation 504 /// was deferred. 505 void EmitDeferred(void); 506 507 /// EmitLLVMUsed - Emit the llvm.used metadata used to force 508 /// references to global which may otherwise be optimized out. 509 void EmitLLVMUsed(void); 510 511 /// MayDeferGeneration - Determine if the given decl can be emitted 512 /// lazily; this is only relevant for definitions. The given decl 513 /// must be either a function or var decl. 514 bool MayDeferGeneration(const ValueDecl *D); 515 }; 516 } // end namespace CodeGen 517 } // end namespace clang 518 519 #endif 520