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