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