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