Coverage Report

Created: 2022-05-14 11:35

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