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