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