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