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