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