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