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