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