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