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