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/ABI.h" 18 #include "clang/Basic/LangOptions.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/GlobalDecl.h" 23 #include "clang/AST/Mangle.h" 24 #include "CGVTables.h" 25 #include "CodeGenTypes.h" 26 #include "llvm/Module.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/ADT/StringMap.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/Support/ValueHandle.h" 31 32 namespace llvm { 33 class Module; 34 class Constant; 35 class ConstantInt; 36 class Function; 37 class GlobalValue; 38 class TargetData; 39 class FunctionType; 40 class LLVMContext; 41 } 42 43 namespace clang { 44 class TargetCodeGenInfo; 45 class ASTContext; 46 class FunctionDecl; 47 class IdentifierInfo; 48 class ObjCMethodDecl; 49 class ObjCImplementationDecl; 50 class ObjCCategoryImplDecl; 51 class ObjCProtocolDecl; 52 class ObjCEncodeExpr; 53 class BlockExpr; 54 class CharUnits; 55 class Decl; 56 class Expr; 57 class Stmt; 58 class StringLiteral; 59 class NamedDecl; 60 class ValueDecl; 61 class VarDecl; 62 class LangOptions; 63 class CodeGenOptions; 64 class DiagnosticsEngine; 65 class AnnotateAttr; 66 class CXXDestructorDecl; 67 class MangleBuffer; 68 69 namespace CodeGen { 70 71 class CallArgList; 72 class CodeGenFunction; 73 class CodeGenTBAA; 74 class CGCXXABI; 75 class CGDebugInfo; 76 class CGObjCRuntime; 77 class CGOpenCLRuntime; 78 class CGCUDARuntime; 79 class BlockFieldFlags; 80 class FunctionArgList; 81 82 struct OrderGlobalInits { 83 unsigned int priority; 84 unsigned int lex_order; 85 OrderGlobalInits(unsigned int p, unsigned int l) 86 : priority(p), lex_order(l) {} 87 88 bool operator==(const OrderGlobalInits &RHS) const { 89 return priority == RHS.priority && 90 lex_order == RHS.lex_order; 91 } 92 93 bool operator<(const OrderGlobalInits &RHS) const { 94 if (priority < RHS.priority) 95 return true; 96 97 return priority == RHS.priority && lex_order < RHS.lex_order; 98 } 99 }; 100 101 struct CodeGenTypeCache { 102 /// void 103 llvm::Type *VoidTy; 104 105 /// i8, i32, and i64 106 llvm::IntegerType *Int8Ty, *Int32Ty, *Int64Ty; 107 108 /// int 109 llvm::IntegerType *IntTy; 110 111 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size. 112 union { 113 llvm::IntegerType *IntPtrTy; 114 llvm::IntegerType *SizeTy; 115 llvm::IntegerType *PtrDiffTy; 116 }; 117 118 /// void* in address space 0 119 union { 120 llvm::PointerType *VoidPtrTy; 121 llvm::PointerType *Int8PtrTy; 122 }; 123 124 /// void** in address space 0 125 union { 126 llvm::PointerType *VoidPtrPtrTy; 127 llvm::PointerType *Int8PtrPtrTy; 128 }; 129 130 /// The width of a pointer into the generic address space. 131 unsigned char PointerWidthInBits; 132 133 /// The size and alignment of a pointer into the generic address 134 /// space. 135 union { 136 unsigned char PointerAlignInBytes; 137 unsigned char PointerSizeInBytes; 138 }; 139 }; 140 141 struct RREntrypoints { 142 RREntrypoints() { memset(this, 0, sizeof(*this)); } 143 /// void objc_autoreleasePoolPop(void*); 144 llvm::Constant *objc_autoreleasePoolPop; 145 146 /// void *objc_autoreleasePoolPush(void); 147 llvm::Constant *objc_autoreleasePoolPush; 148 }; 149 150 struct ARCEntrypoints { 151 ARCEntrypoints() { memset(this, 0, sizeof(*this)); } 152 153 /// id objc_autorelease(id); 154 llvm::Constant *objc_autorelease; 155 156 /// id objc_autoreleaseReturnValue(id); 157 llvm::Constant *objc_autoreleaseReturnValue; 158 159 /// void objc_copyWeak(id *dest, id *src); 160 llvm::Constant *objc_copyWeak; 161 162 /// void objc_destroyWeak(id*); 163 llvm::Constant *objc_destroyWeak; 164 165 /// id objc_initWeak(id*, id); 166 llvm::Constant *objc_initWeak; 167 168 /// id objc_loadWeak(id*); 169 llvm::Constant *objc_loadWeak; 170 171 /// id objc_loadWeakRetained(id*); 172 llvm::Constant *objc_loadWeakRetained; 173 174 /// void objc_moveWeak(id *dest, id *src); 175 llvm::Constant *objc_moveWeak; 176 177 /// id objc_retain(id); 178 llvm::Constant *objc_retain; 179 180 /// id objc_retainAutorelease(id); 181 llvm::Constant *objc_retainAutorelease; 182 183 /// id objc_retainAutoreleaseReturnValue(id); 184 llvm::Constant *objc_retainAutoreleaseReturnValue; 185 186 /// id objc_retainAutoreleasedReturnValue(id); 187 llvm::Constant *objc_retainAutoreleasedReturnValue; 188 189 /// id objc_retainBlock(id); 190 llvm::Constant *objc_retainBlock; 191 192 /// void objc_release(id); 193 llvm::Constant *objc_release; 194 195 /// id objc_storeStrong(id*, id); 196 llvm::Constant *objc_storeStrong; 197 198 /// id objc_storeWeak(id*, id); 199 llvm::Constant *objc_storeWeak; 200 201 /// A void(void) inline asm to use to mark that the return value of 202 /// a call will be immediately retain. 203 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 204 }; 205 206 /// CodeGenModule - This class organizes the cross-function state that is used 207 /// while generating LLVM code. 208 class CodeGenModule : public CodeGenTypeCache { 209 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT 210 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT 211 212 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList; 213 214 ASTContext &Context; 215 const LangOptions &Features; 216 const CodeGenOptions &CodeGenOpts; 217 llvm::Module &TheModule; 218 const llvm::TargetData &TheTargetData; 219 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo; 220 DiagnosticsEngine &Diags; 221 CGCXXABI &ABI; 222 CodeGenTypes Types; 223 CodeGenTBAA *TBAA; 224 225 /// VTables - Holds information about C++ vtables. 226 CodeGenVTables VTables; 227 friend class CodeGenVTables; 228 229 CGObjCRuntime* ObjCRuntime; 230 CGOpenCLRuntime* OpenCLRuntime; 231 CGCUDARuntime* CUDARuntime; 232 CGDebugInfo* DebugInfo; 233 ARCEntrypoints *ARCData; 234 RREntrypoints *RRData; 235 236 // WeakRefReferences - A set of references that have only been seen via 237 // a weakref so far. This is used to remove the weak of the reference if we ever 238 // see a direct reference or a definition. 239 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 240 241 /// DeferredDecls - This contains all the decls which have definitions but 242 /// which are deferred for emission and therefore should only be output if 243 /// they are actually used. If a decl is in this, then it is known to have 244 /// not been referenced yet. 245 llvm::StringMap<GlobalDecl> DeferredDecls; 246 247 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen 248 /// that *are* actually referenced. These get code generated when the module 249 /// is done. 250 std::vector<GlobalDecl> DeferredDeclsToEmit; 251 252 /// LLVMUsed - List of global values which are required to be 253 /// present in the object file; bitcast to i8*. This is used for 254 /// forcing visibility of symbols which may otherwise be optimized 255 /// out. 256 std::vector<llvm::WeakVH> LLVMUsed; 257 258 /// GlobalCtors - Store the list of global constructors and their respective 259 /// priorities to be emitted when the translation unit is complete. 260 CtorList GlobalCtors; 261 262 /// GlobalDtors - Store the list of global destructors and their respective 263 /// priorities to be emitted when the translation unit is complete. 264 CtorList GlobalDtors; 265 266 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names. 267 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames; 268 llvm::BumpPtrAllocator MangledNamesAllocator; 269 270 /// Global annotations. 271 std::vector<llvm::Constant*> Annotations; 272 273 /// Map used to get unique annotation strings. 274 llvm::StringMap<llvm::Constant*> AnnotationStrings; 275 276 llvm::StringMap<llvm::Constant*> CFConstantStringMap; 277 llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap; 278 llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap; 279 280 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap; 281 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap; 282 283 /// CXXGlobalInits - Global variables with initializers that need to run 284 /// before main. 285 std::vector<llvm::Constant*> CXXGlobalInits; 286 287 /// When a C++ decl with an initializer is deferred, null is 288 /// appended to CXXGlobalInits, and the index of that null is placed 289 /// here so that the initializer will be performed in the correct 290 /// order. 291 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 292 293 /// - Global variables with initializers whose order of initialization 294 /// is set by init_priority attribute. 295 296 SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8> 297 PrioritizedCXXGlobalInits; 298 299 /// CXXGlobalDtors - Global destructor functions and arguments that need to 300 /// run on termination. 301 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors; 302 303 /// @name Cache for Objective-C runtime types 304 /// @{ 305 306 /// CFConstantStringClassRef - Cached reference to the class for constant 307 /// strings. This value has type int * but is actually an Obj-C class pointer. 308 llvm::Constant *CFConstantStringClassRef; 309 310 /// ConstantStringClassRef - Cached reference to the class for constant 311 /// strings. This value has type int * but is actually an Obj-C class pointer. 312 llvm::Constant *ConstantStringClassRef; 313 314 /// \brief The LLVM type corresponding to NSConstantString. 315 llvm::StructType *NSConstantStringType; 316 317 /// \brief The type used to describe the state of a fast enumeration in 318 /// Objective-C's for..in loop. 319 QualType ObjCFastEnumerationStateType; 320 321 /// @} 322 323 /// Lazily create the Objective-C runtime 324 void createObjCRuntime(); 325 326 void createOpenCLRuntime(); 327 void createCUDARuntime(); 328 329 bool isTriviallyRecursive(const FunctionDecl *F); 330 bool shouldEmitFunction(const FunctionDecl *F); 331 llvm::LLVMContext &VMContext; 332 333 /// @name Cache for Blocks Runtime Globals 334 /// @{ 335 336 llvm::Constant *NSConcreteGlobalBlock; 337 llvm::Constant *NSConcreteStackBlock; 338 339 llvm::Constant *BlockObjectAssign; 340 llvm::Constant *BlockObjectDispose; 341 342 llvm::Type *BlockDescriptorType; 343 llvm::Type *GenericBlockLiteralType; 344 345 struct { 346 int GlobalUniqueCount; 347 } Block; 348 349 /// @} 350 public: 351 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts, 352 llvm::Module &M, const llvm::TargetData &TD, 353 DiagnosticsEngine &Diags); 354 355 ~CodeGenModule(); 356 357 /// Release - Finalize LLVM code generation. 358 void Release(); 359 360 /// getObjCRuntime() - Return a reference to the configured 361 /// Objective-C runtime. 362 CGObjCRuntime &getObjCRuntime() { 363 if (!ObjCRuntime) createObjCRuntime(); 364 return *ObjCRuntime; 365 } 366 367 /// hasObjCRuntime() - Return true iff an Objective-C runtime has 368 /// been configured. 369 bool hasObjCRuntime() { return !!ObjCRuntime; } 370 371 /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime. 372 CGOpenCLRuntime &getOpenCLRuntime() { 373 assert(OpenCLRuntime != 0); 374 return *OpenCLRuntime; 375 } 376 377 /// getCUDARuntime() - Return a reference to the configured CUDA runtime. 378 CGCUDARuntime &getCUDARuntime() { 379 assert(CUDARuntime != 0); 380 return *CUDARuntime; 381 } 382 383 /// getCXXABI() - Return a reference to the configured C++ ABI. 384 CGCXXABI &getCXXABI() { return ABI; } 385 386 ARCEntrypoints &getARCEntrypoints() const { 387 assert(getLangOptions().ObjCAutoRefCount && ARCData != 0); 388 return *ARCData; 389 } 390 391 RREntrypoints &getRREntrypoints() const { 392 assert(RRData != 0); 393 return *RRData; 394 } 395 396 llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) { 397 return StaticLocalDeclMap[VD]; 398 } 399 void setStaticLocalDeclAddress(const VarDecl *D, 400 llvm::GlobalVariable *GV) { 401 StaticLocalDeclMap[D] = GV; 402 } 403 404 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 405 return AtomicSetterHelperFnMap[Ty]; 406 } 407 void setAtomicSetterHelperFnMap(QualType Ty, 408 llvm::Constant *Fn) { 409 AtomicSetterHelperFnMap[Ty] = Fn; 410 } 411 412 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 413 return AtomicGetterHelperFnMap[Ty]; 414 } 415 void setAtomicGetterHelperFnMap(QualType Ty, 416 llvm::Constant *Fn) { 417 AtomicGetterHelperFnMap[Ty] = Fn; 418 } 419 420 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; } 421 422 ASTContext &getContext() const { return Context; } 423 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 424 const LangOptions &getLangOptions() const { return Features; } 425 llvm::Module &getModule() const { return TheModule; } 426 CodeGenTypes &getTypes() { return Types; } 427 CodeGenVTables &getVTables() { return VTables; } 428 VTableContext &getVTableContext() { return VTables.getVTableContext(); } 429 DiagnosticsEngine &getDiags() const { return Diags; } 430 const llvm::TargetData &getTargetData() const { return TheTargetData; } 431 const TargetInfo &getTarget() const { return Context.getTargetInfo(); } 432 llvm::LLVMContext &getLLVMContext() { return VMContext; } 433 const TargetCodeGenInfo &getTargetCodeGenInfo(); 434 bool isTargetDarwin() const; 435 436 bool shouldUseTBAA() const { return TBAA != 0; } 437 438 llvm::MDNode *getTBAAInfo(QualType QTy); 439 440 static void DecorateInstruction(llvm::Instruction *Inst, 441 llvm::MDNode *TBAAInfo); 442 443 /// getSize - Emit the given number of characters as a value of type size_t. 444 llvm::ConstantInt *getSize(CharUnits numChars); 445 446 /// setGlobalVisibility - Set the visibility for the given LLVM 447 /// GlobalValue. 448 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 449 450 /// TypeVisibilityKind - The kind of global variable that is passed to 451 /// setTypeVisibility 452 enum TypeVisibilityKind { 453 TVK_ForVTT, 454 TVK_ForVTable, 455 TVK_ForConstructionVTable, 456 TVK_ForRTTI, 457 TVK_ForRTTIName 458 }; 459 460 /// setTypeVisibility - Set the visibility for the given global 461 /// value which holds information about a type. 462 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D, 463 TypeVisibilityKind TVK) const; 464 465 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 466 switch (V) { 467 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 468 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 469 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 470 } 471 llvm_unreachable("unknown visibility!"); 472 return llvm::GlobalValue::DefaultVisibility; 473 } 474 475 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) { 476 if (isa<CXXConstructorDecl>(GD.getDecl())) 477 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()), 478 GD.getCtorType()); 479 else if (isa<CXXDestructorDecl>(GD.getDecl())) 480 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()), 481 GD.getDtorType()); 482 else if (isa<FunctionDecl>(GD.getDecl())) 483 return GetAddrOfFunction(GD); 484 else 485 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 486 } 487 488 /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given 489 /// type. If a variable with a different type already exists then a new 490 /// variable with the right type will be created and all uses of the old 491 /// variable will be replaced with a bitcast to the new variable. 492 llvm::GlobalVariable * 493 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 494 llvm::GlobalValue::LinkageTypes Linkage); 495 496 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 497 /// given global variable. If Ty is non-null and if the global doesn't exist, 498 /// then it will be greated with the specified type instead of whatever the 499 /// normal requested type would be. 500 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 501 llvm::Type *Ty = 0); 502 503 504 /// GetAddrOfFunction - Return the address of the given function. If Ty is 505 /// non-null, then this function will use the specified type if it has to 506 /// create it. 507 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, 508 llvm::Type *Ty = 0, 509 bool ForVTable = false); 510 511 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor 512 /// for the given type. 513 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 514 515 /// GetAddrOfThunk - Get the address of the thunk for the given global decl. 516 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk); 517 518 /// GetWeakRefReference - Get a reference to the target of VD. 519 llvm::Constant *GetWeakRefReference(const ValueDecl *VD); 520 521 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to 522 /// a class. Returns null if the offset is 0. 523 llvm::Constant * 524 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 525 CastExpr::path_const_iterator PathBegin, 526 CastExpr::path_const_iterator PathEnd); 527 528 /// A pair of helper functions for a __block variable. 529 class ByrefHelpers : public llvm::FoldingSetNode { 530 public: 531 llvm::Constant *CopyHelper; 532 llvm::Constant *DisposeHelper; 533 534 /// The alignment of the field. This is important because 535 /// different offsets to the field within the byref struct need to 536 /// have different helper functions. 537 CharUnits Alignment; 538 539 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {} 540 virtual ~ByrefHelpers(); 541 542 void Profile(llvm::FoldingSetNodeID &id) const { 543 id.AddInteger(Alignment.getQuantity()); 544 profileImpl(id); 545 } 546 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 547 548 virtual bool needsCopy() const { return true; } 549 virtual void emitCopy(CodeGenFunction &CGF, 550 llvm::Value *dest, llvm::Value *src) = 0; 551 552 virtual bool needsDispose() const { return true; } 553 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0; 554 }; 555 556 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache; 557 558 /// getUniqueBlockCount - Fetches the global unique block count. 559 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 560 561 /// getBlockDescriptorType - Fetches the type of a generic block 562 /// descriptor. 563 llvm::Type *getBlockDescriptorType(); 564 565 /// getGenericBlockLiteralType - The type of a generic block literal. 566 llvm::Type *getGenericBlockLiteralType(); 567 568 /// GetAddrOfGlobalBlock - Gets the address of a block which 569 /// requires no captures. 570 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *); 571 572 /// GetStringForStringLiteral - Return the appropriate bytes for a string 573 /// literal, properly padded to match the literal type. If only the address of 574 /// a constant is needed consider using GetAddrOfConstantStringLiteral. 575 std::string GetStringForStringLiteral(const StringLiteral *E); 576 577 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object 578 /// for the given string. 579 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 580 581 /// GetAddrOfConstantString - Return a pointer to a constant NSString object 582 /// for the given string. Or a user defined String object as defined via 583 /// -fconstant-string-class=class_name option. 584 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal); 585 586 /// GetConstantArrayFromStringLiteral - Return a constant array for the given 587 /// string. 588 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 589 590 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array 591 /// for the given string literal. 592 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 593 594 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 595 /// array for the given ObjCEncodeExpr node. 596 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 597 598 /// GetAddrOfConstantString - Returns a pointer to a character array 599 /// containing the literal. This contents are exactly that of the given 600 /// string, i.e. it will not be null terminated automatically; see 601 /// GetAddrOfConstantCString. Note that whether the result is actually a 602 /// pointer to an LLVM constant depends on Feature.WriteableStrings. 603 /// 604 /// The result has pointer to array type. 605 /// 606 /// \param GlobalName If provided, the name to use for the global 607 /// (if one is created). 608 llvm::Constant *GetAddrOfConstantString(StringRef Str, 609 const char *GlobalName=0, 610 unsigned Alignment=1); 611 612 /// GetAddrOfConstantCString - Returns a pointer to a character array 613 /// containing the literal and a terminating '\0' character. The result has 614 /// pointer to array type. 615 /// 616 /// \param GlobalName If provided, the name to use for the global (if one is 617 /// created). 618 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 619 const char *GlobalName=0, 620 unsigned Alignment=1); 621 622 /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global 623 /// variable for the given file-scope compound literal expression. 624 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 625 626 /// \brief Retrieve the record type that describes the state of an 627 /// Objective-C fast enumeration loop (for..in). 628 QualType getObjCFastEnumerationStateType(); 629 630 /// GetAddrOfCXXConstructor - Return the address of the constructor of the 631 /// given type. 632 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, 633 CXXCtorType ctorType, 634 const CGFunctionInfo *fnInfo = 0); 635 636 /// GetAddrOfCXXDestructor - Return the address of the constructor of the 637 /// given type. 638 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 639 CXXDtorType dtorType, 640 const CGFunctionInfo *fnInfo = 0); 641 642 /// getBuiltinLibFunction - Given a builtin id for a function like 643 /// "__builtin_fabsf", return a Function* for "fabsf". 644 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 645 unsigned BuiltinID); 646 647 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = 648 ArrayRef<llvm::Type*>()); 649 650 /// EmitTopLevelDecl - Emit code for a single top level declaration. 651 void EmitTopLevelDecl(Decl *D); 652 653 /// AddUsedGlobal - Add a global which should be forced to be 654 /// present in the object file; these are emitted to the llvm.used 655 /// metadata global. 656 void AddUsedGlobal(llvm::GlobalValue *GV); 657 658 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global 659 /// destructor function. 660 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) { 661 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object)); 662 } 663 664 /// CreateRuntimeFunction - Create a new runtime function with the specified 665 /// type and name. 666 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty, 667 StringRef Name, 668 llvm::Attributes ExtraAttrs = 669 llvm::Attribute::None); 670 /// CreateRuntimeVariable - Create a new runtime global variable with the 671 /// specified type and name. 672 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 673 StringRef Name); 674 675 ///@name Custom Blocks Runtime Interfaces 676 ///@{ 677 678 llvm::Constant *getNSConcreteGlobalBlock(); 679 llvm::Constant *getNSConcreteStackBlock(); 680 llvm::Constant *getBlockObjectAssign(); 681 llvm::Constant *getBlockObjectDispose(); 682 683 ///@} 684 685 // UpdateCompleteType - Make sure that this type is translated. 686 void UpdateCompletedType(const TagDecl *TD); 687 688 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 689 690 /// EmitConstantExpr - Try to emit the given expression as a 691 /// constant; returns 0 if the expression cannot be emitted as a 692 /// constant. 693 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 694 CodeGenFunction *CGF = 0); 695 696 /// EmitNullConstant - Return the result of value-initializing the given 697 /// type, i.e. a null expression of the given type. This is usually, 698 /// but not always, an LLVM null constant. 699 llvm::Constant *EmitNullConstant(QualType T); 700 701 /// EmitNullConstantForBase - Return a null constant appropriate for 702 /// zero-initializing a base class with the given type. This is usually, 703 /// but not always, an LLVM null constant. 704 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 705 706 /// Error - Emit a general error that something can't be done. 707 void Error(SourceLocation loc, StringRef error); 708 709 /// ErrorUnsupported - Print out an error that codegen doesn't support the 710 /// specified stmt yet. 711 /// \param OmitOnError - If true, then this error should only be emitted if no 712 /// other errors have been reported. 713 void ErrorUnsupported(const Stmt *S, const char *Type, 714 bool OmitOnError=false); 715 716 /// ErrorUnsupported - Print out an error that codegen doesn't support the 717 /// specified decl yet. 718 /// \param OmitOnError - If true, then this error should only be emitted if no 719 /// other errors have been reported. 720 void ErrorUnsupported(const Decl *D, const char *Type, 721 bool OmitOnError=false); 722 723 /// SetInternalFunctionAttributes - Set the attributes on the LLVM 724 /// function for the given decl and function info. This applies 725 /// attributes necessary for handling the ABI as well as user 726 /// specified attributes like section. 727 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 728 const CGFunctionInfo &FI); 729 730 /// SetLLVMFunctionAttributes - Set the LLVM function attributes 731 /// (sext, zext, etc). 732 void SetLLVMFunctionAttributes(const Decl *D, 733 const CGFunctionInfo &Info, 734 llvm::Function *F); 735 736 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes 737 /// which only apply to a function definintion. 738 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 739 740 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used 741 /// as a return type. 742 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 743 744 /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when 745 /// used as a return type. 746 bool ReturnTypeUsesFPRet(QualType ResultType); 747 748 /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when 749 /// used as a return type. 750 bool ReturnTypeUsesFP2Ret(QualType ResultType); 751 752 /// ConstructAttributeList - Get the LLVM attributes and calling convention to 753 /// use for a particular function type. 754 /// 755 /// \param Info - The function type information. 756 /// \param TargetDecl - The decl these attributes are being constructed 757 /// for. If supplied the attributes applied to this decl may contribute to the 758 /// function attributes and calling convention. 759 /// \param PAL [out] - On return, the attribute list to use. 760 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 761 void ConstructAttributeList(const CGFunctionInfo &Info, 762 const Decl *TargetDecl, 763 AttributeListType &PAL, 764 unsigned &CallingConv); 765 766 StringRef getMangledName(GlobalDecl GD); 767 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 768 const BlockDecl *BD); 769 770 void EmitTentativeDefinition(const VarDecl *D); 771 772 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired); 773 774 llvm::GlobalVariable::LinkageTypes 775 getFunctionLinkage(const FunctionDecl *FD); 776 777 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) { 778 V->setLinkage(getFunctionLinkage(FD)); 779 } 780 781 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT, 782 /// and type information of the given class. 783 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 784 785 /// GetTargetTypeStoreSize - Return the store size, in character units, of 786 /// the given LLVM type. 787 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 788 789 /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global 790 /// variable. 791 llvm::GlobalValue::LinkageTypes 792 GetLLVMLinkageVarDefinition(const VarDecl *D, 793 llvm::GlobalVariable *GV); 794 795 std::vector<const CXXRecordDecl*> DeferredVTables; 796 797 /// Emit all the global annotations. 798 void EmitGlobalAnnotations(); 799 800 /// Emit an annotation string. 801 llvm::Constant *EmitAnnotationString(llvm::StringRef Str); 802 803 /// Emit the annotation's translation unit. 804 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 805 806 /// Emit the annotation line number. 807 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 808 809 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 810 /// annotation information for a given GlobalValue. The annotation struct is 811 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 812 /// GlobalValue being annotated. The second field is the constant string 813 /// created from the AnnotateAttr's annotation. The third field is a constant 814 /// string containing the name of the translation unit. The fourth field is 815 /// the line number in the file of the annotated value declaration. 816 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 817 const AnnotateAttr *AA, 818 SourceLocation L); 819 820 /// Add global annotations that are set on D, for the global GV. Those 821 /// annotations are emitted during finalization of the LLVM code. 822 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 823 824 private: 825 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 826 827 llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName, 828 llvm::Type *Ty, 829 GlobalDecl D, 830 bool ForVTable, 831 llvm::Attributes ExtraAttrs = 832 llvm::Attribute::None); 833 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 834 llvm::PointerType *PTy, 835 const VarDecl *D, 836 bool UnnamedAddr = false); 837 838 /// SetCommonAttributes - Set attributes which are common to any 839 /// form of a global definition (alias, Objective-C method, 840 /// function, global variable). 841 /// 842 /// NOTE: This should only be called for definitions. 843 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 844 845 /// SetFunctionDefinitionAttributes - Set attributes for a global definition. 846 void SetFunctionDefinitionAttributes(const FunctionDecl *D, 847 llvm::GlobalValue *GV); 848 849 /// SetFunctionAttributes - Set function attributes for a function 850 /// declaration. 851 void SetFunctionAttributes(GlobalDecl GD, 852 llvm::Function *F, 853 bool IsIncompleteFunction); 854 855 /// EmitGlobal - Emit code for a singal global function or var decl. Forward 856 /// declarations are emitted lazily. 857 void EmitGlobal(GlobalDecl D); 858 859 void EmitGlobalDefinition(GlobalDecl D); 860 861 void EmitGlobalFunctionDefinition(GlobalDecl GD); 862 void EmitGlobalVarDefinition(const VarDecl *D); 863 void EmitAliasDefinition(GlobalDecl GD); 864 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 865 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 866 867 // C++ related functions. 868 869 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target); 870 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 871 872 void EmitNamespace(const NamespaceDecl *D); 873 void EmitLinkageSpec(const LinkageSpecDecl *D); 874 875 /// EmitCXXConstructors - Emit constructors (base, complete) from a 876 /// C++ constructor Decl. 877 void EmitCXXConstructors(const CXXConstructorDecl *D); 878 879 /// EmitCXXConstructor - Emit a single constructor with the given type from 880 /// a C++ constructor Decl. 881 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 882 883 /// EmitCXXDestructors - Emit destructors (base, complete) from a 884 /// C++ destructor Decl. 885 void EmitCXXDestructors(const CXXDestructorDecl *D); 886 887 /// EmitCXXDestructor - Emit a single destructor with the given type from 888 /// a C++ destructor Decl. 889 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 890 891 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals. 892 void EmitCXXGlobalInitFunc(); 893 894 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals. 895 void EmitCXXGlobalDtorFunc(); 896 897 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 898 llvm::GlobalVariable *Addr); 899 900 // FIXME: Hardcoding priority here is gross. 901 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); 902 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); 903 904 /// EmitCtorList - Generates a global array of functions and priorities using 905 /// the given list and name. This array will have appending linkage and is 906 /// suitable for use as a LLVM constructor or destructor array. 907 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 908 909 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the 910 /// given type. 911 void EmitFundamentalRTTIDescriptor(QualType Type); 912 913 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the 914 /// builtin types. 915 void EmitFundamentalRTTIDescriptors(); 916 917 /// EmitDeferred - Emit any needed decls for which code generation 918 /// was deferred. 919 void EmitDeferred(void); 920 921 /// EmitLLVMUsed - Emit the llvm.used metadata used to force 922 /// references to global which may otherwise be optimized out. 923 void EmitLLVMUsed(void); 924 925 void EmitDeclMetadata(); 926 927 /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where 928 /// to emit the .gcno and .gcda files in a way that persists in .bc files. 929 void EmitCoverageFile(); 930 931 /// MayDeferGeneration - Determine if the given decl can be emitted 932 /// lazily; this is only relevant for definitions. The given decl 933 /// must be either a function or var decl. 934 bool MayDeferGeneration(const ValueDecl *D); 935 936 /// SimplifyPersonality - Check whether we can use a "simpler", more 937 /// core exceptions personality function. 938 void SimplifyPersonality(); 939 }; 940 } // end namespace CodeGen 941 } // end namespace clang 942 943 #endif 944