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