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