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