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