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