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