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