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 setGlobalVisibilityAndLocal(llvm::GlobalValue *GV, 763 const NamedDecl *D) const; 764 765 void setDSOLocal(llvm::GlobalValue *GV) const; 766 767 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const; 768 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const; 769 /// Set visibility, dllimport/dllexport and dso_local. 770 /// This must be called after dllimport/dllexport is set. 771 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const; 772 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const; 773 774 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local 775 /// variable declaration D. 776 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const; 777 778 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 779 switch (V) { 780 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 781 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 782 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 783 } 784 llvm_unreachable("unknown visibility!"); 785 } 786 787 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, 788 ForDefinition_t IsForDefinition 789 = NotForDefinition); 790 791 /// Will return a global variable of the given type. If a variable with a 792 /// different type already exists then a new variable with the right type 793 /// will be created and all uses of the old variable will be replaced with a 794 /// bitcast to the new variable. 795 llvm::GlobalVariable * 796 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 797 llvm::GlobalValue::LinkageTypes Linkage, 798 unsigned Alignment); 799 800 llvm::Function * 801 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name, 802 const CGFunctionInfo &FI, 803 SourceLocation Loc = SourceLocation(), 804 bool TLS = false); 805 806 /// Return the AST address space of the underlying global variable for D, as 807 /// determined by its declaration. Normally this is the same as the address 808 /// space of D's type, but in CUDA, address spaces are associated with 809 /// declarations, not types. If D is nullptr, return the default address 810 /// space for global variable. 811 /// 812 /// For languages without explicit address spaces, if D has default address 813 /// space, target-specific global or constant address space may be returned. 814 LangAS GetGlobalVarAddressSpace(const VarDecl *D); 815 816 /// Return the llvm::Constant for the address of the given global variable. 817 /// If Ty is non-null and if the global doesn't exist, then it will be created 818 /// with the specified type instead of whatever the normal requested type 819 /// would be. If IsForDefinition is true, it is guaranteed that an actual 820 /// global with type Ty will be returned, not conversion of a variable with 821 /// the same mangled name but some other type. 822 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 823 llvm::Type *Ty = nullptr, 824 ForDefinition_t IsForDefinition 825 = NotForDefinition); 826 827 /// Return the AST address space of string literal, which is used to emit 828 /// the string literal as global variable in LLVM IR. 829 /// Note: This is not necessarily the address space of the string literal 830 /// in AST. For address space agnostic language, e.g. C++, string literal 831 /// in AST is always in default address space. 832 LangAS getStringLiteralAddressSpace() const; 833 834 /// Return the address of the given function. If Ty is non-null, then this 835 /// function will use the specified type if it has to create it. 836 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr, 837 bool ForVTable = false, 838 bool DontDefer = false, 839 ForDefinition_t IsForDefinition 840 = NotForDefinition); 841 842 /// Get the address of the RTTI descriptor for the given type. 843 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 844 845 /// Get the address of a uuid descriptor . 846 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E); 847 848 /// Get the address of the thunk for the given global decl. 849 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, 850 GlobalDecl GD); 851 852 /// Get a reference to the target of VD. 853 ConstantAddress GetWeakRefReference(const ValueDecl *VD); 854 855 /// Returns the assumed alignment of an opaque pointer to the given class. 856 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD); 857 858 /// Returns the assumed alignment of a virtual base of a class. 859 CharUnits getVBaseAlignment(CharUnits DerivedAlign, 860 const CXXRecordDecl *Derived, 861 const CXXRecordDecl *VBase); 862 863 /// Given a class pointer with an actual known alignment, and the 864 /// expected alignment of an object at a dynamic offset w.r.t that 865 /// pointer, return the alignment to assume at the offset. 866 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign, 867 const CXXRecordDecl *Class, 868 CharUnits ExpectedTargetAlign); 869 870 CharUnits 871 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, 872 CastExpr::path_const_iterator Start, 873 CastExpr::path_const_iterator End); 874 875 /// Returns the offset from a derived class to a class. Returns null if the 876 /// offset is 0. 877 llvm::Constant * 878 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 879 CastExpr::path_const_iterator PathBegin, 880 CastExpr::path_const_iterator PathEnd); 881 882 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache; 883 884 /// Fetches the global unique block count. 885 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 886 887 /// Fetches the type of a generic block descriptor. 888 llvm::Type *getBlockDescriptorType(); 889 890 /// The type of a generic block literal. 891 llvm::Type *getGenericBlockLiteralType(); 892 893 /// Gets the address of a block which requires no captures. 894 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name); 895 896 /// Returns the address of a block which requires no caputres, or null if 897 /// we've yet to emit the block for BE. 898 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) { 899 return EmittedGlobalBlocks.lookup(BE); 900 } 901 902 /// Notes that BE's global block is available via Addr. Asserts that BE 903 /// isn't already emitted. 904 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr); 905 906 /// Return a pointer to a constant CFString object for the given string. 907 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal); 908 909 /// Return a pointer to a constant NSString object for the given string. Or a 910 /// user defined String object as defined via 911 /// -fconstant-string-class=class_name option. 912 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal); 913 914 /// Return a constant array for the given string. 915 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 916 917 /// Return a pointer to a constant array for the given string literal. 918 ConstantAddress 919 GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 920 StringRef Name = ".str"); 921 922 /// Return a pointer to a constant array for the given ObjCEncodeExpr node. 923 ConstantAddress 924 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 925 926 /// Returns a pointer to a character array containing the literal and a 927 /// terminating '\0' character. The result has pointer to array type. 928 /// 929 /// \param GlobalName If provided, the name to use for the global (if one is 930 /// created). 931 ConstantAddress 932 GetAddrOfConstantCString(const std::string &Str, 933 const char *GlobalName = nullptr); 934 935 /// Returns a pointer to a constant global variable for the given file-scope 936 /// compound literal expression. 937 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 938 939 /// If it's been emitted already, returns the GlobalVariable corresponding to 940 /// a compound literal. Otherwise, returns null. 941 llvm::GlobalVariable * 942 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E); 943 944 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already 945 /// emitted. 946 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE, 947 llvm::GlobalVariable *GV); 948 949 /// Returns a pointer to a global variable representing a temporary 950 /// with static or thread storage duration. 951 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, 952 const Expr *Inner); 953 954 /// Retrieve the record type that describes the state of an 955 /// Objective-C fast enumeration loop (for..in). 956 QualType getObjCFastEnumerationStateType(); 957 958 // Produce code for this constructor/destructor. This method doesn't try 959 // to apply any ABI rules about which other constructors/destructors 960 // are needed or if they are alias to each other. 961 llvm::Function *codegenCXXStructor(GlobalDecl GD); 962 963 /// Return the address of the constructor/destructor of the given type. 964 llvm::Constant * 965 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 966 llvm::FunctionType *FnType = nullptr, 967 bool DontDefer = false, 968 ForDefinition_t IsForDefinition = NotForDefinition) { 969 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType, 970 DontDefer, 971 IsForDefinition) 972 .getCallee()); 973 } 974 975 llvm::FunctionCallee getAddrAndTypeOfCXXStructor( 976 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 977 llvm::FunctionType *FnType = nullptr, bool DontDefer = false, 978 ForDefinition_t IsForDefinition = NotForDefinition); 979 980 /// Given a builtin id for a function like "__builtin_fabsf", return a 981 /// Function* for "fabsf". 982 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD, 983 unsigned BuiltinID); 984 985 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None); 986 987 /// Emit code for a single top level declaration. 988 void EmitTopLevelDecl(Decl *D); 989 990 /// Stored a deferred empty coverage mapping for an unused 991 /// and thus uninstrumented top level declaration. 992 void AddDeferredUnusedCoverageMapping(Decl *D); 993 994 /// Remove the deferred empty coverage mapping as this 995 /// declaration is actually instrumented. 996 void ClearUnusedCoverageMapping(const Decl *D); 997 998 /// Emit all the deferred coverage mappings 999 /// for the uninstrumented functions. 1000 void EmitDeferredUnusedCoverageMappings(); 1001 1002 /// Tell the consumer that this variable has been instantiated. 1003 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD); 1004 1005 /// If the declaration has internal linkage but is inside an 1006 /// extern "C" linkage specification, prepare to emit an alias for it 1007 /// to the expected name. 1008 template<typename SomeDecl> 1009 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV); 1010 1011 /// Add a global to a list to be added to the llvm.used metadata. 1012 void addUsedGlobal(llvm::GlobalValue *GV); 1013 1014 /// Add a global to a list to be added to the llvm.compiler.used metadata. 1015 void addCompilerUsedGlobal(llvm::GlobalValue *GV); 1016 1017 /// Add a destructor and object to add to the C++ global destructor function. 1018 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) { 1019 CXXGlobalDtors.emplace_back(DtorFn.getFunctionType(), DtorFn.getCallee(), 1020 Object); 1021 } 1022 1023 /// Create or return a runtime function declaration with the specified type 1024 /// and name. 1025 llvm::FunctionCallee 1026 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, 1027 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1028 bool Local = false); 1029 1030 /// Create a new runtime global variable with the specified type and name. 1031 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 1032 StringRef Name); 1033 1034 ///@name Custom Blocks Runtime Interfaces 1035 ///@{ 1036 1037 llvm::Constant *getNSConcreteGlobalBlock(); 1038 llvm::Constant *getNSConcreteStackBlock(); 1039 llvm::FunctionCallee getBlockObjectAssign(); 1040 llvm::FunctionCallee getBlockObjectDispose(); 1041 1042 ///@} 1043 1044 llvm::Function *getLLVMLifetimeStartFn(); 1045 llvm::Function *getLLVMLifetimeEndFn(); 1046 1047 // Make sure that this type is translated. 1048 void UpdateCompletedType(const TagDecl *TD); 1049 1050 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 1051 1052 /// Emit type info if type of an expression is a variably modified 1053 /// type. Also emit proper debug info for cast types. 1054 void EmitExplicitCastExprType(const ExplicitCastExpr *E, 1055 CodeGenFunction *CGF = nullptr); 1056 1057 /// Return the result of value-initializing the given type, i.e. a null 1058 /// expression of the given type. This is usually, but not always, an LLVM 1059 /// null constant. 1060 llvm::Constant *EmitNullConstant(QualType T); 1061 1062 /// Return a null constant appropriate for zero-initializing a base class with 1063 /// the given type. This is usually, but not always, an LLVM null constant. 1064 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 1065 1066 /// Emit a general error that something can't be done. 1067 void Error(SourceLocation loc, StringRef error); 1068 1069 /// Print out an error that codegen doesn't support the specified stmt yet. 1070 void ErrorUnsupported(const Stmt *S, const char *Type); 1071 1072 /// Print out an error that codegen doesn't support the specified decl yet. 1073 void ErrorUnsupported(const Decl *D, const char *Type); 1074 1075 /// Set the attributes on the LLVM function for the given decl and function 1076 /// info. This applies attributes necessary for handling the ABI as well as 1077 /// user specified attributes like section. 1078 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1079 const CGFunctionInfo &FI); 1080 1081 /// Set the LLVM function attributes (sext, zext, etc). 1082 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, 1083 llvm::Function *F); 1084 1085 /// Set the LLVM function attributes which only apply to a function 1086 /// definition. 1087 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 1088 1089 /// Return true iff the given type uses 'sret' when used as a return type. 1090 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 1091 1092 /// Return true iff the given type uses an argument slot when 'sret' is used 1093 /// as a return type. 1094 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI); 1095 1096 /// Return true iff the given type uses 'fpret' when used as a return type. 1097 bool ReturnTypeUsesFPRet(QualType ResultType); 1098 1099 /// Return true iff the given type uses 'fp2ret' when used as a return type. 1100 bool ReturnTypeUsesFP2Ret(QualType ResultType); 1101 1102 /// Get the LLVM attributes and calling convention to use for a particular 1103 /// function type. 1104 /// 1105 /// \param Name - The function name. 1106 /// \param Info - The function type information. 1107 /// \param CalleeInfo - The callee information these attributes are being 1108 /// constructed for. If valid, the attributes applied to this decl may 1109 /// contribute to the function attributes and calling convention. 1110 /// \param Attrs [out] - On return, the attribute list to use. 1111 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 1112 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, 1113 CGCalleeInfo CalleeInfo, 1114 llvm::AttributeList &Attrs, unsigned &CallingConv, 1115 bool AttrOnCallSite); 1116 1117 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as 1118 /// though we had emitted it ourselves. We remove any attributes on F that 1119 /// conflict with the attributes we add here. 1120 /// 1121 /// This is useful for adding attrs to bitcode modules that you want to link 1122 /// with but don't control, such as CUDA's libdevice. When linking with such 1123 /// a bitcode library, you might want to set e.g. its functions' 1124 /// "unsafe-fp-math" attribute to match the attr of the functions you're 1125 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of 1126 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM 1127 /// will propagate unsafe-fp-math=false up to every transitive caller of a 1128 /// function in the bitcode library! 1129 /// 1130 /// With the exception of fast-math attrs, this will only make the attributes 1131 /// on the function more conservative. But it's unsafe to call this on a 1132 /// function which relies on particular fast-math attributes for correctness. 1133 /// It's up to you to ensure that this is safe. 1134 void AddDefaultFnAttrs(llvm::Function &F); 1135 1136 /// Parses the target attributes passed in, and returns only the ones that are 1137 /// valid feature names. 1138 TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD); 1139 1140 // Fills in the supplied string map with the set of target features for the 1141 // passed in function. 1142 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, GlobalDecl GD); 1143 1144 StringRef getMangledName(GlobalDecl GD); 1145 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD); 1146 1147 void EmitTentativeDefinition(const VarDecl *D); 1148 1149 void EmitVTable(CXXRecordDecl *Class); 1150 1151 void RefreshTypeCacheForClass(const CXXRecordDecl *Class); 1152 1153 /// Appends Opts to the "llvm.linker.options" metadata value. 1154 void AppendLinkerOptions(StringRef Opts); 1155 1156 /// Appends a detect mismatch command to the linker options. 1157 void AddDetectMismatch(StringRef Name, StringRef Value); 1158 1159 /// Appends a dependent lib to the appropriate metadata value. 1160 void AddDependentLib(StringRef Lib); 1161 1162 1163 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD); 1164 1165 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) { 1166 F->setLinkage(getFunctionLinkage(GD)); 1167 } 1168 1169 /// Return the appropriate linkage for the vtable, VTT, and type information 1170 /// of the given class. 1171 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 1172 1173 /// Return the store size, in character units, of the given LLVM type. 1174 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 1175 1176 /// Returns LLVM linkage for a declarator. 1177 llvm::GlobalValue::LinkageTypes 1178 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, 1179 bool IsConstantVariable); 1180 1181 /// Returns LLVM linkage for a declarator. 1182 llvm::GlobalValue::LinkageTypes 1183 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant); 1184 1185 /// Emit all the global annotations. 1186 void EmitGlobalAnnotations(); 1187 1188 /// Emit an annotation string. 1189 llvm::Constant *EmitAnnotationString(StringRef Str); 1190 1191 /// Emit the annotation's translation unit. 1192 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 1193 1194 /// Emit the annotation line number. 1195 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 1196 1197 /// Generate the llvm::ConstantStruct which contains the annotation 1198 /// information for a given GlobalValue. The annotation struct is 1199 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 1200 /// GlobalValue being annotated. The second field is the constant string 1201 /// created from the AnnotateAttr's annotation. The third field is a constant 1202 /// string containing the name of the translation unit. The fourth field is 1203 /// the line number in the file of the annotated value declaration. 1204 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 1205 const AnnotateAttr *AA, 1206 SourceLocation L); 1207 1208 /// Add global annotations that are set on D, for the global GV. Those 1209 /// annotations are emitted during finalization of the LLVM code. 1210 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 1211 1212 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn, 1213 SourceLocation Loc) const; 1214 1215 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc, 1216 QualType Ty, 1217 StringRef Category = StringRef()) const; 1218 1219 /// Imbue XRay attributes to a function, applying the always/never attribute 1220 /// lists in the process. Returns true if we did imbue attributes this way, 1221 /// false otherwise. 1222 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1223 StringRef Category = StringRef()) const; 1224 1225 SanitizerMetadata *getSanitizerMetadata() { 1226 return SanitizerMD.get(); 1227 } 1228 1229 void addDeferredVTable(const CXXRecordDecl *RD) { 1230 DeferredVTables.push_back(RD); 1231 } 1232 1233 /// Emit code for a single global function or var decl. Forward declarations 1234 /// are emitted lazily. 1235 void EmitGlobal(GlobalDecl D); 1236 1237 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 1238 1239 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 1240 1241 /// Set attributes which are common to any form of a global definition (alias, 1242 /// Objective-C method, function, global variable). 1243 /// 1244 /// NOTE: This should only be called for definitions. 1245 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV); 1246 1247 void addReplacement(StringRef Name, llvm::Constant *C); 1248 1249 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C); 1250 1251 /// Emit a code for threadprivate directive. 1252 /// \param D Threadprivate declaration. 1253 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D); 1254 1255 /// Emit a code for declare reduction construct. 1256 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 1257 CodeGenFunction *CGF = nullptr); 1258 1259 /// Emit a code for declare mapper construct. 1260 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, 1261 CodeGenFunction *CGF = nullptr); 1262 1263 /// Emit a code for requires directive. 1264 /// \param D Requires declaration 1265 void EmitOMPRequiresDecl(const OMPRequiresDecl *D); 1266 1267 /// Returns whether the given record has hidden LTO visibility and therefore 1268 /// may participate in (single-module) CFI and whole-program vtable 1269 /// optimization. 1270 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD); 1271 1272 /// Emit type metadata for the given vtable using the given layout. 1273 void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable, 1274 const VTableLayout &VTLayout); 1275 1276 /// Generate a cross-DSO type identifier for MD. 1277 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD); 1278 1279 /// Create a metadata identifier for the given type. This may either be an 1280 /// MDString (for external identifiers) or a distinct unnamed MDNode (for 1281 /// internal identifiers). 1282 llvm::Metadata *CreateMetadataIdentifierForType(QualType T); 1283 1284 /// Create a metadata identifier that is intended to be used to check virtual 1285 /// calls via a member function pointer. 1286 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T); 1287 1288 /// Create a metadata identifier for the generalization of the given type. 1289 /// This may either be an MDString (for external identifiers) or a distinct 1290 /// unnamed MDNode (for internal identifiers). 1291 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T); 1292 1293 /// Create and attach type metadata to the given function. 1294 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1295 llvm::Function *F); 1296 1297 /// Returns whether this module needs the "all-vtables" type identifier. 1298 bool NeedAllVtablesTypeId() const; 1299 1300 /// Create and attach type metadata for the given vtable. 1301 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, 1302 const CXXRecordDecl *RD); 1303 1304 /// Return a vector of most-base classes for RD. This is used to implement 1305 /// control flow integrity checks for member function pointers. 1306 /// 1307 /// A most-base class of a class C is defined as a recursive base class of C, 1308 /// including C itself, that does not have any bases. 1309 std::vector<const CXXRecordDecl *> 1310 getMostBaseClasses(const CXXRecordDecl *RD); 1311 1312 /// Get the declaration of std::terminate for the platform. 1313 llvm::FunctionCallee getTerminateFn(); 1314 1315 llvm::SanitizerStatReport &getSanStats(); 1316 1317 llvm::Value * 1318 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF); 1319 1320 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 1321 /// information in the program executable. The argument information stored 1322 /// includes the argument name, its type, the address and access qualifiers 1323 /// used. This helper can be used to generate metadata for source code kernel 1324 /// function as well as generated implicitly kernels. If a kernel is generated 1325 /// implicitly null value has to be passed to the last two parameters, 1326 /// otherwise all parameters must have valid non-null values. 1327 /// \param FN is a pointer to IR function being generated. 1328 /// \param FD is a pointer to function declaration if any. 1329 /// \param CGF is a pointer to CodeGenFunction that generates this function. 1330 void GenOpenCLArgMetadata(llvm::Function *FN, 1331 const FunctionDecl *FD = nullptr, 1332 CodeGenFunction *CGF = nullptr); 1333 1334 /// Get target specific null pointer. 1335 /// \param T is the LLVM type of the null pointer. 1336 /// \param QT is the clang QualType of the null pointer. 1337 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT); 1338 1339 private: 1340 llvm::Constant *GetOrCreateLLVMFunction( 1341 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable, 1342 bool DontDefer = false, bool IsThunk = false, 1343 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1344 ForDefinition_t IsForDefinition = NotForDefinition); 1345 1346 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD, 1347 llvm::Type *DeclTy, 1348 const FunctionDecl *FD); 1349 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD); 1350 1351 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 1352 llvm::PointerType *PTy, 1353 const VarDecl *D, 1354 ForDefinition_t IsForDefinition 1355 = NotForDefinition); 1356 1357 bool GetCPUAndFeaturesAttributes(GlobalDecl GD, 1358 llvm::AttrBuilder &AttrBuilder); 1359 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO); 1360 1361 /// Set function attributes for a function declaration. 1362 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1363 bool IsIncompleteFunction, bool IsThunk); 1364 1365 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr); 1366 1367 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1368 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1369 1370 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false); 1371 void EmitAliasDefinition(GlobalDecl GD); 1372 void emitIFuncDefinition(GlobalDecl GD); 1373 void emitCPUDispatchDefinition(GlobalDecl GD); 1374 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 1375 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 1376 1377 // C++ related functions. 1378 1379 void EmitDeclContext(const DeclContext *DC); 1380 void EmitLinkageSpec(const LinkageSpecDecl *D); 1381 1382 /// Emit the function that initializes C++ thread_local variables. 1383 void EmitCXXThreadLocalInitFunc(); 1384 1385 /// Emit the function that initializes C++ globals. 1386 void EmitCXXGlobalInitFunc(); 1387 1388 /// Emit the function that destroys C++ globals. 1389 void EmitCXXGlobalDtorFunc(); 1390 1391 /// Emit the function that initializes the specified global (if PerformInit is 1392 /// true) and registers its destructor. 1393 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 1394 llvm::GlobalVariable *Addr, 1395 bool PerformInit); 1396 1397 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr, 1398 llvm::Function *InitFunc, InitSegAttr *ISA); 1399 1400 // FIXME: Hardcoding priority here is gross. 1401 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535, 1402 llvm::Constant *AssociatedData = nullptr); 1403 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535); 1404 1405 /// EmitCtorList - Generates a global array of functions and priorities using 1406 /// the given list and name. This array will have appending linkage and is 1407 /// suitable for use as a LLVM constructor or destructor array. Clears Fns. 1408 void EmitCtorList(CtorList &Fns, const char *GlobalName); 1409 1410 /// Emit any needed decls for which code generation was deferred. 1411 void EmitDeferred(); 1412 1413 /// Try to emit external vtables as available_externally if they have emitted 1414 /// all inlined virtual functions. It runs after EmitDeferred() and therefore 1415 /// is not allowed to create new references to things that need to be emitted 1416 /// lazily. 1417 void EmitVTablesOpportunistically(); 1418 1419 /// Call replaceAllUsesWith on all pairs in Replacements. 1420 void applyReplacements(); 1421 1422 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements. 1423 void applyGlobalValReplacements(); 1424 1425 void checkAliases(); 1426 1427 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit; 1428 1429 /// Register functions annotated with __attribute__((destructor)) using 1430 /// __cxa_atexit, if it is available, or atexit otherwise. 1431 void registerGlobalDtorsWithAtExit(); 1432 1433 void emitMultiVersionFunctions(); 1434 1435 /// Emit any vtables which we deferred and still have a use for. 1436 void EmitDeferredVTables(); 1437 1438 /// Emit a dummy function that reference a CoreFoundation symbol when 1439 /// @available is used on Darwin. 1440 void emitAtAvailableLinkGuard(); 1441 1442 /// Emit the llvm.used and llvm.compiler.used metadata. 1443 void emitLLVMUsed(); 1444 1445 /// Emit the link options introduced by imported modules. 1446 void EmitModuleLinkOptions(); 1447 1448 /// Emit aliases for internal-linkage declarations inside "C" language 1449 /// linkage specifications, giving them the "expected" name where possible. 1450 void EmitStaticExternCAliases(); 1451 1452 void EmitDeclMetadata(); 1453 1454 /// Emit the Clang version as llvm.ident metadata. 1455 void EmitVersionIdentMetadata(); 1456 1457 /// Emit the Clang commandline as llvm.commandline metadata. 1458 void EmitCommandLineMetadata(); 1459 1460 /// Emits target specific Metadata for global declarations. 1461 void EmitTargetMetadata(); 1462 1463 /// Emits OpenCL specific Metadata e.g. OpenCL version. 1464 void EmitOpenCLMetadata(); 1465 1466 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and 1467 /// .gcda files in a way that persists in .bc files. 1468 void EmitCoverageFile(); 1469 1470 /// Emits the initializer for a uuidof string. 1471 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr); 1472 1473 /// Determine whether the definition must be emitted; if this returns \c 1474 /// false, the definition can be emitted lazily if it's used. 1475 bool MustBeEmitted(const ValueDecl *D); 1476 1477 /// Determine whether the definition can be emitted eagerly, or should be 1478 /// delayed until the end of the translation unit. This is relevant for 1479 /// definitions whose linkage can change, e.g. implicit function instantions 1480 /// which may later be explicitly instantiated. 1481 bool MayBeEmittedEagerly(const ValueDecl *D); 1482 1483 /// Check whether we can use a "simpler", more core exceptions personality 1484 /// function. 1485 void SimplifyPersonality(); 1486 1487 /// Helper function for ConstructAttributeList and AddDefaultFnAttrs. 1488 /// Constructs an AttrList for a function with the given properties. 1489 void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone, 1490 bool AttrOnCallSite, 1491 llvm::AttrBuilder &FuncAttrs); 1492 1493 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 1494 StringRef Suffix); 1495 }; 1496 1497 } // end namespace CodeGen 1498 } // end namespace clang 1499 1500 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 1501