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