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