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