]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.h
Merge ^/head r309170 through r309212.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CodeGenFunction.h
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   /// Data for exit block for proper support of OpenMP cancellation constructs.
969   struct OMPCancel {
970     JumpDest ExitBlock;
971     llvm::function_ref<void(CodeGenFunction &CGF)> CodeGen;
972     OMPCancel() : CodeGen([](CodeGenFunction &CGF) {}) {}
973   };
974   SmallVector<OMPCancel, 8> OMPCancelStack;
975
976   /// Controls insertion of cancellation exit blocks in worksharing constructs.
977   class OMPCancelStackRAII {
978     CodeGenFunction &CGF;
979
980   public:
981     OMPCancelStackRAII(CodeGenFunction &CGF) : CGF(CGF) {
982       CGF.OMPCancelStack.push_back({});
983     }
984     ~OMPCancelStackRAII() {
985       if (CGF.HaveInsertPoint() &&
986           CGF.OMPCancelStack.back().ExitBlock.isValid()) {
987         auto CJD = CGF.getJumpDestInCurrentScope("cancel.cont");
988         CGF.EmitBranchThroughCleanup(CJD);
989         CGF.EmitBlock(CGF.OMPCancelStack.back().ExitBlock.getBlock());
990         CGF.OMPCancelStack.back().CodeGen(CGF);
991         CGF.EmitBranchThroughCleanup(CJD);
992         CGF.EmitBlock(CJD.getBlock());
993       }
994     }
995   };
996
997   CodeGenPGO PGO;
998
999   /// Calculate branch weights appropriate for PGO data
1000   llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1001   llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1002   llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1003                                             uint64_t LoopCount);
1004
1005 public:
1006   /// Increment the profiler's counter for the given statement.
1007   void incrementProfileCounter(const Stmt *S) {
1008     if (CGM.getCodeGenOpts().hasProfileClangInstr())
1009       PGO.emitCounterIncrement(Builder, S);
1010     PGO.setCurrentStmt(S);
1011   }
1012
1013   /// Get the profiler's count for the given statement.
1014   uint64_t getProfileCount(const Stmt *S) {
1015     Optional<uint64_t> Count = PGO.getStmtCount(S);
1016     if (!Count.hasValue())
1017       return 0;
1018     return *Count;
1019   }
1020
1021   /// Set the profiler's current count.
1022   void setCurrentProfileCount(uint64_t Count) {
1023     PGO.setCurrentRegionCount(Count);
1024   }
1025
1026   /// Get the profiler's current count. This is generally the count for the most
1027   /// recently incremented counter.
1028   uint64_t getCurrentProfileCount() {
1029     return PGO.getCurrentRegionCount();
1030   }
1031
1032 private:
1033
1034   /// SwitchInsn - This is nearest current switch instruction. It is null if
1035   /// current context is not in a switch.
1036   llvm::SwitchInst *SwitchInsn;
1037   /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1038   SmallVector<uint64_t, 16> *SwitchWeights;
1039
1040   /// CaseRangeBlock - This block holds if condition check for last case
1041   /// statement range in current switch instruction.
1042   llvm::BasicBlock *CaseRangeBlock;
1043
1044   /// OpaqueLValues - Keeps track of the current set of opaque value
1045   /// expressions.
1046   llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1047   llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1048
1049   // VLASizeMap - This keeps track of the associated size for each VLA type.
1050   // We track this by the size expression rather than the type itself because
1051   // in certain situations, like a const qualifier applied to an VLA typedef,
1052   // multiple VLA types can share the same size expression.
1053   // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1054   // enter/leave scopes.
1055   llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1056
1057   /// A block containing a single 'unreachable' instruction.  Created
1058   /// lazily by getUnreachableBlock().
1059   llvm::BasicBlock *UnreachableBlock;
1060
1061   /// Counts of the number return expressions in the function.
1062   unsigned NumReturnExprs;
1063
1064   /// Count the number of simple (constant) return expressions in the function.
1065   unsigned NumSimpleReturnExprs;
1066
1067   /// The last regular (non-return) debug location (breakpoint) in the function.
1068   SourceLocation LastStopPoint;
1069
1070 public:
1071   /// A scope within which we are constructing the fields of an object which
1072   /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1073   /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1074   class FieldConstructionScope {
1075   public:
1076     FieldConstructionScope(CodeGenFunction &CGF, Address This)
1077         : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1078       CGF.CXXDefaultInitExprThis = This;
1079     }
1080     ~FieldConstructionScope() {
1081       CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1082     }
1083
1084   private:
1085     CodeGenFunction &CGF;
1086     Address OldCXXDefaultInitExprThis;
1087   };
1088
1089   /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1090   /// is overridden to be the object under construction.
1091   class CXXDefaultInitExprScope {
1092   public:
1093     CXXDefaultInitExprScope(CodeGenFunction &CGF)
1094       : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1095         OldCXXThisAlignment(CGF.CXXThisAlignment) {
1096       CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1097       CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1098     }
1099     ~CXXDefaultInitExprScope() {
1100       CGF.CXXThisValue = OldCXXThisValue;
1101       CGF.CXXThisAlignment = OldCXXThisAlignment;
1102     }
1103
1104   public:
1105     CodeGenFunction &CGF;
1106     llvm::Value *OldCXXThisValue;
1107     CharUnits OldCXXThisAlignment;
1108   };
1109
1110   class InlinedInheritingConstructorScope {
1111   public:
1112     InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1113         : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1114           OldCurCodeDecl(CGF.CurCodeDecl),
1115           OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1116           OldCXXABIThisValue(CGF.CXXABIThisValue),
1117           OldCXXThisValue(CGF.CXXThisValue),
1118           OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1119           OldCXXThisAlignment(CGF.CXXThisAlignment),
1120           OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1121           OldCXXInheritedCtorInitExprArgs(
1122               std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1123       CGF.CurGD = GD;
1124       CGF.CurFuncDecl = CGF.CurCodeDecl =
1125           cast<CXXConstructorDecl>(GD.getDecl());
1126       CGF.CXXABIThisDecl = nullptr;
1127       CGF.CXXABIThisValue = nullptr;
1128       CGF.CXXThisValue = nullptr;
1129       CGF.CXXABIThisAlignment = CharUnits();
1130       CGF.CXXThisAlignment = CharUnits();
1131       CGF.ReturnValue = Address::invalid();
1132       CGF.FnRetTy = QualType();
1133       CGF.CXXInheritedCtorInitExprArgs.clear();
1134     }
1135     ~InlinedInheritingConstructorScope() {
1136       CGF.CurGD = OldCurGD;
1137       CGF.CurFuncDecl = OldCurFuncDecl;
1138       CGF.CurCodeDecl = OldCurCodeDecl;
1139       CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1140       CGF.CXXABIThisValue = OldCXXABIThisValue;
1141       CGF.CXXThisValue = OldCXXThisValue;
1142       CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1143       CGF.CXXThisAlignment = OldCXXThisAlignment;
1144       CGF.ReturnValue = OldReturnValue;
1145       CGF.FnRetTy = OldFnRetTy;
1146       CGF.CXXInheritedCtorInitExprArgs =
1147           std::move(OldCXXInheritedCtorInitExprArgs);
1148     }
1149
1150   private:
1151     CodeGenFunction &CGF;
1152     GlobalDecl OldCurGD;
1153     const Decl *OldCurFuncDecl;
1154     const Decl *OldCurCodeDecl;
1155     ImplicitParamDecl *OldCXXABIThisDecl;
1156     llvm::Value *OldCXXABIThisValue;
1157     llvm::Value *OldCXXThisValue;
1158     CharUnits OldCXXABIThisAlignment;
1159     CharUnits OldCXXThisAlignment;
1160     Address OldReturnValue;
1161     QualType OldFnRetTy;
1162     CallArgList OldCXXInheritedCtorInitExprArgs;
1163   };
1164
1165 private:
1166   /// CXXThisDecl - When generating code for a C++ member function,
1167   /// this will hold the implicit 'this' declaration.
1168   ImplicitParamDecl *CXXABIThisDecl;
1169   llvm::Value *CXXABIThisValue;
1170   llvm::Value *CXXThisValue;
1171   CharUnits CXXABIThisAlignment;
1172   CharUnits CXXThisAlignment;
1173
1174   /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1175   /// this expression.
1176   Address CXXDefaultInitExprThis = Address::invalid();
1177
1178   /// The values of function arguments to use when evaluating
1179   /// CXXInheritedCtorInitExprs within this context.
1180   CallArgList CXXInheritedCtorInitExprArgs;
1181
1182   /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1183   /// destructor, this will hold the implicit argument (e.g. VTT).
1184   ImplicitParamDecl *CXXStructorImplicitParamDecl;
1185   llvm::Value *CXXStructorImplicitParamValue;
1186
1187   /// OutermostConditional - Points to the outermost active
1188   /// conditional control.  This is used so that we know if a
1189   /// temporary should be destroyed conditionally.
1190   ConditionalEvaluation *OutermostConditional;
1191
1192   /// The current lexical scope.
1193   LexicalScope *CurLexicalScope;
1194
1195   /// The current source location that should be used for exception
1196   /// handling code.
1197   SourceLocation CurEHLocation;
1198
1199   /// BlockByrefInfos - For each __block variable, contains
1200   /// information about the layout of the variable.
1201   llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1202
1203   llvm::BasicBlock *TerminateLandingPad;
1204   llvm::BasicBlock *TerminateHandler;
1205   llvm::BasicBlock *TrapBB;
1206
1207   /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
1208   /// In the kernel metadata node, reference the kernel function and metadata 
1209   /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
1210   /// - A node for the vec_type_hint(<type>) qualifier contains string
1211   ///   "vec_type_hint", an undefined value of the <type> data type,
1212   ///   and a Boolean that is true if the <type> is integer and signed.
1213   /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 
1214   ///   "work_group_size_hint", and three 32-bit integers X, Y and Z.
1215   /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 
1216   ///   "reqd_work_group_size", and three 32-bit integers X, Y and Z.
1217   void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 
1218                                 llvm::Function *Fn);
1219
1220 public:
1221   CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1222   ~CodeGenFunction();
1223
1224   CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1225   ASTContext &getContext() const { return CGM.getContext(); }
1226   CGDebugInfo *getDebugInfo() { 
1227     if (DisableDebugInfo) 
1228       return nullptr;
1229     return DebugInfo; 
1230   }
1231   void disableDebugInfo() { DisableDebugInfo = true; }
1232   void enableDebugInfo() { DisableDebugInfo = false; }
1233
1234   bool shouldUseFusedARCCalls() {
1235     return CGM.getCodeGenOpts().OptimizationLevel == 0;
1236   }
1237
1238   const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1239
1240   /// Returns a pointer to the function's exception object and selector slot,
1241   /// which is assigned in every landing pad.
1242   Address getExceptionSlot();
1243   Address getEHSelectorSlot();
1244
1245   /// Returns the contents of the function's exception object and selector
1246   /// slots.
1247   llvm::Value *getExceptionFromSlot();
1248   llvm::Value *getSelectorFromSlot();
1249
1250   Address getNormalCleanupDestSlot();
1251
1252   llvm::BasicBlock *getUnreachableBlock() {
1253     if (!UnreachableBlock) {
1254       UnreachableBlock = createBasicBlock("unreachable");
1255       new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1256     }
1257     return UnreachableBlock;
1258   }
1259
1260   llvm::BasicBlock *getInvokeDest() {
1261     if (!EHStack.requiresLandingPad()) return nullptr;
1262     return getInvokeDestImpl();
1263   }
1264
1265   bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1266
1267   const TargetInfo &getTarget() const { return Target; }
1268   llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1269
1270   //===--------------------------------------------------------------------===//
1271   //                                  Cleanups
1272   //===--------------------------------------------------------------------===//
1273
1274   typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1275
1276   void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1277                                         Address arrayEndPointer,
1278                                         QualType elementType,
1279                                         CharUnits elementAlignment,
1280                                         Destroyer *destroyer);
1281   void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1282                                       llvm::Value *arrayEnd,
1283                                       QualType elementType,
1284                                       CharUnits elementAlignment,
1285                                       Destroyer *destroyer);
1286
1287   void pushDestroy(QualType::DestructionKind dtorKind,
1288                    Address addr, QualType type);
1289   void pushEHDestroy(QualType::DestructionKind dtorKind,
1290                      Address addr, QualType type);
1291   void pushDestroy(CleanupKind kind, Address addr, QualType type,
1292                    Destroyer *destroyer, bool useEHCleanupForArray);
1293   void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1294                                    QualType type, Destroyer *destroyer,
1295                                    bool useEHCleanupForArray);
1296   void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1297                                    llvm::Value *CompletePtr,
1298                                    QualType ElementType);
1299   void pushStackRestore(CleanupKind kind, Address SPMem);
1300   void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1301                    bool useEHCleanupForArray);
1302   llvm::Function *generateDestroyHelper(Address addr, QualType type,
1303                                         Destroyer *destroyer,
1304                                         bool useEHCleanupForArray,
1305                                         const VarDecl *VD);
1306   void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1307                         QualType elementType, CharUnits elementAlign,
1308                         Destroyer *destroyer,
1309                         bool checkZeroLength, bool useEHCleanup);
1310
1311   Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1312
1313   /// Determines whether an EH cleanup is required to destroy a type
1314   /// with the given destruction kind.
1315   bool needsEHCleanup(QualType::DestructionKind kind) {
1316     switch (kind) {
1317     case QualType::DK_none:
1318       return false;
1319     case QualType::DK_cxx_destructor:
1320     case QualType::DK_objc_weak_lifetime:
1321       return getLangOpts().Exceptions;
1322     case QualType::DK_objc_strong_lifetime:
1323       return getLangOpts().Exceptions &&
1324              CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1325     }
1326     llvm_unreachable("bad destruction kind");
1327   }
1328
1329   CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1330     return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1331   }
1332
1333   //===--------------------------------------------------------------------===//
1334   //                                  Objective-C
1335   //===--------------------------------------------------------------------===//
1336
1337   void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1338
1339   void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1340
1341   /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1342   void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1343                           const ObjCPropertyImplDecl *PID);
1344   void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1345                               const ObjCPropertyImplDecl *propImpl,
1346                               const ObjCMethodDecl *GetterMothodDecl,
1347                               llvm::Constant *AtomicHelperFn);
1348
1349   void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1350                                   ObjCMethodDecl *MD, bool ctor);
1351
1352   /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1353   /// for the given property.
1354   void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1355                           const ObjCPropertyImplDecl *PID);
1356   void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1357                               const ObjCPropertyImplDecl *propImpl,
1358                               llvm::Constant *AtomicHelperFn);
1359
1360   //===--------------------------------------------------------------------===//
1361   //                                  Block Bits
1362   //===--------------------------------------------------------------------===//
1363
1364   llvm::Value *EmitBlockLiteral(const BlockExpr *);
1365   llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
1366   static void destroyBlockInfos(CGBlockInfo *info);
1367
1368   llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1369                                         const CGBlockInfo &Info,
1370                                         const DeclMapTy &ldm,
1371                                         bool IsLambdaConversionToBlock);
1372
1373   llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1374   llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1375   llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1376                                              const ObjCPropertyImplDecl *PID);
1377   llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1378                                              const ObjCPropertyImplDecl *PID);
1379   llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1380
1381   void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1382
1383   class AutoVarEmission;
1384
1385   void emitByrefStructureInit(const AutoVarEmission &emission);
1386   void enterByrefCleanup(const AutoVarEmission &emission);
1387
1388   void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1389                                 llvm::Value *ptr);
1390
1391   Address LoadBlockStruct();
1392   Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1393
1394   /// BuildBlockByrefAddress - Computes the location of the
1395   /// data in a variable which is declared as __block.
1396   Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1397                                 bool followForward = true);
1398   Address emitBlockByrefAddress(Address baseAddr,
1399                                 const BlockByrefInfo &info,
1400                                 bool followForward,
1401                                 const llvm::Twine &name);
1402
1403   const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1404
1405   QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1406
1407   void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1408                     const CGFunctionInfo &FnInfo);
1409   /// \brief Emit code for the start of a function.
1410   /// \param Loc       The location to be associated with the function.
1411   /// \param StartLoc  The location of the function body.
1412   void StartFunction(GlobalDecl GD,
1413                      QualType RetTy,
1414                      llvm::Function *Fn,
1415                      const CGFunctionInfo &FnInfo,
1416                      const FunctionArgList &Args,
1417                      SourceLocation Loc = SourceLocation(),
1418                      SourceLocation StartLoc = SourceLocation());
1419
1420   void EmitConstructorBody(FunctionArgList &Args);
1421   void EmitDestructorBody(FunctionArgList &Args);
1422   void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1423   void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1424   void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1425
1426   void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1427                                   CallArgList &CallArgs);
1428   void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1429   void EmitLambdaBlockInvokeBody();
1430   void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1431   void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1432   void EmitAsanPrologueOrEpilogue(bool Prologue);
1433
1434   /// \brief Emit the unified return block, trying to avoid its emission when
1435   /// possible.
1436   /// \return The debug location of the user written return statement if the
1437   /// return block is is avoided.
1438   llvm::DebugLoc EmitReturnBlock();
1439
1440   /// FinishFunction - Complete IR generation of the current function. It is
1441   /// legal to call this function even if there is no current insertion point.
1442   void FinishFunction(SourceLocation EndLoc=SourceLocation());
1443
1444   void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1445                   const CGFunctionInfo &FnInfo);
1446
1447   void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
1448
1449   void FinishThunk();
1450
1451   /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1452   void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1453                          llvm::Value *Callee);
1454
1455   /// Generate a thunk for the given method.
1456   void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1457                      GlobalDecl GD, const ThunkInfo &Thunk);
1458
1459   llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1460                                        const CGFunctionInfo &FnInfo,
1461                                        GlobalDecl GD, const ThunkInfo &Thunk);
1462
1463   void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1464                         FunctionArgList &Args);
1465
1466   void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
1467                                ArrayRef<VarDecl *> ArrayIndexes);
1468
1469   /// Struct with all informations about dynamic [sub]class needed to set vptr.
1470   struct VPtr {
1471     BaseSubobject Base;
1472     const CXXRecordDecl *NearestVBase;
1473     CharUnits OffsetFromNearestVBase;
1474     const CXXRecordDecl *VTableClass;
1475   };
1476
1477   /// Initialize the vtable pointer of the given subobject.
1478   void InitializeVTablePointer(const VPtr &vptr);
1479
1480   typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1481
1482   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1483   VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1484
1485   void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1486                          CharUnits OffsetFromNearestVBase,
1487                          bool BaseIsNonVirtualPrimaryBase,
1488                          const CXXRecordDecl *VTableClass,
1489                          VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1490
1491   void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1492
1493   /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1494   /// to by This.
1495   llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1496                             const CXXRecordDecl *VTableClass);
1497
1498   enum CFITypeCheckKind {
1499     CFITCK_VCall,
1500     CFITCK_NVCall,
1501     CFITCK_DerivedCast,
1502     CFITCK_UnrelatedCast,
1503     CFITCK_ICall,
1504   };
1505
1506   /// \brief Derived is the presumed address of an object of type T after a
1507   /// cast. If T is a polymorphic class type, emit a check that the virtual
1508   /// table for Derived belongs to a class derived from T.
1509   void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1510                                  bool MayBeNull, CFITypeCheckKind TCK,
1511                                  SourceLocation Loc);
1512
1513   /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1514   /// If vptr CFI is enabled, emit a check that VTable is valid.
1515   void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1516                                  CFITypeCheckKind TCK, SourceLocation Loc);
1517
1518   /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1519   /// RD using llvm.type.test.
1520   void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1521                           CFITypeCheckKind TCK, SourceLocation Loc);
1522
1523   /// If whole-program virtual table optimization is enabled, emit an assumption
1524   /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1525   /// enabled, emit a check that VTable is a member of RD's type identifier.
1526   void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1527                                     llvm::Value *VTable, SourceLocation Loc);
1528
1529   /// Returns whether we should perform a type checked load when loading a
1530   /// virtual function for virtual calls to members of RD. This is generally
1531   /// true when both vcall CFI and whole-program-vtables are enabled.
1532   bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1533
1534   /// Emit a type checked load from the given vtable.
1535   llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1536                                          uint64_t VTableByteOffset);
1537
1538   /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1539   /// expr can be devirtualized.
1540   bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1541                                          const CXXMethodDecl *MD);
1542
1543   /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1544   /// given phase of destruction for a destructor.  The end result
1545   /// should call destructors on members and base classes in reverse
1546   /// order of their construction.
1547   void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1548
1549   /// ShouldInstrumentFunction - Return true if the current function should be
1550   /// instrumented with __cyg_profile_func_* calls
1551   bool ShouldInstrumentFunction();
1552
1553   /// ShouldXRayInstrument - Return true if the current function should be
1554   /// instrumented with XRay nop sleds.
1555   bool ShouldXRayInstrumentFunction() const;
1556
1557   /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1558   /// instrumentation function with the current function and the call site, if
1559   /// function instrumentation is enabled.
1560   void EmitFunctionInstrumentation(const char *Fn);
1561
1562   /// EmitMCountInstrumentation - Emit call to .mcount.
1563   void EmitMCountInstrumentation();
1564
1565   /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1566   /// arguments for the given function. This is also responsible for naming the
1567   /// LLVM function arguments.
1568   void EmitFunctionProlog(const CGFunctionInfo &FI,
1569                           llvm::Function *Fn,
1570                           const FunctionArgList &Args);
1571
1572   /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1573   /// given temporary.
1574   void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1575                           SourceLocation EndLoc);
1576
1577   /// EmitStartEHSpec - Emit the start of the exception spec.
1578   void EmitStartEHSpec(const Decl *D);
1579
1580   /// EmitEndEHSpec - Emit the end of the exception spec.
1581   void EmitEndEHSpec(const Decl *D);
1582
1583   /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1584   llvm::BasicBlock *getTerminateLandingPad();
1585
1586   /// getTerminateHandler - Return a handler (not a landing pad, just
1587   /// a catch handler) that just calls terminate.  This is used when
1588   /// a terminate scope encloses a try.
1589   llvm::BasicBlock *getTerminateHandler();
1590
1591   llvm::Type *ConvertTypeForMem(QualType T);
1592   llvm::Type *ConvertType(QualType T);
1593   llvm::Type *ConvertType(const TypeDecl *T) {
1594     return ConvertType(getContext().getTypeDeclType(T));
1595   }
1596
1597   /// LoadObjCSelf - Load the value of self. This function is only valid while
1598   /// generating code for an Objective-C method.
1599   llvm::Value *LoadObjCSelf();
1600
1601   /// TypeOfSelfObject - Return type of object that this self represents.
1602   QualType TypeOfSelfObject();
1603
1604   /// hasAggregateLLVMType - Return true if the specified AST type will map into
1605   /// an aggregate LLVM type or is void.
1606   static TypeEvaluationKind getEvaluationKind(QualType T);
1607
1608   static bool hasScalarEvaluationKind(QualType T) {
1609     return getEvaluationKind(T) == TEK_Scalar;
1610   }
1611
1612   static bool hasAggregateEvaluationKind(QualType T) {
1613     return getEvaluationKind(T) == TEK_Aggregate;
1614   }
1615
1616   /// createBasicBlock - Create an LLVM basic block.
1617   llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1618                                      llvm::Function *parent = nullptr,
1619                                      llvm::BasicBlock *before = nullptr) {
1620 #ifdef NDEBUG
1621     return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1622 #else
1623     return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1624 #endif
1625   }
1626
1627   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1628   /// label maps to.
1629   JumpDest getJumpDestForLabel(const LabelDecl *S);
1630
1631   /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1632   /// another basic block, simplify it. This assumes that no other code could
1633   /// potentially reference the basic block.
1634   void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1635
1636   /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1637   /// adding a fall-through branch from the current insert block if
1638   /// necessary. It is legal to call this function even if there is no current
1639   /// insertion point.
1640   ///
1641   /// IsFinished - If true, indicates that the caller has finished emitting
1642   /// branches to the given block and does not expect to emit code into it. This
1643   /// means the block can be ignored if it is unreachable.
1644   void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1645
1646   /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1647   /// near its uses, and leave the insertion point in it.
1648   void EmitBlockAfterUses(llvm::BasicBlock *BB);
1649
1650   /// EmitBranch - Emit a branch to the specified basic block from the current
1651   /// insert block, taking care to avoid creation of branches from dummy
1652   /// blocks. It is legal to call this function even if there is no current
1653   /// insertion point.
1654   ///
1655   /// This function clears the current insertion point. The caller should follow
1656   /// calls to this function with calls to Emit*Block prior to generation new
1657   /// code.
1658   void EmitBranch(llvm::BasicBlock *Block);
1659
1660   /// HaveInsertPoint - True if an insertion point is defined. If not, this
1661   /// indicates that the current code being emitted is unreachable.
1662   bool HaveInsertPoint() const {
1663     return Builder.GetInsertBlock() != nullptr;
1664   }
1665
1666   /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1667   /// emitted IR has a place to go. Note that by definition, if this function
1668   /// creates a block then that block is unreachable; callers may do better to
1669   /// detect when no insertion point is defined and simply skip IR generation.
1670   void EnsureInsertPoint() {
1671     if (!HaveInsertPoint())
1672       EmitBlock(createBasicBlock());
1673   }
1674
1675   /// ErrorUnsupported - Print out an error that codegen doesn't support the
1676   /// specified stmt yet.
1677   void ErrorUnsupported(const Stmt *S, const char *Type);
1678
1679   //===--------------------------------------------------------------------===//
1680   //                                  Helpers
1681   //===--------------------------------------------------------------------===//
1682
1683   LValue MakeAddrLValue(Address Addr, QualType T,
1684                         AlignmentSource AlignSource = AlignmentSource::Type) {
1685     return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
1686                             CGM.getTBAAInfo(T));
1687   }
1688
1689   LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1690                         AlignmentSource AlignSource = AlignmentSource::Type) {
1691     return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1692                             AlignSource, CGM.getTBAAInfo(T));
1693   }
1694
1695   LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1696   LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1697   CharUnits getNaturalTypeAlignment(QualType T,
1698                                     AlignmentSource *Source = nullptr,
1699                                     bool forPointeeType = false);
1700   CharUnits getNaturalPointeeTypeAlignment(QualType T,
1701                                            AlignmentSource *Source = nullptr);
1702
1703   Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1704                               AlignmentSource *Source = nullptr);
1705   LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1706
1707   Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1708                             AlignmentSource *Source = nullptr);
1709   LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1710
1711   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1712   /// block. The caller is responsible for setting an appropriate alignment on
1713   /// the alloca.
1714   llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1715                                      const Twine &Name = "tmp");
1716   Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1717                            const Twine &Name = "tmp");
1718
1719   /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1720   /// default ABI alignment of the given LLVM type.
1721   ///
1722   /// IMPORTANT NOTE: This is *not* generally the right alignment for
1723   /// any given AST type that happens to have been lowered to the
1724   /// given IR type.  This should only ever be used for function-local,
1725   /// IR-driven manipulations like saving and restoring a value.  Do
1726   /// not hand this address off to arbitrary IRGen routines, and especially
1727   /// do not pass it as an argument to a function that might expect a
1728   /// properly ABI-aligned value.
1729   Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1730                                        const Twine &Name = "tmp");
1731
1732   /// InitTempAlloca - Provide an initial value for the given alloca which
1733   /// will be observable at all locations in the function.
1734   ///
1735   /// The address should be something that was returned from one of
1736   /// the CreateTempAlloca or CreateMemTemp routines, and the
1737   /// initializer must be valid in the entry block (i.e. it must
1738   /// either be a constant or an argument value).
1739   void InitTempAlloca(Address Alloca, llvm::Value *Value);
1740
1741   /// CreateIRTemp - Create a temporary IR object of the given type, with
1742   /// appropriate alignment. This routine should only be used when an temporary
1743   /// value needs to be stored into an alloca (for example, to avoid explicit
1744   /// PHI construction), but the type is the IR type, not the type appropriate
1745   /// for storing in memory.
1746   ///
1747   /// That is, this is exactly equivalent to CreateMemTemp, but calling
1748   /// ConvertType instead of ConvertTypeForMem.
1749   Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1750
1751   /// CreateMemTemp - Create a temporary memory object of the given type, with
1752   /// appropriate alignment.
1753   Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1754   Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1755
1756   /// CreateAggTemp - Create a temporary memory object for the given
1757   /// aggregate type.
1758   AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1759     return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1760                                  T.getQualifiers(),
1761                                  AggValueSlot::IsNotDestructed,
1762                                  AggValueSlot::DoesNotNeedGCBarriers,
1763                                  AggValueSlot::IsNotAliased);
1764   }
1765
1766   /// Emit a cast to void* in the appropriate address space.
1767   llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1768
1769   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1770   /// expression and compare the result against zero, returning an Int1Ty value.
1771   llvm::Value *EvaluateExprAsBool(const Expr *E);
1772
1773   /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1774   void EmitIgnoredExpr(const Expr *E);
1775
1776   /// EmitAnyExpr - Emit code to compute the specified expression which can have
1777   /// any type.  The result is returned as an RValue struct.  If this is an
1778   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1779   /// the result should be returned.
1780   ///
1781   /// \param ignoreResult True if the resulting value isn't used.
1782   RValue EmitAnyExpr(const Expr *E,
1783                      AggValueSlot aggSlot = AggValueSlot::ignored(),
1784                      bool ignoreResult = false);
1785
1786   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1787   // or the value of the expression, depending on how va_list is defined.
1788   Address EmitVAListRef(const Expr *E);
1789
1790   /// Emit a "reference" to a __builtin_ms_va_list; this is
1791   /// always the value of the expression, because a __builtin_ms_va_list is a
1792   /// pointer to a char.
1793   Address EmitMSVAListRef(const Expr *E);
1794
1795   /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1796   /// always be accessible even if no aggregate location is provided.
1797   RValue EmitAnyExprToTemp(const Expr *E);
1798
1799   /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1800   /// arbitrary expression into the given memory location.
1801   void EmitAnyExprToMem(const Expr *E, Address Location,
1802                         Qualifiers Quals, bool IsInitializer);
1803
1804   void EmitAnyExprToExn(const Expr *E, Address Addr);
1805
1806   /// EmitExprAsInit - Emits the code necessary to initialize a
1807   /// location in memory with the given initializer.
1808   void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
1809                       bool capturedByInit);
1810
1811   /// hasVolatileMember - returns true if aggregate type has a volatile
1812   /// member.
1813   bool hasVolatileMember(QualType T) {
1814     if (const RecordType *RT = T->getAs<RecordType>()) {
1815       const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1816       return RD->hasVolatileMember();
1817     }
1818     return false;
1819   }
1820   /// EmitAggregateCopy - Emit an aggregate assignment.
1821   ///
1822   /// The difference to EmitAggregateCopy is that tail padding is not copied.
1823   /// This is required for correctness when assigning non-POD structures in C++.
1824   void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
1825                            QualType EltTy) {
1826     bool IsVolatile = hasVolatileMember(EltTy);
1827     EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
1828   }
1829
1830   void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
1831                              QualType DestTy, QualType SrcTy) {
1832     EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
1833                       /*IsAssignment=*/false);
1834   }
1835
1836   /// EmitAggregateCopy - Emit an aggregate copy.
1837   ///
1838   /// \param isVolatile - True iff either the source or the destination is
1839   /// volatile.
1840   /// \param isAssignment - If false, allow padding to be copied.  This often
1841   /// yields more efficient.
1842   void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
1843                          QualType EltTy, bool isVolatile=false,
1844                          bool isAssignment = false);
1845
1846   /// GetAddrOfLocalVar - Return the address of a local variable.
1847   Address GetAddrOfLocalVar(const VarDecl *VD) {
1848     auto it = LocalDeclMap.find(VD);
1849     assert(it != LocalDeclMap.end() &&
1850            "Invalid argument to GetAddrOfLocalVar(), no decl!");
1851     return it->second;
1852   }
1853
1854   /// getOpaqueLValueMapping - Given an opaque value expression (which
1855   /// must be mapped to an l-value), return its mapping.
1856   const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1857     assert(OpaqueValueMapping::shouldBindAsLValue(e));
1858
1859     llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1860       it = OpaqueLValues.find(e);
1861     assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
1862     return it->second;
1863   }
1864
1865   /// getOpaqueRValueMapping - Given an opaque value expression (which
1866   /// must be mapped to an r-value), return its mapping.
1867   const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
1868     assert(!OpaqueValueMapping::shouldBindAsLValue(e));
1869
1870     llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
1871       it = OpaqueRValues.find(e);
1872     assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
1873     return it->second;
1874   }
1875
1876   /// getAccessedFieldNo - Given an encoded value and a result number, return
1877   /// the input field number being accessed.
1878   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1879
1880   llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
1881   llvm::BasicBlock *GetIndirectGotoBlock();
1882
1883   /// EmitNullInitialization - Generate code to set a value of the given type to
1884   /// null, If the type contains data member pointers, they will be initialized
1885   /// to -1 in accordance with the Itanium C++ ABI.
1886   void EmitNullInitialization(Address DestPtr, QualType Ty);
1887
1888   /// Emits a call to an LLVM variable-argument intrinsic, either
1889   /// \c llvm.va_start or \c llvm.va_end.
1890   /// \param ArgValue A reference to the \c va_list as emitted by either
1891   /// \c EmitVAListRef or \c EmitMSVAListRef.
1892   /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
1893   /// calls \c llvm.va_end.
1894   llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
1895
1896   /// Generate code to get an argument from the passed in pointer
1897   /// and update it accordingly.
1898   /// \param VE The \c VAArgExpr for which to generate code.
1899   /// \param VAListAddr Receives a reference to the \c va_list as emitted by
1900   /// either \c EmitVAListRef or \c EmitMSVAListRef.
1901   /// \returns A pointer to the argument.
1902   // FIXME: We should be able to get rid of this method and use the va_arg
1903   // instruction in LLVM instead once it works well enough.
1904   Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
1905
1906   /// emitArrayLength - Compute the length of an array, even if it's a
1907   /// VLA, and drill down to the base element type.
1908   llvm::Value *emitArrayLength(const ArrayType *arrayType,
1909                                QualType &baseType,
1910                                Address &addr);
1911
1912   /// EmitVLASize - Capture all the sizes for the VLA expressions in
1913   /// the given variably-modified type and store them in the VLASizeMap.
1914   ///
1915   /// This function can be called with a null (unreachable) insert point.
1916   void EmitVariablyModifiedType(QualType Ty);
1917
1918   /// getVLASize - Returns an LLVM value that corresponds to the size,
1919   /// in non-variably-sized elements, of a variable length array type,
1920   /// plus that largest non-variably-sized element type.  Assumes that
1921   /// the type has already been emitted with EmitVariablyModifiedType.
1922   std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
1923   std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
1924
1925   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1926   /// generating code for an C++ member function.
1927   llvm::Value *LoadCXXThis() {
1928     assert(CXXThisValue && "no 'this' value for this function");
1929     return CXXThisValue;
1930   }
1931   Address LoadCXXThisAddress();
1932
1933   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1934   /// virtual bases.
1935   // FIXME: Every place that calls LoadCXXVTT is something
1936   // that needs to be abstracted properly.
1937   llvm::Value *LoadCXXVTT() {
1938     assert(CXXStructorImplicitParamValue && "no VTT value for this function");
1939     return CXXStructorImplicitParamValue;
1940   }
1941
1942   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1943   /// complete class to the given direct base.
1944   Address
1945   GetAddressOfDirectBaseInCompleteClass(Address Value,
1946                                         const CXXRecordDecl *Derived,
1947                                         const CXXRecordDecl *Base,
1948                                         bool BaseIsVirtual);
1949
1950   static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
1951
1952   /// GetAddressOfBaseClass - This function will add the necessary delta to the
1953   /// load of 'this' and returns address of the base class.
1954   Address GetAddressOfBaseClass(Address Value,
1955                                 const CXXRecordDecl *Derived,
1956                                 CastExpr::path_const_iterator PathBegin,
1957                                 CastExpr::path_const_iterator PathEnd,
1958                                 bool NullCheckValue, SourceLocation Loc);
1959
1960   Address GetAddressOfDerivedClass(Address Value,
1961                                    const CXXRecordDecl *Derived,
1962                                    CastExpr::path_const_iterator PathBegin,
1963                                    CastExpr::path_const_iterator PathEnd,
1964                                    bool NullCheckValue);
1965
1966   /// GetVTTParameter - Return the VTT parameter that should be passed to a
1967   /// base constructor/destructor with virtual bases.
1968   /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
1969   /// to ItaniumCXXABI.cpp together with all the references to VTT.
1970   llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
1971                                bool Delegating);
1972
1973   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1974                                       CXXCtorType CtorType,
1975                                       const FunctionArgList &Args,
1976                                       SourceLocation Loc);
1977   // It's important not to confuse this and the previous function. Delegating
1978   // constructors are the C++0x feature. The constructor delegate optimization
1979   // is used to reduce duplication in the base and complete consturctors where
1980   // they are substantially the same.
1981   void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1982                                         const FunctionArgList &Args);
1983
1984   /// Emit a call to an inheriting constructor (that is, one that invokes a
1985   /// constructor inherited from a base class) by inlining its definition. This
1986   /// is necessary if the ABI does not support forwarding the arguments to the
1987   /// base class constructor (because they're variadic or similar).
1988   void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1989                                                CXXCtorType CtorType,
1990                                                bool ForVirtualBase,
1991                                                bool Delegating,
1992                                                CallArgList &Args);
1993
1994   /// Emit a call to a constructor inherited from a base class, passing the
1995   /// current constructor's arguments along unmodified (without even making
1996   /// a copy).
1997   void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
1998                                        bool ForVirtualBase, Address This,
1999                                        bool InheritedFromVBase,
2000                                        const CXXInheritedCtorInitExpr *E);
2001
2002   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2003                               bool ForVirtualBase, bool Delegating,
2004                               Address This, const CXXConstructExpr *E);
2005
2006   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2007                               bool ForVirtualBase, bool Delegating,
2008                               Address This, CallArgList &Args);
2009
2010   /// Emit assumption load for all bases. Requires to be be called only on
2011   /// most-derived class and not under construction of the object.
2012   void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2013
2014   /// Emit assumption that vptr load == global vtable.
2015   void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2016
2017   void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2018                                       Address This, Address Src,
2019                                       const CXXConstructExpr *E);
2020
2021   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2022                                   const ArrayType *ArrayTy,
2023                                   Address ArrayPtr,
2024                                   const CXXConstructExpr *E,
2025                                   bool ZeroInitialization = false);
2026
2027   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2028                                   llvm::Value *NumElements,
2029                                   Address ArrayPtr,
2030                                   const CXXConstructExpr *E,
2031                                   bool ZeroInitialization = false);
2032
2033   static Destroyer destroyCXXObject;
2034
2035   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2036                              bool ForVirtualBase, bool Delegating,
2037                              Address This);
2038
2039   void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2040                                llvm::Type *ElementTy, Address NewPtr,
2041                                llvm::Value *NumElements,
2042                                llvm::Value *AllocSizeWithoutCookie);
2043
2044   void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2045                         Address Ptr);
2046
2047   llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2048   void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2049
2050   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2051   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2052
2053   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2054                       QualType DeleteTy);
2055
2056   RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2057                                   const Expr *Arg, bool IsDelete);
2058
2059   llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2060   llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2061   Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2062
2063   /// \brief Situations in which we might emit a check for the suitability of a
2064   ///        pointer or glvalue.
2065   enum TypeCheckKind {
2066     /// Checking the operand of a load. Must be suitably sized and aligned.
2067     TCK_Load,
2068     /// Checking the destination of a store. Must be suitably sized and aligned.
2069     TCK_Store,
2070     /// Checking the bound value in a reference binding. Must be suitably sized
2071     /// and aligned, but is not required to refer to an object (until the
2072     /// reference is used), per core issue 453.
2073     TCK_ReferenceBinding,
2074     /// Checking the object expression in a non-static data member access. Must
2075     /// be an object within its lifetime.
2076     TCK_MemberAccess,
2077     /// Checking the 'this' pointer for a call to a non-static member function.
2078     /// Must be an object within its lifetime.
2079     TCK_MemberCall,
2080     /// Checking the 'this' pointer for a constructor call.
2081     TCK_ConstructorCall,
2082     /// Checking the operand of a static_cast to a derived pointer type. Must be
2083     /// null or an object within its lifetime.
2084     TCK_DowncastPointer,
2085     /// Checking the operand of a static_cast to a derived reference type. Must
2086     /// be an object within its lifetime.
2087     TCK_DowncastReference,
2088     /// Checking the operand of a cast to a base object. Must be suitably sized
2089     /// and aligned.
2090     TCK_Upcast,
2091     /// Checking the operand of a cast to a virtual base object. Must be an
2092     /// object within its lifetime.
2093     TCK_UpcastToVirtualBase
2094   };
2095
2096   /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2097   /// calls to EmitTypeCheck can be skipped.
2098   bool sanitizePerformTypeCheck() const;
2099
2100   /// \brief Emit a check that \p V is the address of storage of the
2101   /// appropriate size and alignment for an object of type \p Type.
2102   void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2103                      QualType Type, CharUnits Alignment = CharUnits::Zero(),
2104                      bool SkipNullCheck = false);
2105
2106   /// \brief Emit a check that \p Base points into an array object, which
2107   /// we can access at index \p Index. \p Accessed should be \c false if we
2108   /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2109   void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2110                        QualType IndexType, bool Accessed);
2111
2112   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2113                                        bool isInc, bool isPre);
2114   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2115                                          bool isInc, bool isPre);
2116
2117   void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2118                                llvm::Value *OffsetValue = nullptr) {
2119     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2120                                       OffsetValue);
2121   }
2122
2123   //===--------------------------------------------------------------------===//
2124   //                            Declaration Emission
2125   //===--------------------------------------------------------------------===//
2126
2127   /// EmitDecl - Emit a declaration.
2128   ///
2129   /// This function can be called with a null (unreachable) insert point.
2130   void EmitDecl(const Decl &D);
2131
2132   /// EmitVarDecl - Emit a local variable declaration.
2133   ///
2134   /// This function can be called with a null (unreachable) insert point.
2135   void EmitVarDecl(const VarDecl &D);
2136
2137   void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2138                       bool capturedByInit);
2139   void EmitScalarInit(llvm::Value *init, LValue lvalue);
2140
2141   typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2142                              llvm::Value *Address);
2143
2144   /// \brief Determine whether the given initializer is trivial in the sense
2145   /// that it requires no code to be generated.
2146   bool isTrivialInitializer(const Expr *Init);
2147
2148   /// EmitAutoVarDecl - Emit an auto variable declaration.
2149   ///
2150   /// This function can be called with a null (unreachable) insert point.
2151   void EmitAutoVarDecl(const VarDecl &D);
2152
2153   class AutoVarEmission {
2154     friend class CodeGenFunction;
2155
2156     const VarDecl *Variable;
2157
2158     /// The address of the alloca.  Invalid if the variable was emitted
2159     /// as a global constant.
2160     Address Addr;
2161
2162     llvm::Value *NRVOFlag;
2163
2164     /// True if the variable is a __block variable.
2165     bool IsByRef;
2166
2167     /// True if the variable is of aggregate type and has a constant
2168     /// initializer.
2169     bool IsConstantAggregate;
2170
2171     /// Non-null if we should use lifetime annotations.
2172     llvm::Value *SizeForLifetimeMarkers;
2173
2174     struct Invalid {};
2175     AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2176
2177     AutoVarEmission(const VarDecl &variable)
2178       : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2179         IsByRef(false), IsConstantAggregate(false),
2180         SizeForLifetimeMarkers(nullptr) {}
2181
2182     bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2183
2184   public:
2185     static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2186
2187     bool useLifetimeMarkers() const {
2188       return SizeForLifetimeMarkers != nullptr;
2189     }
2190     llvm::Value *getSizeForLifetimeMarkers() const {
2191       assert(useLifetimeMarkers());
2192       return SizeForLifetimeMarkers;
2193     }
2194
2195     /// Returns the raw, allocated address, which is not necessarily
2196     /// the address of the object itself.
2197     Address getAllocatedAddress() const {
2198       return Addr;
2199     }
2200
2201     /// Returns the address of the object within this declaration.
2202     /// Note that this does not chase the forwarding pointer for
2203     /// __block decls.
2204     Address getObjectAddress(CodeGenFunction &CGF) const {
2205       if (!IsByRef) return Addr;
2206
2207       return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2208     }
2209   };
2210   AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2211   void EmitAutoVarInit(const AutoVarEmission &emission);
2212   void EmitAutoVarCleanups(const AutoVarEmission &emission);  
2213   void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2214                               QualType::DestructionKind dtorKind);
2215
2216   void EmitStaticVarDecl(const VarDecl &D,
2217                          llvm::GlobalValue::LinkageTypes Linkage);
2218
2219   class ParamValue {
2220     llvm::Value *Value;
2221     unsigned Alignment;
2222     ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2223   public:
2224     static ParamValue forDirect(llvm::Value *value) {
2225       return ParamValue(value, 0);
2226     }
2227     static ParamValue forIndirect(Address addr) {
2228       assert(!addr.getAlignment().isZero());
2229       return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2230     }
2231
2232     bool isIndirect() const { return Alignment != 0; }
2233     llvm::Value *getAnyValue() const { return Value; }
2234     
2235     llvm::Value *getDirectValue() const {
2236       assert(!isIndirect());
2237       return Value;
2238     }
2239
2240     Address getIndirectAddress() const {
2241       assert(isIndirect());
2242       return Address(Value, CharUnits::fromQuantity(Alignment));
2243     }
2244   };
2245
2246   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2247   void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2248
2249   /// protectFromPeepholes - Protect a value that we're intending to
2250   /// store to the side, but which will probably be used later, from
2251   /// aggressive peepholing optimizations that might delete it.
2252   ///
2253   /// Pass the result to unprotectFromPeepholes to declare that
2254   /// protection is no longer required.
2255   ///
2256   /// There's no particular reason why this shouldn't apply to
2257   /// l-values, it's just that no existing peepholes work on pointers.
2258   PeepholeProtection protectFromPeepholes(RValue rvalue);
2259   void unprotectFromPeepholes(PeepholeProtection protection);
2260
2261   //===--------------------------------------------------------------------===//
2262   //                             Statement Emission
2263   //===--------------------------------------------------------------------===//
2264
2265   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2266   void EmitStopPoint(const Stmt *S);
2267
2268   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2269   /// this function even if there is no current insertion point.
2270   ///
2271   /// This function may clear the current insertion point; callers should use
2272   /// EnsureInsertPoint if they wish to subsequently generate code without first
2273   /// calling EmitBlock, EmitBranch, or EmitStmt.
2274   void EmitStmt(const Stmt *S);
2275
2276   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2277   /// necessarily require an insertion point or debug information; typically
2278   /// because the statement amounts to a jump or a container of other
2279   /// statements.
2280   ///
2281   /// \return True if the statement was handled.
2282   bool EmitSimpleStmt(const Stmt *S);
2283
2284   Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2285                            AggValueSlot AVS = AggValueSlot::ignored());
2286   Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2287                                        bool GetLast = false,
2288                                        AggValueSlot AVS =
2289                                                 AggValueSlot::ignored());
2290
2291   /// EmitLabel - Emit the block for the given label. It is legal to call this
2292   /// function even if there is no current insertion point.
2293   void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2294
2295   void EmitLabelStmt(const LabelStmt &S);
2296   void EmitAttributedStmt(const AttributedStmt &S);
2297   void EmitGotoStmt(const GotoStmt &S);
2298   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2299   void EmitIfStmt(const IfStmt &S);
2300
2301   void EmitWhileStmt(const WhileStmt &S,
2302                      ArrayRef<const Attr *> Attrs = None);
2303   void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2304   void EmitForStmt(const ForStmt &S,
2305                    ArrayRef<const Attr *> Attrs = None);
2306   void EmitReturnStmt(const ReturnStmt &S);
2307   void EmitDeclStmt(const DeclStmt &S);
2308   void EmitBreakStmt(const BreakStmt &S);
2309   void EmitContinueStmt(const ContinueStmt &S);
2310   void EmitSwitchStmt(const SwitchStmt &S);
2311   void EmitDefaultStmt(const DefaultStmt &S);
2312   void EmitCaseStmt(const CaseStmt &S);
2313   void EmitCaseStmtRange(const CaseStmt &S);
2314   void EmitAsmStmt(const AsmStmt &S);
2315
2316   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2317   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2318   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2319   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2320   void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2321
2322   void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2323   void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2324
2325   void EmitCXXTryStmt(const CXXTryStmt &S);
2326   void EmitSEHTryStmt(const SEHTryStmt &S);
2327   void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2328   void EnterSEHTryStmt(const SEHTryStmt &S);
2329   void ExitSEHTryStmt(const SEHTryStmt &S);
2330
2331   void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2332                               const Stmt *OutlinedStmt);
2333
2334   llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2335                                             const SEHExceptStmt &Except);
2336
2337   llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2338                                              const SEHFinallyStmt &Finally);
2339
2340   void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2341                                 llvm::Value *ParentFP,
2342                                 llvm::Value *EntryEBP);
2343   llvm::Value *EmitSEHExceptionCode();
2344   llvm::Value *EmitSEHExceptionInfo();
2345   llvm::Value *EmitSEHAbnormalTermination();
2346
2347   /// Scan the outlined statement for captures from the parent function. For
2348   /// each capture, mark the capture as escaped and emit a call to
2349   /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2350   void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2351                           bool IsFilter);
2352
2353   /// Recovers the address of a local in a parent function. ParentVar is the
2354   /// address of the variable used in the immediate parent function. It can
2355   /// either be an alloca or a call to llvm.localrecover if there are nested
2356   /// outlined functions. ParentFP is the frame pointer of the outermost parent
2357   /// frame.
2358   Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2359                                     Address ParentVar,
2360                                     llvm::Value *ParentFP);
2361
2362   void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2363                            ArrayRef<const Attr *> Attrs = None);
2364
2365   /// Returns calculated size of the specified type.
2366   llvm::Value *getTypeSize(QualType Ty);
2367   LValue InitCapturedStruct(const CapturedStmt &S);
2368   llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2369   llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2370   Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2371   llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2372   void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2373                                   SmallVectorImpl<llvm::Value *> &CapturedVars);
2374   void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2375                           SourceLocation Loc);
2376   /// \brief Perform element by element copying of arrays with type \a
2377   /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2378   /// generated by \a CopyGen.
2379   ///
2380   /// \param DestAddr Address of the destination array.
2381   /// \param SrcAddr Address of the source array.
2382   /// \param OriginalType Type of destination and source arrays.
2383   /// \param CopyGen Copying procedure that copies value of single array element
2384   /// to another single array element.
2385   void EmitOMPAggregateAssign(
2386       Address DestAddr, Address SrcAddr, QualType OriginalType,
2387       const llvm::function_ref<void(Address, Address)> &CopyGen);
2388   /// \brief Emit proper copying of data from one variable to another.
2389   ///
2390   /// \param OriginalType Original type of the copied variables.
2391   /// \param DestAddr Destination address.
2392   /// \param SrcAddr Source address.
2393   /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2394   /// type of the base array element).
2395   /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2396   /// the base array element).
2397   /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2398   /// DestVD.
2399   void EmitOMPCopy(QualType OriginalType,
2400                    Address DestAddr, Address SrcAddr,
2401                    const VarDecl *DestVD, const VarDecl *SrcVD,
2402                    const Expr *Copy);
2403   /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2404   /// \a X = \a E \a BO \a E.
2405   ///
2406   /// \param X Value to be updated.
2407   /// \param E Update value.
2408   /// \param BO Binary operation for update operation.
2409   /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2410   /// expression, false otherwise.
2411   /// \param AO Atomic ordering of the generated atomic instructions.
2412   /// \param CommonGen Code generator for complex expressions that cannot be
2413   /// expressed through atomicrmw instruction.
2414   /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2415   /// generated, <false, RValue::get(nullptr)> otherwise.
2416   std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2417       LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2418       llvm::AtomicOrdering AO, SourceLocation Loc,
2419       const llvm::function_ref<RValue(RValue)> &CommonGen);
2420   bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2421                                  OMPPrivateScope &PrivateScope);
2422   void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2423                             OMPPrivateScope &PrivateScope);
2424   /// \brief Emit code for copyin clause in \a D directive. The next code is
2425   /// generated at the start of outlined functions for directives:
2426   /// \code
2427   /// threadprivate_var1 = master_threadprivate_var1;
2428   /// operator=(threadprivate_var2, master_threadprivate_var2);
2429   /// ...
2430   /// __kmpc_barrier(&loc, global_tid);
2431   /// \endcode
2432   ///
2433   /// \param D OpenMP directive possibly with 'copyin' clause(s).
2434   /// \returns true if at least one copyin variable is found, false otherwise.
2435   bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2436   /// \brief Emit initial code for lastprivate variables. If some variable is
2437   /// not also firstprivate, then the default initialization is used. Otherwise
2438   /// initialization of this variable is performed by EmitOMPFirstprivateClause
2439   /// method.
2440   ///
2441   /// \param D Directive that may have 'lastprivate' directives.
2442   /// \param PrivateScope Private scope for capturing lastprivate variables for
2443   /// proper codegen in internal captured statement.
2444   ///
2445   /// \returns true if there is at least one lastprivate variable, false
2446   /// otherwise.
2447   bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2448                                     OMPPrivateScope &PrivateScope);
2449   /// \brief Emit final copying of lastprivate values to original variables at
2450   /// the end of the worksharing or simd directive.
2451   ///
2452   /// \param D Directive that has at least one 'lastprivate' directives.
2453   /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2454   /// it is the last iteration of the loop code in associated directive, or to
2455   /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2456   void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2457                                      bool NoFinals,
2458                                      llvm::Value *IsLastIterCond = nullptr);
2459   /// Emit initial code for linear clauses.
2460   void EmitOMPLinearClause(const OMPLoopDirective &D,
2461                            CodeGenFunction::OMPPrivateScope &PrivateScope);
2462   /// Emit final code for linear clauses.
2463   /// \param CondGen Optional conditional code for final part of codegen for
2464   /// linear clause.
2465   void EmitOMPLinearClauseFinal(
2466       const OMPLoopDirective &D,
2467       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2468   /// \brief Emit initial code for reduction variables. Creates reduction copies
2469   /// and initializes them with the values according to OpenMP standard.
2470   ///
2471   /// \param D Directive (possibly) with the 'reduction' clause.
2472   /// \param PrivateScope Private scope for capturing reduction variables for
2473   /// proper codegen in internal captured statement.
2474   ///
2475   void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2476                                   OMPPrivateScope &PrivateScope);
2477   /// \brief Emit final update of reduction values to original variables at
2478   /// the end of the directive.
2479   ///
2480   /// \param D Directive that has at least one 'reduction' directives.
2481   void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
2482   /// \brief Emit initial code for linear variables. Creates private copies
2483   /// and initializes them with the values according to OpenMP standard.
2484   ///
2485   /// \param D Directive (possibly) with the 'linear' clause.
2486   void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2487
2488   typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2489                                         llvm::Value * /*OutlinedFn*/,
2490                                         const OMPTaskDataTy & /*Data*/)>
2491       TaskGenTy;
2492   void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2493                                  const RegionCodeGenTy &BodyGen,
2494                                  const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2495
2496   void EmitOMPParallelDirective(const OMPParallelDirective &S);
2497   void EmitOMPSimdDirective(const OMPSimdDirective &S);
2498   void EmitOMPForDirective(const OMPForDirective &S);
2499   void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2500   void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2501   void EmitOMPSectionDirective(const OMPSectionDirective &S);
2502   void EmitOMPSingleDirective(const OMPSingleDirective &S);
2503   void EmitOMPMasterDirective(const OMPMasterDirective &S);
2504   void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2505   void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2506   void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2507   void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2508   void EmitOMPTaskDirective(const OMPTaskDirective &S);
2509   void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2510   void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2511   void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2512   void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2513   void EmitOMPFlushDirective(const OMPFlushDirective &S);
2514   void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2515   void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2516   void EmitOMPTargetDirective(const OMPTargetDirective &S);
2517   void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2518   void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2519   void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2520   void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2521   void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2522   void
2523   EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2524   void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2525   void
2526   EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2527   void EmitOMPCancelDirective(const OMPCancelDirective &S);
2528   void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2529   void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2530   void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2531   void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2532   void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
2533   void EmitOMPDistributeParallelForDirective(
2534       const OMPDistributeParallelForDirective &S);
2535   void EmitOMPDistributeParallelForSimdDirective(
2536       const OMPDistributeParallelForSimdDirective &S);
2537   void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2538   void EmitOMPTargetParallelForSimdDirective(
2539       const OMPTargetParallelForSimdDirective &S);
2540
2541   /// Emit outlined function for the target directive.
2542   static std::pair<llvm::Function * /*OutlinedFn*/,
2543                    llvm::Constant * /*OutlinedFnID*/>
2544   EmitOMPTargetDirectiveOutlinedFunction(CodeGenModule &CGM,
2545                                          const OMPTargetDirective &S,
2546                                          StringRef ParentName,
2547                                          bool IsOffloadEntry);
2548   /// \brief Emit inner loop of the worksharing/simd construct.
2549   ///
2550   /// \param S Directive, for which the inner loop must be emitted.
2551   /// \param RequiresCleanup true, if directive has some associated private
2552   /// variables.
2553   /// \param LoopCond Bollean condition for loop continuation.
2554   /// \param IncExpr Increment expression for loop control variable.
2555   /// \param BodyGen Generator for the inner body of the inner loop.
2556   /// \param PostIncGen Genrator for post-increment code (required for ordered
2557   /// loop directvies).
2558   void EmitOMPInnerLoop(
2559       const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2560       const Expr *IncExpr,
2561       const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2562       const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2563
2564   JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2565   /// Emit initial code for loop counters of loop-based directives.
2566   void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2567                                   OMPPrivateScope &LoopScope);
2568
2569 private:
2570   /// Helpers for the OpenMP loop directives.
2571   void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2572   void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2573   void EmitOMPSimdFinal(
2574       const OMPLoopDirective &D,
2575       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2576   /// \brief Emit code for the worksharing loop-based directive.
2577   /// \return true, if this construct has any lastprivate clause, false -
2578   /// otherwise.
2579   bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
2580   void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered,
2581       const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2582       Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2583   void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2584                            bool IsMonotonic, const OMPLoopDirective &S,
2585                            OMPPrivateScope &LoopScope, bool Ordered, Address LB,
2586                            Address UB, Address ST, Address IL,
2587                            llvm::Value *Chunk);
2588   void EmitOMPDistributeOuterLoop(
2589       OpenMPDistScheduleClauseKind ScheduleKind,
2590       const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
2591       Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2592   /// \brief Emit code for sections directive.
2593   void EmitSections(const OMPExecutableDirective &S);
2594
2595 public:
2596
2597   //===--------------------------------------------------------------------===//
2598   //                         LValue Expression Emission
2599   //===--------------------------------------------------------------------===//
2600
2601   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2602   RValue GetUndefRValue(QualType Ty);
2603
2604   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2605   /// and issue an ErrorUnsupported style diagnostic (using the
2606   /// provided Name).
2607   RValue EmitUnsupportedRValue(const Expr *E,
2608                                const char *Name);
2609
2610   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2611   /// an ErrorUnsupported style diagnostic (using the provided Name).
2612   LValue EmitUnsupportedLValue(const Expr *E,
2613                                const char *Name);
2614
2615   /// EmitLValue - Emit code to compute a designator that specifies the location
2616   /// of the expression.
2617   ///
2618   /// This can return one of two things: a simple address or a bitfield
2619   /// reference.  In either case, the LLVM Value* in the LValue structure is
2620   /// guaranteed to be an LLVM pointer type.
2621   ///
2622   /// If this returns a bitfield reference, nothing about the pointee type of
2623   /// the LLVM value is known: For example, it may not be a pointer to an
2624   /// integer.
2625   ///
2626   /// If this returns a normal address, and if the lvalue's C type is fixed
2627   /// size, this method guarantees that the returned pointer type will point to
2628   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
2629   /// variable length type, this is not possible.
2630   ///
2631   LValue EmitLValue(const Expr *E);
2632
2633   /// \brief Same as EmitLValue but additionally we generate checking code to
2634   /// guard against undefined behavior.  This is only suitable when we know
2635   /// that the address will be used to access the object.
2636   LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2637
2638   RValue convertTempToRValue(Address addr, QualType type,
2639                              SourceLocation Loc);
2640
2641   void EmitAtomicInit(Expr *E, LValue lvalue);
2642
2643   bool LValueIsSuitableForInlineAtomic(LValue Src);
2644
2645   RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2646                         AggValueSlot Slot = AggValueSlot::ignored());
2647
2648   RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2649                         llvm::AtomicOrdering AO, bool IsVolatile = false,
2650                         AggValueSlot slot = AggValueSlot::ignored());
2651
2652   void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2653
2654   void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2655                        bool IsVolatile, bool isInit);
2656
2657   std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2658       LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2659       llvm::AtomicOrdering Success =
2660           llvm::AtomicOrdering::SequentiallyConsistent,
2661       llvm::AtomicOrdering Failure =
2662           llvm::AtomicOrdering::SequentiallyConsistent,
2663       bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2664
2665   void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2666                         const llvm::function_ref<RValue(RValue)> &UpdateOp,
2667                         bool IsVolatile);
2668
2669   /// EmitToMemory - Change a scalar value from its value
2670   /// representation to its in-memory representation.
2671   llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2672
2673   /// EmitFromMemory - Change a scalar value from its memory
2674   /// representation to its value representation.
2675   llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2676
2677   /// EmitLoadOfScalar - Load a scalar value from an address, taking
2678   /// care to appropriately convert from the memory representation to
2679   /// the LLVM value representation.
2680   llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2681                                 SourceLocation Loc,
2682                                 AlignmentSource AlignSource =
2683                                   AlignmentSource::Type,
2684                                 llvm::MDNode *TBAAInfo = nullptr,
2685                                 QualType TBAABaseTy = QualType(),
2686                                 uint64_t TBAAOffset = 0,
2687                                 bool isNontemporal = false);
2688
2689   /// EmitLoadOfScalar - Load a scalar value from an address, taking
2690   /// care to appropriately convert from the memory representation to
2691   /// the LLVM value representation.  The l-value must be a simple
2692   /// l-value.
2693   llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
2694
2695   /// EmitStoreOfScalar - Store a scalar value to an address, taking
2696   /// care to appropriately convert from the memory representation to
2697   /// the LLVM value representation.
2698   void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2699                          bool Volatile, QualType Ty,
2700                          AlignmentSource AlignSource = AlignmentSource::Type,
2701                          llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
2702                          QualType TBAABaseTy = QualType(),
2703                          uint64_t TBAAOffset = 0, bool isNontemporal = false);
2704
2705   /// EmitStoreOfScalar - Store a scalar value to an address, taking
2706   /// care to appropriately convert from the memory representation to
2707   /// the LLVM value representation.  The l-value must be a simple
2708   /// l-value.  The isInit flag indicates whether this is an initialization.
2709   /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2710   void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
2711
2712   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2713   /// this method emits the address of the lvalue, then loads the result as an
2714   /// rvalue, returning the rvalue.
2715   RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
2716   RValue EmitLoadOfExtVectorElementLValue(LValue V);
2717   RValue EmitLoadOfBitfieldLValue(LValue LV);
2718   RValue EmitLoadOfGlobalRegLValue(LValue LV);
2719
2720   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2721   /// lvalue, where both are guaranteed to the have the same type, and that type
2722   /// is 'Ty'.
2723   void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
2724   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
2725   void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
2726
2727   /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2728   /// as EmitStoreThroughLValue.
2729   ///
2730   /// \param Result [out] - If non-null, this will be set to a Value* for the
2731   /// bit-field contents after the store, appropriate for use as the result of
2732   /// an assignment to the bit-field.
2733   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2734                                       llvm::Value **Result=nullptr);
2735
2736   /// Emit an l-value for an assignment (simple or compound) of complex type.
2737   LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
2738   LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
2739   LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
2740                                              llvm::Value *&Result);
2741
2742   // Note: only available for agg return types
2743   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
2744   LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
2745   // Note: only available for agg return types
2746   LValue EmitCallExprLValue(const CallExpr *E);
2747   // Note: only available for agg return types
2748   LValue EmitVAArgExprLValue(const VAArgExpr *E);
2749   LValue EmitDeclRefLValue(const DeclRefExpr *E);
2750   LValue EmitStringLiteralLValue(const StringLiteral *E);
2751   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
2752   LValue EmitPredefinedLValue(const PredefinedExpr *E);
2753   LValue EmitUnaryOpLValue(const UnaryOperator *E);
2754   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2755                                 bool Accessed = false);
2756   LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2757                                  bool IsLowerBound = true);
2758   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
2759   LValue EmitMemberExpr(const MemberExpr *E);
2760   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
2761   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
2762   LValue EmitInitListLValue(const InitListExpr *E);
2763   LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
2764   LValue EmitCastLValue(const CastExpr *E);
2765   LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2766   LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
2767   
2768   Address EmitExtVectorElementLValue(LValue V);
2769
2770   RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
2771
2772   Address EmitArrayToPointerDecay(const Expr *Array,
2773                                   AlignmentSource *AlignSource = nullptr);
2774
2775   class ConstantEmission {
2776     llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
2777     ConstantEmission(llvm::Constant *C, bool isReference)
2778       : ValueAndIsReference(C, isReference) {}
2779   public:
2780     ConstantEmission() {}
2781     static ConstantEmission forReference(llvm::Constant *C) {
2782       return ConstantEmission(C, true);
2783     }
2784     static ConstantEmission forValue(llvm::Constant *C) {
2785       return ConstantEmission(C, false);
2786     }
2787
2788     explicit operator bool() const {
2789       return ValueAndIsReference.getOpaqueValue() != nullptr;
2790     }
2791
2792     bool isReference() const { return ValueAndIsReference.getInt(); }
2793     LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
2794       assert(isReference());
2795       return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
2796                                             refExpr->getType());
2797     }
2798
2799     llvm::Constant *getValue() const {
2800       assert(!isReference());
2801       return ValueAndIsReference.getPointer();
2802     }
2803   };
2804
2805   ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
2806
2807   RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
2808                                 AggValueSlot slot = AggValueSlot::ignored());
2809   LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
2810
2811   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2812                               const ObjCIvarDecl *Ivar);
2813   LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
2814   LValue EmitLValueForLambdaField(const FieldDecl *Field);
2815
2816   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2817   /// if the Field is a reference, this will return the address of the reference
2818   /// and not the address of the value stored in the reference.
2819   LValue EmitLValueForFieldInitialization(LValue Base,
2820                                           const FieldDecl* Field);
2821
2822   LValue EmitLValueForIvar(QualType ObjectTy,
2823                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
2824                            unsigned CVRQualifiers);
2825
2826   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2827   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2828   LValue EmitLambdaLValue(const LambdaExpr *E);
2829   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2830   LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
2831
2832   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
2833   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
2834   LValue EmitStmtExprLValue(const StmtExpr *E);
2835   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
2836   LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
2837   void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
2838
2839   //===--------------------------------------------------------------------===//
2840   //                         Scalar Expression Emission
2841   //===--------------------------------------------------------------------===//
2842
2843   /// EmitCall - Generate a call of the given function, expecting the given
2844   /// result type, and using the given argument list which specifies both the
2845   /// LLVM arguments and the types they were derived from.
2846   RValue EmitCall(const CGFunctionInfo &FnInfo, llvm::Value *Callee,
2847                   ReturnValueSlot ReturnValue, const CallArgList &Args,
2848                   CGCalleeInfo CalleeInfo = CGCalleeInfo(),
2849                   llvm::Instruction **callOrInvoke = nullptr);
2850
2851   RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
2852                   ReturnValueSlot ReturnValue,
2853                   CGCalleeInfo CalleeInfo = CGCalleeInfo(),
2854                   llvm::Value *Chain = nullptr);
2855   RValue EmitCallExpr(const CallExpr *E,
2856                       ReturnValueSlot ReturnValue = ReturnValueSlot());
2857
2858   void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
2859
2860   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2861                                   const Twine &name = "");
2862   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2863                                   ArrayRef<llvm::Value*> args,
2864                                   const Twine &name = "");
2865   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2866                                           const Twine &name = "");
2867   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2868                                           ArrayRef<llvm::Value*> args,
2869                                           const Twine &name = "");
2870
2871   llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2872                                   ArrayRef<llvm::Value *> Args,
2873                                   const Twine &Name = "");
2874   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2875                                          ArrayRef<llvm::Value*> args,
2876                                          const Twine &name = "");
2877   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2878                                          const Twine &name = "");
2879   void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2880                                        ArrayRef<llvm::Value*> args);
2881
2882   llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 
2883                                          NestedNameSpecifier *Qual,
2884                                          llvm::Type *Ty);
2885   
2886   llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
2887                                                    CXXDtorType Type, 
2888                                                    const CXXRecordDecl *RD);
2889
2890   RValue
2891   EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
2892                               ReturnValueSlot ReturnValue, llvm::Value *This,
2893                               llvm::Value *ImplicitParam,
2894                               QualType ImplicitParamTy, const CallExpr *E);
2895   RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD, llvm::Value *Callee,
2896                                llvm::Value *This, llvm::Value *ImplicitParam,
2897                                QualType ImplicitParamTy, const CallExpr *E,
2898                                StructorType Type);
2899   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
2900                                ReturnValueSlot ReturnValue);
2901   RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
2902                                                const CXXMethodDecl *MD,
2903                                                ReturnValueSlot ReturnValue,
2904                                                bool HasQualifier,
2905                                                NestedNameSpecifier *Qualifier,
2906                                                bool IsArrow, const Expr *Base);
2907   // Compute the object pointer.
2908   Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
2909                                           llvm::Value *memberPtr,
2910                                           const MemberPointerType *memberPtrType,
2911                                           AlignmentSource *AlignSource = nullptr);
2912   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
2913                                       ReturnValueSlot ReturnValue);
2914
2915   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
2916                                        const CXXMethodDecl *MD,
2917                                        ReturnValueSlot ReturnValue);
2918
2919   RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
2920                                 ReturnValueSlot ReturnValue);
2921
2922   RValue EmitCUDADevicePrintfCallExpr(const CallExpr *E,
2923                                       ReturnValueSlot ReturnValue);
2924
2925   RValue EmitBuiltinExpr(const FunctionDecl *FD,
2926                          unsigned BuiltinID, const CallExpr *E,
2927                          ReturnValueSlot ReturnValue);
2928
2929   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
2930
2931   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
2932   /// is unhandled by the current target.
2933   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2934
2935   llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
2936                                              const llvm::CmpInst::Predicate Fp,
2937                                              const llvm::CmpInst::Predicate Ip,
2938                                              const llvm::Twine &Name = "");
2939   llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2940
2941   llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
2942                                          unsigned LLVMIntrinsic,
2943                                          unsigned AltLLVMIntrinsic,
2944                                          const char *NameHint,
2945                                          unsigned Modifier,
2946                                          const CallExpr *E,
2947                                          SmallVectorImpl<llvm::Value *> &Ops,
2948                                          Address PtrOp0, Address PtrOp1);
2949   llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
2950                                           unsigned Modifier, llvm::Type *ArgTy,
2951                                           const CallExpr *E);
2952   llvm::Value *EmitNeonCall(llvm::Function *F,
2953                             SmallVectorImpl<llvm::Value*> &O,
2954                             const char *name,
2955                             unsigned shift = 0, bool rightshift = false);
2956   llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
2957   llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
2958                                    bool negateForRightShift);
2959   llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
2960                                  llvm::Type *Ty, bool usgn, const char *name);
2961   llvm::Value *vectorWrapScalar16(llvm::Value *Op);
2962   llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2963
2964   llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
2965   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2966   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2967   llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2968   llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2969   llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2970   llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
2971                                           const CallExpr *E);
2972
2973   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
2974   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
2975   llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
2976   llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
2977   llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
2978   llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
2979                                 const ObjCMethodDecl *MethodWithObjects);
2980   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
2981   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
2982                              ReturnValueSlot Return = ReturnValueSlot());
2983
2984   /// Retrieves the default cleanup kind for an ARC cleanup.
2985   /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
2986   CleanupKind getARCCleanupKind() {
2987     return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
2988              ? NormalAndEHCleanup : NormalCleanup;
2989   }
2990
2991   // ARC primitives.
2992   void EmitARCInitWeak(Address addr, llvm::Value *value);
2993   void EmitARCDestroyWeak(Address addr);
2994   llvm::Value *EmitARCLoadWeak(Address addr);
2995   llvm::Value *EmitARCLoadWeakRetained(Address addr);
2996   llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
2997   void EmitARCCopyWeak(Address dst, Address src);
2998   void EmitARCMoveWeak(Address dst, Address src);
2999   llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3000   llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3001   llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3002                                   bool resultIgnored);
3003   llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3004                                       bool resultIgnored);
3005   llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3006   llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3007   llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3008   void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3009   void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3010   llvm::Value *EmitARCAutorelease(llvm::Value *value);
3011   llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3012   llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3013   llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3014   llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3015
3016   std::pair<LValue,llvm::Value*>
3017   EmitARCStoreAutoreleasing(const BinaryOperator *e);
3018   std::pair<LValue,llvm::Value*>
3019   EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3020   std::pair<LValue,llvm::Value*>
3021   EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3022
3023   llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3024   llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3025   llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3026
3027   llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3028   llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3029                                             bool allowUnsafeClaim);
3030   llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3031   llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3032   llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3033
3034   void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3035
3036   static Destroyer destroyARCStrongImprecise;
3037   static Destroyer destroyARCStrongPrecise;
3038   static Destroyer destroyARCWeak;
3039
3040   void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 
3041   llvm::Value *EmitObjCAutoreleasePoolPush();
3042   llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3043   void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3044   void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 
3045
3046   /// \brief Emits a reference binding to the passed in expression.
3047   RValue EmitReferenceBindingToExpr(const Expr *E);
3048
3049   //===--------------------------------------------------------------------===//
3050   //                           Expression Emission
3051   //===--------------------------------------------------------------------===//
3052
3053   // Expressions are broken into three classes: scalar, complex, aggregate.
3054
3055   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3056   /// scalar type, returning the result.
3057   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3058
3059   /// Emit a conversion from the specified type to the specified destination
3060   /// type, both of which are LLVM scalar types.
3061   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3062                                     QualType DstTy, SourceLocation Loc);
3063
3064   /// Emit a conversion from the specified complex type to the specified
3065   /// destination type, where the destination type is an LLVM scalar type.
3066   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3067                                              QualType DstTy,
3068                                              SourceLocation Loc);
3069
3070   /// EmitAggExpr - Emit the computation of the specified expression
3071   /// of aggregate type.  The result is computed into the given slot,
3072   /// which may be null to indicate that the value is not needed.
3073   void EmitAggExpr(const Expr *E, AggValueSlot AS);
3074
3075   /// EmitAggExprToLValue - Emit the computation of the specified expression of
3076   /// aggregate type into a temporary LValue.
3077   LValue EmitAggExprToLValue(const Expr *E);
3078
3079   /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3080   /// make sure it survives garbage collection until this point.
3081   void EmitExtendGCLifetime(llvm::Value *object);
3082
3083   /// EmitComplexExpr - Emit the computation of the specified expression of
3084   /// complex type, returning the result.
3085   ComplexPairTy EmitComplexExpr(const Expr *E,
3086                                 bool IgnoreReal = false,
3087                                 bool IgnoreImag = false);
3088
3089   /// EmitComplexExprIntoLValue - Emit the given expression of complex
3090   /// type and place its result into the specified l-value.
3091   void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3092
3093   /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3094   void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3095
3096   /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3097   ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3098
3099   Address emitAddrOfRealComponent(Address complex, QualType complexType);
3100   Address emitAddrOfImagComponent(Address complex, QualType complexType);
3101
3102   /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3103   /// global variable that has already been created for it.  If the initializer
3104   /// has a different type than GV does, this may free GV and return a different
3105   /// one.  Otherwise it just returns GV.
3106   llvm::GlobalVariable *
3107   AddInitializerToStaticVarDecl(const VarDecl &D,
3108                                 llvm::GlobalVariable *GV);
3109
3110
3111   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3112   /// variable with global storage.
3113   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3114                                 bool PerformInit);
3115
3116   llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3117                                    llvm::Constant *Addr);
3118
3119   /// Call atexit() with a function that passes the given argument to
3120   /// the given function.
3121   void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3122                                     llvm::Constant *addr);
3123
3124   /// Emit code in this function to perform a guarded variable
3125   /// initialization.  Guarded initializations are used when it's not
3126   /// possible to prove that an initialization will be done exactly
3127   /// once, e.g. with a static local variable or a static data member
3128   /// of a class template.
3129   void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3130                           bool PerformInit);
3131
3132   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3133   /// variables.
3134   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3135                                  ArrayRef<llvm::Function *> CXXThreadLocals,
3136                                  Address Guard = Address::invalid());
3137
3138   /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3139   /// variables.
3140   void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
3141                                   const std::vector<std::pair<llvm::WeakVH,
3142                                   llvm::Constant*> > &DtorsAndObjects);
3143
3144   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3145                                         const VarDecl *D,
3146                                         llvm::GlobalVariable *Addr,
3147                                         bool PerformInit);
3148
3149   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3150   
3151   void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3152
3153   void enterFullExpression(const ExprWithCleanups *E) {
3154     if (E->getNumObjects() == 0) return;
3155     enterNonTrivialFullExpression(E);
3156   }
3157   void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3158
3159   void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3160
3161   void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3162
3163   RValue EmitAtomicExpr(AtomicExpr *E);
3164
3165   //===--------------------------------------------------------------------===//
3166   //                         Annotations Emission
3167   //===--------------------------------------------------------------------===//
3168
3169   /// Emit an annotation call (intrinsic or builtin).
3170   llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3171                                   llvm::Value *AnnotatedVal,
3172                                   StringRef AnnotationStr,
3173                                   SourceLocation Location);
3174
3175   /// Emit local annotations for the local variable V, declared by D.
3176   void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3177
3178   /// Emit field annotations for the given field & value. Returns the
3179   /// annotation result.
3180   Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3181
3182   //===--------------------------------------------------------------------===//
3183   //                             Internal Helpers
3184   //===--------------------------------------------------------------------===//
3185
3186   /// ContainsLabel - Return true if the statement contains a label in it.  If
3187   /// this statement is not executed normally, it not containing a label means
3188   /// that we can just remove the code.
3189   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3190
3191   /// containsBreak - Return true if the statement contains a break out of it.
3192   /// If the statement (recursively) contains a switch or loop with a break
3193   /// inside of it, this is fine.
3194   static bool containsBreak(const Stmt *S);
3195
3196   /// Determine if the given statement might introduce a declaration into the
3197   /// current scope, by being a (possibly-labelled) DeclStmt.
3198   static bool mightAddDeclToScope(const Stmt *S);
3199   
3200   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3201   /// to a constant, or if it does but contains a label, return false.  If it
3202   /// constant folds return true and set the boolean result in Result.
3203   bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3204                                     bool AllowLabels = false);
3205
3206   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3207   /// to a constant, or if it does but contains a label, return false.  If it
3208   /// constant folds return true and set the folded value.
3209   bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3210                                     bool AllowLabels = false);
3211
3212   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3213   /// if statement) to the specified blocks.  Based on the condition, this might
3214   /// try to simplify the codegen of the conditional based on the branch.
3215   /// TrueCount should be the number of times we expect the condition to
3216   /// evaluate to true based on PGO data.
3217   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3218                             llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3219
3220   /// \brief Emit a description of a type in a format suitable for passing to
3221   /// a runtime sanitizer handler.
3222   llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3223
3224   /// \brief Convert a value into a format suitable for passing to a runtime
3225   /// sanitizer handler.
3226   llvm::Value *EmitCheckValue(llvm::Value *V);
3227
3228   /// \brief Emit a description of a source location in a format suitable for
3229   /// passing to a runtime sanitizer handler.
3230   llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3231
3232   /// \brief Create a basic block that will call a handler function in a
3233   /// sanitizer runtime with the provided arguments, and create a conditional
3234   /// branch to it.
3235   void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3236                  StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
3237                  ArrayRef<llvm::Value *> DynamicArgs);
3238
3239   /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3240   /// if Cond if false.
3241   void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3242                             llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3243                             ArrayRef<llvm::Constant *> StaticArgs);
3244
3245   /// \brief Create a basic block that will call the trap intrinsic, and emit a
3246   /// conditional branch to it, for the -ftrapv checks.
3247   void EmitTrapCheck(llvm::Value *Checked);
3248
3249   /// \brief Emit a call to trap or debugtrap and attach function attribute
3250   /// "trap-func-name" if specified.
3251   llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3252
3253   /// \brief Emit a cross-DSO CFI failure handling function.
3254   void EmitCfiCheckFail();
3255
3256   /// \brief Create a check for a function parameter that may potentially be
3257   /// declared as non-null.
3258   void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3259                            const FunctionDecl *FD, unsigned ParmNum);
3260
3261   /// EmitCallArg - Emit a single call argument.
3262   void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3263
3264   /// EmitDelegateCallArg - We are performing a delegate call; that
3265   /// is, the current function is delegating to another one.  Produce
3266   /// a r-value suitable for passing the given parameter.
3267   void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3268                            SourceLocation loc);
3269
3270   /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3271   /// point operation, expressed as the maximum relative error in ulp.
3272   void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3273
3274 private:
3275   llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3276   void EmitReturnOfRValue(RValue RV, QualType Ty);
3277
3278   void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3279
3280   llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3281   DeferredReplacements;
3282
3283   /// Set the address of a local variable.
3284   void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3285     assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3286     LocalDeclMap.insert({VD, Addr});
3287   }
3288
3289   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3290   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3291   ///
3292   /// \param AI - The first function argument of the expansion.
3293   void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3294                           SmallVectorImpl<llvm::Value *>::iterator &AI);
3295
3296   /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3297   /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3298   /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3299   void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3300                         SmallVectorImpl<llvm::Value *> &IRCallArgs,
3301                         unsigned &IRCallArgPos);
3302
3303   llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3304                             const Expr *InputExpr, std::string &ConstraintStr);
3305
3306   llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3307                                   LValue InputValue, QualType InputType,
3308                                   std::string &ConstraintStr,
3309                                   SourceLocation Loc);
3310
3311   /// \brief Attempts to statically evaluate the object size of E. If that
3312   /// fails, emits code to figure the size of E out for us. This is
3313   /// pass_object_size aware.
3314   llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3315                                                llvm::IntegerType *ResType);
3316
3317   /// \brief Emits the size of E, as required by __builtin_object_size. This
3318   /// function is aware of pass_object_size parameters, and will act accordingly
3319   /// if E is a parameter with the pass_object_size attribute.
3320   llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3321                                      llvm::IntegerType *ResType);
3322
3323 public:
3324 #ifndef NDEBUG
3325   // Determine whether the given argument is an Objective-C method
3326   // that may have type parameters in its signature.
3327   static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3328     const DeclContext *dc = method->getDeclContext();
3329     if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3330       return classDecl->getTypeParamListAsWritten();
3331     }
3332
3333     if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3334       return catDecl->getTypeParamList();
3335     }
3336
3337     return false;
3338   }
3339
3340   template<typename T>
3341   static bool isObjCMethodWithTypeParams(const T *) { return false; }
3342 #endif
3343
3344   /// EmitCallArgs - Emit call arguments for a function.
3345   template <typename T>
3346   void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3347                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3348                     const FunctionDecl *CalleeDecl = nullptr,
3349                     unsigned ParamsToSkip = 0) {
3350     SmallVector<QualType, 16> ArgTypes;
3351     CallExpr::const_arg_iterator Arg = ArgRange.begin();
3352
3353     assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3354            "Can't skip parameters if type info is not provided");
3355     if (CallArgTypeInfo) {
3356 #ifndef NDEBUG
3357       bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3358 #endif
3359
3360       // First, use the argument types that the type info knows about
3361       for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3362                 E = CallArgTypeInfo->param_type_end();
3363            I != E; ++I, ++Arg) {
3364         assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3365         assert((isGenericMethod ||
3366                 ((*I)->isVariablyModifiedType() ||
3367                  (*I).getNonReferenceType()->isObjCRetainableType() ||
3368                  getContext()
3369                          .getCanonicalType((*I).getNonReferenceType())
3370                          .getTypePtr() ==
3371                      getContext()
3372                          .getCanonicalType((*Arg)->getType())
3373                          .getTypePtr())) &&
3374                "type mismatch in call argument!");
3375         ArgTypes.push_back(*I);
3376       }
3377     }
3378
3379     // Either we've emitted all the call args, or we have a call to variadic
3380     // function.
3381     assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3382             CallArgTypeInfo->isVariadic()) &&
3383            "Extra arguments in non-variadic function!");
3384
3385     // If we still have any arguments, emit them using the type of the argument.
3386     for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3387       ArgTypes.push_back(getVarArgType(A));
3388
3389     EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip);
3390   }
3391
3392   void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3393                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3394                     const FunctionDecl *CalleeDecl = nullptr,
3395                     unsigned ParamsToSkip = 0);
3396
3397   /// EmitPointerWithAlignment - Given an expression with a pointer
3398   /// type, emit the value and compute our best estimate of the
3399   /// alignment of the pointee.
3400   ///
3401   /// Note that this function will conservatively fall back on the type
3402   /// when it doesn't 
3403   ///
3404   /// \param Source - If non-null, this will be initialized with
3405   ///   information about the source of the alignment.  Note that this
3406   ///   function will conservatively fall back on the type when it
3407   ///   doesn't recognize the expression, which means that sometimes
3408   ///   
3409   ///   a worst-case One
3410   ///   reasonable way to use this information is when there's a
3411   ///   language guarantee that the pointer must be aligned to some
3412   ///   stricter value, and we're simply trying to ensure that
3413   ///   sufficiently obvious uses of under-aligned objects don't get
3414   ///   miscompiled; for example, a placement new into the address of
3415   ///   a local variable.  In such a case, it's quite reasonable to
3416   ///   just ignore the returned alignment when it isn't from an
3417   ///   explicit source.
3418   Address EmitPointerWithAlignment(const Expr *Addr,
3419                                    AlignmentSource *Source = nullptr);
3420
3421   void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3422
3423 private:
3424   QualType getVarArgType(const Expr *Arg);
3425
3426   const TargetCodeGenInfo &getTargetHooks() const {
3427     return CGM.getTargetCodeGenInfo();
3428   }
3429
3430   void EmitDeclMetadata();
3431
3432   BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3433                                   const AutoVarEmission &emission);
3434
3435   void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3436
3437   llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3438 };
3439
3440 /// Helper class with most of the code for saving a value for a
3441 /// conditional expression cleanup.
3442 struct DominatingLLVMValue {
3443   typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3444
3445   /// Answer whether the given value needs extra work to be saved.
3446   static bool needsSaving(llvm::Value *value) {
3447     // If it's not an instruction, we don't need to save.
3448     if (!isa<llvm::Instruction>(value)) return false;
3449
3450     // If it's an instruction in the entry block, we don't need to save.
3451     llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3452     return (block != &block->getParent()->getEntryBlock());
3453   }
3454
3455   /// Try to save the given value.
3456   static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3457     if (!needsSaving(value)) return saved_type(value, false);
3458
3459     // Otherwise, we need an alloca.
3460     auto align = CharUnits::fromQuantity(
3461               CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3462     Address alloca =
3463       CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3464     CGF.Builder.CreateStore(value, alloca);
3465
3466     return saved_type(alloca.getPointer(), true);
3467   }
3468
3469   static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3470     // If the value says it wasn't saved, trust that it's still dominating.
3471     if (!value.getInt()) return value.getPointer();
3472
3473     // Otherwise, it should be an alloca instruction, as set up in save().
3474     auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3475     return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3476   }
3477 };
3478
3479 /// A partial specialization of DominatingValue for llvm::Values that
3480 /// might be llvm::Instructions.
3481 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3482   typedef T *type;
3483   static type restore(CodeGenFunction &CGF, saved_type value) {
3484     return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3485   }
3486 };
3487
3488 /// A specialization of DominatingValue for Address.
3489 template <> struct DominatingValue<Address> {
3490   typedef Address type;
3491
3492   struct saved_type {
3493     DominatingLLVMValue::saved_type SavedValue;
3494     CharUnits Alignment;
3495   };
3496
3497   static bool needsSaving(type value) {
3498     return DominatingLLVMValue::needsSaving(value.getPointer());
3499   }
3500   static saved_type save(CodeGenFunction &CGF, type value) {
3501     return { DominatingLLVMValue::save(CGF, value.getPointer()),
3502              value.getAlignment() };
3503   }
3504   static type restore(CodeGenFunction &CGF, saved_type value) {
3505     return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3506                    value.Alignment);
3507   }
3508 };
3509
3510 /// A specialization of DominatingValue for RValue.
3511 template <> struct DominatingValue<RValue> {
3512   typedef RValue type;
3513   class saved_type {
3514     enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3515                 AggregateAddress, ComplexAddress };
3516
3517     llvm::Value *Value;
3518     unsigned K : 3;
3519     unsigned Align : 29;
3520     saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3521       : Value(v), K(k), Align(a) {}
3522
3523   public:
3524     static bool needsSaving(RValue value);
3525     static saved_type save(CodeGenFunction &CGF, RValue value);
3526     RValue restore(CodeGenFunction &CGF);
3527
3528     // implementations in CGCleanup.cpp
3529   };
3530
3531   static bool needsSaving(type value) {
3532     return saved_type::needsSaving(value);
3533   }
3534   static saved_type save(CodeGenFunction &CGF, type value) {
3535     return saved_type::save(CGF, value);
3536   }
3537   static type restore(CodeGenFunction &CGF, saved_type value) {
3538     return value.restore(CGF);
3539   }
3540 };
3541
3542 }  // end namespace CodeGen
3543 }  // end namespace clang
3544
3545 #endif