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