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