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