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