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