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