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