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