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