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