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