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