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