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