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