1//===-- CodeGenFunction.h - Per-Function 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-function state used for llvm translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
14#define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15
16#include "CGBuilder.h"
17#include "CGDebugInfo.h"
18#include "CGLoopInfo.h"
19#include "CGValue.h"
20#include "CodeGenModule.h"
21#include "CodeGenPGO.h"
22#include "EHScopeStack.h"
23#include "VarBypassDetector.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/CurrentSourceLocExprScope.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/StmtOpenMP.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/ABI.h"
32#include "clang/Basic/CapturedStmt.h"
33#include "clang/Basic/CodeGenOptions.h"
34#include "clang/Basic/OpenMPKinds.h"
35#include "clang/Basic/TargetInfo.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/MapVector.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
41#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Transforms/Utils/SanitizerStats.h"
44#include <optional>
45
46namespace llvm {
47class BasicBlock;
48class LLVMContext;
49class MDNode;
50class SwitchInst;
51class Twine;
52class Value;
53class CanonicalLoopInfo;
54}
55
56namespace clang {
57class ASTContext;
58class CXXDestructorDecl;
59class CXXForRangeStmt;
60class CXXTryStmt;
61class Decl;
62class LabelDecl;
63class FunctionDecl;
64class FunctionProtoType;
65class LabelStmt;
66class ObjCContainerDecl;
67class ObjCInterfaceDecl;
68class ObjCIvarDecl;
69class ObjCMethodDecl;
70class ObjCImplementationDecl;
71class ObjCPropertyImplDecl;
72class TargetInfo;
73class VarDecl;
74class ObjCForCollectionStmt;
75class ObjCAtTryStmt;
76class ObjCAtThrowStmt;
77class ObjCAtSynchronizedStmt;
78class ObjCAutoreleasePoolStmt;
79class OMPUseDevicePtrClause;
80class OMPUseDeviceAddrClause;
81class SVETypeFlags;
82class OMPExecutableDirective;
83
84namespace analyze_os_log {
85class OSLogBufferLayout;
86}
87
88namespace CodeGen {
89class CodeGenTypes;
90class CGCallee;
91class CGFunctionInfo;
92class CGBlockInfo;
93class CGCXXABI;
94class BlockByrefHelpers;
95class BlockByrefInfo;
96class BlockFieldFlags;
97class RegionCodeGenTy;
98class TargetCodeGenInfo;
99struct OMPTaskDataTy;
100struct CGCoroData;
101
102/// The kind of evaluation to perform on values of a particular
103/// type.  Basically, is the code in CGExprScalar, CGExprComplex, or
104/// CGExprAgg?
105///
106/// TODO: should vectors maybe be split out into their own thing?
107enum TypeEvaluationKind {
108  TEK_Scalar,
109  TEK_Complex,
110  TEK_Aggregate
111};
112
113#define LIST_SANITIZER_CHECKS                                                  \
114  SANITIZER_CHECK(AddOverflow, add_overflow, 0)                                \
115  SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0)                  \
116  SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0)                             \
117  SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0)                          \
118  SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0)            \
119  SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0)                   \
120  SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0)             \
121  SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0)                  \
122  SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0)                          \
123  SANITIZER_CHECK(InvalidObjCCast, invalid_objc_cast, 0)                       \
124  SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0)                     \
125  SANITIZER_CHECK(MissingReturn, missing_return, 0)                            \
126  SANITIZER_CHECK(MulOverflow, mul_overflow, 0)                                \
127  SANITIZER_CHECK(NegateOverflow, negate_overflow, 0)                          \
128  SANITIZER_CHECK(NullabilityArg, nullability_arg, 0)                          \
129  SANITIZER_CHECK(NullabilityReturn, nullability_return, 1)                    \
130  SANITIZER_CHECK(NonnullArg, nonnull_arg, 0)                                  \
131  SANITIZER_CHECK(NonnullReturn, nonnull_return, 1)                            \
132  SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0)                               \
133  SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0)                        \
134  SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0)                    \
135  SANITIZER_CHECK(SubOverflow, sub_overflow, 0)                                \
136  SANITIZER_CHECK(TypeMismatch, type_mismatch, 1)                              \
137  SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0)                \
138  SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
139
140enum SanitizerHandler {
141#define SANITIZER_CHECK(Enum, Name, Version) Enum,
142  LIST_SANITIZER_CHECKS
143#undef SANITIZER_CHECK
144};
145
146/// Helper class with most of the code for saving a value for a
147/// conditional expression cleanup.
148struct DominatingLLVMValue {
149  typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
150
151  /// Answer whether the given value needs extra work to be saved.
152  static bool needsSaving(llvm::Value *value) {
153    // If it's not an instruction, we don't need to save.
154    if (!isa<llvm::Instruction>(value)) return false;
155
156    // If it's an instruction in the entry block, we don't need to save.
157    llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
158    return (block != &block->getParent()->getEntryBlock());
159  }
160
161  static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
162  static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
163};
164
165/// A partial specialization of DominatingValue for llvm::Values that
166/// might be llvm::Instructions.
167template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
168  typedef T *type;
169  static type restore(CodeGenFunction &CGF, saved_type value) {
170    return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
171  }
172};
173
174/// A specialization of DominatingValue for Address.
175template <> struct DominatingValue<Address> {
176  typedef Address type;
177
178  struct saved_type {
179    DominatingLLVMValue::saved_type SavedValue;
180    llvm::Type *ElementType;
181    CharUnits Alignment;
182  };
183
184  static bool needsSaving(type value) {
185    return DominatingLLVMValue::needsSaving(value.getPointer());
186  }
187  static saved_type save(CodeGenFunction &CGF, type value) {
188    return { DominatingLLVMValue::save(CGF, value.getPointer()),
189             value.getElementType(), value.getAlignment() };
190  }
191  static type restore(CodeGenFunction &CGF, saved_type value) {
192    return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
193                   value.ElementType, value.Alignment);
194  }
195};
196
197/// A specialization of DominatingValue for RValue.
198template <> struct DominatingValue<RValue> {
199  typedef RValue type;
200  class saved_type {
201    enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
202                AggregateAddress, ComplexAddress };
203
204    llvm::Value *Value;
205    llvm::Type *ElementType;
206    unsigned K : 3;
207    unsigned Align : 29;
208    saved_type(llvm::Value *v, llvm::Type *e, Kind k, unsigned a = 0)
209      : Value(v), ElementType(e), K(k), Align(a) {}
210
211  public:
212    static bool needsSaving(RValue value);
213    static saved_type save(CodeGenFunction &CGF, RValue value);
214    RValue restore(CodeGenFunction &CGF);
215
216    // implementations in CGCleanup.cpp
217  };
218
219  static bool needsSaving(type value) {
220    return saved_type::needsSaving(value);
221  }
222  static saved_type save(CodeGenFunction &CGF, type value) {
223    return saved_type::save(CGF, value);
224  }
225  static type restore(CodeGenFunction &CGF, saved_type value) {
226    return value.restore(CGF);
227  }
228};
229
230/// CodeGenFunction - This class organizes the per-function state that is used
231/// while generating LLVM code.
232class CodeGenFunction : public CodeGenTypeCache {
233  CodeGenFunction(const CodeGenFunction &) = delete;
234  void operator=(const CodeGenFunction &) = delete;
235
236  friend class CGCXXABI;
237public:
238  /// A jump destination is an abstract label, branching to which may
239  /// require a jump out through normal cleanups.
240  struct JumpDest {
241    JumpDest() : Block(nullptr), Index(0) {}
242    JumpDest(llvm::BasicBlock *Block, EHScopeStack::stable_iterator Depth,
243             unsigned Index)
244        : Block(Block), ScopeDepth(Depth), Index(Index) {}
245
246    bool isValid() const { return Block != nullptr; }
247    llvm::BasicBlock *getBlock() const { return Block; }
248    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
249    unsigned getDestIndex() const { return Index; }
250
251    // This should be used cautiously.
252    void setScopeDepth(EHScopeStack::stable_iterator depth) {
253      ScopeDepth = depth;
254    }
255
256  private:
257    llvm::BasicBlock *Block;
258    EHScopeStack::stable_iterator ScopeDepth;
259    unsigned Index;
260  };
261
262  CodeGenModule &CGM;  // Per-module state.
263  const TargetInfo &Target;
264
265  // For EH/SEH outlined funclets, this field points to parent's CGF
266  CodeGenFunction *ParentCGF = nullptr;
267
268  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
269  LoopInfoStack LoopStack;
270  CGBuilderTy Builder;
271
272  // Stores variables for which we can't generate correct lifetime markers
273  // because of jumps.
274  VarBypassDetector Bypasses;
275
276  /// List of recently emitted OMPCanonicalLoops.
277  ///
278  /// Since OMPCanonicalLoops are nested inside other statements (in particular
279  /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested
280  /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its
281  /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any
282  /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to
283  /// this stack when done. Entering a new loop requires clearing this list; it
284  /// either means we start parsing a new loop nest (in which case the previous
285  /// loop nest goes out of scope) or a second loop in the same level in which
286  /// case it would be ambiguous into which of the two (or more) loops the loop
287  /// nest would extend.
288  SmallVector<llvm::CanonicalLoopInfo *, 4> OMPLoopNestStack;
289
290  /// Stack to track the Logical Operator recursion nest for MC/DC.
291  SmallVector<const BinaryOperator *, 16> MCDCLogOpStack;
292
293  /// Number of nested loop to be consumed by the last surrounding
294  /// loop-associated directive.
295  int ExpectedOMPLoopDepth = 0;
296
297  // CodeGen lambda for loops and support for ordered clause
298  typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
299                                  JumpDest)>
300      CodeGenLoopTy;
301  typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
302                                  const unsigned, const bool)>
303      CodeGenOrderedTy;
304
305  // Codegen lambda for loop bounds in worksharing loop constructs
306  typedef llvm::function_ref<std::pair<LValue, LValue>(
307      CodeGenFunction &, const OMPExecutableDirective &S)>
308      CodeGenLoopBoundsTy;
309
310  // Codegen lambda for loop bounds in dispatch-based loop implementation
311  typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
312      CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
313      Address UB)>
314      CodeGenDispatchBoundsTy;
315
316  /// CGBuilder insert helper. This function is called after an
317  /// instruction is created using Builder.
318  void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
319                    llvm::BasicBlock *BB,
320                    llvm::BasicBlock::iterator InsertPt) const;
321
322  /// CurFuncDecl - Holds the Decl for the current outermost
323  /// non-closure context.
324  const Decl *CurFuncDecl = nullptr;
325  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
326  const Decl *CurCodeDecl = nullptr;
327  const CGFunctionInfo *CurFnInfo = nullptr;
328  QualType FnRetTy;
329  llvm::Function *CurFn = nullptr;
330
331  /// Save Parameter Decl for coroutine.
332  llvm::SmallVector<const ParmVarDecl *, 4> FnArgs;
333
334  // Holds coroutine data if the current function is a coroutine. We use a
335  // wrapper to manage its lifetime, so that we don't have to define CGCoroData
336  // in this header.
337  struct CGCoroInfo {
338    std::unique_ptr<CGCoroData> Data;
339    bool InSuspendBlock = false;
340    CGCoroInfo();
341    ~CGCoroInfo();
342  };
343  CGCoroInfo CurCoro;
344
345  bool isCoroutine() const {
346    return CurCoro.Data != nullptr;
347  }
348
349  bool inSuspendBlock() const {
350    return isCoroutine() && CurCoro.InSuspendBlock;
351  }
352
353  /// CurGD - The GlobalDecl for the current function being compiled.
354  GlobalDecl CurGD;
355
356  /// PrologueCleanupDepth - The cleanup depth enclosing all the
357  /// cleanups associated with the parameters.
358  EHScopeStack::stable_iterator PrologueCleanupDepth;
359
360  /// ReturnBlock - Unified return block.
361  JumpDest ReturnBlock;
362
363  /// ReturnValue - The temporary alloca to hold the return
364  /// value. This is invalid iff the function has no return value.
365  Address ReturnValue = Address::invalid();
366
367  /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
368  /// This is invalid if sret is not in use.
369  Address ReturnValuePointer = Address::invalid();
370
371  /// If a return statement is being visited, this holds the return statment's
372  /// result expression.
373  const Expr *RetExpr = nullptr;
374
375  /// Return true if a label was seen in the current scope.
376  bool hasLabelBeenSeenInCurrentScope() const {
377    if (CurLexicalScope)
378      return CurLexicalScope->hasLabels();
379    return !LabelMap.empty();
380  }
381
382  /// AllocaInsertPoint - This is an instruction in the entry block before which
383  /// we prefer to insert allocas.
384  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
385
386private:
387  /// PostAllocaInsertPt - This is a place in the prologue where code can be
388  /// inserted that will be dominated by all the static allocas. This helps
389  /// achieve two things:
390  ///   1. Contiguity of all static allocas (within the prologue) is maintained.
391  ///   2. All other prologue code (which are dominated by static allocas) do
392  ///      appear in the source order immediately after all static allocas.
393  ///
394  /// PostAllocaInsertPt will be lazily created when it is *really* required.
395  llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr;
396
397public:
398  /// Return PostAllocaInsertPt. If it is not yet created, then insert it
399  /// immediately after AllocaInsertPt.
400  llvm::Instruction *getPostAllocaInsertPoint() {
401    if (!PostAllocaInsertPt) {
402      assert(AllocaInsertPt &&
403             "Expected static alloca insertion point at function prologue");
404      assert(AllocaInsertPt->getParent()->isEntryBlock() &&
405             "EBB should be entry block of the current code gen function");
406      PostAllocaInsertPt = AllocaInsertPt->clone();
407      PostAllocaInsertPt->setName("postallocapt");
408      PostAllocaInsertPt->insertAfter(AllocaInsertPt);
409    }
410
411    return PostAllocaInsertPt;
412  }
413
414  /// API for captured statement code generation.
415  class CGCapturedStmtInfo {
416  public:
417    explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
418        : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
419    explicit CGCapturedStmtInfo(const CapturedStmt &S,
420                                CapturedRegionKind K = CR_Default)
421      : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
422
423      RecordDecl::field_iterator Field =
424        S.getCapturedRecordDecl()->field_begin();
425      for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
426                                                E = S.capture_end();
427           I != E; ++I, ++Field) {
428        if (I->capturesThis())
429          CXXThisFieldDecl = *Field;
430        else if (I->capturesVariable())
431          CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
432        else if (I->capturesVariableByCopy())
433          CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
434      }
435    }
436
437    virtual ~CGCapturedStmtInfo();
438
439    CapturedRegionKind getKind() const { return Kind; }
440
441    virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
442    // Retrieve the value of the context parameter.
443    virtual llvm::Value *getContextValue() const { return ThisValue; }
444
445    /// Lookup the captured field decl for a variable.
446    virtual const FieldDecl *lookup(const VarDecl *VD) const {
447      return CaptureFields.lookup(VD->getCanonicalDecl());
448    }
449
450    bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
451    virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
452
453    static bool classof(const CGCapturedStmtInfo *) {
454      return true;
455    }
456
457    /// Emit the captured statement body.
458    virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
459      CGF.incrementProfileCounter(S);
460      CGF.EmitStmt(S);
461    }
462
463    /// Get the name of the capture helper.
464    virtual StringRef getHelperName() const { return "__captured_stmt"; }
465
466    /// Get the CaptureFields
467    llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() {
468      return CaptureFields;
469    }
470
471  private:
472    /// The kind of captured statement being generated.
473    CapturedRegionKind Kind;
474
475    /// Keep the map between VarDecl and FieldDecl.
476    llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
477
478    /// The base address of the captured record, passed in as the first
479    /// argument of the parallel region function.
480    llvm::Value *ThisValue;
481
482    /// Captured 'this' type.
483    FieldDecl *CXXThisFieldDecl;
484  };
485  CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
486
487  /// RAII for correct setting/restoring of CapturedStmtInfo.
488  class CGCapturedStmtRAII {
489  private:
490    CodeGenFunction &CGF;
491    CGCapturedStmtInfo *PrevCapturedStmtInfo;
492  public:
493    CGCapturedStmtRAII(CodeGenFunction &CGF,
494                       CGCapturedStmtInfo *NewCapturedStmtInfo)
495        : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
496      CGF.CapturedStmtInfo = NewCapturedStmtInfo;
497    }
498    ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
499  };
500
501  /// An abstract representation of regular/ObjC call/message targets.
502  class AbstractCallee {
503    /// The function declaration of the callee.
504    const Decl *CalleeDecl;
505
506  public:
507    AbstractCallee() : CalleeDecl(nullptr) {}
508    AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
509    AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
510    bool hasFunctionDecl() const {
511      return isa_and_nonnull<FunctionDecl>(CalleeDecl);
512    }
513    const Decl *getDecl() const { return CalleeDecl; }
514    unsigned getNumParams() const {
515      if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
516        return FD->getNumParams();
517      return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
518    }
519    const ParmVarDecl *getParamDecl(unsigned I) const {
520      if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
521        return FD->getParamDecl(I);
522      return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
523    }
524  };
525
526  /// Sanitizers enabled for this function.
527  SanitizerSet SanOpts;
528
529  /// True if CodeGen currently emits code implementing sanitizer checks.
530  bool IsSanitizerScope = false;
531
532  /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
533  class SanitizerScope {
534    CodeGenFunction *CGF;
535  public:
536    SanitizerScope(CodeGenFunction *CGF);
537    ~SanitizerScope();
538  };
539
540  /// In C++, whether we are code generating a thunk.  This controls whether we
541  /// should emit cleanups.
542  bool CurFuncIsThunk = false;
543
544  /// In ARC, whether we should autorelease the return value.
545  bool AutoreleaseResult = false;
546
547  /// Whether we processed a Microsoft-style asm block during CodeGen. These can
548  /// potentially set the return value.
549  bool SawAsmBlock = false;
550
551  GlobalDecl CurSEHParent;
552
553  /// True if the current function is an outlined SEH helper. This can be a
554  /// finally block or filter expression.
555  bool IsOutlinedSEHHelper = false;
556
557  /// True if CodeGen currently emits code inside presereved access index
558  /// region.
559  bool IsInPreservedAIRegion = false;
560
561  /// True if the current statement has nomerge attribute.
562  bool InNoMergeAttributedStmt = false;
563
564  /// True if the current statement has noinline attribute.
565  bool InNoInlineAttributedStmt = false;
566
567  /// True if the current statement has always_inline attribute.
568  bool InAlwaysInlineAttributedStmt = false;
569
570  // The CallExpr within the current statement that the musttail attribute
571  // applies to.  nullptr if there is no 'musttail' on the current statement.
572  const CallExpr *MustTailCall = nullptr;
573
574  /// Returns true if a function must make progress, which means the
575  /// mustprogress attribute can be added.
576  bool checkIfFunctionMustProgress() {
577    if (CGM.getCodeGenOpts().getFiniteLoops() ==
578        CodeGenOptions::FiniteLoopsKind::Never)
579      return false;
580
581    // C++11 and later guarantees that a thread eventually will do one of the
582    // following (C++11 [intro.multithread]p24 and C++17 [intro.progress]p1):
583    // - terminate,
584    //  - make a call to a library I/O function,
585    //  - perform an access through a volatile glvalue, or
586    //  - perform a synchronization operation or an atomic operation.
587    //
588    // Hence each function is 'mustprogress' in C++11 or later.
589    return getLangOpts().CPlusPlus11;
590  }
591
592  /// Returns true if a loop must make progress, which means the mustprogress
593  /// attribute can be added. \p HasConstantCond indicates whether the branch
594  /// condition is a known constant.
595  bool checkIfLoopMustProgress(bool HasConstantCond) {
596    if (CGM.getCodeGenOpts().getFiniteLoops() ==
597        CodeGenOptions::FiniteLoopsKind::Always)
598      return true;
599    if (CGM.getCodeGenOpts().getFiniteLoops() ==
600        CodeGenOptions::FiniteLoopsKind::Never)
601      return false;
602
603    // If the containing function must make progress, loops also must make
604    // progress (as in C++11 and later).
605    if (checkIfFunctionMustProgress())
606      return true;
607
608    // Now apply rules for plain C (see  6.8.5.6 in C11).
609    // Loops with constant conditions do not have to make progress in any C
610    // version.
611    if (HasConstantCond)
612      return false;
613
614    // Loops with non-constant conditions must make progress in C11 and later.
615    return getLangOpts().C11;
616  }
617
618  const CodeGen::CGBlockInfo *BlockInfo = nullptr;
619  llvm::Value *BlockPointer = nullptr;
620
621  llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
622  FieldDecl *LambdaThisCaptureField = nullptr;
623
624  /// A mapping from NRVO variables to the flags used to indicate
625  /// when the NRVO has been applied to this variable.
626  llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
627
628  EHScopeStack EHStack;
629  llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
630  llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
631
632  llvm::Instruction *CurrentFuncletPad = nullptr;
633
634  class CallLifetimeEnd final : public EHScopeStack::Cleanup {
635    bool isRedundantBeforeReturn() override { return true; }
636
637    llvm::Value *Addr;
638    llvm::Value *Size;
639
640  public:
641    CallLifetimeEnd(Address addr, llvm::Value *size)
642        : Addr(addr.getPointer()), Size(size) {}
643
644    void Emit(CodeGenFunction &CGF, Flags flags) override {
645      CGF.EmitLifetimeEnd(Size, Addr);
646    }
647  };
648
649  /// Header for data within LifetimeExtendedCleanupStack.
650  struct LifetimeExtendedCleanupHeader {
651    /// The size of the following cleanup object.
652    unsigned Size;
653    /// The kind of cleanup to push: a value from the CleanupKind enumeration.
654    unsigned Kind : 31;
655    /// Whether this is a conditional cleanup.
656    unsigned IsConditional : 1;
657
658    size_t getSize() const { return Size; }
659    CleanupKind getKind() const { return (CleanupKind)Kind; }
660    bool isConditional() const { return IsConditional; }
661  };
662
663  /// i32s containing the indexes of the cleanup destinations.
664  Address NormalCleanupDest = Address::invalid();
665
666  unsigned NextCleanupDestIndex = 1;
667
668  /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
669  llvm::BasicBlock *EHResumeBlock = nullptr;
670
671  /// The exception slot.  All landing pads write the current exception pointer
672  /// into this alloca.
673  llvm::Value *ExceptionSlot = nullptr;
674
675  /// The selector slot.  Under the MandatoryCleanup model, all landing pads
676  /// write the current selector value into this alloca.
677  llvm::AllocaInst *EHSelectorSlot = nullptr;
678
679  /// A stack of exception code slots. Entering an __except block pushes a slot
680  /// on the stack and leaving pops one. The __exception_code() intrinsic loads
681  /// a value from the top of the stack.
682  SmallVector<Address, 1> SEHCodeSlotStack;
683
684  /// Value returned by __exception_info intrinsic.
685  llvm::Value *SEHInfo = nullptr;
686
687  /// Emits a landing pad for the current EH stack.
688  llvm::BasicBlock *EmitLandingPad();
689
690  llvm::BasicBlock *getInvokeDestImpl();
691
692  /// Parent loop-based directive for scan directive.
693  const OMPExecutableDirective *OMPParentLoopDirectiveForScan = nullptr;
694  llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
695  llvm::BasicBlock *OMPAfterScanBlock = nullptr;
696  llvm::BasicBlock *OMPScanExitBlock = nullptr;
697  llvm::BasicBlock *OMPScanDispatch = nullptr;
698  bool OMPFirstScanLoop = false;
699
700  /// Manages parent directive for scan directives.
701  class ParentLoopDirectiveForScanRegion {
702    CodeGenFunction &CGF;
703    const OMPExecutableDirective *ParentLoopDirectiveForScan;
704
705  public:
706    ParentLoopDirectiveForScanRegion(
707        CodeGenFunction &CGF,
708        const OMPExecutableDirective &ParentLoopDirectiveForScan)
709        : CGF(CGF),
710          ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) {
711      CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan;
712    }
713    ~ParentLoopDirectiveForScanRegion() {
714      CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan;
715    }
716  };
717
718  template <class T>
719  typename DominatingValue<T>::saved_type saveValueInCond(T value) {
720    return DominatingValue<T>::save(*this, value);
721  }
722
723  class CGFPOptionsRAII {
724  public:
725    CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures);
726    CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E);
727    ~CGFPOptionsRAII();
728
729  private:
730    void ConstructorHelper(FPOptions FPFeatures);
731    CodeGenFunction &CGF;
732    FPOptions OldFPFeatures;
733    llvm::fp::ExceptionBehavior OldExcept;
734    llvm::RoundingMode OldRounding;
735    std::optional<CGBuilderTy::FastMathFlagGuard> FMFGuard;
736  };
737  FPOptions CurFPFeatures;
738
739public:
740  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
741  /// rethrows.
742  SmallVector<llvm::Value*, 8> ObjCEHValueStack;
743
744  /// A class controlling the emission of a finally block.
745  class FinallyInfo {
746    /// Where the catchall's edge through the cleanup should go.
747    JumpDest RethrowDest;
748
749    /// A function to call to enter the catch.
750    llvm::FunctionCallee BeginCatchFn;
751
752    /// An i1 variable indicating whether or not the @finally is
753    /// running for an exception.
754    llvm::AllocaInst *ForEHVar = nullptr;
755
756    /// An i8* variable into which the exception pointer to rethrow
757    /// has been saved.
758    llvm::AllocaInst *SavedExnVar = nullptr;
759
760  public:
761    void enter(CodeGenFunction &CGF, const Stmt *Finally,
762               llvm::FunctionCallee beginCatchFn,
763               llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
764    void exit(CodeGenFunction &CGF);
765  };
766
767  /// Returns true inside SEH __try blocks.
768  bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
769
770  /// Returns true while emitting a cleanuppad.
771  bool isCleanupPadScope() const {
772    return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
773  }
774
775  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
776  /// current full-expression.  Safe against the possibility that
777  /// we're currently inside a conditionally-evaluated expression.
778  template <class T, class... As>
779  void pushFullExprCleanup(CleanupKind kind, As... A) {
780    // If we're not in a conditional branch, or if none of the
781    // arguments requires saving, then use the unconditional cleanup.
782    if (!isInConditionalBranch())
783      return EHStack.pushCleanup<T>(kind, A...);
784
785    // Stash values in a tuple so we can guarantee the order of saves.
786    typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
787    SavedTuple Saved{saveValueInCond(A)...};
788
789    typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
790    EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
791    initFullExprCleanup();
792  }
793
794  /// Queue a cleanup to be pushed after finishing the current full-expression,
795  /// potentially with an active flag.
796  template <class T, class... As>
797  void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
798    if (!isInConditionalBranch())
799      return pushCleanupAfterFullExprWithActiveFlag<T>(Kind, Address::invalid(),
800                                                       A...);
801
802    Address ActiveFlag = createCleanupActiveFlag();
803    assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
804           "cleanup active flag should never need saving");
805
806    typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
807    SavedTuple Saved{saveValueInCond(A)...};
808
809    typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
810    pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag, Saved);
811  }
812
813  template <class T, class... As>
814  void pushCleanupAfterFullExprWithActiveFlag(CleanupKind Kind,
815                                              Address ActiveFlag, As... A) {
816    LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
817                                            ActiveFlag.isValid()};
818
819    size_t OldSize = LifetimeExtendedCleanupStack.size();
820    LifetimeExtendedCleanupStack.resize(
821        LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
822        (Header.IsConditional ? sizeof(ActiveFlag) : 0));
823
824    static_assert(sizeof(Header) % alignof(T) == 0,
825                  "Cleanup will be allocated on misaligned address");
826    char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
827    new (Buffer) LifetimeExtendedCleanupHeader(Header);
828    new (Buffer + sizeof(Header)) T(A...);
829    if (Header.IsConditional)
830      new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
831  }
832
833  /// Set up the last cleanup that was pushed as a conditional
834  /// full-expression cleanup.
835  void initFullExprCleanup() {
836    initFullExprCleanupWithFlag(createCleanupActiveFlag());
837  }
838
839  void initFullExprCleanupWithFlag(Address ActiveFlag);
840  Address createCleanupActiveFlag();
841
842  /// PushDestructorCleanup - Push a cleanup to call the
843  /// complete-object destructor of an object of the given type at the
844  /// given address.  Does nothing if T is not a C++ class type with a
845  /// non-trivial destructor.
846  void PushDestructorCleanup(QualType T, Address Addr);
847
848  /// PushDestructorCleanup - Push a cleanup to call the
849  /// complete-object variant of the given destructor on the object at
850  /// the given address.
851  void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T,
852                             Address Addr);
853
854  /// PopCleanupBlock - Will pop the cleanup entry on the stack and
855  /// process all branch fixups.
856  void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
857
858  /// DeactivateCleanupBlock - Deactivates the given cleanup block.
859  /// The block cannot be reactivated.  Pops it if it's the top of the
860  /// stack.
861  ///
862  /// \param DominatingIP - An instruction which is known to
863  ///   dominate the current IP (if set) and which lies along
864  ///   all paths of execution between the current IP and the
865  ///   the point at which the cleanup comes into scope.
866  void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
867                              llvm::Instruction *DominatingIP);
868
869  /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
870  /// Cannot be used to resurrect a deactivated cleanup.
871  ///
872  /// \param DominatingIP - An instruction which is known to
873  ///   dominate the current IP (if set) and which lies along
874  ///   all paths of execution between the current IP and the
875  ///   the point at which the cleanup comes into scope.
876  void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
877                            llvm::Instruction *DominatingIP);
878
879  /// Enters a new scope for capturing cleanups, all of which
880  /// will be executed once the scope is exited.
881  class RunCleanupsScope {
882    EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
883    size_t LifetimeExtendedCleanupStackSize;
884    bool OldDidCallStackSave;
885  protected:
886    bool PerformCleanup;
887  private:
888
889    RunCleanupsScope(const RunCleanupsScope &) = delete;
890    void operator=(const RunCleanupsScope &) = delete;
891
892  protected:
893    CodeGenFunction& CGF;
894
895  public:
896    /// Enter a new cleanup scope.
897    explicit RunCleanupsScope(CodeGenFunction &CGF)
898      : PerformCleanup(true), CGF(CGF)
899    {
900      CleanupStackDepth = CGF.EHStack.stable_begin();
901      LifetimeExtendedCleanupStackSize =
902          CGF.LifetimeExtendedCleanupStack.size();
903      OldDidCallStackSave = CGF.DidCallStackSave;
904      CGF.DidCallStackSave = false;
905      OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
906      CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
907    }
908
909    /// Exit this cleanup scope, emitting any accumulated cleanups.
910    ~RunCleanupsScope() {
911      if (PerformCleanup)
912        ForceCleanup();
913    }
914
915    /// Determine whether this scope requires any cleanups.
916    bool requiresCleanups() const {
917      return CGF.EHStack.stable_begin() != CleanupStackDepth;
918    }
919
920    /// Force the emission of cleanups now, instead of waiting
921    /// until this object is destroyed.
922    /// \param ValuesToReload - A list of values that need to be available at
923    /// the insertion point after cleanup emission. If cleanup emission created
924    /// a shared cleanup block, these value pointers will be rewritten.
925    /// Otherwise, they not will be modified.
926    void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
927      assert(PerformCleanup && "Already forced cleanup");
928      CGF.DidCallStackSave = OldDidCallStackSave;
929      CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
930                           ValuesToReload);
931      PerformCleanup = false;
932      CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
933    }
934  };
935
936  // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
937  EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
938      EHScopeStack::stable_end();
939
940  class LexicalScope : public RunCleanupsScope {
941    SourceRange Range;
942    SmallVector<const LabelDecl*, 4> Labels;
943    LexicalScope *ParentScope;
944
945    LexicalScope(const LexicalScope &) = delete;
946    void operator=(const LexicalScope &) = delete;
947
948  public:
949    /// Enter a new cleanup scope.
950    explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
951      : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
952      CGF.CurLexicalScope = this;
953      if (CGDebugInfo *DI = CGF.getDebugInfo())
954        DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
955    }
956
957    void addLabel(const LabelDecl *label) {
958      assert(PerformCleanup && "adding label to dead scope?");
959      Labels.push_back(label);
960    }
961
962    /// Exit this cleanup scope, emitting any accumulated
963    /// cleanups.
964    ~LexicalScope() {
965      if (CGDebugInfo *DI = CGF.getDebugInfo())
966        DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
967
968      // If we should perform a cleanup, force them now.  Note that
969      // this ends the cleanup scope before rescoping any labels.
970      if (PerformCleanup) {
971        ApplyDebugLocation DL(CGF, Range.getEnd());
972        ForceCleanup();
973      }
974    }
975
976    /// Force the emission of cleanups now, instead of waiting
977    /// until this object is destroyed.
978    void ForceCleanup() {
979      CGF.CurLexicalScope = ParentScope;
980      RunCleanupsScope::ForceCleanup();
981
982      if (!Labels.empty())
983        rescopeLabels();
984    }
985
986    bool hasLabels() const {
987      return !Labels.empty();
988    }
989
990    void rescopeLabels();
991  };
992
993  typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
994
995  /// The class used to assign some variables some temporarily addresses.
996  class OMPMapVars {
997    DeclMapTy SavedLocals;
998    DeclMapTy SavedTempAddresses;
999    OMPMapVars(const OMPMapVars &) = delete;
1000    void operator=(const OMPMapVars &) = delete;
1001
1002  public:
1003    explicit OMPMapVars() = default;
1004    ~OMPMapVars() {
1005      assert(SavedLocals.empty() && "Did not restored original addresses.");
1006    };
1007
1008    /// Sets the address of the variable \p LocalVD to be \p TempAddr in
1009    /// function \p CGF.
1010    /// \return true if at least one variable was set already, false otherwise.
1011    bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
1012                    Address TempAddr) {
1013      LocalVD = LocalVD->getCanonicalDecl();
1014      // Only save it once.
1015      if (SavedLocals.count(LocalVD)) return false;
1016
1017      // Copy the existing local entry to SavedLocals.
1018      auto it = CGF.LocalDeclMap.find(LocalVD);
1019      if (it != CGF.LocalDeclMap.end())
1020        SavedLocals.try_emplace(LocalVD, it->second);
1021      else
1022        SavedLocals.try_emplace(LocalVD, Address::invalid());
1023
1024      // Generate the private entry.
1025      QualType VarTy = LocalVD->getType();
1026      if (VarTy->isReferenceType()) {
1027        Address Temp = CGF.CreateMemTemp(VarTy);
1028        CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
1029        TempAddr = Temp;
1030      }
1031      SavedTempAddresses.try_emplace(LocalVD, TempAddr);
1032
1033      return true;
1034    }
1035
1036    /// Applies new addresses to the list of the variables.
1037    /// \return true if at least one variable is using new address, false
1038    /// otherwise.
1039    bool apply(CodeGenFunction &CGF) {
1040      copyInto(SavedTempAddresses, CGF.LocalDeclMap);
1041      SavedTempAddresses.clear();
1042      return !SavedLocals.empty();
1043    }
1044
1045    /// Restores original addresses of the variables.
1046    void restore(CodeGenFunction &CGF) {
1047      if (!SavedLocals.empty()) {
1048        copyInto(SavedLocals, CGF.LocalDeclMap);
1049        SavedLocals.clear();
1050      }
1051    }
1052
1053  private:
1054    /// Copy all the entries in the source map over the corresponding
1055    /// entries in the destination, which must exist.
1056    static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
1057      for (auto &Pair : Src) {
1058        if (!Pair.second.isValid()) {
1059          Dest.erase(Pair.first);
1060          continue;
1061        }
1062
1063        auto I = Dest.find(Pair.first);
1064        if (I != Dest.end())
1065          I->second = Pair.second;
1066        else
1067          Dest.insert(Pair);
1068      }
1069    }
1070  };
1071
1072  /// The scope used to remap some variables as private in the OpenMP loop body
1073  /// (or other captured region emitted without outlining), and to restore old
1074  /// vars back on exit.
1075  class OMPPrivateScope : public RunCleanupsScope {
1076    OMPMapVars MappedVars;
1077    OMPPrivateScope(const OMPPrivateScope &) = delete;
1078    void operator=(const OMPPrivateScope &) = delete;
1079
1080  public:
1081    /// Enter a new OpenMP private scope.
1082    explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
1083
1084    /// Registers \p LocalVD variable as a private with \p Addr as the address
1085    /// of the corresponding private variable. \p
1086    /// PrivateGen is the address of the generated private variable.
1087    /// \return true if the variable is registered as private, false if it has
1088    /// been privatized already.
1089    bool addPrivate(const VarDecl *LocalVD, Address Addr) {
1090      assert(PerformCleanup && "adding private to dead scope");
1091      return MappedVars.setVarAddr(CGF, LocalVD, Addr);
1092    }
1093
1094    /// Privatizes local variables previously registered as private.
1095    /// Registration is separate from the actual privatization to allow
1096    /// initializers use values of the original variables, not the private one.
1097    /// This is important, for example, if the private variable is a class
1098    /// variable initialized by a constructor that references other private
1099    /// variables. But at initialization original variables must be used, not
1100    /// private copies.
1101    /// \return true if at least one variable was privatized, false otherwise.
1102    bool Privatize() { return MappedVars.apply(CGF); }
1103
1104    void ForceCleanup() {
1105      RunCleanupsScope::ForceCleanup();
1106      restoreMap();
1107    }
1108
1109    /// Exit scope - all the mapped variables are restored.
1110    ~OMPPrivateScope() {
1111      if (PerformCleanup)
1112        ForceCleanup();
1113    }
1114
1115    /// Checks if the global variable is captured in current function.
1116    bool isGlobalVarCaptured(const VarDecl *VD) const {
1117      VD = VD->getCanonicalDecl();
1118      return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
1119    }
1120
1121    /// Restore all mapped variables w/o clean up. This is usefully when we want
1122    /// to reference the original variables but don't want the clean up because
1123    /// that could emit lifetime end too early, causing backend issue #56913.
1124    void restoreMap() { MappedVars.restore(CGF); }
1125  };
1126
1127  /// Save/restore original map of previously emitted local vars in case when we
1128  /// need to duplicate emission of the same code several times in the same
1129  /// function for OpenMP code.
1130  class OMPLocalDeclMapRAII {
1131    CodeGenFunction &CGF;
1132    DeclMapTy SavedMap;
1133
1134  public:
1135    OMPLocalDeclMapRAII(CodeGenFunction &CGF)
1136        : CGF(CGF), SavedMap(CGF.LocalDeclMap) {}
1137    ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); }
1138  };
1139
1140  /// Takes the old cleanup stack size and emits the cleanup blocks
1141  /// that have been added.
1142  void
1143  PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
1144                   std::initializer_list<llvm::Value **> ValuesToReload = {});
1145
1146  /// Takes the old cleanup stack size and emits the cleanup blocks
1147  /// that have been added, then adds all lifetime-extended cleanups from
1148  /// the given position to the stack.
1149  void
1150  PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
1151                   size_t OldLifetimeExtendedStackSize,
1152                   std::initializer_list<llvm::Value **> ValuesToReload = {});
1153
1154  void ResolveBranchFixups(llvm::BasicBlock *Target);
1155
1156  /// The given basic block lies in the current EH scope, but may be a
1157  /// target of a potentially scope-crossing jump; get a stable handle
1158  /// to which we can perform this jump later.
1159  JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
1160    return JumpDest(Target,
1161                    EHStack.getInnermostNormalCleanup(),
1162                    NextCleanupDestIndex++);
1163  }
1164
1165  /// The given basic block lies in the current EH scope, but may be a
1166  /// target of a potentially scope-crossing jump; get a stable handle
1167  /// to which we can perform this jump later.
1168  JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
1169    return getJumpDestInCurrentScope(createBasicBlock(Name));
1170  }
1171
1172  /// EmitBranchThroughCleanup - Emit a branch from the current insert
1173  /// block through the normal cleanup handling code (if any) and then
1174  /// on to \arg Dest.
1175  void EmitBranchThroughCleanup(JumpDest Dest);
1176
1177  /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1178  /// specified destination obviously has no cleanups to run.  'false' is always
1179  /// a conservatively correct answer for this method.
1180  bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
1181
1182  /// popCatchScope - Pops the catch scope at the top of the EHScope
1183  /// stack, emitting any required code (other than the catch handlers
1184  /// themselves).
1185  void popCatchScope();
1186
1187  llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
1188  llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
1189  llvm::BasicBlock *
1190  getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
1191
1192  /// An object to manage conditionally-evaluated expressions.
1193  class ConditionalEvaluation {
1194    llvm::BasicBlock *StartBB;
1195
1196  public:
1197    ConditionalEvaluation(CodeGenFunction &CGF)
1198      : StartBB(CGF.Builder.GetInsertBlock()) {}
1199
1200    void begin(CodeGenFunction &CGF) {
1201      assert(CGF.OutermostConditional != this);
1202      if (!CGF.OutermostConditional)
1203        CGF.OutermostConditional = this;
1204    }
1205
1206    void end(CodeGenFunction &CGF) {
1207      assert(CGF.OutermostConditional != nullptr);
1208      if (CGF.OutermostConditional == this)
1209        CGF.OutermostConditional = nullptr;
1210    }
1211
1212    /// Returns a block which will be executed prior to each
1213    /// evaluation of the conditional code.
1214    llvm::BasicBlock *getStartingBlock() const {
1215      return StartBB;
1216    }
1217  };
1218
1219  /// isInConditionalBranch - Return true if we're currently emitting
1220  /// one branch or the other of a conditional expression.
1221  bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1222
1223  void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
1224    assert(isInConditionalBranch());
1225    llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1226    auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
1227    store->setAlignment(addr.getAlignment().getAsAlign());
1228  }
1229
1230  /// An RAII object to record that we're evaluating a statement
1231  /// expression.
1232  class StmtExprEvaluation {
1233    CodeGenFunction &CGF;
1234
1235    /// We have to save the outermost conditional: cleanups in a
1236    /// statement expression aren't conditional just because the
1237    /// StmtExpr is.
1238    ConditionalEvaluation *SavedOutermostConditional;
1239
1240  public:
1241    StmtExprEvaluation(CodeGenFunction &CGF)
1242      : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1243      CGF.OutermostConditional = nullptr;
1244    }
1245
1246    ~StmtExprEvaluation() {
1247      CGF.OutermostConditional = SavedOutermostConditional;
1248      CGF.EnsureInsertPoint();
1249    }
1250  };
1251
1252  /// An object which temporarily prevents a value from being
1253  /// destroyed by aggressive peephole optimizations that assume that
1254  /// all uses of a value have been realized in the IR.
1255  class PeepholeProtection {
1256    llvm::Instruction *Inst = nullptr;
1257    friend class CodeGenFunction;
1258
1259  public:
1260    PeepholeProtection() = default;
1261  };
1262
1263  /// A non-RAII class containing all the information about a bound
1264  /// opaque value.  OpaqueValueMapping, below, is a RAII wrapper for
1265  /// this which makes individual mappings very simple; using this
1266  /// class directly is useful when you have a variable number of
1267  /// opaque values or don't want the RAII functionality for some
1268  /// reason.
1269  class OpaqueValueMappingData {
1270    const OpaqueValueExpr *OpaqueValue;
1271    bool BoundLValue;
1272    CodeGenFunction::PeepholeProtection Protection;
1273
1274    OpaqueValueMappingData(const OpaqueValueExpr *ov,
1275                           bool boundLValue)
1276      : OpaqueValue(ov), BoundLValue(boundLValue) {}
1277  public:
1278    OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1279
1280    static bool shouldBindAsLValue(const Expr *expr) {
1281      // gl-values should be bound as l-values for obvious reasons.
1282      // Records should be bound as l-values because IR generation
1283      // always keeps them in memory.  Expressions of function type
1284      // act exactly like l-values but are formally required to be
1285      // r-values in C.
1286      return expr->isGLValue() ||
1287             expr->getType()->isFunctionType() ||
1288             hasAggregateEvaluationKind(expr->getType());
1289    }
1290
1291    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1292                                       const OpaqueValueExpr *ov,
1293                                       const Expr *e) {
1294      if (shouldBindAsLValue(ov))
1295        return bind(CGF, ov, CGF.EmitLValue(e));
1296      return bind(CGF, ov, CGF.EmitAnyExpr(e));
1297    }
1298
1299    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1300                                       const OpaqueValueExpr *ov,
1301                                       const LValue &lv) {
1302      assert(shouldBindAsLValue(ov));
1303      CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
1304      return OpaqueValueMappingData(ov, true);
1305    }
1306
1307    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1308                                       const OpaqueValueExpr *ov,
1309                                       const RValue &rv) {
1310      assert(!shouldBindAsLValue(ov));
1311      CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
1312
1313      OpaqueValueMappingData data(ov, false);
1314
1315      // Work around an extremely aggressive peephole optimization in
1316      // EmitScalarConversion which assumes that all other uses of a
1317      // value are extant.
1318      data.Protection = CGF.protectFromPeepholes(rv);
1319
1320      return data;
1321    }
1322
1323    bool isValid() const { return OpaqueValue != nullptr; }
1324    void clear() { OpaqueValue = nullptr; }
1325
1326    void unbind(CodeGenFunction &CGF) {
1327      assert(OpaqueValue && "no data to unbind!");
1328
1329      if (BoundLValue) {
1330        CGF.OpaqueLValues.erase(OpaqueValue);
1331      } else {
1332        CGF.OpaqueRValues.erase(OpaqueValue);
1333        CGF.unprotectFromPeepholes(Protection);
1334      }
1335    }
1336  };
1337
1338  /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1339  class OpaqueValueMapping {
1340    CodeGenFunction &CGF;
1341    OpaqueValueMappingData Data;
1342
1343  public:
1344    static bool shouldBindAsLValue(const Expr *expr) {
1345      return OpaqueValueMappingData::shouldBindAsLValue(expr);
1346    }
1347
1348    /// Build the opaque value mapping for the given conditional
1349    /// operator if it's the GNU ?: extension.  This is a common
1350    /// enough pattern that the convenience operator is really
1351    /// helpful.
1352    ///
1353    OpaqueValueMapping(CodeGenFunction &CGF,
1354                       const AbstractConditionalOperator *op) : CGF(CGF) {
1355      if (isa<ConditionalOperator>(op))
1356        // Leave Data empty.
1357        return;
1358
1359      const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1360      Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1361                                          e->getCommon());
1362    }
1363
1364    /// Build the opaque value mapping for an OpaqueValueExpr whose source
1365    /// expression is set to the expression the OVE represents.
1366    OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1367        : CGF(CGF) {
1368      if (OV) {
1369        assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1370                                      "for OVE with no source expression");
1371        Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1372      }
1373    }
1374
1375    OpaqueValueMapping(CodeGenFunction &CGF,
1376                       const OpaqueValueExpr *opaqueValue,
1377                       LValue lvalue)
1378      : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1379    }
1380
1381    OpaqueValueMapping(CodeGenFunction &CGF,
1382                       const OpaqueValueExpr *opaqueValue,
1383                       RValue rvalue)
1384      : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1385    }
1386
1387    void pop() {
1388      Data.unbind(CGF);
1389      Data.clear();
1390    }
1391
1392    ~OpaqueValueMapping() {
1393      if (Data.isValid()) Data.unbind(CGF);
1394    }
1395  };
1396
1397private:
1398  CGDebugInfo *DebugInfo;
1399  /// Used to create unique names for artificial VLA size debug info variables.
1400  unsigned VLAExprCounter = 0;
1401  bool DisableDebugInfo = false;
1402
1403  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1404  /// calling llvm.stacksave for multiple VLAs in the same scope.
1405  bool DidCallStackSave = false;
1406
1407  /// IndirectBranch - The first time an indirect goto is seen we create a block
1408  /// with an indirect branch.  Every time we see the address of a label taken,
1409  /// we add the label to the indirect goto.  Every subsequent indirect goto is
1410  /// codegen'd as a jump to the IndirectBranch's basic block.
1411  llvm::IndirectBrInst *IndirectBranch = nullptr;
1412
1413  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1414  /// decls.
1415  DeclMapTy LocalDeclMap;
1416
1417  // Keep track of the cleanups for callee-destructed parameters pushed to the
1418  // cleanup stack so that they can be deactivated later.
1419  llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1420      CalleeDestructedParamCleanups;
1421
1422  /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1423  /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1424  /// parameter.
1425  llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1426      SizeArguments;
1427
1428  /// Track escaped local variables with auto storage. Used during SEH
1429  /// outlining to produce a call to llvm.localescape.
1430  llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1431
1432  /// LabelMap - This keeps track of the LLVM basic block for each C label.
1433  llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1434
1435  // BreakContinueStack - This keeps track of where break and continue
1436  // statements should jump to.
1437  struct BreakContinue {
1438    BreakContinue(JumpDest Break, JumpDest Continue)
1439      : BreakBlock(Break), ContinueBlock(Continue) {}
1440
1441    JumpDest BreakBlock;
1442    JumpDest ContinueBlock;
1443  };
1444  SmallVector<BreakContinue, 8> BreakContinueStack;
1445
1446  /// Handles cancellation exit points in OpenMP-related constructs.
1447  class OpenMPCancelExitStack {
1448    /// Tracks cancellation exit point and join point for cancel-related exit
1449    /// and normal exit.
1450    struct CancelExit {
1451      CancelExit() = default;
1452      CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1453                 JumpDest ContBlock)
1454          : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1455      OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown;
1456      /// true if the exit block has been emitted already by the special
1457      /// emitExit() call, false if the default codegen is used.
1458      bool HasBeenEmitted = false;
1459      JumpDest ExitBlock;
1460      JumpDest ContBlock;
1461    };
1462
1463    SmallVector<CancelExit, 8> Stack;
1464
1465  public:
1466    OpenMPCancelExitStack() : Stack(1) {}
1467    ~OpenMPCancelExitStack() = default;
1468    /// Fetches the exit block for the current OpenMP construct.
1469    JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1470    /// Emits exit block with special codegen procedure specific for the related
1471    /// OpenMP construct + emits code for normal construct cleanup.
1472    void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1473                  const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1474      if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1475        assert(CGF.getOMPCancelDestination(Kind).isValid());
1476        assert(CGF.HaveInsertPoint());
1477        assert(!Stack.back().HasBeenEmitted);
1478        auto IP = CGF.Builder.saveAndClearIP();
1479        CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1480        CodeGen(CGF);
1481        CGF.EmitBranch(Stack.back().ContBlock.getBlock());
1482        CGF.Builder.restoreIP(IP);
1483        Stack.back().HasBeenEmitted = true;
1484      }
1485      CodeGen(CGF);
1486    }
1487    /// Enter the cancel supporting \a Kind construct.
1488    /// \param Kind OpenMP directive that supports cancel constructs.
1489    /// \param HasCancel true, if the construct has inner cancel directive,
1490    /// false otherwise.
1491    void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1492      Stack.push_back({Kind,
1493                       HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1494                                 : JumpDest(),
1495                       HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1496                                 : JumpDest()});
1497    }
1498    /// Emits default exit point for the cancel construct (if the special one
1499    /// has not be used) + join point for cancel/normal exits.
1500    void exit(CodeGenFunction &CGF) {
1501      if (getExitBlock().isValid()) {
1502        assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1503        bool HaveIP = CGF.HaveInsertPoint();
1504        if (!Stack.back().HasBeenEmitted) {
1505          if (HaveIP)
1506            CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1507          CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1508          CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1509        }
1510        CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1511        if (!HaveIP) {
1512          CGF.Builder.CreateUnreachable();
1513          CGF.Builder.ClearInsertionPoint();
1514        }
1515      }
1516      Stack.pop_back();
1517    }
1518  };
1519  OpenMPCancelExitStack OMPCancelStack;
1520
1521  /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin.
1522  llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
1523                                                    Stmt::Likelihood LH);
1524
1525  CodeGenPGO PGO;
1526
1527  /// Bitmap used by MC/DC to track condition outcomes of a boolean expression.
1528  Address MCDCCondBitmapAddr = Address::invalid();
1529
1530  /// Calculate branch weights appropriate for PGO data
1531  llvm::MDNode *createProfileWeights(uint64_t TrueCount,
1532                                     uint64_t FalseCount) const;
1533  llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const;
1534  llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1535                                            uint64_t LoopCount) const;
1536
1537public:
1538  /// Increment the profiler's counter for the given statement by \p StepV.
1539  /// If \p StepV is null, the default increment is 1.
1540  void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1541    if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1542        !CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1543        !CurFn->hasFnAttribute(llvm::Attribute::SkipProfile))
1544      PGO.emitCounterIncrement(Builder, S, StepV);
1545    PGO.setCurrentStmt(S);
1546  }
1547
1548  bool isMCDCCoverageEnabled() const {
1549    return (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1550            CGM.getCodeGenOpts().MCDCCoverage &&
1551            !CurFn->hasFnAttribute(llvm::Attribute::NoProfile));
1552  }
1553
1554  /// Allocate a temp value on the stack that MCDC can use to track condition
1555  /// results.
1556  void maybeCreateMCDCCondBitmap() {
1557    if (isMCDCCoverageEnabled()) {
1558      PGO.emitMCDCParameters(Builder);
1559      MCDCCondBitmapAddr =
1560          CreateIRTemp(getContext().UnsignedIntTy, "mcdc.addr");
1561    }
1562  }
1563
1564  bool isBinaryLogicalOp(const Expr *E) const {
1565    const BinaryOperator *BOp = dyn_cast<BinaryOperator>(E->IgnoreParens());
1566    return (BOp && BOp->isLogicalOp());
1567  }
1568
1569  /// Zero-init the MCDC temp value.
1570  void maybeResetMCDCCondBitmap(const Expr *E) {
1571    if (isMCDCCoverageEnabled() && isBinaryLogicalOp(E)) {
1572      PGO.emitMCDCCondBitmapReset(Builder, E, MCDCCondBitmapAddr);
1573      PGO.setCurrentStmt(E);
1574    }
1575  }
1576
1577  /// Increment the profiler's counter for the given expression by \p StepV.
1578  /// If \p StepV is null, the default increment is 1.
1579  void maybeUpdateMCDCTestVectorBitmap(const Expr *E) {
1580    if (isMCDCCoverageEnabled() && isBinaryLogicalOp(E)) {
1581      PGO.emitMCDCTestVectorBitmapUpdate(Builder, E, MCDCCondBitmapAddr);
1582      PGO.setCurrentStmt(E);
1583    }
1584  }
1585
1586  /// Update the MCDC temp value with the condition's evaluated result.
1587  void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val) {
1588    if (isMCDCCoverageEnabled()) {
1589      PGO.emitMCDCCondBitmapUpdate(Builder, E, MCDCCondBitmapAddr, Val);
1590      PGO.setCurrentStmt(E);
1591    }
1592  }
1593
1594  /// Get the profiler's count for the given statement.
1595  uint64_t getProfileCount(const Stmt *S) {
1596    return PGO.getStmtCount(S).value_or(0);
1597  }
1598
1599  /// Set the profiler's current count.
1600  void setCurrentProfileCount(uint64_t Count) {
1601    PGO.setCurrentRegionCount(Count);
1602  }
1603
1604  /// Get the profiler's current count. This is generally the count for the most
1605  /// recently incremented counter.
1606  uint64_t getCurrentProfileCount() {
1607    return PGO.getCurrentRegionCount();
1608  }
1609
1610private:
1611
1612  /// SwitchInsn - This is nearest current switch instruction. It is null if
1613  /// current context is not in a switch.
1614  llvm::SwitchInst *SwitchInsn = nullptr;
1615  /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1616  SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1617
1618  /// The likelihood attributes of the SwitchCase.
1619  SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr;
1620
1621  /// CaseRangeBlock - This block holds if condition check for last case
1622  /// statement range in current switch instruction.
1623  llvm::BasicBlock *CaseRangeBlock = nullptr;
1624
1625  /// OpaqueLValues - Keeps track of the current set of opaque value
1626  /// expressions.
1627  llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1628  llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1629
1630  // VLASizeMap - This keeps track of the associated size for each VLA type.
1631  // We track this by the size expression rather than the type itself because
1632  // in certain situations, like a const qualifier applied to an VLA typedef,
1633  // multiple VLA types can share the same size expression.
1634  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1635  // enter/leave scopes.
1636  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1637
1638  /// A block containing a single 'unreachable' instruction.  Created
1639  /// lazily by getUnreachableBlock().
1640  llvm::BasicBlock *UnreachableBlock = nullptr;
1641
1642  /// Counts of the number return expressions in the function.
1643  unsigned NumReturnExprs = 0;
1644
1645  /// Count the number of simple (constant) return expressions in the function.
1646  unsigned NumSimpleReturnExprs = 0;
1647
1648  /// The last regular (non-return) debug location (breakpoint) in the function.
1649  SourceLocation LastStopPoint;
1650
1651public:
1652  /// Source location information about the default argument or member
1653  /// initializer expression we're evaluating, if any.
1654  CurrentSourceLocExprScope CurSourceLocExprScope;
1655  using SourceLocExprScopeGuard =
1656      CurrentSourceLocExprScope::SourceLocExprScopeGuard;
1657
1658  /// A scope within which we are constructing the fields of an object which
1659  /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1660  /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1661  class FieldConstructionScope {
1662  public:
1663    FieldConstructionScope(CodeGenFunction &CGF, Address This)
1664        : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1665      CGF.CXXDefaultInitExprThis = This;
1666    }
1667    ~FieldConstructionScope() {
1668      CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1669    }
1670
1671  private:
1672    CodeGenFunction &CGF;
1673    Address OldCXXDefaultInitExprThis;
1674  };
1675
1676  /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1677  /// is overridden to be the object under construction.
1678  class CXXDefaultInitExprScope  {
1679  public:
1680    CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E)
1681        : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1682          OldCXXThisAlignment(CGF.CXXThisAlignment),
1683          SourceLocScope(E, CGF.CurSourceLocExprScope) {
1684      CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1685      CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1686    }
1687    ~CXXDefaultInitExprScope() {
1688      CGF.CXXThisValue = OldCXXThisValue;
1689      CGF.CXXThisAlignment = OldCXXThisAlignment;
1690    }
1691
1692  public:
1693    CodeGenFunction &CGF;
1694    llvm::Value *OldCXXThisValue;
1695    CharUnits OldCXXThisAlignment;
1696    SourceLocExprScopeGuard SourceLocScope;
1697  };
1698
1699  struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
1700    CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E)
1701        : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {}
1702  };
1703
1704  /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1705  /// current loop index is overridden.
1706  class ArrayInitLoopExprScope {
1707  public:
1708    ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1709      : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1710      CGF.ArrayInitIndex = Index;
1711    }
1712    ~ArrayInitLoopExprScope() {
1713      CGF.ArrayInitIndex = OldArrayInitIndex;
1714    }
1715
1716  private:
1717    CodeGenFunction &CGF;
1718    llvm::Value *OldArrayInitIndex;
1719  };
1720
1721  class InlinedInheritingConstructorScope {
1722  public:
1723    InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1724        : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1725          OldCurCodeDecl(CGF.CurCodeDecl),
1726          OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1727          OldCXXABIThisValue(CGF.CXXABIThisValue),
1728          OldCXXThisValue(CGF.CXXThisValue),
1729          OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1730          OldCXXThisAlignment(CGF.CXXThisAlignment),
1731          OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1732          OldCXXInheritedCtorInitExprArgs(
1733              std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1734      CGF.CurGD = GD;
1735      CGF.CurFuncDecl = CGF.CurCodeDecl =
1736          cast<CXXConstructorDecl>(GD.getDecl());
1737      CGF.CXXABIThisDecl = nullptr;
1738      CGF.CXXABIThisValue = nullptr;
1739      CGF.CXXThisValue = nullptr;
1740      CGF.CXXABIThisAlignment = CharUnits();
1741      CGF.CXXThisAlignment = CharUnits();
1742      CGF.ReturnValue = Address::invalid();
1743      CGF.FnRetTy = QualType();
1744      CGF.CXXInheritedCtorInitExprArgs.clear();
1745    }
1746    ~InlinedInheritingConstructorScope() {
1747      CGF.CurGD = OldCurGD;
1748      CGF.CurFuncDecl = OldCurFuncDecl;
1749      CGF.CurCodeDecl = OldCurCodeDecl;
1750      CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1751      CGF.CXXABIThisValue = OldCXXABIThisValue;
1752      CGF.CXXThisValue = OldCXXThisValue;
1753      CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1754      CGF.CXXThisAlignment = OldCXXThisAlignment;
1755      CGF.ReturnValue = OldReturnValue;
1756      CGF.FnRetTy = OldFnRetTy;
1757      CGF.CXXInheritedCtorInitExprArgs =
1758          std::move(OldCXXInheritedCtorInitExprArgs);
1759    }
1760
1761  private:
1762    CodeGenFunction &CGF;
1763    GlobalDecl OldCurGD;
1764    const Decl *OldCurFuncDecl;
1765    const Decl *OldCurCodeDecl;
1766    ImplicitParamDecl *OldCXXABIThisDecl;
1767    llvm::Value *OldCXXABIThisValue;
1768    llvm::Value *OldCXXThisValue;
1769    CharUnits OldCXXABIThisAlignment;
1770    CharUnits OldCXXThisAlignment;
1771    Address OldReturnValue;
1772    QualType OldFnRetTy;
1773    CallArgList OldCXXInheritedCtorInitExprArgs;
1774  };
1775
1776  // Helper class for the OpenMP IR Builder. Allows reusability of code used for
1777  // region body, and finalization codegen callbacks. This will class will also
1778  // contain privatization functions used by the privatization call backs
1779  //
1780  // TODO: this is temporary class for things that are being moved out of
1781  // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or
1782  // utility function for use with the OMPBuilder. Once that move to use the
1783  // OMPBuilder is done, everything here will either become part of CodeGenFunc.
1784  // directly, or a new helper class that will contain functions used by both
1785  // this and the OMPBuilder
1786
1787  struct OMPBuilderCBHelpers {
1788
1789    OMPBuilderCBHelpers() = delete;
1790    OMPBuilderCBHelpers(const OMPBuilderCBHelpers &) = delete;
1791    OMPBuilderCBHelpers &operator=(const OMPBuilderCBHelpers &) = delete;
1792
1793    using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1794
1795    /// Cleanup action for allocate support.
1796    class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
1797
1798    private:
1799      llvm::CallInst *RTLFnCI;
1800
1801    public:
1802      OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) {
1803        RLFnCI->removeFromParent();
1804      }
1805
1806      void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1807        if (!CGF.HaveInsertPoint())
1808          return;
1809        CGF.Builder.Insert(RTLFnCI);
1810      }
1811    };
1812
1813    /// Returns address of the threadprivate variable for the current
1814    /// thread. This Also create any necessary OMP runtime calls.
1815    ///
1816    /// \param VD VarDecl for Threadprivate variable.
1817    /// \param VDAddr Address of the Vardecl
1818    /// \param Loc  The location where the barrier directive was encountered
1819    static Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
1820                                          const VarDecl *VD, Address VDAddr,
1821                                          SourceLocation Loc);
1822
1823    /// Gets the OpenMP-specific address of the local variable /p VD.
1824    static Address getAddressOfLocalVariable(CodeGenFunction &CGF,
1825                                             const VarDecl *VD);
1826    /// Get the platform-specific name separator.
1827    /// \param Parts different parts of the final name that needs separation
1828    /// \param FirstSeparator First separator used between the initial two
1829    ///        parts of the name.
1830    /// \param Separator separator used between all of the rest consecutinve
1831    ///        parts of the name
1832    static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
1833                                             StringRef FirstSeparator = ".",
1834                                             StringRef Separator = ".");
1835    /// Emit the Finalization for an OMP region
1836    /// \param CGF	The Codegen function this belongs to
1837    /// \param IP	Insertion point for generating the finalization code.
1838    static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP) {
1839      CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1840      assert(IP.getBlock()->end() != IP.getPoint() &&
1841             "OpenMP IR Builder should cause terminated block!");
1842
1843      llvm::BasicBlock *IPBB = IP.getBlock();
1844      llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor();
1845      assert(DestBB && "Finalization block should have one successor!");
1846
1847      // erase and replace with cleanup branch.
1848      IPBB->getTerminator()->eraseFromParent();
1849      CGF.Builder.SetInsertPoint(IPBB);
1850      CodeGenFunction::JumpDest Dest = CGF.getJumpDestInCurrentScope(DestBB);
1851      CGF.EmitBranchThroughCleanup(Dest);
1852    }
1853
1854    /// Emit the body of an OMP region
1855    /// \param CGF	          The Codegen function this belongs to
1856    /// \param RegionBodyStmt The body statement for the OpenMP region being
1857    ///                       generated
1858    /// \param AllocaIP       Where to insert alloca instructions
1859    /// \param CodeGenIP      Where to insert the region code
1860    /// \param RegionName     Name to be used for new blocks
1861    static void EmitOMPInlinedRegionBody(CodeGenFunction &CGF,
1862                                         const Stmt *RegionBodyStmt,
1863                                         InsertPointTy AllocaIP,
1864                                         InsertPointTy CodeGenIP,
1865                                         Twine RegionName);
1866
1867    static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP,
1868                                llvm::BasicBlock &FiniBB, llvm::Function *Fn,
1869                                ArrayRef<llvm::Value *> Args) {
1870      llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1871      if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
1872        CodeGenIPBBTI->eraseFromParent();
1873
1874      CGF.Builder.SetInsertPoint(CodeGenIPBB);
1875
1876      if (Fn->doesNotThrow())
1877        CGF.EmitNounwindRuntimeCall(Fn, Args);
1878      else
1879        CGF.EmitRuntimeCall(Fn, Args);
1880
1881      if (CGF.Builder.saveIP().isSet())
1882        CGF.Builder.CreateBr(&FiniBB);
1883    }
1884
1885    /// Emit the body of an OMP region that will be outlined in
1886    /// OpenMPIRBuilder::finalize().
1887    /// \param CGF	          The Codegen function this belongs to
1888    /// \param RegionBodyStmt The body statement for the OpenMP region being
1889    ///                       generated
1890    /// \param AllocaIP       Where to insert alloca instructions
1891    /// \param CodeGenIP      Where to insert the region code
1892    /// \param RegionName     Name to be used for new blocks
1893    static void EmitOMPOutlinedRegionBody(CodeGenFunction &CGF,
1894                                          const Stmt *RegionBodyStmt,
1895                                          InsertPointTy AllocaIP,
1896                                          InsertPointTy CodeGenIP,
1897                                          Twine RegionName);
1898
1899    /// RAII for preserving necessary info during Outlined region body codegen.
1900    class OutlinedRegionBodyRAII {
1901
1902      llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
1903      CodeGenFunction::JumpDest OldReturnBlock;
1904      CodeGenFunction &CGF;
1905
1906    public:
1907      OutlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
1908                             llvm::BasicBlock &RetBB)
1909          : CGF(cgf) {
1910        assert(AllocaIP.isSet() &&
1911               "Must specify Insertion point for allocas of outlined function");
1912        OldAllocaIP = CGF.AllocaInsertPt;
1913        CGF.AllocaInsertPt = &*AllocaIP.getPoint();
1914
1915        OldReturnBlock = CGF.ReturnBlock;
1916        CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB);
1917      }
1918
1919      ~OutlinedRegionBodyRAII() {
1920        CGF.AllocaInsertPt = OldAllocaIP;
1921        CGF.ReturnBlock = OldReturnBlock;
1922      }
1923    };
1924
1925    /// RAII for preserving necessary info during inlined region body codegen.
1926    class InlinedRegionBodyRAII {
1927
1928      llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
1929      CodeGenFunction &CGF;
1930
1931    public:
1932      InlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
1933                            llvm::BasicBlock &FiniBB)
1934          : CGF(cgf) {
1935        // Alloca insertion block should be in the entry block of the containing
1936        // function so it expects an empty AllocaIP in which case will reuse the
1937        // old alloca insertion point, or a new AllocaIP in the same block as
1938        // the old one
1939        assert((!AllocaIP.isSet() ||
1940                CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) &&
1941               "Insertion point should be in the entry block of containing "
1942               "function!");
1943        OldAllocaIP = CGF.AllocaInsertPt;
1944        if (AllocaIP.isSet())
1945          CGF.AllocaInsertPt = &*AllocaIP.getPoint();
1946
1947        // TODO: Remove the call, after making sure the counter is not used by
1948        //       the EHStack.
1949        // Since this is an inlined region, it should not modify the
1950        // ReturnBlock, and should reuse the one for the enclosing outlined
1951        // region. So, the JumpDest being return by the function is discarded
1952        (void)CGF.getJumpDestInCurrentScope(&FiniBB);
1953      }
1954
1955      ~InlinedRegionBodyRAII() { CGF.AllocaInsertPt = OldAllocaIP; }
1956    };
1957  };
1958
1959private:
1960  /// CXXThisDecl - When generating code for a C++ member function,
1961  /// this will hold the implicit 'this' declaration.
1962  ImplicitParamDecl *CXXABIThisDecl = nullptr;
1963  llvm::Value *CXXABIThisValue = nullptr;
1964  llvm::Value *CXXThisValue = nullptr;
1965  CharUnits CXXABIThisAlignment;
1966  CharUnits CXXThisAlignment;
1967
1968  /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1969  /// this expression.
1970  Address CXXDefaultInitExprThis = Address::invalid();
1971
1972  /// The current array initialization index when evaluating an
1973  /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1974  llvm::Value *ArrayInitIndex = nullptr;
1975
1976  /// The values of function arguments to use when evaluating
1977  /// CXXInheritedCtorInitExprs within this context.
1978  CallArgList CXXInheritedCtorInitExprArgs;
1979
1980  /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1981  /// destructor, this will hold the implicit argument (e.g. VTT).
1982  ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
1983  llvm::Value *CXXStructorImplicitParamValue = nullptr;
1984
1985  /// OutermostConditional - Points to the outermost active
1986  /// conditional control.  This is used so that we know if a
1987  /// temporary should be destroyed conditionally.
1988  ConditionalEvaluation *OutermostConditional = nullptr;
1989
1990  /// The current lexical scope.
1991  LexicalScope *CurLexicalScope = nullptr;
1992
1993  /// The current source location that should be used for exception
1994  /// handling code.
1995  SourceLocation CurEHLocation;
1996
1997  /// BlockByrefInfos - For each __block variable, contains
1998  /// information about the layout of the variable.
1999  llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
2000
2001  /// Used by -fsanitize=nullability-return to determine whether the return
2002  /// value can be checked.
2003  llvm::Value *RetValNullabilityPrecondition = nullptr;
2004
2005  /// Check if -fsanitize=nullability-return instrumentation is required for
2006  /// this function.
2007  bool requiresReturnValueNullabilityCheck() const {
2008    return RetValNullabilityPrecondition;
2009  }
2010
2011  /// Used to store precise source locations for return statements by the
2012  /// runtime return value checks.
2013  Address ReturnLocation = Address::invalid();
2014
2015  /// Check if the return value of this function requires sanitization.
2016  bool requiresReturnValueCheck() const;
2017
2018  bool isInAllocaArgument(CGCXXABI &ABI, QualType Ty);
2019  bool hasInAllocaArg(const CXXMethodDecl *MD);
2020
2021  llvm::BasicBlock *TerminateLandingPad = nullptr;
2022  llvm::BasicBlock *TerminateHandler = nullptr;
2023  llvm::SmallVector<llvm::BasicBlock *, 2> TrapBBs;
2024
2025  /// Terminate funclets keyed by parent funclet pad.
2026  llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
2027
2028  /// Largest vector width used in ths function. Will be used to create a
2029  /// function attribute.
2030  unsigned LargestVectorWidth = 0;
2031
2032  /// True if we need emit the life-time markers. This is initially set in
2033  /// the constructor, but could be overwritten to true if this is a coroutine.
2034  bool ShouldEmitLifetimeMarkers;
2035
2036  /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
2037  /// the function metadata.
2038  void EmitKernelMetadata(const FunctionDecl *FD, llvm::Function *Fn);
2039
2040public:
2041  CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
2042  ~CodeGenFunction();
2043
2044  CodeGenTypes &getTypes() const { return CGM.getTypes(); }
2045  ASTContext &getContext() const { return CGM.getContext(); }
2046  CGDebugInfo *getDebugInfo() {
2047    if (DisableDebugInfo)
2048      return nullptr;
2049    return DebugInfo;
2050  }
2051  void disableDebugInfo() { DisableDebugInfo = true; }
2052  void enableDebugInfo() { DisableDebugInfo = false; }
2053
2054  bool shouldUseFusedARCCalls() {
2055    return CGM.getCodeGenOpts().OptimizationLevel == 0;
2056  }
2057
2058  const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
2059
2060  /// Returns a pointer to the function's exception object and selector slot,
2061  /// which is assigned in every landing pad.
2062  Address getExceptionSlot();
2063  Address getEHSelectorSlot();
2064
2065  /// Returns the contents of the function's exception object and selector
2066  /// slots.
2067  llvm::Value *getExceptionFromSlot();
2068  llvm::Value *getSelectorFromSlot();
2069
2070  Address getNormalCleanupDestSlot();
2071
2072  llvm::BasicBlock *getUnreachableBlock() {
2073    if (!UnreachableBlock) {
2074      UnreachableBlock = createBasicBlock("unreachable");
2075      new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
2076    }
2077    return UnreachableBlock;
2078  }
2079
2080  llvm::BasicBlock *getInvokeDest() {
2081    if (!EHStack.requiresLandingPad()) return nullptr;
2082    return getInvokeDestImpl();
2083  }
2084
2085  bool currentFunctionUsesSEHTry() const { return !!CurSEHParent; }
2086
2087  const TargetInfo &getTarget() const { return Target; }
2088  llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
2089  const TargetCodeGenInfo &getTargetHooks() const {
2090    return CGM.getTargetCodeGenInfo();
2091  }
2092
2093  //===--------------------------------------------------------------------===//
2094  //                                  Cleanups
2095  //===--------------------------------------------------------------------===//
2096
2097  typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
2098
2099  void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2100                                        Address arrayEndPointer,
2101                                        QualType elementType,
2102                                        CharUnits elementAlignment,
2103                                        Destroyer *destroyer);
2104  void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2105                                      llvm::Value *arrayEnd,
2106                                      QualType elementType,
2107                                      CharUnits elementAlignment,
2108                                      Destroyer *destroyer);
2109
2110  void pushDestroy(QualType::DestructionKind dtorKind,
2111                   Address addr, QualType type);
2112  void pushEHDestroy(QualType::DestructionKind dtorKind,
2113                     Address addr, QualType type);
2114  void pushDestroy(CleanupKind kind, Address addr, QualType type,
2115                   Destroyer *destroyer, bool useEHCleanupForArray);
2116  void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
2117                                   QualType type, Destroyer *destroyer,
2118                                   bool useEHCleanupForArray);
2119  void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
2120                                   llvm::Value *CompletePtr,
2121                                   QualType ElementType);
2122  void pushStackRestore(CleanupKind kind, Address SPMem);
2123  void pushKmpcAllocFree(CleanupKind Kind,
2124                         std::pair<llvm::Value *, llvm::Value *> AddrSizePair);
2125  void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
2126                   bool useEHCleanupForArray);
2127  llvm::Function *generateDestroyHelper(Address addr, QualType type,
2128                                        Destroyer *destroyer,
2129                                        bool useEHCleanupForArray,
2130                                        const VarDecl *VD);
2131  void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
2132                        QualType elementType, CharUnits elementAlign,
2133                        Destroyer *destroyer,
2134                        bool checkZeroLength, bool useEHCleanup);
2135
2136  Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
2137
2138  /// Determines whether an EH cleanup is required to destroy a type
2139  /// with the given destruction kind.
2140  bool needsEHCleanup(QualType::DestructionKind kind) {
2141    switch (kind) {
2142    case QualType::DK_none:
2143      return false;
2144    case QualType::DK_cxx_destructor:
2145    case QualType::DK_objc_weak_lifetime:
2146    case QualType::DK_nontrivial_c_struct:
2147      return getLangOpts().Exceptions;
2148    case QualType::DK_objc_strong_lifetime:
2149      return getLangOpts().Exceptions &&
2150             CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
2151    }
2152    llvm_unreachable("bad destruction kind");
2153  }
2154
2155  CleanupKind getCleanupKind(QualType::DestructionKind kind) {
2156    return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
2157  }
2158
2159  //===--------------------------------------------------------------------===//
2160  //                                  Objective-C
2161  //===--------------------------------------------------------------------===//
2162
2163  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
2164
2165  void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
2166
2167  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
2168  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
2169                          const ObjCPropertyImplDecl *PID);
2170  void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
2171                              const ObjCPropertyImplDecl *propImpl,
2172                              const ObjCMethodDecl *GetterMothodDecl,
2173                              llvm::Constant *AtomicHelperFn);
2174
2175  void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
2176                                  ObjCMethodDecl *MD, bool ctor);
2177
2178  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
2179  /// for the given property.
2180  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
2181                          const ObjCPropertyImplDecl *PID);
2182  void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
2183                              const ObjCPropertyImplDecl *propImpl,
2184                              llvm::Constant *AtomicHelperFn);
2185
2186  //===--------------------------------------------------------------------===//
2187  //                                  Block Bits
2188  //===--------------------------------------------------------------------===//
2189
2190  /// Emit block literal.
2191  /// \return an LLVM value which is a pointer to a struct which contains
2192  /// information about the block, including the block invoke function, the
2193  /// captured variables, etc.
2194  llvm::Value *EmitBlockLiteral(const BlockExpr *);
2195
2196  llvm::Function *GenerateBlockFunction(GlobalDecl GD,
2197                                        const CGBlockInfo &Info,
2198                                        const DeclMapTy &ldm,
2199                                        bool IsLambdaConversionToBlock,
2200                                        bool BuildGlobalBlock);
2201
2202  /// Check if \p T is a C++ class that has a destructor that can throw.
2203  static bool cxxDestructorCanThrow(QualType T);
2204
2205  llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
2206  llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
2207  llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
2208                                             const ObjCPropertyImplDecl *PID);
2209  llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
2210                                             const ObjCPropertyImplDecl *PID);
2211  llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
2212
2213  void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
2214                         bool CanThrow);
2215
2216  class AutoVarEmission;
2217
2218  void emitByrefStructureInit(const AutoVarEmission &emission);
2219
2220  /// Enter a cleanup to destroy a __block variable.  Note that this
2221  /// cleanup should be a no-op if the variable hasn't left the stack
2222  /// yet; if a cleanup is required for the variable itself, that needs
2223  /// to be done externally.
2224  ///
2225  /// \param Kind Cleanup kind.
2226  ///
2227  /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
2228  /// structure that will be passed to _Block_object_dispose. When
2229  /// \p LoadBlockVarAddr is true, the address of the field of the block
2230  /// structure that holds the address of the __block structure.
2231  ///
2232  /// \param Flags The flag that will be passed to _Block_object_dispose.
2233  ///
2234  /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
2235  /// \p Addr to get the address of the __block structure.
2236  void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
2237                         bool LoadBlockVarAddr, bool CanThrow);
2238
2239  void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
2240                                llvm::Value *ptr);
2241
2242  Address LoadBlockStruct();
2243  Address GetAddrOfBlockDecl(const VarDecl *var);
2244
2245  /// BuildBlockByrefAddress - Computes the location of the
2246  /// data in a variable which is declared as __block.
2247  Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
2248                                bool followForward = true);
2249  Address emitBlockByrefAddress(Address baseAddr,
2250                                const BlockByrefInfo &info,
2251                                bool followForward,
2252                                const llvm::Twine &name);
2253
2254  const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
2255
2256  QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
2257
2258  void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
2259                    const CGFunctionInfo &FnInfo);
2260
2261  /// Annotate the function with an attribute that disables TSan checking at
2262  /// runtime.
2263  void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
2264
2265  /// Emit code for the start of a function.
2266  /// \param Loc       The location to be associated with the function.
2267  /// \param StartLoc  The location of the function body.
2268  void StartFunction(GlobalDecl GD,
2269                     QualType RetTy,
2270                     llvm::Function *Fn,
2271                     const CGFunctionInfo &FnInfo,
2272                     const FunctionArgList &Args,
2273                     SourceLocation Loc = SourceLocation(),
2274                     SourceLocation StartLoc = SourceLocation());
2275
2276  static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
2277
2278  void EmitConstructorBody(FunctionArgList &Args);
2279  void EmitDestructorBody(FunctionArgList &Args);
2280  void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
2281  void EmitFunctionBody(const Stmt *Body);
2282  void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
2283
2284  void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
2285                                  CallArgList &CallArgs,
2286                                  const CGFunctionInfo *CallOpFnInfo = nullptr,
2287                                  llvm::Constant *CallOpFn = nullptr);
2288  void EmitLambdaBlockInvokeBody();
2289  void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
2290  void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD,
2291                                      CallArgList &CallArgs);
2292  void EmitLambdaInAllocaImplFn(const CXXMethodDecl *CallOp,
2293                                const CGFunctionInfo **ImplFnInfo,
2294                                llvm::Function **ImplFn);
2295  void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD);
2296  void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) {
2297    EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2298  }
2299  void EmitAsanPrologueOrEpilogue(bool Prologue);
2300
2301  /// Emit the unified return block, trying to avoid its emission when
2302  /// possible.
2303  /// \return The debug location of the user written return statement if the
2304  /// return block is avoided.
2305  llvm::DebugLoc EmitReturnBlock();
2306
2307  /// FinishFunction - Complete IR generation of the current function. It is
2308  /// legal to call this function even if there is no current insertion point.
2309  void FinishFunction(SourceLocation EndLoc=SourceLocation());
2310
2311  void StartThunk(llvm::Function *Fn, GlobalDecl GD,
2312                  const CGFunctionInfo &FnInfo, bool IsUnprototyped);
2313
2314  void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
2315                                 const ThunkInfo *Thunk, bool IsUnprototyped);
2316
2317  void FinishThunk();
2318
2319  /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
2320  void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
2321                         llvm::FunctionCallee Callee);
2322
2323  /// Generate a thunk for the given method.
2324  void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
2325                     GlobalDecl GD, const ThunkInfo &Thunk,
2326                     bool IsUnprototyped);
2327
2328  llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
2329                                       const CGFunctionInfo &FnInfo,
2330                                       GlobalDecl GD, const ThunkInfo &Thunk);
2331
2332  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
2333                        FunctionArgList &Args);
2334
2335  void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
2336
2337  /// Struct with all information about dynamic [sub]class needed to set vptr.
2338  struct VPtr {
2339    BaseSubobject Base;
2340    const CXXRecordDecl *NearestVBase;
2341    CharUnits OffsetFromNearestVBase;
2342    const CXXRecordDecl *VTableClass;
2343  };
2344
2345  /// Initialize the vtable pointer of the given subobject.
2346  void InitializeVTablePointer(const VPtr &vptr);
2347
2348  typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
2349
2350  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
2351  VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
2352
2353  void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
2354                         CharUnits OffsetFromNearestVBase,
2355                         bool BaseIsNonVirtualPrimaryBase,
2356                         const CXXRecordDecl *VTableClass,
2357                         VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
2358
2359  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
2360
2361  /// GetVTablePtr - Return the Value of the vtable pointer member pointed
2362  /// to by This.
2363  llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
2364                            const CXXRecordDecl *VTableClass);
2365
2366  enum CFITypeCheckKind {
2367    CFITCK_VCall,
2368    CFITCK_NVCall,
2369    CFITCK_DerivedCast,
2370    CFITCK_UnrelatedCast,
2371    CFITCK_ICall,
2372    CFITCK_NVMFCall,
2373    CFITCK_VMFCall,
2374  };
2375
2376  /// Derived is the presumed address of an object of type T after a
2377  /// cast. If T is a polymorphic class type, emit a check that the virtual
2378  /// table for Derived belongs to a class derived from T.
2379  void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull,
2380                                 CFITypeCheckKind TCK, SourceLocation Loc);
2381
2382  /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
2383  /// If vptr CFI is enabled, emit a check that VTable is valid.
2384  void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
2385                                 CFITypeCheckKind TCK, SourceLocation Loc);
2386
2387  /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
2388  /// RD using llvm.type.test.
2389  void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
2390                          CFITypeCheckKind TCK, SourceLocation Loc);
2391
2392  /// If whole-program virtual table optimization is enabled, emit an assumption
2393  /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
2394  /// enabled, emit a check that VTable is a member of RD's type identifier.
2395  void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2396                                    llvm::Value *VTable, SourceLocation Loc);
2397
2398  /// Returns whether we should perform a type checked load when loading a
2399  /// virtual function for virtual calls to members of RD. This is generally
2400  /// true when both vcall CFI and whole-program-vtables are enabled.
2401  bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
2402
2403  /// Emit a type checked load from the given vtable.
2404  llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD,
2405                                         llvm::Value *VTable,
2406                                         llvm::Type *VTableTy,
2407                                         uint64_t VTableByteOffset);
2408
2409  /// EnterDtorCleanups - Enter the cleanups necessary to complete the
2410  /// given phase of destruction for a destructor.  The end result
2411  /// should call destructors on members and base classes in reverse
2412  /// order of their construction.
2413  void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
2414
2415  /// ShouldInstrumentFunction - Return true if the current function should be
2416  /// instrumented with __cyg_profile_func_* calls
2417  bool ShouldInstrumentFunction();
2418
2419  /// ShouldSkipSanitizerInstrumentation - Return true if the current function
2420  /// should not be instrumented with sanitizers.
2421  bool ShouldSkipSanitizerInstrumentation();
2422
2423  /// ShouldXRayInstrument - Return true if the current function should be
2424  /// instrumented with XRay nop sleds.
2425  bool ShouldXRayInstrumentFunction() const;
2426
2427  /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
2428  /// XRay custom event handling calls.
2429  bool AlwaysEmitXRayCustomEvents() const;
2430
2431  /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
2432  /// XRay typed event handling calls.
2433  bool AlwaysEmitXRayTypedEvents() const;
2434
2435  /// Return a type hash constant for a function instrumented by
2436  /// -fsanitize=function.
2437  llvm::ConstantInt *getUBSanFunctionTypeHash(QualType T) const;
2438
2439  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
2440  /// arguments for the given function. This is also responsible for naming the
2441  /// LLVM function arguments.
2442  void EmitFunctionProlog(const CGFunctionInfo &FI,
2443                          llvm::Function *Fn,
2444                          const FunctionArgList &Args);
2445
2446  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
2447  /// given temporary.
2448  void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
2449                          SourceLocation EndLoc);
2450
2451  /// Emit a test that checks if the return value \p RV is nonnull.
2452  void EmitReturnValueCheck(llvm::Value *RV);
2453
2454  /// EmitStartEHSpec - Emit the start of the exception spec.
2455  void EmitStartEHSpec(const Decl *D);
2456
2457  /// EmitEndEHSpec - Emit the end of the exception spec.
2458  void EmitEndEHSpec(const Decl *D);
2459
2460  /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2461  llvm::BasicBlock *getTerminateLandingPad();
2462
2463  /// getTerminateLandingPad - Return a cleanup funclet that just calls
2464  /// terminate.
2465  llvm::BasicBlock *getTerminateFunclet();
2466
2467  /// getTerminateHandler - Return a handler (not a landing pad, just
2468  /// a catch handler) that just calls terminate.  This is used when
2469  /// a terminate scope encloses a try.
2470  llvm::BasicBlock *getTerminateHandler();
2471
2472  llvm::Type *ConvertTypeForMem(QualType T);
2473  llvm::Type *ConvertType(QualType T);
2474  llvm::Type *ConvertType(const TypeDecl *T) {
2475    return ConvertType(getContext().getTypeDeclType(T));
2476  }
2477
2478  /// LoadObjCSelf - Load the value of self. This function is only valid while
2479  /// generating code for an Objective-C method.
2480  llvm::Value *LoadObjCSelf();
2481
2482  /// TypeOfSelfObject - Return type of object that this self represents.
2483  QualType TypeOfSelfObject();
2484
2485  /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2486  static TypeEvaluationKind getEvaluationKind(QualType T);
2487
2488  static bool hasScalarEvaluationKind(QualType T) {
2489    return getEvaluationKind(T) == TEK_Scalar;
2490  }
2491
2492  static bool hasAggregateEvaluationKind(QualType T) {
2493    return getEvaluationKind(T) == TEK_Aggregate;
2494  }
2495
2496  /// createBasicBlock - Create an LLVM basic block.
2497  llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2498                                     llvm::Function *parent = nullptr,
2499                                     llvm::BasicBlock *before = nullptr) {
2500    return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
2501  }
2502
2503  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2504  /// label maps to.
2505  JumpDest getJumpDestForLabel(const LabelDecl *S);
2506
2507  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2508  /// another basic block, simplify it. This assumes that no other code could
2509  /// potentially reference the basic block.
2510  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2511
2512  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2513  /// adding a fall-through branch from the current insert block if
2514  /// necessary. It is legal to call this function even if there is no current
2515  /// insertion point.
2516  ///
2517  /// IsFinished - If true, indicates that the caller has finished emitting
2518  /// branches to the given block and does not expect to emit code into it. This
2519  /// means the block can be ignored if it is unreachable.
2520  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
2521
2522  /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2523  /// near its uses, and leave the insertion point in it.
2524  void EmitBlockAfterUses(llvm::BasicBlock *BB);
2525
2526  /// EmitBranch - Emit a branch to the specified basic block from the current
2527  /// insert block, taking care to avoid creation of branches from dummy
2528  /// blocks. It is legal to call this function even if there is no current
2529  /// insertion point.
2530  ///
2531  /// This function clears the current insertion point. The caller should follow
2532  /// calls to this function with calls to Emit*Block prior to generation new
2533  /// code.
2534  void EmitBranch(llvm::BasicBlock *Block);
2535
2536  /// HaveInsertPoint - True if an insertion point is defined. If not, this
2537  /// indicates that the current code being emitted is unreachable.
2538  bool HaveInsertPoint() const {
2539    return Builder.GetInsertBlock() != nullptr;
2540  }
2541
2542  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2543  /// emitted IR has a place to go. Note that by definition, if this function
2544  /// creates a block then that block is unreachable; callers may do better to
2545  /// detect when no insertion point is defined and simply skip IR generation.
2546  void EnsureInsertPoint() {
2547    if (!HaveInsertPoint())
2548      EmitBlock(createBasicBlock());
2549  }
2550
2551  /// ErrorUnsupported - Print out an error that codegen doesn't support the
2552  /// specified stmt yet.
2553  void ErrorUnsupported(const Stmt *S, const char *Type);
2554
2555  //===--------------------------------------------------------------------===//
2556  //                                  Helpers
2557  //===--------------------------------------------------------------------===//
2558
2559  LValue MakeAddrLValue(Address Addr, QualType T,
2560                        AlignmentSource Source = AlignmentSource::Type) {
2561    return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2562                            CGM.getTBAAAccessInfo(T));
2563  }
2564
2565  LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
2566                        TBAAAccessInfo TBAAInfo) {
2567    return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
2568  }
2569
2570  LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2571                        AlignmentSource Source = AlignmentSource::Type) {
2572    Address Addr(V, ConvertTypeForMem(T), Alignment);
2573    return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2574                            CGM.getTBAAAccessInfo(T));
2575  }
2576
2577  LValue
2578  MakeAddrLValueWithoutTBAA(Address Addr, QualType T,
2579                            AlignmentSource Source = AlignmentSource::Type) {
2580    return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2581                            TBAAAccessInfo());
2582  }
2583
2584  LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
2585  LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
2586
2587  Address EmitLoadOfReference(LValue RefLVal,
2588                              LValueBaseInfo *PointeeBaseInfo = nullptr,
2589                              TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2590  LValue EmitLoadOfReferenceLValue(LValue RefLVal);
2591  LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
2592                                   AlignmentSource Source =
2593                                       AlignmentSource::Type) {
2594    LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
2595                                    CGM.getTBAAAccessInfo(RefTy));
2596    return EmitLoadOfReferenceLValue(RefLVal);
2597  }
2598
2599  /// Load a pointer with type \p PtrTy stored at address \p Ptr.
2600  /// Note that \p PtrTy is the type of the loaded pointer, not the addresses
2601  /// it is loaded from.
2602  Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
2603                            LValueBaseInfo *BaseInfo = nullptr,
2604                            TBAAAccessInfo *TBAAInfo = nullptr);
2605  LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
2606
2607  /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2608  /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2609  /// insertion point of the builder. The caller is responsible for setting an
2610  /// appropriate alignment on
2611  /// the alloca.
2612  ///
2613  /// \p ArraySize is the number of array elements to be allocated if it
2614  ///    is not nullptr.
2615  ///
2616  /// LangAS::Default is the address space of pointers to local variables and
2617  /// temporaries, as exposed in the source language. In certain
2618  /// configurations, this is not the same as the alloca address space, and a
2619  /// cast is needed to lift the pointer from the alloca AS into
2620  /// LangAS::Default. This can happen when the target uses a restricted
2621  /// address space for the stack but the source language requires
2622  /// LangAS::Default to be a generic address space. The latter condition is
2623  /// common for most programming languages; OpenCL is an exception in that
2624  /// LangAS::Default is the private address space, which naturally maps
2625  /// to the stack.
2626  ///
2627  /// Because the address of a temporary is often exposed to the program in
2628  /// various ways, this function will perform the cast. The original alloca
2629  /// instruction is returned through \p Alloca if it is not nullptr.
2630  ///
2631  /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2632  /// more efficient if the caller knows that the address will not be exposed.
2633  llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2634                                     llvm::Value *ArraySize = nullptr);
2635  Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2636                           const Twine &Name = "tmp",
2637                           llvm::Value *ArraySize = nullptr,
2638                           Address *Alloca = nullptr);
2639  Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
2640                                      const Twine &Name = "tmp",
2641                                      llvm::Value *ArraySize = nullptr);
2642
2643  /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2644  /// default ABI alignment of the given LLVM type.
2645  ///
2646  /// IMPORTANT NOTE: This is *not* generally the right alignment for
2647  /// any given AST type that happens to have been lowered to the
2648  /// given IR type.  This should only ever be used for function-local,
2649  /// IR-driven manipulations like saving and restoring a value.  Do
2650  /// not hand this address off to arbitrary IRGen routines, and especially
2651  /// do not pass it as an argument to a function that might expect a
2652  /// properly ABI-aligned value.
2653  Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
2654                                       const Twine &Name = "tmp");
2655
2656  /// CreateIRTemp - Create a temporary IR object of the given type, with
2657  /// appropriate alignment. This routine should only be used when an temporary
2658  /// value needs to be stored into an alloca (for example, to avoid explicit
2659  /// PHI construction), but the type is the IR type, not the type appropriate
2660  /// for storing in memory.
2661  ///
2662  /// That is, this is exactly equivalent to CreateMemTemp, but calling
2663  /// ConvertType instead of ConvertTypeForMem.
2664  Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
2665
2666  /// CreateMemTemp - Create a temporary memory object of the given type, with
2667  /// appropriate alignmen and cast it to the default address space. Returns
2668  /// the original alloca instruction by \p Alloca if it is not nullptr.
2669  Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
2670                        Address *Alloca = nullptr);
2671  Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
2672                        Address *Alloca = nullptr);
2673
2674  /// CreateMemTemp - Create a temporary memory object of the given type, with
2675  /// appropriate alignmen without casting it to the default address space.
2676  Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2677  Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
2678                                   const Twine &Name = "tmp");
2679
2680  /// CreateAggTemp - Create a temporary memory object for the given
2681  /// aggregate type.
2682  AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp",
2683                             Address *Alloca = nullptr) {
2684    return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca),
2685                                 T.getQualifiers(),
2686                                 AggValueSlot::IsNotDestructed,
2687                                 AggValueSlot::DoesNotNeedGCBarriers,
2688                                 AggValueSlot::IsNotAliased,
2689                                 AggValueSlot::DoesNotOverlap);
2690  }
2691
2692  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2693  /// expression and compare the result against zero, returning an Int1Ty value.
2694  llvm::Value *EvaluateExprAsBool(const Expr *E);
2695
2696  /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
2697  void EmitIgnoredExpr(const Expr *E);
2698
2699  /// EmitAnyExpr - Emit code to compute the specified expression which can have
2700  /// any type.  The result is returned as an RValue struct.  If this is an
2701  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2702  /// the result should be returned.
2703  ///
2704  /// \param ignoreResult True if the resulting value isn't used.
2705  RValue EmitAnyExpr(const Expr *E,
2706                     AggValueSlot aggSlot = AggValueSlot::ignored(),
2707                     bool ignoreResult = false);
2708
2709  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2710  // or the value of the expression, depending on how va_list is defined.
2711  Address EmitVAListRef(const Expr *E);
2712
2713  /// Emit a "reference" to a __builtin_ms_va_list; this is
2714  /// always the value of the expression, because a __builtin_ms_va_list is a
2715  /// pointer to a char.
2716  Address EmitMSVAListRef(const Expr *E);
2717
2718  /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2719  /// always be accessible even if no aggregate location is provided.
2720  RValue EmitAnyExprToTemp(const Expr *E);
2721
2722  /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2723  /// arbitrary expression into the given memory location.
2724  void EmitAnyExprToMem(const Expr *E, Address Location,
2725                        Qualifiers Quals, bool IsInitializer);
2726
2727  void EmitAnyExprToExn(const Expr *E, Address Addr);
2728
2729  /// EmitExprAsInit - Emits the code necessary to initialize a
2730  /// location in memory with the given initializer.
2731  void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2732                      bool capturedByInit);
2733
2734  /// hasVolatileMember - returns true if aggregate type has a volatile
2735  /// member.
2736  bool hasVolatileMember(QualType T) {
2737    if (const RecordType *RT = T->getAs<RecordType>()) {
2738      const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2739      return RD->hasVolatileMember();
2740    }
2741    return false;
2742  }
2743
2744  /// Determine whether a return value slot may overlap some other object.
2745  AggValueSlot::Overlap_t getOverlapForReturnValue() {
2746    // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
2747    // class subobjects. These cases may need to be revisited depending on the
2748    // resolution of the relevant core issue.
2749    return AggValueSlot::DoesNotOverlap;
2750  }
2751
2752  /// Determine whether a field initialization may overlap some other object.
2753  AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD);
2754
2755  /// Determine whether a base class initialization may overlap some other
2756  /// object.
2757  AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
2758                                                const CXXRecordDecl *BaseRD,
2759                                                bool IsVirtual);
2760
2761  /// Emit an aggregate assignment.
2762  void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
2763    bool IsVolatile = hasVolatileMember(EltTy);
2764    EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
2765  }
2766
2767  void EmitAggregateCopyCtor(LValue Dest, LValue Src,
2768                             AggValueSlot::Overlap_t MayOverlap) {
2769    EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
2770  }
2771
2772  /// EmitAggregateCopy - Emit an aggregate copy.
2773  ///
2774  /// \param isVolatile \c true iff either the source or the destination is
2775  ///        volatile.
2776  /// \param MayOverlap Whether the tail padding of the destination might be
2777  ///        occupied by some other object. More efficient code can often be
2778  ///        generated if not.
2779  void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
2780                         AggValueSlot::Overlap_t MayOverlap,
2781                         bool isVolatile = false);
2782
2783  /// GetAddrOfLocalVar - Return the address of a local variable.
2784  Address GetAddrOfLocalVar(const VarDecl *VD) {
2785    auto it = LocalDeclMap.find(VD);
2786    assert(it != LocalDeclMap.end() &&
2787           "Invalid argument to GetAddrOfLocalVar(), no decl!");
2788    return it->second;
2789  }
2790
2791  /// Given an opaque value expression, return its LValue mapping if it exists,
2792  /// otherwise create one.
2793  LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
2794
2795  /// Given an opaque value expression, return its RValue mapping if it exists,
2796  /// otherwise create one.
2797  RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
2798
2799  /// Get the index of the current ArrayInitLoopExpr, if any.
2800  llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2801
2802  /// getAccessedFieldNo - Given an encoded value and a result number, return
2803  /// the input field number being accessed.
2804  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2805
2806  llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2807  llvm::BasicBlock *GetIndirectGotoBlock();
2808
2809  /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2810  static bool IsWrappedCXXThis(const Expr *E);
2811
2812  /// EmitNullInitialization - Generate code to set a value of the given type to
2813  /// null, If the type contains data member pointers, they will be initialized
2814  /// to -1 in accordance with the Itanium C++ ABI.
2815  void EmitNullInitialization(Address DestPtr, QualType Ty);
2816
2817  /// Emits a call to an LLVM variable-argument intrinsic, either
2818  /// \c llvm.va_start or \c llvm.va_end.
2819  /// \param ArgValue A reference to the \c va_list as emitted by either
2820  /// \c EmitVAListRef or \c EmitMSVAListRef.
2821  /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2822  /// calls \c llvm.va_end.
2823  llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2824
2825  /// Generate code to get an argument from the passed in pointer
2826  /// and update it accordingly.
2827  /// \param VE The \c VAArgExpr for which to generate code.
2828  /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2829  /// either \c EmitVAListRef or \c EmitMSVAListRef.
2830  /// \returns A pointer to the argument.
2831  // FIXME: We should be able to get rid of this method and use the va_arg
2832  // instruction in LLVM instead once it works well enough.
2833  Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2834
2835  /// emitArrayLength - Compute the length of an array, even if it's a
2836  /// VLA, and drill down to the base element type.
2837  llvm::Value *emitArrayLength(const ArrayType *arrayType,
2838                               QualType &baseType,
2839                               Address &addr);
2840
2841  /// EmitVLASize - Capture all the sizes for the VLA expressions in
2842  /// the given variably-modified type and store them in the VLASizeMap.
2843  ///
2844  /// This function can be called with a null (unreachable) insert point.
2845  void EmitVariablyModifiedType(QualType Ty);
2846
2847  struct VlaSizePair {
2848    llvm::Value *NumElts;
2849    QualType Type;
2850
2851    VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
2852  };
2853
2854  /// Return the number of elements for a single dimension
2855  /// for the given array type.
2856  VlaSizePair getVLAElements1D(const VariableArrayType *vla);
2857  VlaSizePair getVLAElements1D(QualType vla);
2858
2859  /// Returns an LLVM value that corresponds to the size,
2860  /// in non-variably-sized elements, of a variable length array type,
2861  /// plus that largest non-variably-sized element type.  Assumes that
2862  /// the type has already been emitted with EmitVariablyModifiedType.
2863  VlaSizePair getVLASize(const VariableArrayType *vla);
2864  VlaSizePair getVLASize(QualType vla);
2865
2866  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2867  /// generating code for an C++ member function.
2868  llvm::Value *LoadCXXThis() {
2869    assert(CXXThisValue && "no 'this' value for this function");
2870    return CXXThisValue;
2871  }
2872  Address LoadCXXThisAddress();
2873
2874  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2875  /// virtual bases.
2876  // FIXME: Every place that calls LoadCXXVTT is something
2877  // that needs to be abstracted properly.
2878  llvm::Value *LoadCXXVTT() {
2879    assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2880    return CXXStructorImplicitParamValue;
2881  }
2882
2883  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2884  /// complete class to the given direct base.
2885  Address
2886  GetAddressOfDirectBaseInCompleteClass(Address Value,
2887                                        const CXXRecordDecl *Derived,
2888                                        const CXXRecordDecl *Base,
2889                                        bool BaseIsVirtual);
2890
2891  static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2892
2893  /// GetAddressOfBaseClass - This function will add the necessary delta to the
2894  /// load of 'this' and returns address of the base class.
2895  Address GetAddressOfBaseClass(Address Value,
2896                                const CXXRecordDecl *Derived,
2897                                CastExpr::path_const_iterator PathBegin,
2898                                CastExpr::path_const_iterator PathEnd,
2899                                bool NullCheckValue, SourceLocation Loc);
2900
2901  Address GetAddressOfDerivedClass(Address Value,
2902                                   const CXXRecordDecl *Derived,
2903                                   CastExpr::path_const_iterator PathBegin,
2904                                   CastExpr::path_const_iterator PathEnd,
2905                                   bool NullCheckValue);
2906
2907  /// GetVTTParameter - Return the VTT parameter that should be passed to a
2908  /// base constructor/destructor with virtual bases.
2909  /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2910  /// to ItaniumCXXABI.cpp together with all the references to VTT.
2911  llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2912                               bool Delegating);
2913
2914  void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2915                                      CXXCtorType CtorType,
2916                                      const FunctionArgList &Args,
2917                                      SourceLocation Loc);
2918  // It's important not to confuse this and the previous function. Delegating
2919  // constructors are the C++0x feature. The constructor delegate optimization
2920  // is used to reduce duplication in the base and complete consturctors where
2921  // they are substantially the same.
2922  void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2923                                        const FunctionArgList &Args);
2924
2925  /// Emit a call to an inheriting constructor (that is, one that invokes a
2926  /// constructor inherited from a base class) by inlining its definition. This
2927  /// is necessary if the ABI does not support forwarding the arguments to the
2928  /// base class constructor (because they're variadic or similar).
2929  void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2930                                               CXXCtorType CtorType,
2931                                               bool ForVirtualBase,
2932                                               bool Delegating,
2933                                               CallArgList &Args);
2934
2935  /// Emit a call to a constructor inherited from a base class, passing the
2936  /// current constructor's arguments along unmodified (without even making
2937  /// a copy).
2938  void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2939                                       bool ForVirtualBase, Address This,
2940                                       bool InheritedFromVBase,
2941                                       const CXXInheritedCtorInitExpr *E);
2942
2943  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2944                              bool ForVirtualBase, bool Delegating,
2945                              AggValueSlot ThisAVS, const CXXConstructExpr *E);
2946
2947  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2948                              bool ForVirtualBase, bool Delegating,
2949                              Address This, CallArgList &Args,
2950                              AggValueSlot::Overlap_t Overlap,
2951                              SourceLocation Loc, bool NewPointerIsChecked);
2952
2953  /// Emit assumption load for all bases. Requires to be called only on
2954  /// most-derived class and not under construction of the object.
2955  void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2956
2957  /// Emit assumption that vptr load == global vtable.
2958  void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2959
2960  void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2961                                      Address This, Address Src,
2962                                      const CXXConstructExpr *E);
2963
2964  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2965                                  const ArrayType *ArrayTy,
2966                                  Address ArrayPtr,
2967                                  const CXXConstructExpr *E,
2968                                  bool NewPointerIsChecked,
2969                                  bool ZeroInitialization = false);
2970
2971  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2972                                  llvm::Value *NumElements,
2973                                  Address ArrayPtr,
2974                                  const CXXConstructExpr *E,
2975                                  bool NewPointerIsChecked,
2976                                  bool ZeroInitialization = false);
2977
2978  static Destroyer destroyCXXObject;
2979
2980  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2981                             bool ForVirtualBase, bool Delegating, Address This,
2982                             QualType ThisTy);
2983
2984  void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2985                               llvm::Type *ElementTy, Address NewPtr,
2986                               llvm::Value *NumElements,
2987                               llvm::Value *AllocSizeWithoutCookie);
2988
2989  void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2990                        Address Ptr);
2991
2992  void EmitSehCppScopeBegin();
2993  void EmitSehCppScopeEnd();
2994  void EmitSehTryScopeBegin();
2995  void EmitSehTryScopeEnd();
2996
2997  llvm::Value *EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr);
2998  void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2999
3000  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
3001  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
3002
3003  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
3004                      QualType DeleteTy, llvm::Value *NumElements = nullptr,
3005                      CharUnits CookieSize = CharUnits());
3006
3007  RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
3008                                  const CallExpr *TheCallExpr, bool IsDelete);
3009
3010  llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
3011  llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
3012  Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
3013
3014  /// Situations in which we might emit a check for the suitability of a
3015  /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
3016  /// compiler-rt.
3017  enum TypeCheckKind {
3018    /// Checking the operand of a load. Must be suitably sized and aligned.
3019    TCK_Load,
3020    /// Checking the destination of a store. Must be suitably sized and aligned.
3021    TCK_Store,
3022    /// Checking the bound value in a reference binding. Must be suitably sized
3023    /// and aligned, but is not required to refer to an object (until the
3024    /// reference is used), per core issue 453.
3025    TCK_ReferenceBinding,
3026    /// Checking the object expression in a non-static data member access. Must
3027    /// be an object within its lifetime.
3028    TCK_MemberAccess,
3029    /// Checking the 'this' pointer for a call to a non-static member function.
3030    /// Must be an object within its lifetime.
3031    TCK_MemberCall,
3032    /// Checking the 'this' pointer for a constructor call.
3033    TCK_ConstructorCall,
3034    /// Checking the operand of a static_cast to a derived pointer type. Must be
3035    /// null or an object within its lifetime.
3036    TCK_DowncastPointer,
3037    /// Checking the operand of a static_cast to a derived reference type. Must
3038    /// be an object within its lifetime.
3039    TCK_DowncastReference,
3040    /// Checking the operand of a cast to a base object. Must be suitably sized
3041    /// and aligned.
3042    TCK_Upcast,
3043    /// Checking the operand of a cast to a virtual base object. Must be an
3044    /// object within its lifetime.
3045    TCK_UpcastToVirtualBase,
3046    /// Checking the value assigned to a _Nonnull pointer. Must not be null.
3047    TCK_NonnullAssign,
3048    /// Checking the operand of a dynamic_cast or a typeid expression.  Must be
3049    /// null or an object within its lifetime.
3050    TCK_DynamicOperation
3051  };
3052
3053  /// Determine whether the pointer type check \p TCK permits null pointers.
3054  static bool isNullPointerAllowed(TypeCheckKind TCK);
3055
3056  /// Determine whether the pointer type check \p TCK requires a vptr check.
3057  static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
3058
3059  /// Whether any type-checking sanitizers are enabled. If \c false,
3060  /// calls to EmitTypeCheck can be skipped.
3061  bool sanitizePerformTypeCheck() const;
3062
3063  /// Emit a check that \p V is the address of storage of the
3064  /// appropriate size and alignment for an object of type \p Type
3065  /// (or if ArraySize is provided, for an array of that bound).
3066  void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
3067                     QualType Type, CharUnits Alignment = CharUnits::Zero(),
3068                     SanitizerSet SkippedChecks = SanitizerSet(),
3069                     llvm::Value *ArraySize = nullptr);
3070
3071  /// Emit a check that \p Base points into an array object, which
3072  /// we can access at index \p Index. \p Accessed should be \c false if we
3073  /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
3074  void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
3075                       QualType IndexType, bool Accessed);
3076  void EmitBoundsCheckImpl(const Expr *E, llvm::Value *Bound,
3077                           llvm::Value *Index, QualType IndexType,
3078                           QualType IndexedType, bool Accessed);
3079
3080  // Find a struct's flexible array member. It may be embedded inside multiple
3081  // sub-structs, but must still be the last field.
3082  const FieldDecl *FindFlexibleArrayMemberField(ASTContext &Ctx,
3083                                                const RecordDecl *RD,
3084                                                StringRef Name,
3085                                                uint64_t &Offset);
3086
3087  /// Find the FieldDecl specified in a FAM's "counted_by" attribute. Returns
3088  /// \p nullptr if either the attribute or the field doesn't exist.
3089  const FieldDecl *FindCountedByField(const FieldDecl *FD);
3090
3091  /// Build an expression accessing the "counted_by" field.
3092  llvm::Value *EmitCountedByFieldExpr(const Expr *Base,
3093                                      const FieldDecl *FAMDecl,
3094                                      const FieldDecl *CountDecl);
3095
3096  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3097                                       bool isInc, bool isPre);
3098  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
3099                                         bool isInc, bool isPre);
3100
3101  /// Converts Location to a DebugLoc, if debug information is enabled.
3102  llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
3103
3104  /// Get the record field index as represented in debug info.
3105  unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
3106
3107
3108  //===--------------------------------------------------------------------===//
3109  //                            Declaration Emission
3110  //===--------------------------------------------------------------------===//
3111
3112  /// EmitDecl - Emit a declaration.
3113  ///
3114  /// This function can be called with a null (unreachable) insert point.
3115  void EmitDecl(const Decl &D);
3116
3117  /// EmitVarDecl - Emit a local variable declaration.
3118  ///
3119  /// This function can be called with a null (unreachable) insert point.
3120  void EmitVarDecl(const VarDecl &D);
3121
3122  void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
3123                      bool capturedByInit);
3124
3125  typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
3126                             llvm::Value *Address);
3127
3128  /// Determine whether the given initializer is trivial in the sense
3129  /// that it requires no code to be generated.
3130  bool isTrivialInitializer(const Expr *Init);
3131
3132  /// EmitAutoVarDecl - Emit an auto variable declaration.
3133  ///
3134  /// This function can be called with a null (unreachable) insert point.
3135  void EmitAutoVarDecl(const VarDecl &D);
3136
3137  class AutoVarEmission {
3138    friend class CodeGenFunction;
3139
3140    const VarDecl *Variable;
3141
3142    /// The address of the alloca for languages with explicit address space
3143    /// (e.g. OpenCL) or alloca casted to generic pointer for address space
3144    /// agnostic languages (e.g. C++). Invalid if the variable was emitted
3145    /// as a global constant.
3146    Address Addr;
3147
3148    llvm::Value *NRVOFlag;
3149
3150    /// True if the variable is a __block variable that is captured by an
3151    /// escaping block.
3152    bool IsEscapingByRef;
3153
3154    /// True if the variable is of aggregate type and has a constant
3155    /// initializer.
3156    bool IsConstantAggregate;
3157
3158    /// Non-null if we should use lifetime annotations.
3159    llvm::Value *SizeForLifetimeMarkers;
3160
3161    /// Address with original alloca instruction. Invalid if the variable was
3162    /// emitted as a global constant.
3163    Address AllocaAddr;
3164
3165    struct Invalid {};
3166    AutoVarEmission(Invalid)
3167        : Variable(nullptr), Addr(Address::invalid()),
3168          AllocaAddr(Address::invalid()) {}
3169
3170    AutoVarEmission(const VarDecl &variable)
3171        : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
3172          IsEscapingByRef(false), IsConstantAggregate(false),
3173          SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
3174
3175    bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
3176
3177  public:
3178    static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
3179
3180    bool useLifetimeMarkers() const {
3181      return SizeForLifetimeMarkers != nullptr;
3182    }
3183    llvm::Value *getSizeForLifetimeMarkers() const {
3184      assert(useLifetimeMarkers());
3185      return SizeForLifetimeMarkers;
3186    }
3187
3188    /// Returns the raw, allocated address, which is not necessarily
3189    /// the address of the object itself. It is casted to default
3190    /// address space for address space agnostic languages.
3191    Address getAllocatedAddress() const {
3192      return Addr;
3193    }
3194
3195    /// Returns the address for the original alloca instruction.
3196    Address getOriginalAllocatedAddress() const { return AllocaAddr; }
3197
3198    /// Returns the address of the object within this declaration.
3199    /// Note that this does not chase the forwarding pointer for
3200    /// __block decls.
3201    Address getObjectAddress(CodeGenFunction &CGF) const {
3202      if (!IsEscapingByRef) return Addr;
3203
3204      return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
3205    }
3206  };
3207  AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
3208  void EmitAutoVarInit(const AutoVarEmission &emission);
3209  void EmitAutoVarCleanups(const AutoVarEmission &emission);
3210  void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
3211                              QualType::DestructionKind dtorKind);
3212
3213  /// Emits the alloca and debug information for the size expressions for each
3214  /// dimension of an array. It registers the association of its (1-dimensional)
3215  /// QualTypes and size expression's debug node, so that CGDebugInfo can
3216  /// reference this node when creating the DISubrange object to describe the
3217  /// array types.
3218  void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
3219                                              const VarDecl &D,
3220                                              bool EmitDebugInfo);
3221
3222  void EmitStaticVarDecl(const VarDecl &D,
3223                         llvm::GlobalValue::LinkageTypes Linkage);
3224
3225  class ParamValue {
3226    llvm::Value *Value;
3227    llvm::Type *ElementType;
3228    unsigned Alignment;
3229    ParamValue(llvm::Value *V, llvm::Type *T, unsigned A)
3230        : Value(V), ElementType(T), Alignment(A) {}
3231  public:
3232    static ParamValue forDirect(llvm::Value *value) {
3233      return ParamValue(value, nullptr, 0);
3234    }
3235    static ParamValue forIndirect(Address addr) {
3236      assert(!addr.getAlignment().isZero());
3237      return ParamValue(addr.getPointer(), addr.getElementType(),
3238                        addr.getAlignment().getQuantity());
3239    }
3240
3241    bool isIndirect() const { return Alignment != 0; }
3242    llvm::Value *getAnyValue() const { return Value; }
3243
3244    llvm::Value *getDirectValue() const {
3245      assert(!isIndirect());
3246      return Value;
3247    }
3248
3249    Address getIndirectAddress() const {
3250      assert(isIndirect());
3251      return Address(Value, ElementType, CharUnits::fromQuantity(Alignment),
3252                     KnownNonNull);
3253    }
3254  };
3255
3256  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
3257  void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
3258
3259  /// protectFromPeepholes - Protect a value that we're intending to
3260  /// store to the side, but which will probably be used later, from
3261  /// aggressive peepholing optimizations that might delete it.
3262  ///
3263  /// Pass the result to unprotectFromPeepholes to declare that
3264  /// protection is no longer required.
3265  ///
3266  /// There's no particular reason why this shouldn't apply to
3267  /// l-values, it's just that no existing peepholes work on pointers.
3268  PeepholeProtection protectFromPeepholes(RValue rvalue);
3269  void unprotectFromPeepholes(PeepholeProtection protection);
3270
3271  void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
3272                                    SourceLocation Loc,
3273                                    SourceLocation AssumptionLoc,
3274                                    llvm::Value *Alignment,
3275                                    llvm::Value *OffsetValue,
3276                                    llvm::Value *TheCheck,
3277                                    llvm::Instruction *Assumption);
3278
3279  void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
3280                               SourceLocation Loc, SourceLocation AssumptionLoc,
3281                               llvm::Value *Alignment,
3282                               llvm::Value *OffsetValue = nullptr);
3283
3284  void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
3285                               SourceLocation AssumptionLoc,
3286                               llvm::Value *Alignment,
3287                               llvm::Value *OffsetValue = nullptr);
3288
3289  //===--------------------------------------------------------------------===//
3290  //                             Statement Emission
3291  //===--------------------------------------------------------------------===//
3292
3293  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
3294  void EmitStopPoint(const Stmt *S);
3295
3296  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
3297  /// this function even if there is no current insertion point.
3298  ///
3299  /// This function may clear the current insertion point; callers should use
3300  /// EnsureInsertPoint if they wish to subsequently generate code without first
3301  /// calling EmitBlock, EmitBranch, or EmitStmt.
3302  void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = std::nullopt);
3303
3304  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
3305  /// necessarily require an insertion point or debug information; typically
3306  /// because the statement amounts to a jump or a container of other
3307  /// statements.
3308  ///
3309  /// \return True if the statement was handled.
3310  bool EmitSimpleStmt(const Stmt *S, ArrayRef<const Attr *> Attrs);
3311
3312  Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
3313                           AggValueSlot AVS = AggValueSlot::ignored());
3314  Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
3315                                       bool GetLast = false,
3316                                       AggValueSlot AVS =
3317                                                AggValueSlot::ignored());
3318
3319  /// EmitLabel - Emit the block for the given label. It is legal to call this
3320  /// function even if there is no current insertion point.
3321  void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
3322
3323  void EmitLabelStmt(const LabelStmt &S);
3324  void EmitAttributedStmt(const AttributedStmt &S);
3325  void EmitGotoStmt(const GotoStmt &S);
3326  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
3327  void EmitIfStmt(const IfStmt &S);
3328
3329  void EmitWhileStmt(const WhileStmt &S,
3330                     ArrayRef<const Attr *> Attrs = std::nullopt);
3331  void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = std::nullopt);
3332  void EmitForStmt(const ForStmt &S,
3333                   ArrayRef<const Attr *> Attrs = std::nullopt);
3334  void EmitReturnStmt(const ReturnStmt &S);
3335  void EmitDeclStmt(const DeclStmt &S);
3336  void EmitBreakStmt(const BreakStmt &S);
3337  void EmitContinueStmt(const ContinueStmt &S);
3338  void EmitSwitchStmt(const SwitchStmt &S);
3339  void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs);
3340  void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
3341  void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
3342  void EmitAsmStmt(const AsmStmt &S);
3343
3344  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
3345  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
3346  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
3347  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
3348  void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
3349
3350  void EmitCoroutineBody(const CoroutineBodyStmt &S);
3351  void EmitCoreturnStmt(const CoreturnStmt &S);
3352  RValue EmitCoawaitExpr(const CoawaitExpr &E,
3353                         AggValueSlot aggSlot = AggValueSlot::ignored(),
3354                         bool ignoreResult = false);
3355  LValue EmitCoawaitLValue(const CoawaitExpr *E);
3356  RValue EmitCoyieldExpr(const CoyieldExpr &E,
3357                         AggValueSlot aggSlot = AggValueSlot::ignored(),
3358                         bool ignoreResult = false);
3359  LValue EmitCoyieldLValue(const CoyieldExpr *E);
3360  RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
3361
3362  void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3363  void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3364
3365  void EmitCXXTryStmt(const CXXTryStmt &S);
3366  void EmitSEHTryStmt(const SEHTryStmt &S);
3367  void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
3368  void EnterSEHTryStmt(const SEHTryStmt &S);
3369  void ExitSEHTryStmt(const SEHTryStmt &S);
3370  void VolatilizeTryBlocks(llvm::BasicBlock *BB,
3371                           llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V);
3372
3373  void pushSEHCleanup(CleanupKind kind,
3374                      llvm::Function *FinallyFunc);
3375  void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
3376                              const Stmt *OutlinedStmt);
3377
3378  llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
3379                                            const SEHExceptStmt &Except);
3380
3381  llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
3382                                             const SEHFinallyStmt &Finally);
3383
3384  void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
3385                                llvm::Value *ParentFP,
3386                                llvm::Value *EntryEBP);
3387  llvm::Value *EmitSEHExceptionCode();
3388  llvm::Value *EmitSEHExceptionInfo();
3389  llvm::Value *EmitSEHAbnormalTermination();
3390
3391  /// Emit simple code for OpenMP directives in Simd-only mode.
3392  void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
3393
3394  /// Scan the outlined statement for captures from the parent function. For
3395  /// each capture, mark the capture as escaped and emit a call to
3396  /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
3397  void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
3398                          bool IsFilter);
3399
3400  /// Recovers the address of a local in a parent function. ParentVar is the
3401  /// address of the variable used in the immediate parent function. It can
3402  /// either be an alloca or a call to llvm.localrecover if there are nested
3403  /// outlined functions. ParentFP is the frame pointer of the outermost parent
3404  /// frame.
3405  Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
3406                                    Address ParentVar,
3407                                    llvm::Value *ParentFP);
3408
3409  void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
3410                           ArrayRef<const Attr *> Attrs = std::nullopt);
3411
3412  /// Controls insertion of cancellation exit blocks in worksharing constructs.
3413  class OMPCancelStackRAII {
3414    CodeGenFunction &CGF;
3415
3416  public:
3417    OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
3418                       bool HasCancel)
3419        : CGF(CGF) {
3420      CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
3421    }
3422    ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
3423  };
3424
3425  /// Returns calculated size of the specified type.
3426  llvm::Value *getTypeSize(QualType Ty);
3427  LValue InitCapturedStruct(const CapturedStmt &S);
3428  llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
3429  llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
3430  Address GenerateCapturedStmtArgument(const CapturedStmt &S);
3431  llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
3432                                                     SourceLocation Loc);
3433  void GenerateOpenMPCapturedVars(const CapturedStmt &S,
3434                                  SmallVectorImpl<llvm::Value *> &CapturedVars);
3435  void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
3436                          SourceLocation Loc);
3437  /// Perform element by element copying of arrays with type \a
3438  /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
3439  /// generated by \a CopyGen.
3440  ///
3441  /// \param DestAddr Address of the destination array.
3442  /// \param SrcAddr Address of the source array.
3443  /// \param OriginalType Type of destination and source arrays.
3444  /// \param CopyGen Copying procedure that copies value of single array element
3445  /// to another single array element.
3446  void EmitOMPAggregateAssign(
3447      Address DestAddr, Address SrcAddr, QualType OriginalType,
3448      const llvm::function_ref<void(Address, Address)> CopyGen);
3449  /// Emit proper copying of data from one variable to another.
3450  ///
3451  /// \param OriginalType Original type of the copied variables.
3452  /// \param DestAddr Destination address.
3453  /// \param SrcAddr Source address.
3454  /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
3455  /// type of the base array element).
3456  /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
3457  /// the base array element).
3458  /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
3459  /// DestVD.
3460  void EmitOMPCopy(QualType OriginalType,
3461                   Address DestAddr, Address SrcAddr,
3462                   const VarDecl *DestVD, const VarDecl *SrcVD,
3463                   const Expr *Copy);
3464  /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
3465  /// \a X = \a E \a BO \a E.
3466  ///
3467  /// \param X Value to be updated.
3468  /// \param E Update value.
3469  /// \param BO Binary operation for update operation.
3470  /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3471  /// expression, false otherwise.
3472  /// \param AO Atomic ordering of the generated atomic instructions.
3473  /// \param CommonGen Code generator for complex expressions that cannot be
3474  /// expressed through atomicrmw instruction.
3475  /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3476  /// generated, <false, RValue::get(nullptr)> otherwise.
3477  std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3478      LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3479      llvm::AtomicOrdering AO, SourceLocation Loc,
3480      const llvm::function_ref<RValue(RValue)> CommonGen);
3481  bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
3482                                 OMPPrivateScope &PrivateScope);
3483  void EmitOMPPrivateClause(const OMPExecutableDirective &D,
3484                            OMPPrivateScope &PrivateScope);
3485  void EmitOMPUseDevicePtrClause(
3486      const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
3487      const llvm::DenseMap<const ValueDecl *, llvm::Value *>
3488          CaptureDeviceAddrMap);
3489  void EmitOMPUseDeviceAddrClause(
3490      const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
3491      const llvm::DenseMap<const ValueDecl *, llvm::Value *>
3492          CaptureDeviceAddrMap);
3493  /// Emit code for copyin clause in \a D directive. The next code is
3494  /// generated at the start of outlined functions for directives:
3495  /// \code
3496  /// threadprivate_var1 = master_threadprivate_var1;
3497  /// operator=(threadprivate_var2, master_threadprivate_var2);
3498  /// ...
3499  /// __kmpc_barrier(&loc, global_tid);
3500  /// \endcode
3501  ///
3502  /// \param D OpenMP directive possibly with 'copyin' clause(s).
3503  /// \returns true if at least one copyin variable is found, false otherwise.
3504  bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
3505  /// Emit initial code for lastprivate variables. If some variable is
3506  /// not also firstprivate, then the default initialization is used. Otherwise
3507  /// initialization of this variable is performed by EmitOMPFirstprivateClause
3508  /// method.
3509  ///
3510  /// \param D Directive that may have 'lastprivate' directives.
3511  /// \param PrivateScope Private scope for capturing lastprivate variables for
3512  /// proper codegen in internal captured statement.
3513  ///
3514  /// \returns true if there is at least one lastprivate variable, false
3515  /// otherwise.
3516  bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
3517                                    OMPPrivateScope &PrivateScope);
3518  /// Emit final copying of lastprivate values to original variables at
3519  /// the end of the worksharing or simd directive.
3520  ///
3521  /// \param D Directive that has at least one 'lastprivate' directives.
3522  /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3523  /// it is the last iteration of the loop code in associated directive, or to
3524  /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3525  void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
3526                                     bool NoFinals,
3527                                     llvm::Value *IsLastIterCond = nullptr);
3528  /// Emit initial code for linear clauses.
3529  void EmitOMPLinearClause(const OMPLoopDirective &D,
3530                           CodeGenFunction::OMPPrivateScope &PrivateScope);
3531  /// Emit final code for linear clauses.
3532  /// \param CondGen Optional conditional code for final part of codegen for
3533  /// linear clause.
3534  void EmitOMPLinearClauseFinal(
3535      const OMPLoopDirective &D,
3536      const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3537  /// Emit initial code for reduction variables. Creates reduction copies
3538  /// and initializes them with the values according to OpenMP standard.
3539  ///
3540  /// \param D Directive (possibly) with the 'reduction' clause.
3541  /// \param PrivateScope Private scope for capturing reduction variables for
3542  /// proper codegen in internal captured statement.
3543  ///
3544  void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
3545                                  OMPPrivateScope &PrivateScope,
3546                                  bool ForInscan = false);
3547  /// Emit final update of reduction values to original variables at
3548  /// the end of the directive.
3549  ///
3550  /// \param D Directive that has at least one 'reduction' directives.
3551  /// \param ReductionKind The kind of reduction to perform.
3552  void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
3553                                   const OpenMPDirectiveKind ReductionKind);
3554  /// Emit initial code for linear variables. Creates private copies
3555  /// and initializes them with the values according to OpenMP standard.
3556  ///
3557  /// \param D Directive (possibly) with the 'linear' clause.
3558  /// \return true if at least one linear variable is found that should be
3559  /// initialized with the value of the original variable, false otherwise.
3560  bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
3561
3562  typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3563                                        llvm::Function * /*OutlinedFn*/,
3564                                        const OMPTaskDataTy & /*Data*/)>
3565      TaskGenTy;
3566  void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
3567                                 const OpenMPDirectiveKind CapturedRegion,
3568                                 const RegionCodeGenTy &BodyGen,
3569                                 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3570  struct OMPTargetDataInfo {
3571    Address BasePointersArray = Address::invalid();
3572    Address PointersArray = Address::invalid();
3573    Address SizesArray = Address::invalid();
3574    Address MappersArray = Address::invalid();
3575    unsigned NumberOfTargetItems = 0;
3576    explicit OMPTargetDataInfo() = default;
3577    OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
3578                      Address SizesArray, Address MappersArray,
3579                      unsigned NumberOfTargetItems)
3580        : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
3581          SizesArray(SizesArray), MappersArray(MappersArray),
3582          NumberOfTargetItems(NumberOfTargetItems) {}
3583  };
3584  void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
3585                                       const RegionCodeGenTy &BodyGen,
3586                                       OMPTargetDataInfo &InputInfo);
3587  void processInReduction(const OMPExecutableDirective &S,
3588                          OMPTaskDataTy &Data,
3589                          CodeGenFunction &CGF,
3590                          const CapturedStmt *CS,
3591                          OMPPrivateScope &Scope);
3592  void EmitOMPMetaDirective(const OMPMetaDirective &S);
3593  void EmitOMPParallelDirective(const OMPParallelDirective &S);
3594  void EmitOMPSimdDirective(const OMPSimdDirective &S);
3595  void EmitOMPTileDirective(const OMPTileDirective &S);
3596  void EmitOMPUnrollDirective(const OMPUnrollDirective &S);
3597  void EmitOMPForDirective(const OMPForDirective &S);
3598  void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
3599  void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
3600  void EmitOMPSectionDirective(const OMPSectionDirective &S);
3601  void EmitOMPSingleDirective(const OMPSingleDirective &S);
3602  void EmitOMPMasterDirective(const OMPMasterDirective &S);
3603  void EmitOMPMaskedDirective(const OMPMaskedDirective &S);
3604  void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
3605  void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
3606  void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
3607  void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
3608  void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S);
3609  void EmitOMPTaskDirective(const OMPTaskDirective &S);
3610  void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
3611  void EmitOMPErrorDirective(const OMPErrorDirective &S);
3612  void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
3613  void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
3614  void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
3615  void EmitOMPFlushDirective(const OMPFlushDirective &S);
3616  void EmitOMPDepobjDirective(const OMPDepobjDirective &S);
3617  void EmitOMPScanDirective(const OMPScanDirective &S);
3618  void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
3619  void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
3620  void EmitOMPTargetDirective(const OMPTargetDirective &S);
3621  void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
3622  void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
3623  void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
3624  void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
3625  void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
3626  void
3627  EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
3628  void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
3629  void
3630  EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
3631  void EmitOMPCancelDirective(const OMPCancelDirective &S);
3632  void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
3633  void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
3634  void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
3635  void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S);
3636  void
3637  EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S);
3638  void EmitOMPParallelMasterTaskLoopDirective(
3639      const OMPParallelMasterTaskLoopDirective &S);
3640  void EmitOMPParallelMasterTaskLoopSimdDirective(
3641      const OMPParallelMasterTaskLoopSimdDirective &S);
3642  void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
3643  void EmitOMPDistributeParallelForDirective(
3644      const OMPDistributeParallelForDirective &S);
3645  void EmitOMPDistributeParallelForSimdDirective(
3646      const OMPDistributeParallelForSimdDirective &S);
3647  void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
3648  void EmitOMPTargetParallelForSimdDirective(
3649      const OMPTargetParallelForSimdDirective &S);
3650  void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
3651  void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
3652  void
3653  EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
3654  void EmitOMPTeamsDistributeParallelForSimdDirective(
3655      const OMPTeamsDistributeParallelForSimdDirective &S);
3656  void EmitOMPTeamsDistributeParallelForDirective(
3657      const OMPTeamsDistributeParallelForDirective &S);
3658  void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
3659  void EmitOMPTargetTeamsDistributeDirective(
3660      const OMPTargetTeamsDistributeDirective &S);
3661  void EmitOMPTargetTeamsDistributeParallelForDirective(
3662      const OMPTargetTeamsDistributeParallelForDirective &S);
3663  void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
3664      const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3665  void EmitOMPTargetTeamsDistributeSimdDirective(
3666      const OMPTargetTeamsDistributeSimdDirective &S);
3667  void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S);
3668  void EmitOMPParallelGenericLoopDirective(const OMPLoopDirective &S);
3669  void EmitOMPTargetParallelGenericLoopDirective(
3670      const OMPTargetParallelGenericLoopDirective &S);
3671  void EmitOMPTargetTeamsGenericLoopDirective(
3672      const OMPTargetTeamsGenericLoopDirective &S);
3673  void EmitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &S);
3674  void EmitOMPInteropDirective(const OMPInteropDirective &S);
3675  void EmitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &S);
3676
3677  /// Emit device code for the target directive.
3678  static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3679                                          StringRef ParentName,
3680                                          const OMPTargetDirective &S);
3681  static void
3682  EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3683                                      const OMPTargetParallelDirective &S);
3684  /// Emit device code for the target parallel for directive.
3685  static void EmitOMPTargetParallelForDeviceFunction(
3686      CodeGenModule &CGM, StringRef ParentName,
3687      const OMPTargetParallelForDirective &S);
3688  /// Emit device code for the target parallel for simd directive.
3689  static void EmitOMPTargetParallelForSimdDeviceFunction(
3690      CodeGenModule &CGM, StringRef ParentName,
3691      const OMPTargetParallelForSimdDirective &S);
3692  /// Emit device code for the target teams directive.
3693  static void
3694  EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3695                                   const OMPTargetTeamsDirective &S);
3696  /// Emit device code for the target teams distribute directive.
3697  static void EmitOMPTargetTeamsDistributeDeviceFunction(
3698      CodeGenModule &CGM, StringRef ParentName,
3699      const OMPTargetTeamsDistributeDirective &S);
3700  /// Emit device code for the target teams distribute simd directive.
3701  static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
3702      CodeGenModule &CGM, StringRef ParentName,
3703      const OMPTargetTeamsDistributeSimdDirective &S);
3704  /// Emit device code for the target simd directive.
3705  static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
3706                                              StringRef ParentName,
3707                                              const OMPTargetSimdDirective &S);
3708  /// Emit device code for the target teams distribute parallel for simd
3709  /// directive.
3710  static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
3711      CodeGenModule &CGM, StringRef ParentName,
3712      const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3713
3714  /// Emit device code for the target teams loop directive.
3715  static void EmitOMPTargetTeamsGenericLoopDeviceFunction(
3716      CodeGenModule &CGM, StringRef ParentName,
3717      const OMPTargetTeamsGenericLoopDirective &S);
3718
3719  /// Emit device code for the target parallel loop directive.
3720  static void EmitOMPTargetParallelGenericLoopDeviceFunction(
3721      CodeGenModule &CGM, StringRef ParentName,
3722      const OMPTargetParallelGenericLoopDirective &S);
3723
3724  static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
3725      CodeGenModule &CGM, StringRef ParentName,
3726      const OMPTargetTeamsDistributeParallelForDirective &S);
3727
3728  /// Emit the Stmt \p S and return its topmost canonical loop, if any.
3729  /// TODO: The \p Depth paramter is not yet implemented and must be 1. In the
3730  /// future it is meant to be the number of loops expected in the loop nests
3731  /// (usually specified by the "collapse" clause) that are collapsed to a
3732  /// single loop by this function.
3733  llvm::CanonicalLoopInfo *EmitOMPCollapsedCanonicalLoopNest(const Stmt *S,
3734                                                             int Depth);
3735
3736  /// Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
3737  void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S);
3738
3739  /// Emit inner loop of the worksharing/simd construct.
3740  ///
3741  /// \param S Directive, for which the inner loop must be emitted.
3742  /// \param RequiresCleanup true, if directive has some associated private
3743  /// variables.
3744  /// \param LoopCond Bollean condition for loop continuation.
3745  /// \param IncExpr Increment expression for loop control variable.
3746  /// \param BodyGen Generator for the inner body of the inner loop.
3747  /// \param PostIncGen Genrator for post-increment code (required for ordered
3748  /// loop directvies).
3749  void EmitOMPInnerLoop(
3750      const OMPExecutableDirective &S, bool RequiresCleanup,
3751      const Expr *LoopCond, const Expr *IncExpr,
3752      const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
3753      const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
3754
3755  JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
3756  /// Emit initial code for loop counters of loop-based directives.
3757  void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
3758                                  OMPPrivateScope &LoopScope);
3759
3760  /// Helper for the OpenMP loop directives.
3761  void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
3762
3763  /// Emit code for the worksharing loop-based directive.
3764  /// \return true, if this construct has any lastprivate clause, false -
3765  /// otherwise.
3766  bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
3767                              const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3768                              const CodeGenDispatchBoundsTy &CGDispatchBounds);
3769
3770  /// Emit code for the distribute loop-based directive.
3771  void EmitOMPDistributeLoop(const OMPLoopDirective &S,
3772                             const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
3773
3774  /// Helpers for the OpenMP loop directives.
3775  void EmitOMPSimdInit(const OMPLoopDirective &D);
3776  void EmitOMPSimdFinal(
3777      const OMPLoopDirective &D,
3778      const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3779
3780  /// Emits the lvalue for the expression with possibly captured variable.
3781  LValue EmitOMPSharedLValue(const Expr *E);
3782
3783private:
3784  /// Helpers for blocks.
3785  llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
3786
3787  /// struct with the values to be passed to the OpenMP loop-related functions
3788  struct OMPLoopArguments {
3789    /// loop lower bound
3790    Address LB = Address::invalid();
3791    /// loop upper bound
3792    Address UB = Address::invalid();
3793    /// loop stride
3794    Address ST = Address::invalid();
3795    /// isLastIteration argument for runtime functions
3796    Address IL = Address::invalid();
3797    /// Chunk value generated by sema
3798    llvm::Value *Chunk = nullptr;
3799    /// EnsureUpperBound
3800    Expr *EUB = nullptr;
3801    /// IncrementExpression
3802    Expr *IncExpr = nullptr;
3803    /// Loop initialization
3804    Expr *Init = nullptr;
3805    /// Loop exit condition
3806    Expr *Cond = nullptr;
3807    /// Update of LB after a whole chunk has been executed
3808    Expr *NextLB = nullptr;
3809    /// Update of UB after a whole chunk has been executed
3810    Expr *NextUB = nullptr;
3811    OMPLoopArguments() = default;
3812    OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
3813                     llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
3814                     Expr *IncExpr = nullptr, Expr *Init = nullptr,
3815                     Expr *Cond = nullptr, Expr *NextLB = nullptr,
3816                     Expr *NextUB = nullptr)
3817        : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
3818          IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
3819          NextUB(NextUB) {}
3820  };
3821  void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
3822                        const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
3823                        const OMPLoopArguments &LoopArgs,
3824                        const CodeGenLoopTy &CodeGenLoop,
3825                        const CodeGenOrderedTy &CodeGenOrdered);
3826  void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
3827                           bool IsMonotonic, const OMPLoopDirective &S,
3828                           OMPPrivateScope &LoopScope, bool Ordered,
3829                           const OMPLoopArguments &LoopArgs,
3830                           const CodeGenDispatchBoundsTy &CGDispatchBounds);
3831  void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
3832                                  const OMPLoopDirective &S,
3833                                  OMPPrivateScope &LoopScope,
3834                                  const OMPLoopArguments &LoopArgs,
3835                                  const CodeGenLoopTy &CodeGenLoopContent);
3836  /// Emit code for sections directive.
3837  void EmitSections(const OMPExecutableDirective &S);
3838
3839public:
3840
3841  //===--------------------------------------------------------------------===//
3842  //                         LValue Expression Emission
3843  //===--------------------------------------------------------------------===//
3844
3845  /// Create a check that a scalar RValue is non-null.
3846  llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T);
3847
3848  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
3849  RValue GetUndefRValue(QualType Ty);
3850
3851  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
3852  /// and issue an ErrorUnsupported style diagnostic (using the
3853  /// provided Name).
3854  RValue EmitUnsupportedRValue(const Expr *E,
3855                               const char *Name);
3856
3857  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
3858  /// an ErrorUnsupported style diagnostic (using the provided Name).
3859  LValue EmitUnsupportedLValue(const Expr *E,
3860                               const char *Name);
3861
3862  /// EmitLValue - Emit code to compute a designator that specifies the location
3863  /// of the expression.
3864  ///
3865  /// This can return one of two things: a simple address or a bitfield
3866  /// reference.  In either case, the LLVM Value* in the LValue structure is
3867  /// guaranteed to be an LLVM pointer type.
3868  ///
3869  /// If this returns a bitfield reference, nothing about the pointee type of
3870  /// the LLVM value is known: For example, it may not be a pointer to an
3871  /// integer.
3872  ///
3873  /// If this returns a normal address, and if the lvalue's C type is fixed
3874  /// size, this method guarantees that the returned pointer type will point to
3875  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
3876  /// variable length type, this is not possible.
3877  ///
3878  LValue EmitLValue(const Expr *E,
3879                    KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
3880
3881private:
3882  LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
3883
3884public:
3885  /// Same as EmitLValue but additionally we generate checking code to
3886  /// guard against undefined behavior.  This is only suitable when we know
3887  /// that the address will be used to access the object.
3888  LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
3889
3890  RValue convertTempToRValue(Address addr, QualType type,
3891                             SourceLocation Loc);
3892
3893  void EmitAtomicInit(Expr *E, LValue lvalue);
3894
3895  bool LValueIsSuitableForInlineAtomic(LValue Src);
3896
3897  RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
3898                        AggValueSlot Slot = AggValueSlot::ignored());
3899
3900  RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
3901                        llvm::AtomicOrdering AO, bool IsVolatile = false,
3902                        AggValueSlot slot = AggValueSlot::ignored());
3903
3904  void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
3905
3906  void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
3907                       bool IsVolatile, bool isInit);
3908
3909  std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
3910      LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
3911      llvm::AtomicOrdering Success =
3912          llvm::AtomicOrdering::SequentiallyConsistent,
3913      llvm::AtomicOrdering Failure =
3914          llvm::AtomicOrdering::SequentiallyConsistent,
3915      bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
3916
3917  void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
3918                        const llvm::function_ref<RValue(RValue)> &UpdateOp,
3919                        bool IsVolatile);
3920
3921  /// EmitToMemory - Change a scalar value from its value
3922  /// representation to its in-memory representation.
3923  llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
3924
3925  /// EmitFromMemory - Change a scalar value from its memory
3926  /// representation to its value representation.
3927  llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
3928
3929  /// Check if the scalar \p Value is within the valid range for the given
3930  /// type \p Ty.
3931  ///
3932  /// Returns true if a check is needed (even if the range is unknown).
3933  bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
3934                            SourceLocation Loc);
3935
3936  /// EmitLoadOfScalar - Load a scalar value from an address, taking
3937  /// care to appropriately convert from the memory representation to
3938  /// the LLVM value representation.
3939  llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3940                                SourceLocation Loc,
3941                                AlignmentSource Source = AlignmentSource::Type,
3942                                bool isNontemporal = false) {
3943    return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
3944                            CGM.getTBAAAccessInfo(Ty), isNontemporal);
3945  }
3946
3947  llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3948                                SourceLocation Loc, LValueBaseInfo BaseInfo,
3949                                TBAAAccessInfo TBAAInfo,
3950                                bool isNontemporal = false);
3951
3952  /// EmitLoadOfScalar - Load a scalar value from an address, taking
3953  /// care to appropriately convert from the memory representation to
3954  /// the LLVM value representation.  The l-value must be a simple
3955  /// l-value.
3956  llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3957
3958  /// EmitStoreOfScalar - Store a scalar value to an address, taking
3959  /// care to appropriately convert from the memory representation to
3960  /// the LLVM value representation.
3961  void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3962                         bool Volatile, QualType Ty,
3963                         AlignmentSource Source = AlignmentSource::Type,
3964                         bool isInit = false, bool isNontemporal = false) {
3965    EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
3966                      CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
3967  }
3968
3969  void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3970                         bool Volatile, QualType Ty,
3971                         LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
3972                         bool isInit = false, bool isNontemporal = false);
3973
3974  /// EmitStoreOfScalar - Store a scalar value to an address, taking
3975  /// care to appropriately convert from the memory representation to
3976  /// the LLVM value representation.  The l-value must be a simple
3977  /// l-value.  The isInit flag indicates whether this is an initialization.
3978  /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3979  void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3980
3981  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3982  /// this method emits the address of the lvalue, then loads the result as an
3983  /// rvalue, returning the rvalue.
3984  RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3985  RValue EmitLoadOfExtVectorElementLValue(LValue V);
3986  RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3987  RValue EmitLoadOfGlobalRegLValue(LValue LV);
3988
3989  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3990  /// lvalue, where both are guaranteed to the have the same type, and that type
3991  /// is 'Ty'.
3992  void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3993  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3994  void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3995
3996  /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3997  /// as EmitStoreThroughLValue.
3998  ///
3999  /// \param Result [out] - If non-null, this will be set to a Value* for the
4000  /// bit-field contents after the store, appropriate for use as the result of
4001  /// an assignment to the bit-field.
4002  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
4003                                      llvm::Value **Result=nullptr);
4004
4005  /// Emit an l-value for an assignment (simple or compound) of complex type.
4006  LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
4007  LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
4008  LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
4009                                             llvm::Value *&Result);
4010
4011  // Note: only available for agg return types
4012  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
4013  LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
4014  // Note: only available for agg return types
4015  LValue EmitCallExprLValue(const CallExpr *E);
4016  // Note: only available for agg return types
4017  LValue EmitVAArgExprLValue(const VAArgExpr *E);
4018  LValue EmitDeclRefLValue(const DeclRefExpr *E);
4019  LValue EmitStringLiteralLValue(const StringLiteral *E);
4020  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
4021  LValue EmitPredefinedLValue(const PredefinedExpr *E);
4022  LValue EmitUnaryOpLValue(const UnaryOperator *E);
4023  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
4024                                bool Accessed = false);
4025  LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E);
4026  LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
4027                                 bool IsLowerBound = true);
4028  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
4029  LValue EmitMemberExpr(const MemberExpr *E);
4030  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
4031  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
4032  LValue EmitInitListLValue(const InitListExpr *E);
4033  void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E);
4034  LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
4035  LValue EmitCastLValue(const CastExpr *E);
4036  LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4037  LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
4038
4039  Address EmitExtVectorElementLValue(LValue V);
4040
4041  RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
4042
4043  Address EmitArrayToPointerDecay(const Expr *Array,
4044                                  LValueBaseInfo *BaseInfo = nullptr,
4045                                  TBAAAccessInfo *TBAAInfo = nullptr);
4046
4047  class ConstantEmission {
4048    llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
4049    ConstantEmission(llvm::Constant *C, bool isReference)
4050      : ValueAndIsReference(C, isReference) {}
4051  public:
4052    ConstantEmission() {}
4053    static ConstantEmission forReference(llvm::Constant *C) {
4054      return ConstantEmission(C, true);
4055    }
4056    static ConstantEmission forValue(llvm::Constant *C) {
4057      return ConstantEmission(C, false);
4058    }
4059
4060    explicit operator bool() const {
4061      return ValueAndIsReference.getOpaqueValue() != nullptr;
4062    }
4063
4064    bool isReference() const { return ValueAndIsReference.getInt(); }
4065    LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
4066      assert(isReference());
4067      return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
4068                                            refExpr->getType());
4069    }
4070
4071    llvm::Constant *getValue() const {
4072      assert(!isReference());
4073      return ValueAndIsReference.getPointer();
4074    }
4075  };
4076
4077  ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
4078  ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
4079  llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
4080
4081  RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
4082                                AggValueSlot slot = AggValueSlot::ignored());
4083  LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
4084
4085  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4086                              const ObjCIvarDecl *Ivar);
4087  llvm::Value *EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
4088                                           const ObjCIvarDecl *Ivar);
4089  LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
4090  LValue EmitLValueForLambdaField(const FieldDecl *Field);
4091  LValue EmitLValueForLambdaField(const FieldDecl *Field,
4092                                  llvm::Value *ThisValue);
4093
4094  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
4095  /// if the Field is a reference, this will return the address of the reference
4096  /// and not the address of the value stored in the reference.
4097  LValue EmitLValueForFieldInitialization(LValue Base,
4098                                          const FieldDecl* Field);
4099
4100  LValue EmitLValueForIvar(QualType ObjectTy,
4101                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
4102                           unsigned CVRQualifiers);
4103
4104  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
4105  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
4106  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
4107  LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
4108
4109  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
4110  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
4111  LValue EmitStmtExprLValue(const StmtExpr *E);
4112  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
4113  LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
4114  void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
4115
4116  //===--------------------------------------------------------------------===//
4117  //                         Scalar Expression Emission
4118  //===--------------------------------------------------------------------===//
4119
4120  /// EmitCall - Generate a call of the given function, expecting the given
4121  /// result type, and using the given argument list which specifies both the
4122  /// LLVM arguments and the types they were derived from.
4123  RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4124                  ReturnValueSlot ReturnValue, const CallArgList &Args,
4125                  llvm::CallBase **callOrInvoke, bool IsMustTail,
4126                  SourceLocation Loc);
4127  RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4128                  ReturnValueSlot ReturnValue, const CallArgList &Args,
4129                  llvm::CallBase **callOrInvoke = nullptr,
4130                  bool IsMustTail = false) {
4131    return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
4132                    IsMustTail, SourceLocation());
4133  }
4134  RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
4135                  ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
4136  RValue EmitCallExpr(const CallExpr *E,
4137                      ReturnValueSlot ReturnValue = ReturnValueSlot());
4138  RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
4139  CGCallee EmitCallee(const Expr *E);
4140
4141  void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
4142  void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
4143
4144  llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4145                                  const Twine &name = "");
4146  llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4147                                  ArrayRef<llvm::Value *> args,
4148                                  const Twine &name = "");
4149  llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4150                                          const Twine &name = "");
4151  llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4152                                          ArrayRef<llvm::Value *> args,
4153                                          const Twine &name = "");
4154
4155  SmallVector<llvm::OperandBundleDef, 1>
4156  getBundlesForFunclet(llvm::Value *Callee);
4157
4158  llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
4159                                   ArrayRef<llvm::Value *> Args,
4160                                   const Twine &Name = "");
4161  llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4162                                          ArrayRef<llvm::Value *> args,
4163                                          const Twine &name = "");
4164  llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4165                                          const Twine &name = "");
4166  void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4167                                       ArrayRef<llvm::Value *> args);
4168
4169  CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
4170                                     NestedNameSpecifier *Qual,
4171                                     llvm::Type *Ty);
4172
4173  CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
4174                                               CXXDtorType Type,
4175                                               const CXXRecordDecl *RD);
4176
4177  // Return the copy constructor name with the prefix "__copy_constructor_"
4178  // removed.
4179  static std::string getNonTrivialCopyConstructorStr(QualType QT,
4180                                                     CharUnits Alignment,
4181                                                     bool IsVolatile,
4182                                                     ASTContext &Ctx);
4183
4184  // Return the destructor name with the prefix "__destructor_" removed.
4185  static std::string getNonTrivialDestructorStr(QualType QT,
4186                                                CharUnits Alignment,
4187                                                bool IsVolatile,
4188                                                ASTContext &Ctx);
4189
4190  // These functions emit calls to the special functions of non-trivial C
4191  // structs.
4192  void defaultInitNonTrivialCStructVar(LValue Dst);
4193  void callCStructDefaultConstructor(LValue Dst);
4194  void callCStructDestructor(LValue Dst);
4195  void callCStructCopyConstructor(LValue Dst, LValue Src);
4196  void callCStructMoveConstructor(LValue Dst, LValue Src);
4197  void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
4198  void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
4199
4200  RValue
4201  EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
4202                              const CGCallee &Callee,
4203                              ReturnValueSlot ReturnValue, llvm::Value *This,
4204                              llvm::Value *ImplicitParam,
4205                              QualType ImplicitParamTy, const CallExpr *E,
4206                              CallArgList *RtlArgs);
4207  RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
4208                               llvm::Value *This, QualType ThisTy,
4209                               llvm::Value *ImplicitParam,
4210                               QualType ImplicitParamTy, const CallExpr *E);
4211  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
4212                               ReturnValueSlot ReturnValue);
4213  RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
4214                                               const CXXMethodDecl *MD,
4215                                               ReturnValueSlot ReturnValue,
4216                                               bool HasQualifier,
4217                                               NestedNameSpecifier *Qualifier,
4218                                               bool IsArrow, const Expr *Base);
4219  // Compute the object pointer.
4220  Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
4221                                          llvm::Value *memberPtr,
4222                                          const MemberPointerType *memberPtrType,
4223                                          LValueBaseInfo *BaseInfo = nullptr,
4224                                          TBAAAccessInfo *TBAAInfo = nullptr);
4225  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
4226                                      ReturnValueSlot ReturnValue);
4227
4228  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
4229                                       const CXXMethodDecl *MD,
4230                                       ReturnValueSlot ReturnValue);
4231  RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
4232
4233  RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
4234                                ReturnValueSlot ReturnValue);
4235
4236  RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E);
4237  RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E);
4238  RValue EmitOpenMPDevicePrintfCallExpr(const CallExpr *E);
4239
4240  RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
4241                         const CallExpr *E, ReturnValueSlot ReturnValue);
4242
4243  RValue emitRotate(const CallExpr *E, bool IsRotateRight);
4244
4245  /// Emit IR for __builtin_os_log_format.
4246  RValue emitBuiltinOSLogFormat(const CallExpr &E);
4247
4248  /// Emit IR for __builtin_is_aligned.
4249  RValue EmitBuiltinIsAligned(const CallExpr *E);
4250  /// Emit IR for __builtin_align_up/__builtin_align_down.
4251  RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp);
4252
4253  llvm::Function *generateBuiltinOSLogHelperFunction(
4254      const analyze_os_log::OSLogBufferLayout &Layout,
4255      CharUnits BufferAlignment);
4256
4257  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
4258
4259  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
4260  /// is unhandled by the current target.
4261  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4262                                     ReturnValueSlot ReturnValue);
4263
4264  llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
4265                                             const llvm::CmpInst::Predicate Fp,
4266                                             const llvm::CmpInst::Predicate Ip,
4267                                             const llvm::Twine &Name = "");
4268  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4269                                  ReturnValueSlot ReturnValue,
4270                                  llvm::Triple::ArchType Arch);
4271  llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4272                                     ReturnValueSlot ReturnValue,
4273                                     llvm::Triple::ArchType Arch);
4274  llvm::Value *EmitARMCDEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4275                                     ReturnValueSlot ReturnValue,
4276                                     llvm::Triple::ArchType Arch);
4277  llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy,
4278                                   QualType RTy);
4279  llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::ArrayType *ATy,
4280                                   QualType RTy);
4281
4282  llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
4283                                         unsigned LLVMIntrinsic,
4284                                         unsigned AltLLVMIntrinsic,
4285                                         const char *NameHint,
4286                                         unsigned Modifier,
4287                                         const CallExpr *E,
4288                                         SmallVectorImpl<llvm::Value *> &Ops,
4289                                         Address PtrOp0, Address PtrOp1,
4290                                         llvm::Triple::ArchType Arch);
4291
4292  llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
4293                                          unsigned Modifier, llvm::Type *ArgTy,
4294                                          const CallExpr *E);
4295  llvm::Value *EmitNeonCall(llvm::Function *F,
4296                            SmallVectorImpl<llvm::Value*> &O,
4297                            const char *name,
4298                            unsigned shift = 0, bool rightshift = false);
4299  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
4300                             const llvm::ElementCount &Count);
4301  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
4302  llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
4303                                   bool negateForRightShift);
4304  llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
4305                                 llvm::Type *Ty, bool usgn, const char *name);
4306  llvm::Value *vectorWrapScalar16(llvm::Value *Op);
4307  /// SVEBuiltinMemEltTy - Returns the memory element type for this memory
4308  /// access builtin.  Only required if it can't be inferred from the base
4309  /// pointer operand.
4310  llvm::Type *SVEBuiltinMemEltTy(const SVETypeFlags &TypeFlags);
4311
4312  SmallVector<llvm::Type *, 2>
4313  getSVEOverloadTypes(const SVETypeFlags &TypeFlags, llvm::Type *ReturnType,
4314                      ArrayRef<llvm::Value *> Ops);
4315  llvm::Type *getEltType(const SVETypeFlags &TypeFlags);
4316  llvm::ScalableVectorType *getSVEType(const SVETypeFlags &TypeFlags);
4317  llvm::ScalableVectorType *getSVEPredType(const SVETypeFlags &TypeFlags);
4318  llvm::Value *EmitSVETupleSetOrGet(const SVETypeFlags &TypeFlags,
4319                                    llvm::Type *ReturnType,
4320                                    ArrayRef<llvm::Value *> Ops);
4321  llvm::Value *EmitSVETupleCreate(const SVETypeFlags &TypeFlags,
4322                                  llvm::Type *ReturnType,
4323                                  ArrayRef<llvm::Value *> Ops);
4324  llvm::Value *EmitSVEAllTruePred(const SVETypeFlags &TypeFlags);
4325  llvm::Value *EmitSVEDupX(llvm::Value *Scalar);
4326  llvm::Value *EmitSVEDupX(llvm::Value *Scalar, llvm::Type *Ty);
4327  llvm::Value *EmitSVEReinterpret(llvm::Value *Val, llvm::Type *Ty);
4328  llvm::Value *EmitSVEPMull(const SVETypeFlags &TypeFlags,
4329                            llvm::SmallVectorImpl<llvm::Value *> &Ops,
4330                            unsigned BuiltinID);
4331  llvm::Value *EmitSVEMovl(const SVETypeFlags &TypeFlags,
4332                           llvm::ArrayRef<llvm::Value *> Ops,
4333                           unsigned BuiltinID);
4334  llvm::Value *EmitSVEPredicateCast(llvm::Value *Pred,
4335                                    llvm::ScalableVectorType *VTy);
4336  llvm::Value *EmitSVEGatherLoad(const SVETypeFlags &TypeFlags,
4337                                 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4338                                 unsigned IntID);
4339  llvm::Value *EmitSVEScatterStore(const SVETypeFlags &TypeFlags,
4340                                   llvm::SmallVectorImpl<llvm::Value *> &Ops,
4341                                   unsigned IntID);
4342  llvm::Value *EmitSVEMaskedLoad(const CallExpr *, llvm::Type *ReturnTy,
4343                                 SmallVectorImpl<llvm::Value *> &Ops,
4344                                 unsigned BuiltinID, bool IsZExtReturn);
4345  llvm::Value *EmitSVEMaskedStore(const CallExpr *,
4346                                  SmallVectorImpl<llvm::Value *> &Ops,
4347                                  unsigned BuiltinID);
4348  llvm::Value *EmitSVEPrefetchLoad(const SVETypeFlags &TypeFlags,
4349                                   SmallVectorImpl<llvm::Value *> &Ops,
4350                                   unsigned BuiltinID);
4351  llvm::Value *EmitSVEGatherPrefetch(const SVETypeFlags &TypeFlags,
4352                                     SmallVectorImpl<llvm::Value *> &Ops,
4353                                     unsigned IntID);
4354  llvm::Value *EmitSVEStructLoad(const SVETypeFlags &TypeFlags,
4355                                 SmallVectorImpl<llvm::Value *> &Ops,
4356                                 unsigned IntID);
4357  llvm::Value *EmitSVEStructStore(const SVETypeFlags &TypeFlags,
4358                                  SmallVectorImpl<llvm::Value *> &Ops,
4359                                  unsigned IntID);
4360  /// FormSVEBuiltinResult - Returns the struct of scalable vectors as a wider
4361  /// vector. It extracts the scalable vector from the struct and inserts into
4362  /// the wider vector. This avoids the error when allocating space in llvm
4363  /// for struct of scalable vectors if a function returns struct.
4364  llvm::Value *FormSVEBuiltinResult(llvm::Value *Call);
4365
4366  llvm::Value *EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4367
4368  llvm::Value *EmitSMELd1St1(const SVETypeFlags &TypeFlags,
4369                             llvm::SmallVectorImpl<llvm::Value *> &Ops,
4370                             unsigned IntID);
4371  llvm::Value *EmitSMEReadWrite(const SVETypeFlags &TypeFlags,
4372                                llvm::SmallVectorImpl<llvm::Value *> &Ops,
4373                                unsigned IntID);
4374  llvm::Value *EmitSMEZero(const SVETypeFlags &TypeFlags,
4375                           llvm::SmallVectorImpl<llvm::Value *> &Ops,
4376                           unsigned IntID);
4377  llvm::Value *EmitSMELdrStr(const SVETypeFlags &TypeFlags,
4378                             llvm::SmallVectorImpl<llvm::Value *> &Ops,
4379                             unsigned IntID);
4380
4381  void GetAArch64SVEProcessedOperands(unsigned BuiltinID, const CallExpr *E,
4382                                      SmallVectorImpl<llvm::Value *> &Ops,
4383                                      SVETypeFlags TypeFlags);
4384
4385  llvm::Value *EmitAArch64SMEBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4386
4387  llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4388                                      llvm::Triple::ArchType Arch);
4389  llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4390
4391  llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
4392  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4393  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4394  llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4395  llvm::Value *EmitScalarOrConstFoldImmArg(unsigned ICEArguments, unsigned Idx,
4396                                           const CallExpr *E);
4397  llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4398  llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4399  llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
4400                                          const CallExpr *E);
4401  llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4402  llvm::Value *EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4403                                    ReturnValueSlot ReturnValue);
4404  void ProcessOrderScopeAMDGCN(llvm::Value *Order, llvm::Value *Scope,
4405                               llvm::AtomicOrdering &AO,
4406                               llvm::SyncScope::ID &SSID);
4407
4408  enum class MSVCIntrin;
4409  llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
4410
4411  llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version);
4412
4413  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
4414  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
4415  llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
4416  llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
4417  llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
4418  llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
4419                                const ObjCMethodDecl *MethodWithObjects);
4420  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
4421  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
4422                             ReturnValueSlot Return = ReturnValueSlot());
4423
4424  /// Retrieves the default cleanup kind for an ARC cleanup.
4425  /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
4426  CleanupKind getARCCleanupKind() {
4427    return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
4428             ? NormalAndEHCleanup : NormalCleanup;
4429  }
4430
4431  // ARC primitives.
4432  void EmitARCInitWeak(Address addr, llvm::Value *value);
4433  void EmitARCDestroyWeak(Address addr);
4434  llvm::Value *EmitARCLoadWeak(Address addr);
4435  llvm::Value *EmitARCLoadWeakRetained(Address addr);
4436  llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
4437  void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
4438  void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
4439  void EmitARCCopyWeak(Address dst, Address src);
4440  void EmitARCMoveWeak(Address dst, Address src);
4441  llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
4442  llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
4443  llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
4444                                  bool resultIgnored);
4445  llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
4446                                      bool resultIgnored);
4447  llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
4448  llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
4449  llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
4450  void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
4451  void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
4452  llvm::Value *EmitARCAutorelease(llvm::Value *value);
4453  llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
4454  llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
4455  llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
4456  llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
4457
4458  llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
4459  llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
4460                                      llvm::Type *returnType);
4461  void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
4462
4463  std::pair<LValue,llvm::Value*>
4464  EmitARCStoreAutoreleasing(const BinaryOperator *e);
4465  std::pair<LValue,llvm::Value*>
4466  EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
4467  std::pair<LValue,llvm::Value*>
4468  EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
4469
4470  llvm::Value *EmitObjCAlloc(llvm::Value *value,
4471                             llvm::Type *returnType);
4472  llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
4473                                     llvm::Type *returnType);
4474  llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
4475
4476  llvm::Value *EmitObjCThrowOperand(const Expr *expr);
4477  llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
4478  llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
4479
4480  llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
4481  llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
4482                                            bool allowUnsafeClaim);
4483  llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
4484  llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
4485  llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
4486
4487  void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
4488
4489  void EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values);
4490
4491  static Destroyer destroyARCStrongImprecise;
4492  static Destroyer destroyARCStrongPrecise;
4493  static Destroyer destroyARCWeak;
4494  static Destroyer emitARCIntrinsicUse;
4495  static Destroyer destroyNonTrivialCStruct;
4496
4497  void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
4498  llvm::Value *EmitObjCAutoreleasePoolPush();
4499  llvm::Value *EmitObjCMRRAutoreleasePoolPush();
4500  void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
4501  void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
4502
4503  /// Emits a reference binding to the passed in expression.
4504  RValue EmitReferenceBindingToExpr(const Expr *E);
4505
4506  //===--------------------------------------------------------------------===//
4507  //                           Expression Emission
4508  //===--------------------------------------------------------------------===//
4509
4510  // Expressions are broken into three classes: scalar, complex, aggregate.
4511
4512  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
4513  /// scalar type, returning the result.
4514  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
4515
4516  /// Emit a conversion from the specified type to the specified destination
4517  /// type, both of which are LLVM scalar types.
4518  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
4519                                    QualType DstTy, SourceLocation Loc);
4520
4521  /// Emit a conversion from the specified complex type to the specified
4522  /// destination type, where the destination type is an LLVM scalar type.
4523  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
4524                                             QualType DstTy,
4525                                             SourceLocation Loc);
4526
4527  /// EmitAggExpr - Emit the computation of the specified expression
4528  /// of aggregate type.  The result is computed into the given slot,
4529  /// which may be null to indicate that the value is not needed.
4530  void EmitAggExpr(const Expr *E, AggValueSlot AS);
4531
4532  /// EmitAggExprToLValue - Emit the computation of the specified expression of
4533  /// aggregate type into a temporary LValue.
4534  LValue EmitAggExprToLValue(const Expr *E);
4535
4536  /// Build all the stores needed to initialize an aggregate at Dest with the
4537  /// value Val.
4538  void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile);
4539
4540  /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
4541  /// make sure it survives garbage collection until this point.
4542  void EmitExtendGCLifetime(llvm::Value *object);
4543
4544  /// EmitComplexExpr - Emit the computation of the specified expression of
4545  /// complex type, returning the result.
4546  ComplexPairTy EmitComplexExpr(const Expr *E,
4547                                bool IgnoreReal = false,
4548                                bool IgnoreImag = false);
4549
4550  /// EmitComplexExprIntoLValue - Emit the given expression of complex
4551  /// type and place its result into the specified l-value.
4552  void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
4553
4554  /// EmitStoreOfComplex - Store a complex number into the specified l-value.
4555  void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
4556
4557  /// EmitLoadOfComplex - Load a complex number from the specified l-value.
4558  ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
4559
4560  ComplexPairTy EmitPromotedComplexExpr(const Expr *E, QualType PromotionType);
4561  llvm::Value *EmitPromotedScalarExpr(const Expr *E, QualType PromotionType);
4562  ComplexPairTy EmitPromotedValue(ComplexPairTy result, QualType PromotionType);
4563  ComplexPairTy EmitUnPromotedValue(ComplexPairTy result, QualType PromotionType);
4564
4565  Address emitAddrOfRealComponent(Address complex, QualType complexType);
4566  Address emitAddrOfImagComponent(Address complex, QualType complexType);
4567
4568  /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
4569  /// global variable that has already been created for it.  If the initializer
4570  /// has a different type than GV does, this may free GV and return a different
4571  /// one.  Otherwise it just returns GV.
4572  llvm::GlobalVariable *
4573  AddInitializerToStaticVarDecl(const VarDecl &D,
4574                                llvm::GlobalVariable *GV);
4575
4576  // Emit an @llvm.invariant.start call for the given memory region.
4577  void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
4578
4579  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
4580  /// variable with global storage.
4581  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV,
4582                                bool PerformInit);
4583
4584  llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
4585                                   llvm::Constant *Addr);
4586
4587  llvm::Function *createTLSAtExitStub(const VarDecl &VD,
4588                                      llvm::FunctionCallee Dtor,
4589                                      llvm::Constant *Addr,
4590                                      llvm::FunctionCallee &AtExit);
4591
4592  /// Call atexit() with a function that passes the given argument to
4593  /// the given function.
4594  void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
4595                                    llvm::Constant *addr);
4596
4597  /// Registers the dtor using 'llvm.global_dtors' for platforms that do not
4598  /// support an 'atexit()' function.
4599  void registerGlobalDtorWithLLVM(const VarDecl &D, llvm::FunctionCallee fn,
4600                                  llvm::Constant *addr);
4601
4602  /// Call atexit() with function dtorStub.
4603  void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
4604
4605  /// Call unatexit() with function dtorStub.
4606  llvm::Value *unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub);
4607
4608  /// Emit code in this function to perform a guarded variable
4609  /// initialization.  Guarded initializations are used when it's not
4610  /// possible to prove that an initialization will be done exactly
4611  /// once, e.g. with a static local variable or a static data member
4612  /// of a class template.
4613  void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
4614                          bool PerformInit);
4615
4616  enum class GuardKind { VariableGuard, TlsGuard };
4617
4618  /// Emit a branch to select whether or not to perform guarded initialization.
4619  void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
4620                                llvm::BasicBlock *InitBlock,
4621                                llvm::BasicBlock *NoInitBlock,
4622                                GuardKind Kind, const VarDecl *D);
4623
4624  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
4625  /// variables.
4626  void
4627  GenerateCXXGlobalInitFunc(llvm::Function *Fn,
4628                            ArrayRef<llvm::Function *> CXXThreadLocals,
4629                            ConstantAddress Guard = ConstantAddress::invalid());
4630
4631  /// GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global
4632  /// variables.
4633  void GenerateCXXGlobalCleanUpFunc(
4634      llvm::Function *Fn,
4635      ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
4636                          llvm::Constant *>>
4637          DtorsOrStermFinalizers);
4638
4639  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
4640                                        const VarDecl *D,
4641                                        llvm::GlobalVariable *Addr,
4642                                        bool PerformInit);
4643
4644  void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
4645
4646  void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
4647
4648  void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
4649
4650  RValue EmitAtomicExpr(AtomicExpr *E);
4651
4652  //===--------------------------------------------------------------------===//
4653  //                         Annotations Emission
4654  //===--------------------------------------------------------------------===//
4655
4656  /// Emit an annotation call (intrinsic).
4657  llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
4658                                  llvm::Value *AnnotatedVal,
4659                                  StringRef AnnotationStr,
4660                                  SourceLocation Location,
4661                                  const AnnotateAttr *Attr);
4662
4663  /// Emit local annotations for the local variable V, declared by D.
4664  void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
4665
4666  /// Emit field annotations for the given field & value. Returns the
4667  /// annotation result.
4668  Address EmitFieldAnnotations(const FieldDecl *D, Address V);
4669
4670  //===--------------------------------------------------------------------===//
4671  //                             Internal Helpers
4672  //===--------------------------------------------------------------------===//
4673
4674  /// ContainsLabel - Return true if the statement contains a label in it.  If
4675  /// this statement is not executed normally, it not containing a label means
4676  /// that we can just remove the code.
4677  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
4678
4679  /// containsBreak - Return true if the statement contains a break out of it.
4680  /// If the statement (recursively) contains a switch or loop with a break
4681  /// inside of it, this is fine.
4682  static bool containsBreak(const Stmt *S);
4683
4684  /// Determine if the given statement might introduce a declaration into the
4685  /// current scope, by being a (possibly-labelled) DeclStmt.
4686  static bool mightAddDeclToScope(const Stmt *S);
4687
4688  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4689  /// to a constant, or if it does but contains a label, return false.  If it
4690  /// constant folds return true and set the boolean result in Result.
4691  bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
4692                                    bool AllowLabels = false);
4693
4694  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4695  /// to a constant, or if it does but contains a label, return false.  If it
4696  /// constant folds return true and set the folded value.
4697  bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
4698                                    bool AllowLabels = false);
4699
4700  /// Ignore parentheses and logical-NOT to track conditions consistently.
4701  static const Expr *stripCond(const Expr *C);
4702
4703  /// isInstrumentedCondition - Determine whether the given condition is an
4704  /// instrumentable condition (i.e. no "&&" or "||").
4705  static bool isInstrumentedCondition(const Expr *C);
4706
4707  /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
4708  /// increments a profile counter based on the semantics of the given logical
4709  /// operator opcode.  This is used to instrument branch condition coverage
4710  /// for logical operators.
4711  void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp,
4712                                llvm::BasicBlock *TrueBlock,
4713                                llvm::BasicBlock *FalseBlock,
4714                                uint64_t TrueCount = 0,
4715                                Stmt::Likelihood LH = Stmt::LH_None,
4716                                const Expr *CntrIdx = nullptr);
4717
4718  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
4719  /// if statement) to the specified blocks.  Based on the condition, this might
4720  /// try to simplify the codegen of the conditional based on the branch.
4721  /// TrueCount should be the number of times we expect the condition to
4722  /// evaluate to true based on PGO data.
4723  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
4724                            llvm::BasicBlock *FalseBlock, uint64_t TrueCount,
4725                            Stmt::Likelihood LH = Stmt::LH_None,
4726                            const Expr *ConditionalOp = nullptr);
4727
4728  /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
4729  /// nonnull, if \p LHS is marked _Nonnull.
4730  void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
4731
4732  /// An enumeration which makes it easier to specify whether or not an
4733  /// operation is a subtraction.
4734  enum { NotSubtraction = false, IsSubtraction = true };
4735
4736  /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
4737  /// detect undefined behavior when the pointer overflow sanitizer is enabled.
4738  /// \p SignedIndices indicates whether any of the GEP indices are signed.
4739  /// \p IsSubtraction indicates whether the expression used to form the GEP
4740  /// is a subtraction.
4741  llvm::Value *EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr,
4742                                      ArrayRef<llvm::Value *> IdxList,
4743                                      bool SignedIndices,
4744                                      bool IsSubtraction,
4745                                      SourceLocation Loc,
4746                                      const Twine &Name = "");
4747
4748  /// Specifies which type of sanitizer check to apply when handling a
4749  /// particular builtin.
4750  enum BuiltinCheckKind {
4751    BCK_CTZPassedZero,
4752    BCK_CLZPassedZero,
4753  };
4754
4755  /// Emits an argument for a call to a builtin. If the builtin sanitizer is
4756  /// enabled, a runtime check specified by \p Kind is also emitted.
4757  llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
4758
4759  /// Emit a description of a type in a format suitable for passing to
4760  /// a runtime sanitizer handler.
4761  llvm::Constant *EmitCheckTypeDescriptor(QualType T);
4762
4763  /// Convert a value into a format suitable for passing to a runtime
4764  /// sanitizer handler.
4765  llvm::Value *EmitCheckValue(llvm::Value *V);
4766
4767  /// Emit a description of a source location in a format suitable for
4768  /// passing to a runtime sanitizer handler.
4769  llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
4770
4771  void EmitKCFIOperandBundle(const CGCallee &Callee,
4772                             SmallVectorImpl<llvm::OperandBundleDef> &Bundles);
4773
4774  /// Create a basic block that will either trap or call a handler function in
4775  /// the UBSan runtime with the provided arguments, and create a conditional
4776  /// branch to it.
4777  void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
4778                 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
4779                 ArrayRef<llvm::Value *> DynamicArgs);
4780
4781  /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
4782  /// if Cond if false.
4783  void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
4784                            llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4785                            ArrayRef<llvm::Constant *> StaticArgs);
4786
4787  /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
4788  /// checking is enabled. Otherwise, just emit an unreachable instruction.
4789  void EmitUnreachable(SourceLocation Loc);
4790
4791  /// Create a basic block that will call the trap intrinsic, and emit a
4792  /// conditional branch to it, for the -ftrapv checks.
4793  void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID);
4794
4795  /// Emit a call to trap or debugtrap and attach function attribute
4796  /// "trap-func-name" if specified.
4797  llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
4798
4799  /// Emit a stub for the cross-DSO CFI check function.
4800  void EmitCfiCheckStub();
4801
4802  /// Emit a cross-DSO CFI failure handling function.
4803  void EmitCfiCheckFail();
4804
4805  /// Create a check for a function parameter that may potentially be
4806  /// declared as non-null.
4807  void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
4808                           AbstractCallee AC, unsigned ParmNum);
4809
4810  /// EmitCallArg - Emit a single call argument.
4811  void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
4812
4813  /// EmitDelegateCallArg - We are performing a delegate call; that
4814  /// is, the current function is delegating to another one.  Produce
4815  /// a r-value suitable for passing the given parameter.
4816  void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
4817                           SourceLocation loc);
4818
4819  /// SetFPAccuracy - Set the minimum required accuracy of the given floating
4820  /// point operation, expressed as the maximum relative error in ulp.
4821  void SetFPAccuracy(llvm::Value *Val, float Accuracy);
4822
4823  /// Set the minimum required accuracy of the given sqrt operation
4824  /// based on CodeGenOpts.
4825  void SetSqrtFPAccuracy(llvm::Value *Val);
4826
4827  /// Set the minimum required accuracy of the given sqrt operation based on
4828  /// CodeGenOpts.
4829  void SetDivFPAccuracy(llvm::Value *Val);
4830
4831  /// Set the codegen fast-math flags.
4832  void SetFastMathFlags(FPOptions FPFeatures);
4833
4834  // Truncate or extend a boolean vector to the requested number of elements.
4835  llvm::Value *emitBoolVecConversion(llvm::Value *SrcVec,
4836                                     unsigned NumElementsDst,
4837                                     const llvm::Twine &Name = "");
4838
4839private:
4840  llvm::MDNode *getRangeForLoadFromType(QualType Ty);
4841  void EmitReturnOfRValue(RValue RV, QualType Ty);
4842
4843  void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
4844
4845  llvm::SmallVector<std::pair<llvm::WeakTrackingVH, llvm::Value *>, 4>
4846      DeferredReplacements;
4847
4848  /// Set the address of a local variable.
4849  void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
4850    assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
4851    LocalDeclMap.insert({VD, Addr});
4852  }
4853
4854  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
4855  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
4856  ///
4857  /// \param AI - The first function argument of the expansion.
4858  void ExpandTypeFromArgs(QualType Ty, LValue Dst,
4859                          llvm::Function::arg_iterator &AI);
4860
4861  /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
4862  /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
4863  /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
4864  void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
4865                        SmallVectorImpl<llvm::Value *> &IRCallArgs,
4866                        unsigned &IRCallArgPos);
4867
4868  std::pair<llvm::Value *, llvm::Type *>
4869  EmitAsmInput(const TargetInfo::ConstraintInfo &Info, const Expr *InputExpr,
4870               std::string &ConstraintStr);
4871
4872  std::pair<llvm::Value *, llvm::Type *>
4873  EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, LValue InputValue,
4874                     QualType InputType, std::string &ConstraintStr,
4875                     SourceLocation Loc);
4876
4877  /// Attempts to statically evaluate the object size of E. If that
4878  /// fails, emits code to figure the size of E out for us. This is
4879  /// pass_object_size aware.
4880  ///
4881  /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
4882  llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
4883                                               llvm::IntegerType *ResType,
4884                                               llvm::Value *EmittedE,
4885                                               bool IsDynamic);
4886
4887  /// Emits the size of E, as required by __builtin_object_size. This
4888  /// function is aware of pass_object_size parameters, and will act accordingly
4889  /// if E is a parameter with the pass_object_size attribute.
4890  llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
4891                                     llvm::IntegerType *ResType,
4892                                     llvm::Value *EmittedE,
4893                                     bool IsDynamic);
4894
4895  llvm::Value *emitFlexibleArrayMemberSize(const Expr *E, unsigned Type,
4896                                           llvm::IntegerType *ResType);
4897
4898  void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D,
4899                                       Address Loc);
4900
4901public:
4902  enum class EvaluationOrder {
4903    ///! No language constraints on evaluation order.
4904    Default,
4905    ///! Language semantics require left-to-right evaluation.
4906    ForceLeftToRight,
4907    ///! Language semantics require right-to-left evaluation.
4908    ForceRightToLeft
4909  };
4910
4911  // Wrapper for function prototype sources. Wraps either a FunctionProtoType or
4912  // an ObjCMethodDecl.
4913  struct PrototypeWrapper {
4914    llvm::PointerUnion<const FunctionProtoType *, const ObjCMethodDecl *> P;
4915
4916    PrototypeWrapper(const FunctionProtoType *FT) : P(FT) {}
4917    PrototypeWrapper(const ObjCMethodDecl *MD) : P(MD) {}
4918  };
4919
4920  void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype,
4921                    llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4922                    AbstractCallee AC = AbstractCallee(),
4923                    unsigned ParamsToSkip = 0,
4924                    EvaluationOrder Order = EvaluationOrder::Default);
4925
4926  /// EmitPointerWithAlignment - Given an expression with a pointer type,
4927  /// emit the value and compute our best estimate of the alignment of the
4928  /// pointee.
4929  ///
4930  /// \param BaseInfo - If non-null, this will be initialized with
4931  /// information about the source of the alignment and the may-alias
4932  /// attribute.  Note that this function will conservatively fall back on
4933  /// the type when it doesn't recognize the expression and may-alias will
4934  /// be set to false.
4935  ///
4936  /// One reasonable way to use this information is when there's a language
4937  /// guarantee that the pointer must be aligned to some stricter value, and
4938  /// we're simply trying to ensure that sufficiently obvious uses of under-
4939  /// aligned objects don't get miscompiled; for example, a placement new
4940  /// into the address of a local variable.  In such a case, it's quite
4941  /// reasonable to just ignore the returned alignment when it isn't from an
4942  /// explicit source.
4943  Address
4944  EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo = nullptr,
4945                           TBAAAccessInfo *TBAAInfo = nullptr,
4946                           KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
4947
4948  /// If \p E references a parameter with pass_object_size info or a constant
4949  /// array size modifier, emit the object size divided by the size of \p EltTy.
4950  /// Otherwise return null.
4951  llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
4952
4953  void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
4954
4955  struct MultiVersionResolverOption {
4956    llvm::Function *Function;
4957    struct Conds {
4958      StringRef Architecture;
4959      llvm::SmallVector<StringRef, 8> Features;
4960
4961      Conds(StringRef Arch, ArrayRef<StringRef> Feats)
4962          : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
4963    } Conditions;
4964
4965    MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
4966                               ArrayRef<StringRef> Feats)
4967        : Function(F), Conditions(Arch, Feats) {}
4968  };
4969
4970  // Emits the body of a multiversion function's resolver. Assumes that the
4971  // options are already sorted in the proper order, with the 'default' option
4972  // last (if it exists).
4973  void EmitMultiVersionResolver(llvm::Function *Resolver,
4974                                ArrayRef<MultiVersionResolverOption> Options);
4975  void
4976  EmitX86MultiVersionResolver(llvm::Function *Resolver,
4977                              ArrayRef<MultiVersionResolverOption> Options);
4978  void
4979  EmitAArch64MultiVersionResolver(llvm::Function *Resolver,
4980                                  ArrayRef<MultiVersionResolverOption> Options);
4981
4982private:
4983  QualType getVarArgType(const Expr *Arg);
4984
4985  void EmitDeclMetadata();
4986
4987  BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
4988                                  const AutoVarEmission &emission);
4989
4990  void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
4991
4992  llvm::Value *GetValueForARMHint(unsigned BuiltinID);
4993  llvm::Value *EmitX86CpuIs(const CallExpr *E);
4994  llvm::Value *EmitX86CpuIs(StringRef CPUStr);
4995  llvm::Value *EmitX86CpuSupports(const CallExpr *E);
4996  llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
4997  llvm::Value *EmitX86CpuSupports(std::array<uint32_t, 4> FeatureMask);
4998  llvm::Value *EmitX86CpuInit();
4999  llvm::Value *FormX86ResolverCondition(const MultiVersionResolverOption &RO);
5000  llvm::Value *EmitAArch64CpuInit();
5001  llvm::Value *
5002  FormAArch64ResolverCondition(const MultiVersionResolverOption &RO);
5003  llvm::Value *EmitAArch64CpuSupports(ArrayRef<StringRef> FeatureStrs);
5004};
5005
5006
5007inline DominatingLLVMValue::saved_type
5008DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
5009  if (!needsSaving(value)) return saved_type(value, false);
5010
5011  // Otherwise, we need an alloca.
5012  auto align = CharUnits::fromQuantity(
5013      CGF.CGM.getDataLayout().getPrefTypeAlign(value->getType()));
5014  Address alloca =
5015      CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
5016  CGF.Builder.CreateStore(value, alloca);
5017
5018  return saved_type(alloca.getPointer(), true);
5019}
5020
5021inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
5022                                                 saved_type value) {
5023  // If the value says it wasn't saved, trust that it's still dominating.
5024  if (!value.getInt()) return value.getPointer();
5025
5026  // Otherwise, it should be an alloca instruction, as set up in save().
5027  auto alloca = cast<llvm::AllocaInst>(value.getPointer());
5028  return CGF.Builder.CreateAlignedLoad(alloca->getAllocatedType(), alloca,
5029                                       alloca->getAlign());
5030}
5031
5032}  // end namespace CodeGen
5033
5034// Map the LangOption for floating point exception behavior into
5035// the corresponding enum in the IR.
5036llvm::fp::ExceptionBehavior
5037ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind);
5038}  // end namespace clang
5039
5040#endif
5041