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