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/ProfileList.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Basic/XRayLists.h" 32 #include "clang/Lex/PreprocessorOptions.h" 33 #include "llvm/ADT/DenseMap.h" 34 #include "llvm/ADT/MapVector.h" 35 #include "llvm/ADT/SetVector.h" 36 #include "llvm/ADT/SmallPtrSet.h" 37 #include "llvm/ADT/StringMap.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/ValueHandle.h" 40 #include "llvm/Transforms/Utils/SanitizerStats.h" 41 #include <optional> 42 43 namespace llvm { 44 class Module; 45 class Constant; 46 class ConstantInt; 47 class Function; 48 class GlobalValue; 49 class DataLayout; 50 class FunctionType; 51 class LLVMContext; 52 class IndexedInstrProfReader; 53 54 namespace vfs { 55 class FileSystem; 56 } 57 } 58 59 namespace clang { 60 class ASTContext; 61 class AtomicType; 62 class FunctionDecl; 63 class IdentifierInfo; 64 class ObjCImplementationDecl; 65 class ObjCEncodeExpr; 66 class BlockExpr; 67 class CharUnits; 68 class Decl; 69 class Expr; 70 class Stmt; 71 class StringLiteral; 72 class NamedDecl; 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::DenseMap<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 struct GlobalInitPriorityCmp { 489 bool operator()(const GlobalInitData &LHS, 490 const GlobalInitData &RHS) const { 491 return LHS.first.priority < RHS.first.priority; 492 } 493 }; 494 495 /// Global variables with initializers whose order of initialization is set by 496 /// init_priority attribute. 497 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits; 498 499 /// Global destructor functions and arguments that need to run on termination. 500 /// When UseSinitAndSterm is set, it instead contains sterm finalizer 501 /// functions, which also run on unloading a shared library. 502 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, 503 llvm::Constant *> 504 CXXGlobalDtorsOrStermFinalizer_t; 505 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8> 506 CXXGlobalDtorsOrStermFinalizers; 507 508 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *> 509 StermFinalizerData; 510 511 struct StermFinalizerPriorityCmp { 512 bool operator()(const StermFinalizerData &LHS, 513 const StermFinalizerData &RHS) const { 514 return LHS.first.priority < RHS.first.priority; 515 } 516 }; 517 518 /// Global variables with sterm finalizers whose order of initialization is 519 /// set by init_priority attribute. 520 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers; 521 522 /// The complete set of modules that has been imported. 523 llvm::SetVector<clang::Module *> ImportedModules; 524 525 /// The set of modules for which the module initializers 526 /// have been emitted. 527 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers; 528 529 /// A vector of metadata strings for linker options. 530 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata; 531 532 /// A vector of metadata strings for dependent libraries for ELF. 533 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries; 534 535 /// @name Cache for Objective-C runtime types 536 /// @{ 537 538 /// Cached reference to the class for constant strings. This value has type 539 /// int * but is actually an Obj-C class pointer. 540 llvm::WeakTrackingVH CFConstantStringClassRef; 541 542 /// The type used to describe the state of a fast enumeration in 543 /// Objective-C's for..in loop. 544 QualType ObjCFastEnumerationStateType; 545 546 /// @} 547 548 /// Lazily create the Objective-C runtime 549 void createObjCRuntime(); 550 551 void createOpenCLRuntime(); 552 void createOpenMPRuntime(); 553 void createCUDARuntime(); 554 void createHLSLRuntime(); 555 556 bool isTriviallyRecursive(const FunctionDecl *F); 557 bool shouldEmitFunction(GlobalDecl GD); 558 bool shouldOpportunisticallyEmitVTables(); 559 /// Map used to be sure we don't emit the same CompoundLiteral twice. 560 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *> 561 EmittedCompoundLiterals; 562 563 /// Map of the global blocks we've emitted, so that we don't have to re-emit 564 /// them if the constexpr evaluator gets aggressive. 565 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks; 566 567 /// @name Cache for Blocks Runtime Globals 568 /// @{ 569 570 llvm::Constant *NSConcreteGlobalBlock = nullptr; 571 llvm::Constant *NSConcreteStackBlock = nullptr; 572 573 llvm::FunctionCallee BlockObjectAssign = nullptr; 574 llvm::FunctionCallee BlockObjectDispose = nullptr; 575 576 llvm::Type *BlockDescriptorType = nullptr; 577 llvm::Type *GenericBlockLiteralType = nullptr; 578 579 struct { 580 int GlobalUniqueCount; 581 } Block; 582 583 GlobalDecl initializedGlobalDecl; 584 585 /// @} 586 587 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>) 588 llvm::Function *LifetimeStartFn = nullptr; 589 590 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>) 591 llvm::Function *LifetimeEndFn = nullptr; 592 593 std::unique_ptr<SanitizerMetadata> SanitizerMD; 594 595 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls; 596 597 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping; 598 599 /// Mapping from canonical types to their metadata identifiers. We need to 600 /// maintain this mapping because identifiers may be formed from distinct 601 /// MDNodes. 602 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap; 603 MetadataTypeMap MetadataIdMap; 604 MetadataTypeMap VirtualMetadataIdMap; 605 MetadataTypeMap GeneralizedMetadataIdMap; 606 607 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function 608 // when used with -fincremental-extensions. 609 std::pair<std::unique_ptr<CodeGenFunction>, const TopLevelStmtDecl *> 610 GlobalTopLevelStmtBlockInFlight; 611 612 public: 613 CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 614 const HeaderSearchOptions &headersearchopts, 615 const PreprocessorOptions &ppopts, 616 const CodeGenOptions &CodeGenOpts, llvm::Module &M, 617 DiagnosticsEngine &Diags, 618 CoverageSourceInfo *CoverageInfo = nullptr); 619 620 ~CodeGenModule(); 621 622 void clear(); 623 624 /// Finalize LLVM code generation. 625 void Release(); 626 627 /// Return true if we should emit location information for expressions. 628 bool getExpressionLocationsEnabled() const; 629 630 /// Return a reference to the configured Objective-C runtime. 631 CGObjCRuntime &getObjCRuntime() { 632 if (!ObjCRuntime) createObjCRuntime(); 633 return *ObjCRuntime; 634 } 635 636 /// Return true iff an Objective-C runtime has been configured. 637 bool hasObjCRuntime() { return !!ObjCRuntime; } 638 639 const std::string &getModuleNameHash() const { return ModuleNameHash; } 640 641 /// Return a reference to the configured OpenCL runtime. 642 CGOpenCLRuntime &getOpenCLRuntime() { 643 assert(OpenCLRuntime != nullptr); 644 return *OpenCLRuntime; 645 } 646 647 /// Return a reference to the configured OpenMP runtime. 648 CGOpenMPRuntime &getOpenMPRuntime() { 649 assert(OpenMPRuntime != nullptr); 650 return *OpenMPRuntime; 651 } 652 653 /// Return a reference to the configured CUDA runtime. 654 CGCUDARuntime &getCUDARuntime() { 655 assert(CUDARuntime != nullptr); 656 return *CUDARuntime; 657 } 658 659 /// Return a reference to the configured HLSL runtime. 660 CGHLSLRuntime &getHLSLRuntime() { 661 assert(HLSLRuntime != nullptr); 662 return *HLSLRuntime; 663 } 664 665 ObjCEntrypoints &getObjCEntrypoints() const { 666 assert(ObjCData != nullptr); 667 return *ObjCData; 668 } 669 670 // Version checking functions, used to implement ObjC's @available: 671 // i32 @__isOSVersionAtLeast(i32, i32, i32) 672 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr; 673 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32) 674 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr; 675 676 InstrProfStats &getPGOStats() { return PGOStats; } 677 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); } 678 679 CoverageMappingModuleGen *getCoverageMapping() const { 680 return CoverageMapping.get(); 681 } 682 683 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) { 684 return StaticLocalDeclMap[D]; 685 } 686 void setStaticLocalDeclAddress(const VarDecl *D, 687 llvm::Constant *C) { 688 StaticLocalDeclMap[D] = C; 689 } 690 691 llvm::Constant * 692 getOrCreateStaticVarDecl(const VarDecl &D, 693 llvm::GlobalValue::LinkageTypes Linkage); 694 695 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) { 696 return StaticLocalDeclGuardMap[D]; 697 } 698 void setStaticLocalDeclGuardAddress(const VarDecl *D, 699 llvm::GlobalVariable *C) { 700 StaticLocalDeclGuardMap[D] = C; 701 } 702 703 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant, 704 CharUnits Align); 705 706 bool lookupRepresentativeDecl(StringRef MangledName, 707 GlobalDecl &Result) const; 708 709 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 710 return AtomicSetterHelperFnMap[Ty]; 711 } 712 void setAtomicSetterHelperFnMap(QualType Ty, 713 llvm::Constant *Fn) { 714 AtomicSetterHelperFnMap[Ty] = Fn; 715 } 716 717 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 718 return AtomicGetterHelperFnMap[Ty]; 719 } 720 void setAtomicGetterHelperFnMap(QualType Ty, 721 llvm::Constant *Fn) { 722 AtomicGetterHelperFnMap[Ty] = Fn; 723 } 724 725 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) { 726 return TypeDescriptorMap[Ty]; 727 } 728 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) { 729 TypeDescriptorMap[Ty] = C; 730 } 731 732 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); } 733 734 llvm::MDNode *getNoObjCARCExceptionsMetadata() { 735 if (!NoObjCARCExceptionsMetadata) 736 NoObjCARCExceptionsMetadata = 737 llvm::MDNode::get(getLLVMContext(), std::nullopt); 738 return NoObjCARCExceptionsMetadata; 739 } 740 741 ASTContext &getContext() const { return Context; } 742 const LangOptions &getLangOpts() const { return LangOpts; } 743 const IntrusiveRefCntPtr<llvm::vfs::FileSystem> &getFileSystem() const { 744 return FS; 745 } 746 const HeaderSearchOptions &getHeaderSearchOpts() 747 const { return HeaderSearchOpts; } 748 const PreprocessorOptions &getPreprocessorOpts() 749 const { return PreprocessorOpts; } 750 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 751 llvm::Module &getModule() const { return TheModule; } 752 DiagnosticsEngine &getDiags() const { return Diags; } 753 const llvm::DataLayout &getDataLayout() const { 754 return TheModule.getDataLayout(); 755 } 756 const TargetInfo &getTarget() const { return Target; } 757 const llvm::Triple &getTriple() const { return Target.getTriple(); } 758 bool supportsCOMDAT() const; 759 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO); 760 761 CGCXXABI &getCXXABI() const { return *ABI; } 762 llvm::LLVMContext &getLLVMContext() { return VMContext; } 763 764 bool shouldUseTBAA() const { return TBAA != nullptr; } 765 766 const TargetCodeGenInfo &getTargetCodeGenInfo(); 767 768 CodeGenTypes &getTypes() { return Types; } 769 770 CodeGenVTables &getVTables() { return VTables; } 771 772 ItaniumVTableContext &getItaniumVTableContext() { 773 return VTables.getItaniumVTableContext(); 774 } 775 776 const ItaniumVTableContext &getItaniumVTableContext() const { 777 return VTables.getItaniumVTableContext(); 778 } 779 780 MicrosoftVTableContext &getMicrosoftVTableContext() { 781 return VTables.getMicrosoftVTableContext(); 782 } 783 784 CtorList &getGlobalCtors() { return GlobalCtors; } 785 CtorList &getGlobalDtors() { return GlobalDtors; } 786 787 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of 788 /// the given type. 789 llvm::MDNode *getTBAATypeInfo(QualType QTy); 790 791 /// getTBAAAccessInfo - Get TBAA information that describes an access to 792 /// an object of the given type. 793 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType); 794 795 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an 796 /// access to a virtual table pointer. 797 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType); 798 799 llvm::MDNode *getTBAAStructInfo(QualType QTy); 800 801 /// getTBAABaseTypeInfo - Get metadata that describes the given base access 802 /// type. Return null if the type is not suitable for use in TBAA access tags. 803 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy); 804 805 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access. 806 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info); 807 808 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of 809 /// type casts. 810 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 811 TBAAAccessInfo TargetInfo); 812 813 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the 814 /// purposes of conditional operator. 815 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 816 TBAAAccessInfo InfoB); 817 818 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the 819 /// purposes of memory transfer calls. 820 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 821 TBAAAccessInfo SrcInfo); 822 823 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given 824 /// base lvalue. 825 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) { 826 if (Base.getTBAAInfo().isMayAlias()) 827 return TBAAAccessInfo::getMayAliasInfo(); 828 return getTBAAAccessInfo(AccessType); 829 } 830 831 bool isPaddedAtomicType(QualType type); 832 bool isPaddedAtomicType(const AtomicType *type); 833 834 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag. 835 void DecorateInstructionWithTBAA(llvm::Instruction *Inst, 836 TBAAAccessInfo TBAAInfo); 837 838 /// Adds !invariant.barrier !tag to instruction 839 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, 840 const CXXRecordDecl *RD); 841 842 /// Emit the given number of characters as a value of type size_t. 843 llvm::ConstantInt *getSize(CharUnits numChars); 844 845 /// Set the visibility for the given LLVM GlobalValue. 846 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 847 848 void setDSOLocal(llvm::GlobalValue *GV) const; 849 850 bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const { 851 return getLangOpts().hasDefaultVisibilityExportMapping() && D && 852 (D->getLinkageAndVisibility().getVisibility() == 853 DefaultVisibility) && 854 (getLangOpts().isAllDefaultVisibilityExportMapping() || 855 (getLangOpts().isExplicitDefaultVisibilityExportMapping() && 856 D->getLinkageAndVisibility().isVisibilityExplicit())); 857 } 858 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const; 859 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const; 860 /// Set visibility, dllimport/dllexport and dso_local. 861 /// This must be called after dllimport/dllexport is set. 862 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const; 863 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const; 864 865 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const; 866 867 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local 868 /// variable declaration D. 869 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const; 870 871 /// Get LLVM TLS mode from CodeGenOptions. 872 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const; 873 874 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 875 switch (V) { 876 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 877 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 878 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 879 } 880 llvm_unreachable("unknown visibility!"); 881 } 882 883 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, 884 ForDefinition_t IsForDefinition 885 = NotForDefinition); 886 887 /// Will return a global variable of the given type. If a variable with a 888 /// different type already exists then a new variable with the right type 889 /// will be created and all uses of the old variable will be replaced with a 890 /// bitcast to the new variable. 891 llvm::GlobalVariable * 892 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 893 llvm::GlobalValue::LinkageTypes Linkage, 894 llvm::Align Alignment); 895 896 llvm::Function *CreateGlobalInitOrCleanUpFunction( 897 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, 898 SourceLocation Loc = SourceLocation(), bool TLS = false, 899 llvm::GlobalVariable::LinkageTypes Linkage = 900 llvm::GlobalVariable::InternalLinkage); 901 902 /// Return the AST address space of the underlying global variable for D, as 903 /// determined by its declaration. Normally this is the same as the address 904 /// space of D's type, but in CUDA, address spaces are associated with 905 /// declarations, not types. If D is nullptr, return the default address 906 /// space for global variable. 907 /// 908 /// For languages without explicit address spaces, if D has default address 909 /// space, target-specific global or constant address space may be returned. 910 LangAS GetGlobalVarAddressSpace(const VarDecl *D); 911 912 /// Return the AST address space of constant literal, which is used to emit 913 /// the constant literal as global variable in LLVM IR. 914 /// Note: This is not necessarily the address space of the constant literal 915 /// in AST. For address space agnostic language, e.g. C++, constant literal 916 /// in AST is always in default address space. 917 LangAS GetGlobalConstantAddressSpace() const; 918 919 /// Return the llvm::Constant for the address of the given global variable. 920 /// If Ty is non-null and if the global doesn't exist, then it will be created 921 /// with the specified type instead of whatever the normal requested type 922 /// would be. If IsForDefinition is true, it is guaranteed that an actual 923 /// global with type Ty will be returned, not conversion of a variable with 924 /// the same mangled name but some other type. 925 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 926 llvm::Type *Ty = nullptr, 927 ForDefinition_t IsForDefinition 928 = NotForDefinition); 929 930 /// Return the address of the given function. If Ty is non-null, then this 931 /// function will use the specified type if it has to create it. 932 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr, 933 bool ForVTable = false, 934 bool DontDefer = false, 935 ForDefinition_t IsForDefinition 936 = NotForDefinition); 937 938 // Return the function body address of the given function. 939 llvm::Constant *GetFunctionStart(const ValueDecl *Decl); 940 941 // Return whether RTTI information should be emitted for this target. 942 bool shouldEmitRTTI(bool ForEH = false) { 943 return (ForEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice && 944 !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && 945 getTriple().isNVPTX()); 946 } 947 948 /// Get the address of the RTTI descriptor for the given type. 949 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 950 951 /// Get the address of a GUID. 952 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD); 953 954 /// Get the address of a UnnamedGlobalConstant 955 ConstantAddress 956 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD); 957 958 /// Get the address of a template parameter object. 959 ConstantAddress 960 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO); 961 962 /// Get the address of the thunk for the given global decl. 963 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, 964 GlobalDecl GD); 965 966 /// Get a reference to the target of VD. 967 ConstantAddress GetWeakRefReference(const ValueDecl *VD); 968 969 /// Returns the assumed alignment of an opaque pointer to the given class. 970 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD); 971 972 /// Returns the minimum object size for an object of the given class type 973 /// (or a class derived from it). 974 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD); 975 976 /// Returns the minimum object size for an object of the given type. 977 CharUnits getMinimumObjectSize(QualType Ty) { 978 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) 979 return getMinimumClassObjectSize(RD); 980 return getContext().getTypeSizeInChars(Ty); 981 } 982 983 /// Returns the assumed alignment of a virtual base of a class. 984 CharUnits getVBaseAlignment(CharUnits DerivedAlign, 985 const CXXRecordDecl *Derived, 986 const CXXRecordDecl *VBase); 987 988 /// Given a class pointer with an actual known alignment, and the 989 /// expected alignment of an object at a dynamic offset w.r.t that 990 /// pointer, return the alignment to assume at the offset. 991 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign, 992 const CXXRecordDecl *Class, 993 CharUnits ExpectedTargetAlign); 994 995 CharUnits 996 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, 997 CastExpr::path_const_iterator Start, 998 CastExpr::path_const_iterator End); 999 1000 /// Returns the offset from a derived class to a class. Returns null if the 1001 /// offset is 0. 1002 llvm::Constant * 1003 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 1004 CastExpr::path_const_iterator PathBegin, 1005 CastExpr::path_const_iterator PathEnd); 1006 1007 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache; 1008 1009 /// Fetches the global unique block count. 1010 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 1011 1012 /// Fetches the type of a generic block descriptor. 1013 llvm::Type *getBlockDescriptorType(); 1014 1015 /// The type of a generic block literal. 1016 llvm::Type *getGenericBlockLiteralType(); 1017 1018 /// Gets the address of a block which requires no captures. 1019 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name); 1020 1021 /// Returns the address of a block which requires no caputres, or null if 1022 /// we've yet to emit the block for BE. 1023 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) { 1024 return EmittedGlobalBlocks.lookup(BE); 1025 } 1026 1027 /// Notes that BE's global block is available via Addr. Asserts that BE 1028 /// isn't already emitted. 1029 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr); 1030 1031 /// Return a pointer to a constant CFString object for the given string. 1032 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal); 1033 1034 /// Return a constant array for the given string. 1035 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 1036 1037 /// Return a pointer to a constant array for the given string literal. 1038 ConstantAddress 1039 GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 1040 StringRef Name = ".str"); 1041 1042 /// Return a pointer to a constant array for the given ObjCEncodeExpr node. 1043 ConstantAddress 1044 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 1045 1046 /// Returns a pointer to a character array containing the literal and a 1047 /// terminating '\0' character. The result has pointer to array type. 1048 /// 1049 /// \param GlobalName If provided, the name to use for the global (if one is 1050 /// created). 1051 ConstantAddress 1052 GetAddrOfConstantCString(const std::string &Str, 1053 const char *GlobalName = nullptr); 1054 1055 /// Returns a pointer to a constant global variable for the given file-scope 1056 /// compound literal expression. 1057 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 1058 1059 /// If it's been emitted already, returns the GlobalVariable corresponding to 1060 /// a compound literal. Otherwise, returns null. 1061 llvm::GlobalVariable * 1062 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E); 1063 1064 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already 1065 /// emitted. 1066 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE, 1067 llvm::GlobalVariable *GV); 1068 1069 /// Returns a pointer to a global variable representing a temporary 1070 /// with static or thread storage duration. 1071 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, 1072 const Expr *Inner); 1073 1074 /// Retrieve the record type that describes the state of an 1075 /// Objective-C fast enumeration loop (for..in). 1076 QualType getObjCFastEnumerationStateType(); 1077 1078 // Produce code for this constructor/destructor. This method doesn't try 1079 // to apply any ABI rules about which other constructors/destructors 1080 // are needed or if they are alias to each other. 1081 llvm::Function *codegenCXXStructor(GlobalDecl GD); 1082 1083 /// Return the address of the constructor/destructor of the given type. 1084 llvm::Constant * 1085 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 1086 llvm::FunctionType *FnType = nullptr, 1087 bool DontDefer = false, 1088 ForDefinition_t IsForDefinition = NotForDefinition) { 1089 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType, 1090 DontDefer, 1091 IsForDefinition) 1092 .getCallee()); 1093 } 1094 1095 llvm::FunctionCallee getAddrAndTypeOfCXXStructor( 1096 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 1097 llvm::FunctionType *FnType = nullptr, bool DontDefer = false, 1098 ForDefinition_t IsForDefinition = NotForDefinition); 1099 1100 /// Given a builtin id for a function like "__builtin_fabsf", return a 1101 /// Function* for "fabsf". 1102 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD, 1103 unsigned BuiltinID); 1104 1105 llvm::Function *getIntrinsic(unsigned IID, 1106 ArrayRef<llvm::Type *> Tys = std::nullopt); 1107 1108 /// Emit code for a single top level declaration. 1109 void EmitTopLevelDecl(Decl *D); 1110 1111 /// Stored a deferred empty coverage mapping for an unused 1112 /// and thus uninstrumented top level declaration. 1113 void AddDeferredUnusedCoverageMapping(Decl *D); 1114 1115 /// Remove the deferred empty coverage mapping as this 1116 /// declaration is actually instrumented. 1117 void ClearUnusedCoverageMapping(const Decl *D); 1118 1119 /// Emit all the deferred coverage mappings 1120 /// for the uninstrumented functions. 1121 void EmitDeferredUnusedCoverageMappings(); 1122 1123 /// Emit an alias for "main" if it has no arguments (needed for wasm). 1124 void EmitMainVoidAlias(); 1125 1126 /// Tell the consumer that this variable has been instantiated. 1127 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD); 1128 1129 /// If the declaration has internal linkage but is inside an 1130 /// extern "C" linkage specification, prepare to emit an alias for it 1131 /// to the expected name. 1132 template<typename SomeDecl> 1133 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV); 1134 1135 /// Add a global to a list to be added to the llvm.used metadata. 1136 void addUsedGlobal(llvm::GlobalValue *GV); 1137 1138 /// Add a global to a list to be added to the llvm.compiler.used metadata. 1139 void addCompilerUsedGlobal(llvm::GlobalValue *GV); 1140 1141 /// Add a global to a list to be added to the llvm.compiler.used metadata. 1142 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV); 1143 1144 /// Add a destructor and object to add to the C++ global destructor function. 1145 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) { 1146 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(), 1147 DtorFn.getCallee(), Object); 1148 } 1149 1150 /// Add an sterm finalizer to the C++ global cleanup function. 1151 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) { 1152 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(), 1153 DtorFn.getCallee(), nullptr); 1154 } 1155 1156 /// Add an sterm finalizer to its own llvm.global_dtors entry. 1157 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer, 1158 int Priority) { 1159 AddGlobalDtor(StermFinalizer, Priority); 1160 } 1161 1162 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer, 1163 int Priority) { 1164 OrderGlobalInitsOrStermFinalizers Key(Priority, 1165 PrioritizedCXXStermFinalizers.size()); 1166 PrioritizedCXXStermFinalizers.push_back( 1167 std::make_pair(Key, StermFinalizer)); 1168 } 1169 1170 /// Create or return a runtime function declaration with the specified type 1171 /// and name. If \p AssumeConvergent is true, the call will have the 1172 /// convergent attribute added. 1173 llvm::FunctionCallee 1174 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, 1175 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1176 bool Local = false, bool AssumeConvergent = false); 1177 1178 /// Create a new runtime global variable with the specified type and name. 1179 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 1180 StringRef Name); 1181 1182 ///@name Custom Blocks Runtime Interfaces 1183 ///@{ 1184 1185 llvm::Constant *getNSConcreteGlobalBlock(); 1186 llvm::Constant *getNSConcreteStackBlock(); 1187 llvm::FunctionCallee getBlockObjectAssign(); 1188 llvm::FunctionCallee getBlockObjectDispose(); 1189 1190 ///@} 1191 1192 llvm::Function *getLLVMLifetimeStartFn(); 1193 llvm::Function *getLLVMLifetimeEndFn(); 1194 1195 // Make sure that this type is translated. 1196 void UpdateCompletedType(const TagDecl *TD); 1197 1198 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 1199 1200 /// Emit type info if type of an expression is a variably modified 1201 /// type. Also emit proper debug info for cast types. 1202 void EmitExplicitCastExprType(const ExplicitCastExpr *E, 1203 CodeGenFunction *CGF = nullptr); 1204 1205 /// Return the result of value-initializing the given type, i.e. a null 1206 /// expression of the given type. This is usually, but not always, an LLVM 1207 /// null constant. 1208 llvm::Constant *EmitNullConstant(QualType T); 1209 1210 /// Return a null constant appropriate for zero-initializing a base class with 1211 /// the given type. This is usually, but not always, an LLVM null constant. 1212 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 1213 1214 /// Emit a general error that something can't be done. 1215 void Error(SourceLocation loc, StringRef error); 1216 1217 /// Print out an error that codegen doesn't support the specified stmt yet. 1218 void ErrorUnsupported(const Stmt *S, const char *Type); 1219 1220 /// Print out an error that codegen doesn't support the specified decl yet. 1221 void ErrorUnsupported(const Decl *D, const char *Type); 1222 1223 /// Set the attributes on the LLVM function for the given decl and function 1224 /// info. This applies attributes necessary for handling the ABI as well as 1225 /// user specified attributes like section. 1226 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1227 const CGFunctionInfo &FI); 1228 1229 /// Set the LLVM function attributes (sext, zext, etc). 1230 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, 1231 llvm::Function *F, bool IsThunk); 1232 1233 /// Set the LLVM function attributes which only apply to a function 1234 /// definition. 1235 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 1236 1237 /// Set the LLVM function attributes that represent floating point 1238 /// environment. 1239 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F); 1240 1241 /// Return true iff the given type uses 'sret' when used as a return type. 1242 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 1243 1244 /// Return true iff the given type has `inreg` set. 1245 bool ReturnTypeHasInReg(const CGFunctionInfo &FI); 1246 1247 /// Return true iff the given type uses an argument slot when 'sret' is used 1248 /// as a return type. 1249 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI); 1250 1251 /// Return true iff the given type uses 'fpret' when used as a return type. 1252 bool ReturnTypeUsesFPRet(QualType ResultType); 1253 1254 /// Return true iff the given type uses 'fp2ret' when used as a return type. 1255 bool ReturnTypeUsesFP2Ret(QualType ResultType); 1256 1257 /// Get the LLVM attributes and calling convention to use for a particular 1258 /// function type. 1259 /// 1260 /// \param Name - The function name. 1261 /// \param Info - The function type information. 1262 /// \param CalleeInfo - The callee information these attributes are being 1263 /// constructed for. If valid, the attributes applied to this decl may 1264 /// contribute to the function attributes and calling convention. 1265 /// \param Attrs [out] - On return, the attribute list to use. 1266 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 1267 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, 1268 CGCalleeInfo CalleeInfo, 1269 llvm::AttributeList &Attrs, unsigned &CallingConv, 1270 bool AttrOnCallSite, bool IsThunk); 1271 1272 /// Adjust Memory attribute to ensure that the BE gets the right attribute 1273 // in order to generate the library call or the intrinsic for the function 1274 // name 'Name'. 1275 void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo, 1276 llvm::AttributeList &Attrs); 1277 1278 /// Like the overload taking a `Function &`, but intended specifically 1279 /// for frontends that want to build on Clang's target-configuration logic. 1280 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs); 1281 1282 StringRef getMangledName(GlobalDecl GD); 1283 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD); 1284 const GlobalDecl getMangledNameDecl(StringRef); 1285 1286 void EmitTentativeDefinition(const VarDecl *D); 1287 1288 void EmitExternalDeclaration(const VarDecl *D); 1289 1290 void EmitVTable(CXXRecordDecl *Class); 1291 1292 void RefreshTypeCacheForClass(const CXXRecordDecl *Class); 1293 1294 /// Appends Opts to the "llvm.linker.options" metadata value. 1295 void AppendLinkerOptions(StringRef Opts); 1296 1297 /// Appends a detect mismatch command to the linker options. 1298 void AddDetectMismatch(StringRef Name, StringRef Value); 1299 1300 /// Appends a dependent lib to the appropriate metadata value. 1301 void AddDependentLib(StringRef Lib); 1302 1303 1304 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD); 1305 1306 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) { 1307 F->setLinkage(getFunctionLinkage(GD)); 1308 } 1309 1310 /// Return the appropriate linkage for the vtable, VTT, and type information 1311 /// of the given class. 1312 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 1313 1314 /// Return the store size, in character units, of the given LLVM type. 1315 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 1316 1317 /// Returns LLVM linkage for a declarator. 1318 llvm::GlobalValue::LinkageTypes 1319 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage); 1320 1321 /// Returns LLVM linkage for a declarator. 1322 llvm::GlobalValue::LinkageTypes 1323 getLLVMLinkageVarDefinition(const VarDecl *VD); 1324 1325 /// Emit all the global annotations. 1326 void EmitGlobalAnnotations(); 1327 1328 /// Emit an annotation string. 1329 llvm::Constant *EmitAnnotationString(StringRef Str); 1330 1331 /// Emit the annotation's translation unit. 1332 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 1333 1334 /// Emit the annotation line number. 1335 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 1336 1337 /// Emit additional args of the annotation. 1338 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr); 1339 1340 /// Generate the llvm::ConstantStruct which contains the annotation 1341 /// information for a given GlobalValue. The annotation struct is 1342 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 1343 /// GlobalValue being annotated. The second field is the constant string 1344 /// created from the AnnotateAttr's annotation. The third field is a constant 1345 /// string containing the name of the translation unit. The fourth field is 1346 /// the line number in the file of the annotated value declaration. 1347 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 1348 const AnnotateAttr *AA, 1349 SourceLocation L); 1350 1351 /// Add global annotations that are set on D, for the global GV. Those 1352 /// annotations are emitted during finalization of the LLVM code. 1353 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 1354 1355 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 1356 SourceLocation Loc) const; 1357 1358 bool isInNoSanitizeList(SanitizerMask Kind, llvm::GlobalVariable *GV, 1359 SourceLocation Loc, QualType Ty, 1360 StringRef Category = StringRef()) const; 1361 1362 /// Imbue XRay attributes to a function, applying the always/never attribute 1363 /// lists in the process. Returns true if we did imbue attributes this way, 1364 /// false otherwise. 1365 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1366 StringRef Category = StringRef()) const; 1367 1368 /// \returns true if \p Fn at \p Loc should be excluded from profile 1369 /// instrumentation by the SCL passed by \p -fprofile-list. 1370 ProfileList::ExclusionType 1371 isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const; 1372 1373 /// \returns true if \p Fn at \p Loc should be excluded from profile 1374 /// instrumentation. 1375 ProfileList::ExclusionType 1376 isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 1377 SourceLocation Loc) const; 1378 1379 SanitizerMetadata *getSanitizerMetadata() { 1380 return SanitizerMD.get(); 1381 } 1382 1383 void addDeferredVTable(const CXXRecordDecl *RD) { 1384 DeferredVTables.push_back(RD); 1385 } 1386 1387 /// Emit code for a single global function or var decl. Forward declarations 1388 /// are emitted lazily. 1389 void EmitGlobal(GlobalDecl D); 1390 1391 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 1392 1393 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 1394 1395 /// Set attributes which are common to any form of a global definition (alias, 1396 /// Objective-C method, function, global variable). 1397 /// 1398 /// NOTE: This should only be called for definitions. 1399 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV); 1400 1401 void addReplacement(StringRef Name, llvm::Constant *C); 1402 1403 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C); 1404 1405 /// Emit a code for threadprivate directive. 1406 /// \param D Threadprivate declaration. 1407 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D); 1408 1409 /// Emit a code for declare reduction construct. 1410 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 1411 CodeGenFunction *CGF = nullptr); 1412 1413 /// Emit a code for declare mapper construct. 1414 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, 1415 CodeGenFunction *CGF = nullptr); 1416 1417 /// Emit a code for requires directive. 1418 /// \param D Requires declaration 1419 void EmitOMPRequiresDecl(const OMPRequiresDecl *D); 1420 1421 /// Emit a code for the allocate directive. 1422 /// \param D The allocate declaration 1423 void EmitOMPAllocateDecl(const OMPAllocateDecl *D); 1424 1425 /// Return the alignment specified in an allocate directive, if present. 1426 std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD); 1427 1428 /// Returns whether the given record has hidden LTO visibility and therefore 1429 /// may participate in (single-module) CFI and whole-program vtable 1430 /// optimization. 1431 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD); 1432 1433 /// Returns whether the given record has public LTO visibility (regardless of 1434 /// -lto-whole-program-visibility) and therefore may not participate in 1435 /// (single-module) CFI and whole-program vtable optimization. 1436 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD); 1437 1438 /// Returns the vcall visibility of the given type. This is the scope in which 1439 /// a virtual function call could be made which ends up being dispatched to a 1440 /// member function of this class. This scope can be wider than the visibility 1441 /// of the class itself when the class has a more-visible dynamic base class. 1442 /// The client should pass in an empty Visited set, which is used to prevent 1443 /// redundant recursive processing. 1444 llvm::GlobalObject::VCallVisibility 1445 GetVCallVisibilityLevel(const CXXRecordDecl *RD, 1446 llvm::DenseSet<const CXXRecordDecl *> &Visited); 1447 1448 /// Emit type metadata for the given vtable using the given layout. 1449 void EmitVTableTypeMetadata(const CXXRecordDecl *RD, 1450 llvm::GlobalVariable *VTable, 1451 const VTableLayout &VTLayout); 1452 1453 llvm::Type *getVTableComponentType() const; 1454 1455 /// Generate a cross-DSO type identifier for MD. 1456 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD); 1457 1458 /// Generate a KCFI type identifier for T. 1459 llvm::ConstantInt *CreateKCFITypeId(QualType T); 1460 1461 /// Create a metadata identifier for the given type. This may either be an 1462 /// MDString (for external identifiers) or a distinct unnamed MDNode (for 1463 /// internal identifiers). 1464 llvm::Metadata *CreateMetadataIdentifierForType(QualType T); 1465 1466 /// Create a metadata identifier that is intended to be used to check virtual 1467 /// calls via a member function pointer. 1468 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T); 1469 1470 /// Create a metadata identifier for the generalization of the given type. 1471 /// This may either be an MDString (for external identifiers) or a distinct 1472 /// unnamed MDNode (for internal identifiers). 1473 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T); 1474 1475 /// Create and attach type metadata to the given function. 1476 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1477 llvm::Function *F); 1478 1479 /// Set type metadata to the given function. 1480 void setKCFIType(const FunctionDecl *FD, llvm::Function *F); 1481 1482 /// Emit KCFI type identifier constants and remove unused identifiers. 1483 void finalizeKCFITypes(); 1484 1485 /// Whether this function's return type has no side effects, and thus may 1486 /// be trivially discarded if it is unused. 1487 bool MayDropFunctionReturn(const ASTContext &Context, 1488 QualType ReturnType) const; 1489 1490 /// Returns whether this module needs the "all-vtables" type identifier. 1491 bool NeedAllVtablesTypeId() const; 1492 1493 /// Create and attach type metadata for the given vtable. 1494 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, 1495 const CXXRecordDecl *RD); 1496 1497 /// Return a vector of most-base classes for RD. This is used to implement 1498 /// control flow integrity checks for member function pointers. 1499 /// 1500 /// A most-base class of a class C is defined as a recursive base class of C, 1501 /// including C itself, that does not have any bases. 1502 SmallVector<const CXXRecordDecl *, 0> 1503 getMostBaseClasses(const CXXRecordDecl *RD); 1504 1505 /// Get the declaration of std::terminate for the platform. 1506 llvm::FunctionCallee getTerminateFn(); 1507 1508 llvm::SanitizerStatReport &getSanStats(); 1509 1510 llvm::Value * 1511 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF); 1512 1513 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 1514 /// information in the program executable. The argument information stored 1515 /// includes the argument name, its type, the address and access qualifiers 1516 /// used. This helper can be used to generate metadata for source code kernel 1517 /// function as well as generated implicitly kernels. If a kernel is generated 1518 /// implicitly null value has to be passed to the last two parameters, 1519 /// otherwise all parameters must have valid non-null values. 1520 /// \param FN is a pointer to IR function being generated. 1521 /// \param FD is a pointer to function declaration if any. 1522 /// \param CGF is a pointer to CodeGenFunction that generates this function. 1523 void GenKernelArgMetadata(llvm::Function *FN, 1524 const FunctionDecl *FD = nullptr, 1525 CodeGenFunction *CGF = nullptr); 1526 1527 /// Get target specific null pointer. 1528 /// \param T is the LLVM type of the null pointer. 1529 /// \param QT is the clang QualType of the null pointer. 1530 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT); 1531 1532 CharUnits getNaturalTypeAlignment(QualType T, 1533 LValueBaseInfo *BaseInfo = nullptr, 1534 TBAAAccessInfo *TBAAInfo = nullptr, 1535 bool forPointeeType = false); 1536 CharUnits getNaturalPointeeTypeAlignment(QualType T, 1537 LValueBaseInfo *BaseInfo = nullptr, 1538 TBAAAccessInfo *TBAAInfo = nullptr); 1539 bool stopAutoInit(); 1540 1541 /// Print the postfix for externalized static variable or kernels for single 1542 /// source offloading languages CUDA and HIP. The unique postfix is created 1543 /// using either the CUID argument, or the file's UniqueID and active macros. 1544 /// The fallback method without a CUID requires that the offloading toolchain 1545 /// does not define separate macros via the -cc1 options. 1546 void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 1547 const Decl *D) const; 1548 1549 /// Move some lazily-emitted states to the NewBuilder. This is especially 1550 /// essential for the incremental parsing environment like Clang Interpreter, 1551 /// because we'll lose all important information after each repl. 1552 void moveLazyEmissionStates(CodeGenModule *NewBuilder); 1553 1554 /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F. 1555 /// If \p MaxThreadsVal is not nullptr, the max threads value is stored in it, 1556 /// if a valid one was found. 1557 void handleCUDALaunchBoundsAttr(llvm::Function *F, 1558 const CUDALaunchBoundsAttr *A, 1559 int32_t *MaxThreadsVal = nullptr, 1560 int32_t *MinBlocksVal = nullptr, 1561 int32_t *MaxClusterRankVal = nullptr); 1562 1563 /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute 1564 /// to \p F. Alternatively, the work group size can be taken from a \p 1565 /// ReqdWGS. If \p MinThreadsVal is not nullptr, the min threads value is 1566 /// stored in it, if a valid one was found. If \p MaxThreadsVal is not 1567 /// nullptr, the max threads value is stored in it, if a valid one was found. 1568 void handleAMDGPUFlatWorkGroupSizeAttr( 1569 llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A, 1570 const ReqdWorkGroupSizeAttr *ReqdWGS = nullptr, 1571 int32_t *MinThreadsVal = nullptr, int32_t *MaxThreadsVal = nullptr); 1572 1573 /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F. 1574 void handleAMDGPUWavesPerEUAttr(llvm::Function *F, 1575 const AMDGPUWavesPerEUAttr *A); 1576 1577 llvm::Constant * 1578 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, 1579 const VarDecl *D, 1580 ForDefinition_t IsForDefinition = NotForDefinition); 1581 1582 // FIXME: Hardcoding priority here is gross. 1583 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535, 1584 unsigned LexOrder = ~0U, 1585 llvm::Constant *AssociatedData = nullptr); 1586 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535, 1587 bool IsDtorAttrFunc = false); 1588 1589 // Return whether structured convergence intrinsics should be generated for 1590 // this target. 1591 bool shouldEmitConvergenceTokens() const { 1592 // TODO: this should probably become unconditional once the controlled 1593 // convergence becomes the norm. 1594 return getTriple().isSPIRVLogical(); 1595 } 1596 1597 private: 1598 llvm::Constant *GetOrCreateLLVMFunction( 1599 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable, 1600 bool DontDefer = false, bool IsThunk = false, 1601 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1602 ForDefinition_t IsForDefinition = NotForDefinition); 1603 1604 // Adds a declaration to the list of multi version functions if not present. 1605 void AddDeferredMultiVersionResolverToEmit(GlobalDecl GD); 1606 1607 // References to multiversion functions are resolved through an implicitly 1608 // defined resolver function. This function is responsible for creating 1609 // the resolver symbol for the provided declaration. The value returned 1610 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports 1611 // that feature and for a regular function (llvm::GlobalValue) otherwise. 1612 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD); 1613 1614 // In scenarios where a function is not known to be a multiversion function 1615 // until a later declaration, it is sometimes necessary to change the 1616 // previously created mangled name to align with requirements of whatever 1617 // multiversion function kind the function is now known to be. This function 1618 // is responsible for performing such mangled name updates. 1619 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD, 1620 StringRef &CurName); 1621 1622 bool GetCPUAndFeaturesAttributes(GlobalDecl GD, 1623 llvm::AttrBuilder &AttrBuilder, 1624 bool SetTargetFeatures = true); 1625 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO); 1626 1627 /// Set function attributes for a function declaration. 1628 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1629 bool IsIncompleteFunction, bool IsThunk); 1630 1631 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr); 1632 1633 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1634 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1635 1636 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false); 1637 void EmitExternalVarDeclaration(const VarDecl *D); 1638 void EmitAliasDefinition(GlobalDecl GD); 1639 void emitIFuncDefinition(GlobalDecl GD); 1640 void emitCPUDispatchDefinition(GlobalDecl GD); 1641 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 1642 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 1643 1644 // C++ related functions. 1645 1646 void EmitDeclContext(const DeclContext *DC); 1647 void EmitLinkageSpec(const LinkageSpecDecl *D); 1648 void EmitTopLevelStmt(const TopLevelStmtDecl *D); 1649 1650 /// Emit the function that initializes C++ thread_local variables. 1651 void EmitCXXThreadLocalInitFunc(); 1652 1653 /// Emit the function that initializes global variables for a C++ Module. 1654 void EmitCXXModuleInitFunc(clang::Module *Primary); 1655 1656 /// Emit the function that initializes C++ globals. 1657 void EmitCXXGlobalInitFunc(); 1658 1659 /// Emit the function that performs cleanup associated with C++ globals. 1660 void EmitCXXGlobalCleanUpFunc(); 1661 1662 /// Emit the function that initializes the specified global (if PerformInit is 1663 /// true) and registers its destructor. 1664 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 1665 llvm::GlobalVariable *Addr, 1666 bool PerformInit); 1667 1668 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr, 1669 llvm::Function *InitFunc, InitSegAttr *ISA); 1670 1671 /// EmitCtorList - Generates a global array of functions and priorities using 1672 /// the given list and name. This array will have appending linkage and is 1673 /// suitable for use as a LLVM constructor or destructor array. Clears Fns. 1674 void EmitCtorList(CtorList &Fns, const char *GlobalName); 1675 1676 /// Emit any needed decls for which code generation was deferred. 1677 void EmitDeferred(); 1678 1679 /// Try to emit external vtables as available_externally if they have emitted 1680 /// all inlined virtual functions. It runs after EmitDeferred() and therefore 1681 /// is not allowed to create new references to things that need to be emitted 1682 /// lazily. 1683 void EmitVTablesOpportunistically(); 1684 1685 /// Call replaceAllUsesWith on all pairs in Replacements. 1686 void applyReplacements(); 1687 1688 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements. 1689 void applyGlobalValReplacements(); 1690 1691 void checkAliases(); 1692 1693 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit; 1694 1695 /// Register functions annotated with __attribute__((destructor)) using 1696 /// __cxa_atexit, if it is available, or atexit otherwise. 1697 void registerGlobalDtorsWithAtExit(); 1698 1699 // When using sinit and sterm functions, unregister 1700 // __attribute__((destructor)) annotated functions which were previously 1701 // registered by the atexit subroutine using unatexit. 1702 void unregisterGlobalDtorsWithUnAtExit(); 1703 1704 /// Emit deferred multiversion function resolvers and associated variants. 1705 void emitMultiVersionFunctions(); 1706 1707 /// Emit any vtables which we deferred and still have a use for. 1708 void EmitDeferredVTables(); 1709 1710 /// Emit a dummy function that reference a CoreFoundation symbol when 1711 /// @available is used on Darwin. 1712 void emitAtAvailableLinkGuard(); 1713 1714 /// Emit the llvm.used and llvm.compiler.used metadata. 1715 void emitLLVMUsed(); 1716 1717 /// For C++20 Itanium ABI, emit the initializers for the module. 1718 void EmitModuleInitializers(clang::Module *Primary); 1719 1720 /// Emit the link options introduced by imported modules. 1721 void EmitModuleLinkOptions(); 1722 1723 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that 1724 /// have a resolver name that matches 'Elem' to instead resolve to the name of 1725 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name 1726 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs 1727 /// may not reference aliases. Redirection is only performed if 'Elem' is only 1728 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if 1729 /// redirection is successful, and 'false' is returned otherwise. 1730 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 1731 llvm::GlobalValue *CppFunc); 1732 1733 /// Emit aliases for internal-linkage declarations inside "C" language 1734 /// linkage specifications, giving them the "expected" name where possible. 1735 void EmitStaticExternCAliases(); 1736 1737 void EmitDeclMetadata(); 1738 1739 /// Emit the Clang version as llvm.ident metadata. 1740 void EmitVersionIdentMetadata(); 1741 1742 /// Emit the Clang commandline as llvm.commandline metadata. 1743 void EmitCommandLineMetadata(); 1744 1745 /// Emit the module flag metadata used to pass options controlling the 1746 /// the backend to LLVM. 1747 void EmitBackendOptionsMetadata(const CodeGenOptions &CodeGenOpts); 1748 1749 /// Emits OpenCL specific Metadata e.g. OpenCL version. 1750 void EmitOpenCLMetadata(); 1751 1752 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and 1753 /// .gcda files in a way that persists in .bc files. 1754 void EmitCoverageFile(); 1755 1756 /// Determine whether the definition must be emitted; if this returns \c 1757 /// false, the definition can be emitted lazily if it's used. 1758 bool MustBeEmitted(const ValueDecl *D); 1759 1760 /// Determine whether the definition can be emitted eagerly, or should be 1761 /// delayed until the end of the translation unit. This is relevant for 1762 /// definitions whose linkage can change, e.g. implicit function instantions 1763 /// which may later be explicitly instantiated. 1764 bool MayBeEmittedEagerly(const ValueDecl *D); 1765 1766 /// Check whether we can use a "simpler", more core exceptions personality 1767 /// function. 1768 void SimplifyPersonality(); 1769 1770 /// Helper function for getDefaultFunctionAttributes. Builds a set of function 1771 /// attributes which can be simply added to a function. 1772 void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone, 1773 bool AttrOnCallSite, 1774 llvm::AttrBuilder &FuncAttrs); 1775 1776 /// Helper function for ConstructAttributeList and 1777 /// addDefaultFunctionDefinitionAttributes. Builds a set of function 1778 /// attributes to add to a function with the given properties. 1779 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone, 1780 bool AttrOnCallSite, 1781 llvm::AttrBuilder &FuncAttrs); 1782 1783 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 1784 StringRef Suffix); 1785 }; 1786 1787 } // end namespace CodeGen 1788 } // end namespace clang 1789 1790 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 1791