1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is the internal per-translation-unit state used for llvm translation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 15 16 #include "CGVTables.h" 17 #include "CodeGenTypeCache.h" 18 #include "CodeGenTypes.h" 19 #include "SanitizerMetadata.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclOpenMP.h" 23 #include "clang/AST/GlobalDecl.h" 24 #include "clang/AST/Mangle.h" 25 #include "clang/Basic/ABI.h" 26 #include "clang/Basic/LangOptions.h" 27 #include "clang/Basic/Module.h" 28 #include "clang/Basic/NoSanitizeList.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Basic/XRayLists.h" 31 #include "clang/Lex/PreprocessorOptions.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/SetVector.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/StringMap.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/ValueHandle.h" 38 #include "llvm/Transforms/Utils/SanitizerStats.h" 39 40 namespace llvm { 41 class Module; 42 class Constant; 43 class ConstantInt; 44 class Function; 45 class GlobalValue; 46 class DataLayout; 47 class FunctionType; 48 class LLVMContext; 49 class IndexedInstrProfReader; 50 } 51 52 namespace clang { 53 class ASTContext; 54 class AtomicType; 55 class FunctionDecl; 56 class IdentifierInfo; 57 class ObjCImplementationDecl; 58 class ObjCEncodeExpr; 59 class BlockExpr; 60 class CharUnits; 61 class Decl; 62 class Expr; 63 class Stmt; 64 class StringLiteral; 65 class NamedDecl; 66 class ValueDecl; 67 class VarDecl; 68 class LangOptions; 69 class CodeGenOptions; 70 class HeaderSearchOptions; 71 class DiagnosticsEngine; 72 class AnnotateAttr; 73 class CXXDestructorDecl; 74 class Module; 75 class CoverageSourceInfo; 76 class InitSegAttr; 77 78 namespace CodeGen { 79 80 class CodeGenFunction; 81 class CodeGenTBAA; 82 class CGCXXABI; 83 class CGDebugInfo; 84 class CGObjCRuntime; 85 class CGOpenCLRuntime; 86 class CGOpenMPRuntime; 87 class CGCUDARuntime; 88 class CoverageMappingModuleGen; 89 class TargetCodeGenInfo; 90 91 enum ForDefinition_t : bool { 92 NotForDefinition = false, 93 ForDefinition = true 94 }; 95 96 struct OrderGlobalInitsOrStermFinalizers { 97 unsigned int priority; 98 unsigned int lex_order; 99 OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l) 100 : priority(p), lex_order(l) {} 101 102 bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const { 103 return priority == RHS.priority && lex_order == RHS.lex_order; 104 } 105 106 bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const { 107 return std::tie(priority, lex_order) < 108 std::tie(RHS.priority, RHS.lex_order); 109 } 110 }; 111 112 struct ObjCEntrypoints { 113 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); } 114 115 /// void objc_alloc(id); 116 llvm::FunctionCallee objc_alloc; 117 118 /// void objc_allocWithZone(id); 119 llvm::FunctionCallee objc_allocWithZone; 120 121 /// void objc_alloc_init(id); 122 llvm::FunctionCallee objc_alloc_init; 123 124 /// void objc_autoreleasePoolPop(void*); 125 llvm::FunctionCallee objc_autoreleasePoolPop; 126 127 /// void objc_autoreleasePoolPop(void*); 128 /// Note this method is used when we are using exception handling 129 llvm::FunctionCallee objc_autoreleasePoolPopInvoke; 130 131 /// void *objc_autoreleasePoolPush(void); 132 llvm::Function *objc_autoreleasePoolPush; 133 134 /// id objc_autorelease(id); 135 llvm::Function *objc_autorelease; 136 137 /// id objc_autorelease(id); 138 /// Note this is the runtime method not the intrinsic. 139 llvm::FunctionCallee objc_autoreleaseRuntimeFunction; 140 141 /// id objc_autoreleaseReturnValue(id); 142 llvm::Function *objc_autoreleaseReturnValue; 143 144 /// void objc_copyWeak(id *dest, id *src); 145 llvm::Function *objc_copyWeak; 146 147 /// void objc_destroyWeak(id*); 148 llvm::Function *objc_destroyWeak; 149 150 /// id objc_initWeak(id*, id); 151 llvm::Function *objc_initWeak; 152 153 /// id objc_loadWeak(id*); 154 llvm::Function *objc_loadWeak; 155 156 /// id objc_loadWeakRetained(id*); 157 llvm::Function *objc_loadWeakRetained; 158 159 /// void objc_moveWeak(id *dest, id *src); 160 llvm::Function *objc_moveWeak; 161 162 /// id objc_retain(id); 163 llvm::Function *objc_retain; 164 165 /// id objc_retain(id); 166 /// Note this is the runtime method not the intrinsic. 167 llvm::FunctionCallee objc_retainRuntimeFunction; 168 169 /// id objc_retainAutorelease(id); 170 llvm::Function *objc_retainAutorelease; 171 172 /// id objc_retainAutoreleaseReturnValue(id); 173 llvm::Function *objc_retainAutoreleaseReturnValue; 174 175 /// id objc_retainAutoreleasedReturnValue(id); 176 llvm::Function *objc_retainAutoreleasedReturnValue; 177 178 /// id objc_retainBlock(id); 179 llvm::Function *objc_retainBlock; 180 181 /// void objc_release(id); 182 llvm::Function *objc_release; 183 184 /// void objc_release(id); 185 /// Note this is the runtime method not the intrinsic. 186 llvm::FunctionCallee objc_releaseRuntimeFunction; 187 188 /// void objc_storeStrong(id*, id); 189 llvm::Function *objc_storeStrong; 190 191 /// id objc_storeWeak(id*, id); 192 llvm::Function *objc_storeWeak; 193 194 /// id objc_unsafeClaimAutoreleasedReturnValue(id); 195 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue; 196 197 /// A void(void) inline asm to use to mark that the return value of 198 /// a call will be immediately retain. 199 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 200 201 /// void clang.arc.use(...); 202 llvm::Function *clang_arc_use; 203 204 /// void clang.arc.noop.use(...); 205 llvm::Function *clang_arc_noop_use; 206 }; 207 208 /// This class records statistics on instrumentation based profiling. 209 class InstrProfStats { 210 uint32_t VisitedInMainFile; 211 uint32_t MissingInMainFile; 212 uint32_t Visited; 213 uint32_t Missing; 214 uint32_t Mismatched; 215 216 public: 217 InstrProfStats() 218 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0), 219 Mismatched(0) {} 220 /// Record that we've visited a function and whether or not that function was 221 /// in the main source file. 222 void addVisited(bool MainFile) { 223 if (MainFile) 224 ++VisitedInMainFile; 225 ++Visited; 226 } 227 /// Record that a function we've visited has no profile data. 228 void addMissing(bool MainFile) { 229 if (MainFile) 230 ++MissingInMainFile; 231 ++Missing; 232 } 233 /// Record that a function we've visited has mismatched profile data. 234 void addMismatched(bool MainFile) { ++Mismatched; } 235 /// Whether or not the stats we've gathered indicate any potential problems. 236 bool hasDiagnostics() { return Missing || Mismatched; } 237 /// Report potential problems we've found to \c Diags. 238 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile); 239 }; 240 241 /// A pair of helper functions for a __block variable. 242 class BlockByrefHelpers : public llvm::FoldingSetNode { 243 // MSVC requires this type to be complete in order to process this 244 // header. 245 public: 246 llvm::Constant *CopyHelper; 247 llvm::Constant *DisposeHelper; 248 249 /// The alignment of the field. This is important because 250 /// different offsets to the field within the byref struct need to 251 /// have different helper functions. 252 CharUnits Alignment; 253 254 BlockByrefHelpers(CharUnits alignment) 255 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {} 256 BlockByrefHelpers(const BlockByrefHelpers &) = default; 257 virtual ~BlockByrefHelpers(); 258 259 void Profile(llvm::FoldingSetNodeID &id) const { 260 id.AddInteger(Alignment.getQuantity()); 261 profileImpl(id); 262 } 263 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 264 265 virtual bool needsCopy() const { return true; } 266 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0; 267 268 virtual bool needsDispose() const { return true; } 269 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0; 270 }; 271 272 /// This class organizes the cross-function state that is used while generating 273 /// LLVM code. 274 class CodeGenModule : public CodeGenTypeCache { 275 CodeGenModule(const CodeGenModule &) = delete; 276 void operator=(const CodeGenModule &) = delete; 277 278 public: 279 struct Structor { 280 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {} 281 Structor(int Priority, llvm::Constant *Initializer, 282 llvm::Constant *AssociatedData) 283 : Priority(Priority), Initializer(Initializer), 284 AssociatedData(AssociatedData) {} 285 int Priority; 286 llvm::Constant *Initializer; 287 llvm::Constant *AssociatedData; 288 }; 289 290 typedef std::vector<Structor> CtorList; 291 292 private: 293 ASTContext &Context; 294 const LangOptions &LangOpts; 295 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info. 296 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info. 297 const CodeGenOptions &CodeGenOpts; 298 unsigned NumAutoVarInit = 0; 299 llvm::Module &TheModule; 300 DiagnosticsEngine &Diags; 301 const TargetInfo &Target; 302 std::unique_ptr<CGCXXABI> ABI; 303 llvm::LLVMContext &VMContext; 304 std::string ModuleNameHash; 305 306 std::unique_ptr<CodeGenTBAA> TBAA; 307 308 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo; 309 310 // This should not be moved earlier, since its initialization depends on some 311 // of the previous reference members being already initialized and also checks 312 // if TheTargetCodeGenInfo is NULL 313 CodeGenTypes Types; 314 315 /// Holds information about C++ vtables. 316 CodeGenVTables VTables; 317 318 std::unique_ptr<CGObjCRuntime> ObjCRuntime; 319 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime; 320 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime; 321 std::unique_ptr<CGCUDARuntime> CUDARuntime; 322 std::unique_ptr<CGDebugInfo> DebugInfo; 323 std::unique_ptr<ObjCEntrypoints> ObjCData; 324 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr; 325 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader; 326 InstrProfStats PGOStats; 327 std::unique_ptr<llvm::SanitizerStatReport> SanStats; 328 329 // A set of references that have only been seen via a weakref so far. This is 330 // used to remove the weak of the reference if we ever see a direct reference 331 // or a definition. 332 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 333 334 /// This contains all the decls which have definitions but/ which are deferred 335 /// for emission and therefore should only be output if they are actually 336 /// used. If a decl is in this, then it is known to have not been referenced 337 /// yet. 338 llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls; 339 340 /// This is a list of deferred decls which we have seen that *are* actually 341 /// referenced. These get code generated when the module is done. 342 std::vector<GlobalDecl> DeferredDeclsToEmit; 343 void addDeferredDeclToEmit(GlobalDecl GD) { 344 DeferredDeclsToEmit.emplace_back(GD); 345 } 346 347 /// List of alias we have emitted. Used to make sure that what they point to 348 /// is defined once we get to the end of the of the translation unit. 349 std::vector<GlobalDecl> Aliases; 350 351 /// List of multiversion functions that have to be emitted. Used to make sure 352 /// we properly emit the iFunc. 353 std::vector<GlobalDecl> MultiVersionFuncs; 354 355 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy; 356 ReplacementsTy Replacements; 357 358 /// List of global values to be replaced with something else. Used when we 359 /// want to replace a GlobalValue but can't identify it by its mangled name 360 /// anymore (because the name is already taken). 361 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8> 362 GlobalValReplacements; 363 364 /// Variables for which we've emitted globals containing their constant 365 /// values along with the corresponding globals, for opportunistic reuse. 366 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants; 367 368 /// Set of global decls for which we already diagnosed mangled name conflict. 369 /// Required to not issue a warning (on a mangling conflict) multiple times 370 /// for the same decl. 371 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions; 372 373 /// A queue of (optional) vtables to consider emitting. 374 std::vector<const CXXRecordDecl*> DeferredVTables; 375 376 /// A queue of (optional) vtables that may be emitted opportunistically. 377 std::vector<const CXXRecordDecl *> OpportunisticVTables; 378 379 /// List of global values which are required to be present in the object file; 380 /// bitcast to i8*. This is used for forcing visibility of symbols which may 381 /// otherwise be optimized out. 382 std::vector<llvm::WeakTrackingVH> LLVMUsed; 383 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed; 384 385 /// Store the list of global constructors and their respective priorities to 386 /// be emitted when the translation unit is complete. 387 CtorList GlobalCtors; 388 389 /// Store the list of global destructors and their respective priorities to be 390 /// emitted when the translation unit is complete. 391 CtorList GlobalDtors; 392 393 /// An ordered map of canonical GlobalDecls to their mangled names. 394 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames; 395 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings; 396 397 // An ordered map of canonical GlobalDecls paired with the cpu-index for 398 // cpu-specific name manglings. 399 llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef> 400 CPUSpecificMangledDeclNames; 401 llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator> 402 CPUSpecificManglings; 403 404 /// Global annotations. 405 std::vector<llvm::Constant*> Annotations; 406 407 /// Map used to get unique annotation strings. 408 llvm::StringMap<llvm::Constant*> AnnotationStrings; 409 410 /// Used for uniquing of annotation arguments. 411 llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs; 412 413 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap; 414 415 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap; 416 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap; 417 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap; 418 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap; 419 420 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap; 421 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap; 422 423 /// Map used to get unique type descriptor constants for sanitizers. 424 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap; 425 426 /// Map used to track internal linkage functions declared within 427 /// extern "C" regions. 428 typedef llvm::MapVector<IdentifierInfo *, 429 llvm::GlobalValue *> StaticExternCMap; 430 StaticExternCMap StaticExternCValues; 431 432 /// thread_local variables defined or used in this TU. 433 std::vector<const VarDecl *> CXXThreadLocals; 434 435 /// thread_local variables with initializers that need to run 436 /// before any thread_local variable in this TU is odr-used. 437 std::vector<llvm::Function *> CXXThreadLocalInits; 438 std::vector<const VarDecl *> CXXThreadLocalInitVars; 439 440 /// Global variables with initializers that need to run before main. 441 std::vector<llvm::Function *> CXXGlobalInits; 442 443 /// When a C++ decl with an initializer is deferred, null is 444 /// appended to CXXGlobalInits, and the index of that null is placed 445 /// here so that the initializer will be performed in the correct 446 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure 447 /// that we don't re-emit the initializer. 448 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 449 450 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *> 451 GlobalInitData; 452 453 struct GlobalInitPriorityCmp { 454 bool operator()(const GlobalInitData &LHS, 455 const GlobalInitData &RHS) const { 456 return LHS.first.priority < RHS.first.priority; 457 } 458 }; 459 460 /// Global variables with initializers whose order of initialization is set by 461 /// init_priority attribute. 462 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits; 463 464 /// Global destructor functions and arguments that need to run on termination. 465 /// When UseSinitAndSterm is set, it instead contains sterm finalizer 466 /// functions, which also run on unloading a shared library. 467 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, 468 llvm::Constant *> 469 CXXGlobalDtorsOrStermFinalizer_t; 470 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8> 471 CXXGlobalDtorsOrStermFinalizers; 472 473 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *> 474 StermFinalizerData; 475 476 struct StermFinalizerPriorityCmp { 477 bool operator()(const StermFinalizerData &LHS, 478 const StermFinalizerData &RHS) const { 479 return LHS.first.priority < RHS.first.priority; 480 } 481 }; 482 483 /// Global variables with sterm finalizers whose order of initialization is 484 /// set by init_priority attribute. 485 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers; 486 487 /// The complete set of modules that has been imported. 488 llvm::SetVector<clang::Module *> ImportedModules; 489 490 /// The set of modules for which the module initializers 491 /// have been emitted. 492 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers; 493 494 /// A vector of metadata strings for linker options. 495 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata; 496 497 /// A vector of metadata strings for dependent libraries for ELF. 498 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries; 499 500 /// @name Cache for Objective-C runtime types 501 /// @{ 502 503 /// Cached reference to the class for constant strings. This value has type 504 /// int * but is actually an Obj-C class pointer. 505 llvm::WeakTrackingVH CFConstantStringClassRef; 506 507 /// The type used to describe the state of a fast enumeration in 508 /// Objective-C's for..in loop. 509 QualType ObjCFastEnumerationStateType; 510 511 /// @} 512 513 /// Lazily create the Objective-C runtime 514 void createObjCRuntime(); 515 516 void createOpenCLRuntime(); 517 void createOpenMPRuntime(); 518 void createCUDARuntime(); 519 520 bool isTriviallyRecursive(const FunctionDecl *F); 521 bool shouldEmitFunction(GlobalDecl GD); 522 bool shouldOpportunisticallyEmitVTables(); 523 /// Map used to be sure we don't emit the same CompoundLiteral twice. 524 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *> 525 EmittedCompoundLiterals; 526 527 /// Map of the global blocks we've emitted, so that we don't have to re-emit 528 /// them if the constexpr evaluator gets aggressive. 529 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks; 530 531 /// @name Cache for Blocks Runtime Globals 532 /// @{ 533 534 llvm::Constant *NSConcreteGlobalBlock = nullptr; 535 llvm::Constant *NSConcreteStackBlock = nullptr; 536 537 llvm::FunctionCallee BlockObjectAssign = nullptr; 538 llvm::FunctionCallee BlockObjectDispose = nullptr; 539 540 llvm::Type *BlockDescriptorType = nullptr; 541 llvm::Type *GenericBlockLiteralType = nullptr; 542 543 struct { 544 int GlobalUniqueCount; 545 } Block; 546 547 GlobalDecl initializedGlobalDecl; 548 549 /// @} 550 551 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>) 552 llvm::Function *LifetimeStartFn = nullptr; 553 554 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>) 555 llvm::Function *LifetimeEndFn = nullptr; 556 557 std::unique_ptr<SanitizerMetadata> SanitizerMD; 558 559 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls; 560 561 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping; 562 563 /// Mapping from canonical types to their metadata identifiers. We need to 564 /// maintain this mapping because identifiers may be formed from distinct 565 /// MDNodes. 566 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap; 567 MetadataTypeMap MetadataIdMap; 568 MetadataTypeMap VirtualMetadataIdMap; 569 MetadataTypeMap GeneralizedMetadataIdMap; 570 571 public: 572 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts, 573 const PreprocessorOptions &ppopts, 574 const CodeGenOptions &CodeGenOpts, llvm::Module &M, 575 DiagnosticsEngine &Diags, 576 CoverageSourceInfo *CoverageInfo = nullptr); 577 578 ~CodeGenModule(); 579 580 void clear(); 581 582 /// Finalize LLVM code generation. 583 void Release(); 584 585 /// Return true if we should emit location information for expressions. 586 bool getExpressionLocationsEnabled() const; 587 588 /// Return a reference to the configured Objective-C runtime. 589 CGObjCRuntime &getObjCRuntime() { 590 if (!ObjCRuntime) createObjCRuntime(); 591 return *ObjCRuntime; 592 } 593 594 /// Return true iff an Objective-C runtime has been configured. 595 bool hasObjCRuntime() { return !!ObjCRuntime; } 596 597 const std::string &getModuleNameHash() const { return ModuleNameHash; } 598 599 /// Return a reference to the configured OpenCL runtime. 600 CGOpenCLRuntime &getOpenCLRuntime() { 601 assert(OpenCLRuntime != nullptr); 602 return *OpenCLRuntime; 603 } 604 605 /// Return a reference to the configured OpenMP runtime. 606 CGOpenMPRuntime &getOpenMPRuntime() { 607 assert(OpenMPRuntime != nullptr); 608 return *OpenMPRuntime; 609 } 610 611 /// Return a reference to the configured CUDA runtime. 612 CGCUDARuntime &getCUDARuntime() { 613 assert(CUDARuntime != nullptr); 614 return *CUDARuntime; 615 } 616 617 ObjCEntrypoints &getObjCEntrypoints() const { 618 assert(ObjCData != nullptr); 619 return *ObjCData; 620 } 621 622 // Version checking functions, used to implement ObjC's @available: 623 // i32 @__isOSVersionAtLeast(i32, i32, i32) 624 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr; 625 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32) 626 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr; 627 628 InstrProfStats &getPGOStats() { return PGOStats; } 629 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); } 630 631 CoverageMappingModuleGen *getCoverageMapping() const { 632 return CoverageMapping.get(); 633 } 634 635 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) { 636 return StaticLocalDeclMap[D]; 637 } 638 void setStaticLocalDeclAddress(const VarDecl *D, 639 llvm::Constant *C) { 640 StaticLocalDeclMap[D] = C; 641 } 642 643 llvm::Constant * 644 getOrCreateStaticVarDecl(const VarDecl &D, 645 llvm::GlobalValue::LinkageTypes Linkage); 646 647 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) { 648 return StaticLocalDeclGuardMap[D]; 649 } 650 void setStaticLocalDeclGuardAddress(const VarDecl *D, 651 llvm::GlobalVariable *C) { 652 StaticLocalDeclGuardMap[D] = C; 653 } 654 655 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant, 656 CharUnits Align); 657 658 bool lookupRepresentativeDecl(StringRef MangledName, 659 GlobalDecl &Result) const; 660 661 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 662 return AtomicSetterHelperFnMap[Ty]; 663 } 664 void setAtomicSetterHelperFnMap(QualType Ty, 665 llvm::Constant *Fn) { 666 AtomicSetterHelperFnMap[Ty] = Fn; 667 } 668 669 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 670 return AtomicGetterHelperFnMap[Ty]; 671 } 672 void setAtomicGetterHelperFnMap(QualType Ty, 673 llvm::Constant *Fn) { 674 AtomicGetterHelperFnMap[Ty] = Fn; 675 } 676 677 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) { 678 return TypeDescriptorMap[Ty]; 679 } 680 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) { 681 TypeDescriptorMap[Ty] = C; 682 } 683 684 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); } 685 686 llvm::MDNode *getNoObjCARCExceptionsMetadata() { 687 if (!NoObjCARCExceptionsMetadata) 688 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None); 689 return NoObjCARCExceptionsMetadata; 690 } 691 692 ASTContext &getContext() const { return Context; } 693 const LangOptions &getLangOpts() const { return LangOpts; } 694 const HeaderSearchOptions &getHeaderSearchOpts() 695 const { return HeaderSearchOpts; } 696 const PreprocessorOptions &getPreprocessorOpts() 697 const { return PreprocessorOpts; } 698 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 699 llvm::Module &getModule() const { return TheModule; } 700 DiagnosticsEngine &getDiags() const { return Diags; } 701 const llvm::DataLayout &getDataLayout() const { 702 return TheModule.getDataLayout(); 703 } 704 const TargetInfo &getTarget() const { return Target; } 705 const llvm::Triple &getTriple() const { return Target.getTriple(); } 706 bool supportsCOMDAT() const; 707 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO); 708 709 CGCXXABI &getCXXABI() const { return *ABI; } 710 llvm::LLVMContext &getLLVMContext() { return VMContext; } 711 712 bool shouldUseTBAA() const { return TBAA != nullptr; } 713 714 const TargetCodeGenInfo &getTargetCodeGenInfo(); 715 716 CodeGenTypes &getTypes() { return Types; } 717 718 CodeGenVTables &getVTables() { return VTables; } 719 720 ItaniumVTableContext &getItaniumVTableContext() { 721 return VTables.getItaniumVTableContext(); 722 } 723 724 MicrosoftVTableContext &getMicrosoftVTableContext() { 725 return VTables.getMicrosoftVTableContext(); 726 } 727 728 CtorList &getGlobalCtors() { return GlobalCtors; } 729 CtorList &getGlobalDtors() { return GlobalDtors; } 730 731 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of 732 /// the given type. 733 llvm::MDNode *getTBAATypeInfo(QualType QTy); 734 735 /// getTBAAAccessInfo - Get TBAA information that describes an access to 736 /// an object of the given type. 737 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType); 738 739 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an 740 /// access to a virtual table pointer. 741 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType); 742 743 llvm::MDNode *getTBAAStructInfo(QualType QTy); 744 745 /// getTBAABaseTypeInfo - Get metadata that describes the given base access 746 /// type. Return null if the type is not suitable for use in TBAA access tags. 747 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy); 748 749 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access. 750 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info); 751 752 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of 753 /// type casts. 754 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 755 TBAAAccessInfo TargetInfo); 756 757 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the 758 /// purposes of conditional operator. 759 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 760 TBAAAccessInfo InfoB); 761 762 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the 763 /// purposes of memory transfer calls. 764 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 765 TBAAAccessInfo SrcInfo); 766 767 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given 768 /// base lvalue. 769 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) { 770 if (Base.getTBAAInfo().isMayAlias()) 771 return TBAAAccessInfo::getMayAliasInfo(); 772 return getTBAAAccessInfo(AccessType); 773 } 774 775 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor); 776 777 bool isPaddedAtomicType(QualType type); 778 bool isPaddedAtomicType(const AtomicType *type); 779 780 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag. 781 void DecorateInstructionWithTBAA(llvm::Instruction *Inst, 782 TBAAAccessInfo TBAAInfo); 783 784 /// Adds !invariant.barrier !tag to instruction 785 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, 786 const CXXRecordDecl *RD); 787 788 /// Emit the given number of characters as a value of type size_t. 789 llvm::ConstantInt *getSize(CharUnits numChars); 790 791 /// Set the visibility for the given LLVM GlobalValue. 792 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 793 794 void setDSOLocal(llvm::GlobalValue *GV) const; 795 796 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const; 797 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const; 798 /// Set visibility, dllimport/dllexport and dso_local. 799 /// This must be called after dllimport/dllexport is set. 800 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const; 801 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const; 802 803 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const; 804 805 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local 806 /// variable declaration D. 807 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const; 808 809 /// Get LLVM TLS mode from CodeGenOptions. 810 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const; 811 812 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 813 switch (V) { 814 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 815 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 816 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 817 } 818 llvm_unreachable("unknown visibility!"); 819 } 820 821 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, 822 ForDefinition_t IsForDefinition 823 = NotForDefinition); 824 825 /// Will return a global variable of the given type. If a variable with a 826 /// different type already exists then a new variable with the right type 827 /// will be created and all uses of the old variable will be replaced with a 828 /// bitcast to the new variable. 829 llvm::GlobalVariable * 830 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 831 llvm::GlobalValue::LinkageTypes Linkage, 832 unsigned Alignment); 833 834 llvm::Function *CreateGlobalInitOrCleanUpFunction( 835 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, 836 SourceLocation Loc = SourceLocation(), bool TLS = false); 837 838 /// Return the AST address space of the underlying global variable for D, as 839 /// determined by its declaration. Normally this is the same as the address 840 /// space of D's type, but in CUDA, address spaces are associated with 841 /// declarations, not types. If D is nullptr, return the default address 842 /// space for global variable. 843 /// 844 /// For languages without explicit address spaces, if D has default address 845 /// space, target-specific global or constant address space may be returned. 846 LangAS GetGlobalVarAddressSpace(const VarDecl *D); 847 848 /// Return the AST address space of constant literal, which is used to emit 849 /// the constant literal as global variable in LLVM IR. 850 /// Note: This is not necessarily the address space of the constant literal 851 /// in AST. For address space agnostic language, e.g. C++, constant literal 852 /// in AST is always in default address space. 853 LangAS GetGlobalConstantAddressSpace() const; 854 855 /// Return the llvm::Constant for the address of the given global variable. 856 /// If Ty is non-null and if the global doesn't exist, then it will be created 857 /// with the specified type instead of whatever the normal requested type 858 /// would be. If IsForDefinition is true, it is guaranteed that an actual 859 /// global with type Ty will be returned, not conversion of a variable with 860 /// the same mangled name but some other type. 861 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 862 llvm::Type *Ty = nullptr, 863 ForDefinition_t IsForDefinition 864 = NotForDefinition); 865 866 /// Return the address of the given function. If Ty is non-null, then this 867 /// function will use the specified type if it has to create it. 868 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr, 869 bool ForVTable = false, 870 bool DontDefer = false, 871 ForDefinition_t IsForDefinition 872 = NotForDefinition); 873 874 // Return the function body address of the given function. 875 llvm::Constant *GetFunctionStart(const ValueDecl *Decl); 876 877 /// Get the address of the RTTI descriptor for the given type. 878 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 879 880 /// Get the address of a GUID. 881 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD); 882 883 /// Get the address of a template parameter object. 884 ConstantAddress 885 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO); 886 887 /// Get the address of the thunk for the given global decl. 888 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, 889 GlobalDecl GD); 890 891 /// Get a reference to the target of VD. 892 ConstantAddress GetWeakRefReference(const ValueDecl *VD); 893 894 /// Returns the assumed alignment of an opaque pointer to the given class. 895 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD); 896 897 /// Returns the minimum object size for an object of the given class type 898 /// (or a class derived from it). 899 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD); 900 901 /// Returns the minimum object size for an object of the given type. 902 CharUnits getMinimumObjectSize(QualType Ty) { 903 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) 904 return getMinimumClassObjectSize(RD); 905 return getContext().getTypeSizeInChars(Ty); 906 } 907 908 /// Returns the assumed alignment of a virtual base of a class. 909 CharUnits getVBaseAlignment(CharUnits DerivedAlign, 910 const CXXRecordDecl *Derived, 911 const CXXRecordDecl *VBase); 912 913 /// Given a class pointer with an actual known alignment, and the 914 /// expected alignment of an object at a dynamic offset w.r.t that 915 /// pointer, return the alignment to assume at the offset. 916 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign, 917 const CXXRecordDecl *Class, 918 CharUnits ExpectedTargetAlign); 919 920 CharUnits 921 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, 922 CastExpr::path_const_iterator Start, 923 CastExpr::path_const_iterator End); 924 925 /// Returns the offset from a derived class to a class. Returns null if the 926 /// offset is 0. 927 llvm::Constant * 928 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 929 CastExpr::path_const_iterator PathBegin, 930 CastExpr::path_const_iterator PathEnd); 931 932 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache; 933 934 /// Fetches the global unique block count. 935 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 936 937 /// Fetches the type of a generic block descriptor. 938 llvm::Type *getBlockDescriptorType(); 939 940 /// The type of a generic block literal. 941 llvm::Type *getGenericBlockLiteralType(); 942 943 /// Gets the address of a block which requires no captures. 944 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name); 945 946 /// Returns the address of a block which requires no caputres, or null if 947 /// we've yet to emit the block for BE. 948 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) { 949 return EmittedGlobalBlocks.lookup(BE); 950 } 951 952 /// Notes that BE's global block is available via Addr. Asserts that BE 953 /// isn't already emitted. 954 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr); 955 956 /// Return a pointer to a constant CFString object for the given string. 957 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal); 958 959 /// Return a pointer to a constant NSString object for the given string. Or a 960 /// user defined String object as defined via 961 /// -fconstant-string-class=class_name option. 962 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal); 963 964 /// Return a constant array for the given string. 965 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 966 967 /// Return a pointer to a constant array for the given string literal. 968 ConstantAddress 969 GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 970 StringRef Name = ".str"); 971 972 /// Return a pointer to a constant array for the given ObjCEncodeExpr node. 973 ConstantAddress 974 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 975 976 /// Returns a pointer to a character array containing the literal and a 977 /// terminating '\0' character. The result has pointer to array type. 978 /// 979 /// \param GlobalName If provided, the name to use for the global (if one is 980 /// created). 981 ConstantAddress 982 GetAddrOfConstantCString(const std::string &Str, 983 const char *GlobalName = nullptr); 984 985 /// Returns a pointer to a constant global variable for the given file-scope 986 /// compound literal expression. 987 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 988 989 /// If it's been emitted already, returns the GlobalVariable corresponding to 990 /// a compound literal. Otherwise, returns null. 991 llvm::GlobalVariable * 992 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E); 993 994 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already 995 /// emitted. 996 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE, 997 llvm::GlobalVariable *GV); 998 999 /// Returns a pointer to a global variable representing a temporary 1000 /// with static or thread storage duration. 1001 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, 1002 const Expr *Inner); 1003 1004 /// Retrieve the record type that describes the state of an 1005 /// Objective-C fast enumeration loop (for..in). 1006 QualType getObjCFastEnumerationStateType(); 1007 1008 // Produce code for this constructor/destructor. This method doesn't try 1009 // to apply any ABI rules about which other constructors/destructors 1010 // are needed or if they are alias to each other. 1011 llvm::Function *codegenCXXStructor(GlobalDecl GD); 1012 1013 /// Return the address of the constructor/destructor of the given type. 1014 llvm::Constant * 1015 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 1016 llvm::FunctionType *FnType = nullptr, 1017 bool DontDefer = false, 1018 ForDefinition_t IsForDefinition = NotForDefinition) { 1019 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType, 1020 DontDefer, 1021 IsForDefinition) 1022 .getCallee()); 1023 } 1024 1025 llvm::FunctionCallee getAddrAndTypeOfCXXStructor( 1026 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 1027 llvm::FunctionType *FnType = nullptr, bool DontDefer = false, 1028 ForDefinition_t IsForDefinition = NotForDefinition); 1029 1030 /// Given a builtin id for a function like "__builtin_fabsf", return a 1031 /// Function* for "fabsf". 1032 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD, 1033 unsigned BuiltinID); 1034 1035 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None); 1036 1037 /// Emit code for a single top level declaration. 1038 void EmitTopLevelDecl(Decl *D); 1039 1040 /// Stored a deferred empty coverage mapping for an unused 1041 /// and thus uninstrumented top level declaration. 1042 void AddDeferredUnusedCoverageMapping(Decl *D); 1043 1044 /// Remove the deferred empty coverage mapping as this 1045 /// declaration is actually instrumented. 1046 void ClearUnusedCoverageMapping(const Decl *D); 1047 1048 /// Emit all the deferred coverage mappings 1049 /// for the uninstrumented functions. 1050 void EmitDeferredUnusedCoverageMappings(); 1051 1052 /// Emit an alias for "main" if it has no arguments (needed for wasm). 1053 void EmitMainVoidAlias(); 1054 1055 /// Tell the consumer that this variable has been instantiated. 1056 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD); 1057 1058 /// If the declaration has internal linkage but is inside an 1059 /// extern "C" linkage specification, prepare to emit an alias for it 1060 /// to the expected name. 1061 template<typename SomeDecl> 1062 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV); 1063 1064 /// Add a global to a list to be added to the llvm.used metadata. 1065 void addUsedGlobal(llvm::GlobalValue *GV); 1066 1067 /// Add a global to a list to be added to the llvm.compiler.used metadata. 1068 void addCompilerUsedGlobal(llvm::GlobalValue *GV); 1069 1070 /// Add a global to a list to be added to the llvm.compiler.used metadata. 1071 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV); 1072 1073 /// Add a destructor and object to add to the C++ global destructor function. 1074 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) { 1075 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(), 1076 DtorFn.getCallee(), Object); 1077 } 1078 1079 /// Add an sterm finalizer to the C++ global cleanup function. 1080 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) { 1081 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(), 1082 DtorFn.getCallee(), nullptr); 1083 } 1084 1085 /// Add an sterm finalizer to its own llvm.global_dtors entry. 1086 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer, 1087 int Priority) { 1088 AddGlobalDtor(StermFinalizer, Priority); 1089 } 1090 1091 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer, 1092 int Priority) { 1093 OrderGlobalInitsOrStermFinalizers Key(Priority, 1094 PrioritizedCXXStermFinalizers.size()); 1095 PrioritizedCXXStermFinalizers.push_back( 1096 std::make_pair(Key, StermFinalizer)); 1097 } 1098 1099 /// Create or return a runtime function declaration with the specified type 1100 /// and name. If \p AssumeConvergent is true, the call will have the 1101 /// convergent attribute added. 1102 llvm::FunctionCallee 1103 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, 1104 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1105 bool Local = false, bool AssumeConvergent = false); 1106 1107 /// Create a new runtime global variable with the specified type and name. 1108 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 1109 StringRef Name); 1110 1111 ///@name Custom Blocks Runtime Interfaces 1112 ///@{ 1113 1114 llvm::Constant *getNSConcreteGlobalBlock(); 1115 llvm::Constant *getNSConcreteStackBlock(); 1116 llvm::FunctionCallee getBlockObjectAssign(); 1117 llvm::FunctionCallee getBlockObjectDispose(); 1118 1119 ///@} 1120 1121 llvm::Function *getLLVMLifetimeStartFn(); 1122 llvm::Function *getLLVMLifetimeEndFn(); 1123 1124 // Make sure that this type is translated. 1125 void UpdateCompletedType(const TagDecl *TD); 1126 1127 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 1128 1129 /// Emit type info if type of an expression is a variably modified 1130 /// type. Also emit proper debug info for cast types. 1131 void EmitExplicitCastExprType(const ExplicitCastExpr *E, 1132 CodeGenFunction *CGF = nullptr); 1133 1134 /// Return the result of value-initializing the given type, i.e. a null 1135 /// expression of the given type. This is usually, but not always, an LLVM 1136 /// null constant. 1137 llvm::Constant *EmitNullConstant(QualType T); 1138 1139 /// Return a null constant appropriate for zero-initializing a base class with 1140 /// the given type. This is usually, but not always, an LLVM null constant. 1141 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 1142 1143 /// Emit a general error that something can't be done. 1144 void Error(SourceLocation loc, StringRef error); 1145 1146 /// Print out an error that codegen doesn't support the specified stmt yet. 1147 void ErrorUnsupported(const Stmt *S, const char *Type); 1148 1149 /// Print out an error that codegen doesn't support the specified decl yet. 1150 void ErrorUnsupported(const Decl *D, const char *Type); 1151 1152 /// Set the attributes on the LLVM function for the given decl and function 1153 /// info. This applies attributes necessary for handling the ABI as well as 1154 /// user specified attributes like section. 1155 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1156 const CGFunctionInfo &FI); 1157 1158 /// Set the LLVM function attributes (sext, zext, etc). 1159 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, 1160 llvm::Function *F, bool IsThunk); 1161 1162 /// Set the LLVM function attributes which only apply to a function 1163 /// definition. 1164 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 1165 1166 /// Set the LLVM function attributes that represent floating point 1167 /// environment. 1168 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F); 1169 1170 /// Return true iff the given type uses 'sret' when used as a return type. 1171 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 1172 1173 /// Return true iff the given type uses an argument slot when 'sret' is used 1174 /// as a return type. 1175 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI); 1176 1177 /// Return true iff the given type uses 'fpret' when used as a return type. 1178 bool ReturnTypeUsesFPRet(QualType ResultType); 1179 1180 /// Return true iff the given type uses 'fp2ret' when used as a return type. 1181 bool ReturnTypeUsesFP2Ret(QualType ResultType); 1182 1183 /// Get the LLVM attributes and calling convention to use for a particular 1184 /// function type. 1185 /// 1186 /// \param Name - The function name. 1187 /// \param Info - The function type information. 1188 /// \param CalleeInfo - The callee information these attributes are being 1189 /// constructed for. If valid, the attributes applied to this decl may 1190 /// contribute to the function attributes and calling convention. 1191 /// \param Attrs [out] - On return, the attribute list to use. 1192 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 1193 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, 1194 CGCalleeInfo CalleeInfo, 1195 llvm::AttributeList &Attrs, unsigned &CallingConv, 1196 bool AttrOnCallSite, bool IsThunk); 1197 1198 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as 1199 /// though we had emitted it ourselves. We remove any attributes on F that 1200 /// conflict with the attributes we add here. 1201 /// 1202 /// This is useful for adding attrs to bitcode modules that you want to link 1203 /// with but don't control, such as CUDA's libdevice. When linking with such 1204 /// a bitcode library, you might want to set e.g. its functions' 1205 /// "unsafe-fp-math" attribute to match the attr of the functions you're 1206 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of 1207 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM 1208 /// will propagate unsafe-fp-math=false up to every transitive caller of a 1209 /// function in the bitcode library! 1210 /// 1211 /// With the exception of fast-math attrs, this will only make the attributes 1212 /// on the function more conservative. But it's unsafe to call this on a 1213 /// function which relies on particular fast-math attributes for correctness. 1214 /// It's up to you to ensure that this is safe. 1215 void addDefaultFunctionDefinitionAttributes(llvm::Function &F); 1216 1217 /// Like the overload taking a `Function &`, but intended specifically 1218 /// for frontends that want to build on Clang's target-configuration logic. 1219 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs); 1220 1221 StringRef getMangledName(GlobalDecl GD); 1222 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD); 1223 1224 void EmitTentativeDefinition(const VarDecl *D); 1225 1226 void EmitExternalDeclaration(const VarDecl *D); 1227 1228 void EmitVTable(CXXRecordDecl *Class); 1229 1230 void RefreshTypeCacheForClass(const CXXRecordDecl *Class); 1231 1232 /// Appends Opts to the "llvm.linker.options" metadata value. 1233 void AppendLinkerOptions(StringRef Opts); 1234 1235 /// Appends a detect mismatch command to the linker options. 1236 void AddDetectMismatch(StringRef Name, StringRef Value); 1237 1238 /// Appends a dependent lib to the appropriate metadata value. 1239 void AddDependentLib(StringRef Lib); 1240 1241 1242 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD); 1243 1244 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) { 1245 F->setLinkage(getFunctionLinkage(GD)); 1246 } 1247 1248 /// Return the appropriate linkage for the vtable, VTT, and type information 1249 /// of the given class. 1250 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 1251 1252 /// Return the store size, in character units, of the given LLVM type. 1253 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 1254 1255 /// Returns LLVM linkage for a declarator. 1256 llvm::GlobalValue::LinkageTypes 1257 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, 1258 bool IsConstantVariable); 1259 1260 /// Returns LLVM linkage for a declarator. 1261 llvm::GlobalValue::LinkageTypes 1262 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant); 1263 1264 /// Emit all the global annotations. 1265 void EmitGlobalAnnotations(); 1266 1267 /// Emit an annotation string. 1268 llvm::Constant *EmitAnnotationString(StringRef Str); 1269 1270 /// Emit the annotation's translation unit. 1271 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 1272 1273 /// Emit the annotation line number. 1274 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 1275 1276 /// Emit additional args of the annotation. 1277 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr); 1278 1279 /// Generate the llvm::ConstantStruct which contains the annotation 1280 /// information for a given GlobalValue. The annotation struct is 1281 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 1282 /// GlobalValue being annotated. The second field is the constant string 1283 /// created from the AnnotateAttr's annotation. The third field is a constant 1284 /// string containing the name of the translation unit. The fourth field is 1285 /// the line number in the file of the annotated value declaration. 1286 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 1287 const AnnotateAttr *AA, 1288 SourceLocation L); 1289 1290 /// Add global annotations that are set on D, for the global GV. Those 1291 /// annotations are emitted during finalization of the LLVM code. 1292 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 1293 1294 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 1295 SourceLocation Loc) const; 1296 1297 bool isInNoSanitizeList(llvm::GlobalVariable *GV, SourceLocation Loc, 1298 QualType Ty, StringRef Category = StringRef()) const; 1299 1300 /// Imbue XRay attributes to a function, applying the always/never attribute 1301 /// lists in the process. Returns true if we did imbue attributes this way, 1302 /// false otherwise. 1303 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1304 StringRef Category = StringRef()) const; 1305 1306 /// Returns true if function at the given location should be excluded from 1307 /// profile instrumentation. 1308 bool isProfileInstrExcluded(llvm::Function *Fn, SourceLocation Loc) const; 1309 1310 SanitizerMetadata *getSanitizerMetadata() { 1311 return SanitizerMD.get(); 1312 } 1313 1314 void addDeferredVTable(const CXXRecordDecl *RD) { 1315 DeferredVTables.push_back(RD); 1316 } 1317 1318 /// Emit code for a single global function or var decl. Forward declarations 1319 /// are emitted lazily. 1320 void EmitGlobal(GlobalDecl D); 1321 1322 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 1323 1324 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 1325 1326 /// Set attributes which are common to any form of a global definition (alias, 1327 /// Objective-C method, function, global variable). 1328 /// 1329 /// NOTE: This should only be called for definitions. 1330 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV); 1331 1332 void addReplacement(StringRef Name, llvm::Constant *C); 1333 1334 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C); 1335 1336 /// Emit a code for threadprivate directive. 1337 /// \param D Threadprivate declaration. 1338 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D); 1339 1340 /// Emit a code for declare reduction construct. 1341 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 1342 CodeGenFunction *CGF = nullptr); 1343 1344 /// Emit a code for declare mapper construct. 1345 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, 1346 CodeGenFunction *CGF = nullptr); 1347 1348 /// Emit a code for requires directive. 1349 /// \param D Requires declaration 1350 void EmitOMPRequiresDecl(const OMPRequiresDecl *D); 1351 1352 /// Emit a code for the allocate directive. 1353 /// \param D The allocate declaration 1354 void EmitOMPAllocateDecl(const OMPAllocateDecl *D); 1355 1356 /// Returns whether the given record has hidden LTO visibility and therefore 1357 /// may participate in (single-module) CFI and whole-program vtable 1358 /// optimization. 1359 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD); 1360 1361 /// Returns whether the given record has public std LTO visibility 1362 /// and therefore may not participate in (single-module) CFI and whole-program 1363 /// vtable optimization. 1364 bool HasLTOVisibilityPublicStd(const CXXRecordDecl *RD); 1365 1366 /// Returns the vcall visibility of the given type. This is the scope in which 1367 /// a virtual function call could be made which ends up being dispatched to a 1368 /// member function of this class. This scope can be wider than the visibility 1369 /// of the class itself when the class has a more-visible dynamic base class. 1370 /// The client should pass in an empty Visited set, which is used to prevent 1371 /// redundant recursive processing. 1372 llvm::GlobalObject::VCallVisibility 1373 GetVCallVisibilityLevel(const CXXRecordDecl *RD, 1374 llvm::DenseSet<const CXXRecordDecl *> &Visited); 1375 1376 /// Emit type metadata for the given vtable using the given layout. 1377 void EmitVTableTypeMetadata(const CXXRecordDecl *RD, 1378 llvm::GlobalVariable *VTable, 1379 const VTableLayout &VTLayout); 1380 1381 /// Generate a cross-DSO type identifier for MD. 1382 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD); 1383 1384 /// Create a metadata identifier for the given type. This may either be an 1385 /// MDString (for external identifiers) or a distinct unnamed MDNode (for 1386 /// internal identifiers). 1387 llvm::Metadata *CreateMetadataIdentifierForType(QualType T); 1388 1389 /// Create a metadata identifier that is intended to be used to check virtual 1390 /// calls via a member function pointer. 1391 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T); 1392 1393 /// Create a metadata identifier for the generalization of the given type. 1394 /// This may either be an MDString (for external identifiers) or a distinct 1395 /// unnamed MDNode (for internal identifiers). 1396 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T); 1397 1398 /// Create and attach type metadata to the given function. 1399 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1400 llvm::Function *F); 1401 1402 /// Whether this function's return type has no side effects, and thus may 1403 /// be trivially discarded if it is unused. 1404 bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType); 1405 1406 /// Returns whether this module needs the "all-vtables" type identifier. 1407 bool NeedAllVtablesTypeId() const; 1408 1409 /// Create and attach type metadata for the given vtable. 1410 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, 1411 const CXXRecordDecl *RD); 1412 1413 /// Return a vector of most-base classes for RD. This is used to implement 1414 /// control flow integrity checks for member function pointers. 1415 /// 1416 /// A most-base class of a class C is defined as a recursive base class of C, 1417 /// including C itself, that does not have any bases. 1418 std::vector<const CXXRecordDecl *> 1419 getMostBaseClasses(const CXXRecordDecl *RD); 1420 1421 /// Get the declaration of std::terminate for the platform. 1422 llvm::FunctionCallee getTerminateFn(); 1423 1424 llvm::SanitizerStatReport &getSanStats(); 1425 1426 llvm::Value * 1427 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF); 1428 1429 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 1430 /// information in the program executable. The argument information stored 1431 /// includes the argument name, its type, the address and access qualifiers 1432 /// used. This helper can be used to generate metadata for source code kernel 1433 /// function as well as generated implicitly kernels. If a kernel is generated 1434 /// implicitly null value has to be passed to the last two parameters, 1435 /// otherwise all parameters must have valid non-null values. 1436 /// \param FN is a pointer to IR function being generated. 1437 /// \param FD is a pointer to function declaration if any. 1438 /// \param CGF is a pointer to CodeGenFunction that generates this function. 1439 void GenOpenCLArgMetadata(llvm::Function *FN, 1440 const FunctionDecl *FD = nullptr, 1441 CodeGenFunction *CGF = nullptr); 1442 1443 /// Get target specific null pointer. 1444 /// \param T is the LLVM type of the null pointer. 1445 /// \param QT is the clang QualType of the null pointer. 1446 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT); 1447 1448 CharUnits getNaturalTypeAlignment(QualType T, 1449 LValueBaseInfo *BaseInfo = nullptr, 1450 TBAAAccessInfo *TBAAInfo = nullptr, 1451 bool forPointeeType = false); 1452 CharUnits getNaturalPointeeTypeAlignment(QualType T, 1453 LValueBaseInfo *BaseInfo = nullptr, 1454 TBAAAccessInfo *TBAAInfo = nullptr); 1455 bool stopAutoInit(); 1456 1457 /// Print the postfix for externalized static variable for single source 1458 /// offloading languages CUDA and HIP. 1459 void printPostfixForExternalizedStaticVar(llvm::raw_ostream &OS) const; 1460 1461 private: 1462 llvm::Constant *GetOrCreateLLVMFunction( 1463 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable, 1464 bool DontDefer = false, bool IsThunk = false, 1465 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1466 ForDefinition_t IsForDefinition = NotForDefinition); 1467 1468 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD, 1469 llvm::Type *DeclTy, 1470 const FunctionDecl *FD); 1471 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD, 1472 StringRef &CurName); 1473 1474 llvm::Constant * 1475 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, 1476 const VarDecl *D, 1477 ForDefinition_t IsForDefinition = NotForDefinition); 1478 1479 bool GetCPUAndFeaturesAttributes(GlobalDecl GD, 1480 llvm::AttrBuilder &AttrBuilder); 1481 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO); 1482 1483 /// Set function attributes for a function declaration. 1484 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1485 bool IsIncompleteFunction, bool IsThunk); 1486 1487 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr); 1488 1489 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1490 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1491 1492 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false); 1493 void EmitExternalVarDeclaration(const VarDecl *D); 1494 void EmitAliasDefinition(GlobalDecl GD); 1495 void emitIFuncDefinition(GlobalDecl GD); 1496 void emitCPUDispatchDefinition(GlobalDecl GD); 1497 void EmitTargetClonesResolver(GlobalDecl GD); 1498 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 1499 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 1500 1501 // C++ related functions. 1502 1503 void EmitDeclContext(const DeclContext *DC); 1504 void EmitLinkageSpec(const LinkageSpecDecl *D); 1505 1506 /// Emit the function that initializes C++ thread_local variables. 1507 void EmitCXXThreadLocalInitFunc(); 1508 1509 /// Emit the function that initializes C++ globals. 1510 void EmitCXXGlobalInitFunc(); 1511 1512 /// Emit the function that performs cleanup associated with C++ globals. 1513 void EmitCXXGlobalCleanUpFunc(); 1514 1515 /// Emit the function that initializes the specified global (if PerformInit is 1516 /// true) and registers its destructor. 1517 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 1518 llvm::GlobalVariable *Addr, 1519 bool PerformInit); 1520 1521 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr, 1522 llvm::Function *InitFunc, InitSegAttr *ISA); 1523 1524 // FIXME: Hardcoding priority here is gross. 1525 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535, 1526 llvm::Constant *AssociatedData = nullptr); 1527 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535, 1528 bool IsDtorAttrFunc = false); 1529 1530 /// EmitCtorList - Generates a global array of functions and priorities using 1531 /// the given list and name. This array will have appending linkage and is 1532 /// suitable for use as a LLVM constructor or destructor array. Clears Fns. 1533 void EmitCtorList(CtorList &Fns, const char *GlobalName); 1534 1535 /// Emit any needed decls for which code generation was deferred. 1536 void EmitDeferred(); 1537 1538 /// Try to emit external vtables as available_externally if they have emitted 1539 /// all inlined virtual functions. It runs after EmitDeferred() and therefore 1540 /// is not allowed to create new references to things that need to be emitted 1541 /// lazily. 1542 void EmitVTablesOpportunistically(); 1543 1544 /// Call replaceAllUsesWith on all pairs in Replacements. 1545 void applyReplacements(); 1546 1547 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements. 1548 void applyGlobalValReplacements(); 1549 1550 void checkAliases(); 1551 1552 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit; 1553 1554 /// Register functions annotated with __attribute__((destructor)) using 1555 /// __cxa_atexit, if it is available, or atexit otherwise. 1556 void registerGlobalDtorsWithAtExit(); 1557 1558 // When using sinit and sterm functions, unregister 1559 // __attribute__((destructor)) annotated functions which were previously 1560 // registered by the atexit subroutine using unatexit. 1561 void unregisterGlobalDtorsWithUnAtExit(); 1562 1563 void emitMultiVersionFunctions(); 1564 1565 /// Emit any vtables which we deferred and still have a use for. 1566 void EmitDeferredVTables(); 1567 1568 /// Emit a dummy function that reference a CoreFoundation symbol when 1569 /// @available is used on Darwin. 1570 void emitAtAvailableLinkGuard(); 1571 1572 /// Emit the llvm.used and llvm.compiler.used metadata. 1573 void emitLLVMUsed(); 1574 1575 /// Emit the link options introduced by imported modules. 1576 void EmitModuleLinkOptions(); 1577 1578 /// Emit aliases for internal-linkage declarations inside "C" language 1579 /// linkage specifications, giving them the "expected" name where possible. 1580 void EmitStaticExternCAliases(); 1581 1582 void EmitDeclMetadata(); 1583 1584 /// Emit the Clang version as llvm.ident metadata. 1585 void EmitVersionIdentMetadata(); 1586 1587 /// Emit the Clang commandline as llvm.commandline metadata. 1588 void EmitCommandLineMetadata(); 1589 1590 /// Emit the module flag metadata used to pass options controlling the 1591 /// the backend to LLVM. 1592 void EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts); 1593 1594 /// Emits OpenCL specific Metadata e.g. OpenCL version. 1595 void EmitOpenCLMetadata(); 1596 1597 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and 1598 /// .gcda files in a way that persists in .bc files. 1599 void EmitCoverageFile(); 1600 1601 /// Determine whether the definition must be emitted; if this returns \c 1602 /// false, the definition can be emitted lazily if it's used. 1603 bool MustBeEmitted(const ValueDecl *D); 1604 1605 /// Determine whether the definition can be emitted eagerly, or should be 1606 /// delayed until the end of the translation unit. This is relevant for 1607 /// definitions whose linkage can change, e.g. implicit function instantions 1608 /// which may later be explicitly instantiated. 1609 bool MayBeEmittedEagerly(const ValueDecl *D); 1610 1611 /// Check whether we can use a "simpler", more core exceptions personality 1612 /// function. 1613 void SimplifyPersonality(); 1614 1615 /// Helper function for ConstructAttributeList and 1616 /// addDefaultFunctionDefinitionAttributes. Builds a set of function 1617 /// attributes to add to a function with the given properties. 1618 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone, 1619 bool AttrOnCallSite, 1620 llvm::AttrBuilder &FuncAttrs); 1621 1622 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 1623 StringRef Suffix); 1624 }; 1625 1626 } // end namespace CodeGen 1627 } // end namespace clang 1628 1629 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 1630