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