xref: /minix3/external/bsd/llvm/dist/clang/lib/CodeGen/CGCall.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // These classes wrap the information about a call or function
11f4a2713aSLionel Sambuc // definition used to handle ABI compliancy.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc 
15f4a2713aSLionel Sambuc #include "CGCall.h"
16f4a2713aSLionel Sambuc #include "ABIInfo.h"
17f4a2713aSLionel Sambuc #include "CGCXXABI.h"
18f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
19f4a2713aSLionel Sambuc #include "CodeGenModule.h"
20f4a2713aSLionel Sambuc #include "TargetInfo.h"
21f4a2713aSLionel Sambuc #include "clang/AST/Decl.h"
22f4a2713aSLionel Sambuc #include "clang/AST/DeclCXX.h"
23f4a2713aSLionel Sambuc #include "clang/AST/DeclObjC.h"
24f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
25f4a2713aSLionel Sambuc #include "clang/CodeGen/CGFunctionInfo.h"
26f4a2713aSLionel Sambuc #include "clang/Frontend/CodeGenOptions.h"
27f4a2713aSLionel Sambuc #include "llvm/ADT/StringExtras.h"
28f4a2713aSLionel Sambuc #include "llvm/IR/Attributes.h"
29*0a6a1f1dSLionel Sambuc #include "llvm/IR/CallSite.h"
30f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
31f4a2713aSLionel Sambuc #include "llvm/IR/InlineAsm.h"
32*0a6a1f1dSLionel Sambuc #include "llvm/IR/Intrinsics.h"
33f4a2713aSLionel Sambuc #include "llvm/Transforms/Utils/Local.h"
34f4a2713aSLionel Sambuc using namespace clang;
35f4a2713aSLionel Sambuc using namespace CodeGen;
36f4a2713aSLionel Sambuc 
37f4a2713aSLionel Sambuc /***/
38f4a2713aSLionel Sambuc 
ClangCallConvToLLVMCallConv(CallingConv CC)39f4a2713aSLionel Sambuc static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40f4a2713aSLionel Sambuc   switch (CC) {
41f4a2713aSLionel Sambuc   default: return llvm::CallingConv::C;
42f4a2713aSLionel Sambuc   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43f4a2713aSLionel Sambuc   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
44f4a2713aSLionel Sambuc   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
45f4a2713aSLionel Sambuc   case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46f4a2713aSLionel Sambuc   case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
47f4a2713aSLionel Sambuc   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48f4a2713aSLionel Sambuc   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
49f4a2713aSLionel Sambuc   case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
50*0a6a1f1dSLionel Sambuc   // TODO: Add support for __pascal to LLVM.
51*0a6a1f1dSLionel Sambuc   case CC_X86Pascal: return llvm::CallingConv::C;
52*0a6a1f1dSLionel Sambuc   // TODO: Add support for __vectorcall to LLVM.
53*0a6a1f1dSLionel Sambuc   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
54f4a2713aSLionel Sambuc   }
55f4a2713aSLionel Sambuc }
56f4a2713aSLionel Sambuc 
57f4a2713aSLionel Sambuc /// Derives the 'this' type for codegen purposes, i.e. ignoring method
58f4a2713aSLionel Sambuc /// qualification.
59f4a2713aSLionel Sambuc /// FIXME: address space qualification?
GetThisType(ASTContext & Context,const CXXRecordDecl * RD)60f4a2713aSLionel Sambuc static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
61f4a2713aSLionel Sambuc   QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
62f4a2713aSLionel Sambuc   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
63f4a2713aSLionel Sambuc }
64f4a2713aSLionel Sambuc 
65f4a2713aSLionel Sambuc /// Returns the canonical formal type of the given C++ method.
GetFormalType(const CXXMethodDecl * MD)66f4a2713aSLionel Sambuc static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
67f4a2713aSLionel Sambuc   return MD->getType()->getCanonicalTypeUnqualified()
68f4a2713aSLionel Sambuc            .getAs<FunctionProtoType>();
69f4a2713aSLionel Sambuc }
70f4a2713aSLionel Sambuc 
71f4a2713aSLionel Sambuc /// Returns the "extra-canonicalized" return type, which discards
72f4a2713aSLionel Sambuc /// qualifiers on the return type.  Codegen doesn't care about them,
73f4a2713aSLionel Sambuc /// and it makes ABI code a little easier to be able to assume that
74f4a2713aSLionel Sambuc /// all parameter and return types are top-level unqualified.
GetReturnType(QualType RetTy)75f4a2713aSLionel Sambuc static CanQualType GetReturnType(QualType RetTy) {
76f4a2713aSLionel Sambuc   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
77f4a2713aSLionel Sambuc }
78f4a2713aSLionel Sambuc 
79f4a2713aSLionel Sambuc /// Arrange the argument and result information for a value of the given
80f4a2713aSLionel Sambuc /// unprototyped freestanding function type.
81f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP)82f4a2713aSLionel Sambuc CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
83f4a2713aSLionel Sambuc   // When translating an unprototyped function type, always use a
84f4a2713aSLionel Sambuc   // variadic type.
85*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
86*0a6a1f1dSLionel Sambuc                                  /*instanceMethod=*/false,
87*0a6a1f1dSLionel Sambuc                                  /*chainCall=*/false, None,
88*0a6a1f1dSLionel Sambuc                                  FTNP->getExtInfo(), RequiredArgs(0));
89f4a2713aSLionel Sambuc }
90f4a2713aSLionel Sambuc 
91f4a2713aSLionel Sambuc /// Arrange the LLVM function layout for a value of the given function
92*0a6a1f1dSLionel Sambuc /// type, on top of any implicit parameters already stored.
93*0a6a1f1dSLionel Sambuc static const CGFunctionInfo &
arrangeLLVMFunctionInfo(CodeGenTypes & CGT,bool instanceMethod,SmallVectorImpl<CanQualType> & prefix,CanQual<FunctionProtoType> FTP)94*0a6a1f1dSLionel Sambuc arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
95f4a2713aSLionel Sambuc                         SmallVectorImpl<CanQualType> &prefix,
96*0a6a1f1dSLionel Sambuc                         CanQual<FunctionProtoType> FTP) {
97f4a2713aSLionel Sambuc   RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
98f4a2713aSLionel Sambuc   // FIXME: Kill copy.
99*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
100*0a6a1f1dSLionel Sambuc     prefix.push_back(FTP->getParamType(i));
101*0a6a1f1dSLionel Sambuc   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
102*0a6a1f1dSLionel Sambuc   return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
103*0a6a1f1dSLionel Sambuc                                      /*chainCall=*/false, prefix,
104*0a6a1f1dSLionel Sambuc                                      FTP->getExtInfo(), required);
105f4a2713aSLionel Sambuc }
106f4a2713aSLionel Sambuc 
107f4a2713aSLionel Sambuc /// Arrange the argument and result information for a value of the
108f4a2713aSLionel Sambuc /// given freestanding function type.
109f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP)110f4a2713aSLionel Sambuc CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
111f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
112*0a6a1f1dSLionel Sambuc   return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
113*0a6a1f1dSLionel Sambuc                                    FTP);
114f4a2713aSLionel Sambuc }
115f4a2713aSLionel Sambuc 
getCallingConventionForDecl(const Decl * D,bool IsWindows)116*0a6a1f1dSLionel Sambuc static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
117f4a2713aSLionel Sambuc   // Set the appropriate calling convention for the Function.
118f4a2713aSLionel Sambuc   if (D->hasAttr<StdCallAttr>())
119f4a2713aSLionel Sambuc     return CC_X86StdCall;
120f4a2713aSLionel Sambuc 
121f4a2713aSLionel Sambuc   if (D->hasAttr<FastCallAttr>())
122f4a2713aSLionel Sambuc     return CC_X86FastCall;
123f4a2713aSLionel Sambuc 
124f4a2713aSLionel Sambuc   if (D->hasAttr<ThisCallAttr>())
125f4a2713aSLionel Sambuc     return CC_X86ThisCall;
126f4a2713aSLionel Sambuc 
127*0a6a1f1dSLionel Sambuc   if (D->hasAttr<VectorCallAttr>())
128*0a6a1f1dSLionel Sambuc     return CC_X86VectorCall;
129*0a6a1f1dSLionel Sambuc 
130f4a2713aSLionel Sambuc   if (D->hasAttr<PascalAttr>())
131f4a2713aSLionel Sambuc     return CC_X86Pascal;
132f4a2713aSLionel Sambuc 
133f4a2713aSLionel Sambuc   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
134f4a2713aSLionel Sambuc     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
135f4a2713aSLionel Sambuc 
136f4a2713aSLionel Sambuc   if (D->hasAttr<PnaclCallAttr>())
137f4a2713aSLionel Sambuc     return CC_PnaclCall;
138f4a2713aSLionel Sambuc 
139f4a2713aSLionel Sambuc   if (D->hasAttr<IntelOclBiccAttr>())
140f4a2713aSLionel Sambuc     return CC_IntelOclBicc;
141f4a2713aSLionel Sambuc 
142*0a6a1f1dSLionel Sambuc   if (D->hasAttr<MSABIAttr>())
143*0a6a1f1dSLionel Sambuc     return IsWindows ? CC_C : CC_X86_64Win64;
144*0a6a1f1dSLionel Sambuc 
145*0a6a1f1dSLionel Sambuc   if (D->hasAttr<SysVABIAttr>())
146*0a6a1f1dSLionel Sambuc     return IsWindows ? CC_X86_64SysV : CC_C;
147*0a6a1f1dSLionel Sambuc 
148f4a2713aSLionel Sambuc   return CC_C;
149f4a2713aSLionel Sambuc }
150f4a2713aSLionel Sambuc 
151f4a2713aSLionel Sambuc /// Arrange the argument and result information for a call to an
152f4a2713aSLionel Sambuc /// unknown C++ non-static member function of the given abstract type.
153f4a2713aSLionel Sambuc /// (Zero value of RD means we don't have any meaningful "this" argument type,
154f4a2713aSLionel Sambuc ///  so fall back to a generic pointer type).
155f4a2713aSLionel Sambuc /// The member function must be an ordinary function, i.e. not a
156f4a2713aSLionel Sambuc /// constructor or destructor.
157f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeCXXMethodType(const CXXRecordDecl * RD,const FunctionProtoType * FTP)158f4a2713aSLionel Sambuc CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
159f4a2713aSLionel Sambuc                                    const FunctionProtoType *FTP) {
160f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
161f4a2713aSLionel Sambuc 
162f4a2713aSLionel Sambuc   // Add the 'this' pointer.
163f4a2713aSLionel Sambuc   if (RD)
164f4a2713aSLionel Sambuc     argTypes.push_back(GetThisType(Context, RD));
165f4a2713aSLionel Sambuc   else
166f4a2713aSLionel Sambuc     argTypes.push_back(Context.VoidPtrTy);
167f4a2713aSLionel Sambuc 
168*0a6a1f1dSLionel Sambuc   return ::arrangeLLVMFunctionInfo(
169*0a6a1f1dSLionel Sambuc       *this, true, argTypes,
170f4a2713aSLionel Sambuc       FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
171f4a2713aSLionel Sambuc }
172f4a2713aSLionel Sambuc 
173f4a2713aSLionel Sambuc /// Arrange the argument and result information for a declaration or
174f4a2713aSLionel Sambuc /// definition of the given C++ non-static member function.  The
175f4a2713aSLionel Sambuc /// member function must be an ordinary function, i.e. not a
176f4a2713aSLionel Sambuc /// constructor or destructor.
177f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeCXXMethodDeclaration(const CXXMethodDecl * MD)178f4a2713aSLionel Sambuc CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
179f4a2713aSLionel Sambuc   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
180f4a2713aSLionel Sambuc   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
181f4a2713aSLionel Sambuc 
182f4a2713aSLionel Sambuc   CanQual<FunctionProtoType> prototype = GetFormalType(MD);
183f4a2713aSLionel Sambuc 
184f4a2713aSLionel Sambuc   if (MD->isInstance()) {
185f4a2713aSLionel Sambuc     // The abstract case is perfectly fine.
186f4a2713aSLionel Sambuc     const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
187f4a2713aSLionel Sambuc     return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
188f4a2713aSLionel Sambuc   }
189f4a2713aSLionel Sambuc 
190f4a2713aSLionel Sambuc   return arrangeFreeFunctionType(prototype);
191f4a2713aSLionel Sambuc }
192f4a2713aSLionel Sambuc 
193f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeCXXStructorDeclaration(const CXXMethodDecl * MD,StructorType Type)194*0a6a1f1dSLionel Sambuc CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
195*0a6a1f1dSLionel Sambuc                                             StructorType Type) {
196*0a6a1f1dSLionel Sambuc 
197f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
198*0a6a1f1dSLionel Sambuc   argTypes.push_back(GetThisType(Context, MD->getParent()));
199f4a2713aSLionel Sambuc 
200*0a6a1f1dSLionel Sambuc   GlobalDecl GD;
201*0a6a1f1dSLionel Sambuc   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
202*0a6a1f1dSLionel Sambuc     GD = GlobalDecl(CD, toCXXCtorType(Type));
203*0a6a1f1dSLionel Sambuc   } else {
204*0a6a1f1dSLionel Sambuc     auto *DD = dyn_cast<CXXDestructorDecl>(MD);
205*0a6a1f1dSLionel Sambuc     GD = GlobalDecl(DD, toCXXDtorType(Type));
206f4a2713aSLionel Sambuc   }
207f4a2713aSLionel Sambuc 
208*0a6a1f1dSLionel Sambuc   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
209f4a2713aSLionel Sambuc 
210*0a6a1f1dSLionel Sambuc   // Add the formal parameters.
211*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
212*0a6a1f1dSLionel Sambuc     argTypes.push_back(FTP->getParamType(i));
213f4a2713aSLionel Sambuc 
214*0a6a1f1dSLionel Sambuc   TheCXXABI.buildStructorSignature(MD, Type, argTypes);
215f4a2713aSLionel Sambuc 
216*0a6a1f1dSLionel Sambuc   RequiredArgs required =
217*0a6a1f1dSLionel Sambuc       (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
218f4a2713aSLionel Sambuc 
219f4a2713aSLionel Sambuc   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
220*0a6a1f1dSLionel Sambuc   CanQualType resultType = TheCXXABI.HasThisReturn(GD)
221*0a6a1f1dSLionel Sambuc                                ? argTypes.front()
222*0a6a1f1dSLionel Sambuc                                : TheCXXABI.hasMostDerivedReturn(GD)
223*0a6a1f1dSLionel Sambuc                                      ? CGM.getContext().VoidPtrTy
224*0a6a1f1dSLionel Sambuc                                      : Context.VoidTy;
225*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
226*0a6a1f1dSLionel Sambuc                                  /*chainCall=*/false, argTypes, extInfo,
227*0a6a1f1dSLionel Sambuc                                  required);
228*0a6a1f1dSLionel Sambuc }
229*0a6a1f1dSLionel Sambuc 
230*0a6a1f1dSLionel Sambuc /// Arrange a call to a C++ method, passing the given arguments.
231*0a6a1f1dSLionel Sambuc const CGFunctionInfo &
arrangeCXXConstructorCall(const CallArgList & args,const CXXConstructorDecl * D,CXXCtorType CtorKind,unsigned ExtraArgs)232*0a6a1f1dSLionel Sambuc CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
233*0a6a1f1dSLionel Sambuc                                         const CXXConstructorDecl *D,
234*0a6a1f1dSLionel Sambuc                                         CXXCtorType CtorKind,
235*0a6a1f1dSLionel Sambuc                                         unsigned ExtraArgs) {
236*0a6a1f1dSLionel Sambuc   // FIXME: Kill copy.
237*0a6a1f1dSLionel Sambuc   SmallVector<CanQualType, 16> ArgTypes;
238*0a6a1f1dSLionel Sambuc   for (const auto &Arg : args)
239*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
240*0a6a1f1dSLionel Sambuc 
241*0a6a1f1dSLionel Sambuc   CanQual<FunctionProtoType> FPT = GetFormalType(D);
242*0a6a1f1dSLionel Sambuc   RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
243*0a6a1f1dSLionel Sambuc   GlobalDecl GD(D, CtorKind);
244*0a6a1f1dSLionel Sambuc   CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
245*0a6a1f1dSLionel Sambuc                                ? ArgTypes.front()
246*0a6a1f1dSLionel Sambuc                                : TheCXXABI.hasMostDerivedReturn(GD)
247*0a6a1f1dSLionel Sambuc                                      ? CGM.getContext().VoidPtrTy
248*0a6a1f1dSLionel Sambuc                                      : Context.VoidTy;
249*0a6a1f1dSLionel Sambuc 
250*0a6a1f1dSLionel Sambuc   FunctionType::ExtInfo Info = FPT->getExtInfo();
251*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
252*0a6a1f1dSLionel Sambuc                                  /*chainCall=*/false, ArgTypes, Info,
253*0a6a1f1dSLionel Sambuc                                  Required);
254f4a2713aSLionel Sambuc }
255f4a2713aSLionel Sambuc 
256f4a2713aSLionel Sambuc /// Arrange the argument and result information for the declaration or
257f4a2713aSLionel Sambuc /// definition of the given function.
258f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeFunctionDeclaration(const FunctionDecl * FD)259f4a2713aSLionel Sambuc CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
260f4a2713aSLionel Sambuc   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
261f4a2713aSLionel Sambuc     if (MD->isInstance())
262f4a2713aSLionel Sambuc       return arrangeCXXMethodDeclaration(MD);
263f4a2713aSLionel Sambuc 
264f4a2713aSLionel Sambuc   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
265f4a2713aSLionel Sambuc 
266f4a2713aSLionel Sambuc   assert(isa<FunctionType>(FTy));
267f4a2713aSLionel Sambuc 
268f4a2713aSLionel Sambuc   // When declaring a function without a prototype, always use a
269f4a2713aSLionel Sambuc   // non-variadic type.
270f4a2713aSLionel Sambuc   if (isa<FunctionNoProtoType>(FTy)) {
271f4a2713aSLionel Sambuc     CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
272*0a6a1f1dSLionel Sambuc     return arrangeLLVMFunctionInfo(
273*0a6a1f1dSLionel Sambuc         noProto->getReturnType(), /*instanceMethod=*/false,
274*0a6a1f1dSLionel Sambuc         /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
275f4a2713aSLionel Sambuc   }
276f4a2713aSLionel Sambuc 
277f4a2713aSLionel Sambuc   assert(isa<FunctionProtoType>(FTy));
278f4a2713aSLionel Sambuc   return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
279f4a2713aSLionel Sambuc }
280f4a2713aSLionel Sambuc 
281f4a2713aSLionel Sambuc /// Arrange the argument and result information for the declaration or
282f4a2713aSLionel Sambuc /// definition of an Objective-C method.
283f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeObjCMethodDeclaration(const ObjCMethodDecl * MD)284f4a2713aSLionel Sambuc CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
285f4a2713aSLionel Sambuc   // It happens that this is the same as a call with no optional
286f4a2713aSLionel Sambuc   // arguments, except also using the formal 'self' type.
287f4a2713aSLionel Sambuc   return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
288f4a2713aSLionel Sambuc }
289f4a2713aSLionel Sambuc 
290f4a2713aSLionel Sambuc /// Arrange the argument and result information for the function type
291f4a2713aSLionel Sambuc /// through which to perform a send to the given Objective-C method,
292f4a2713aSLionel Sambuc /// using the given receiver type.  The receiver type is not always
293f4a2713aSLionel Sambuc /// the 'self' type of the method or even an Objective-C pointer type.
294f4a2713aSLionel Sambuc /// This is *not* the right method for actually performing such a
295f4a2713aSLionel Sambuc /// message send, due to the possibility of optional arguments.
296f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeObjCMessageSendSignature(const ObjCMethodDecl * MD,QualType receiverType)297f4a2713aSLionel Sambuc CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
298f4a2713aSLionel Sambuc                                               QualType receiverType) {
299f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTys;
300f4a2713aSLionel Sambuc   argTys.push_back(Context.getCanonicalParamType(receiverType));
301f4a2713aSLionel Sambuc   argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
302f4a2713aSLionel Sambuc   // FIXME: Kill copy?
303*0a6a1f1dSLionel Sambuc   for (const auto *I : MD->params()) {
304*0a6a1f1dSLionel Sambuc     argTys.push_back(Context.getCanonicalParamType(I->getType()));
305f4a2713aSLionel Sambuc   }
306f4a2713aSLionel Sambuc 
307f4a2713aSLionel Sambuc   FunctionType::ExtInfo einfo;
308*0a6a1f1dSLionel Sambuc   bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
309*0a6a1f1dSLionel Sambuc   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
310f4a2713aSLionel Sambuc 
311f4a2713aSLionel Sambuc   if (getContext().getLangOpts().ObjCAutoRefCount &&
312f4a2713aSLionel Sambuc       MD->hasAttr<NSReturnsRetainedAttr>())
313f4a2713aSLionel Sambuc     einfo = einfo.withProducesResult(true);
314f4a2713aSLionel Sambuc 
315f4a2713aSLionel Sambuc   RequiredArgs required =
316f4a2713aSLionel Sambuc     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
317f4a2713aSLionel Sambuc 
318*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(
319*0a6a1f1dSLionel Sambuc       GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
320*0a6a1f1dSLionel Sambuc       /*chainCall=*/false, argTys, einfo, required);
321f4a2713aSLionel Sambuc }
322f4a2713aSLionel Sambuc 
323f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeGlobalDeclaration(GlobalDecl GD)324f4a2713aSLionel Sambuc CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
325f4a2713aSLionel Sambuc   // FIXME: Do we need to handle ObjCMethodDecl?
326f4a2713aSLionel Sambuc   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
327f4a2713aSLionel Sambuc 
328f4a2713aSLionel Sambuc   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
329*0a6a1f1dSLionel Sambuc     return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
330f4a2713aSLionel Sambuc 
331f4a2713aSLionel Sambuc   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
332*0a6a1f1dSLionel Sambuc     return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
333f4a2713aSLionel Sambuc 
334f4a2713aSLionel Sambuc   return arrangeFunctionDeclaration(FD);
335f4a2713aSLionel Sambuc }
336f4a2713aSLionel Sambuc 
337*0a6a1f1dSLionel Sambuc /// Arrange a thunk that takes 'this' as the first parameter followed by
338*0a6a1f1dSLionel Sambuc /// varargs.  Return a void pointer, regardless of the actual return type.
339*0a6a1f1dSLionel Sambuc /// The body of the thunk will end in a musttail call to a function of the
340*0a6a1f1dSLionel Sambuc /// correct type, and the caller will bitcast the function to the correct
341*0a6a1f1dSLionel Sambuc /// prototype.
342*0a6a1f1dSLionel Sambuc const CGFunctionInfo &
arrangeMSMemberPointerThunk(const CXXMethodDecl * MD)343*0a6a1f1dSLionel Sambuc CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
344*0a6a1f1dSLionel Sambuc   assert(MD->isVirtual() && "only virtual memptrs have thunks");
345*0a6a1f1dSLionel Sambuc   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
346*0a6a1f1dSLionel Sambuc   CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
347*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
348*0a6a1f1dSLionel Sambuc                                  /*chainCall=*/false, ArgTys,
349*0a6a1f1dSLionel Sambuc                                  FTP->getExtInfo(), RequiredArgs(1));
350*0a6a1f1dSLionel Sambuc }
351*0a6a1f1dSLionel Sambuc 
352f4a2713aSLionel Sambuc /// Arrange a call as unto a free function, except possibly with an
353f4a2713aSLionel Sambuc /// additional number of formal parameters considered required.
354f4a2713aSLionel Sambuc static const CGFunctionInfo &
arrangeFreeFunctionLikeCall(CodeGenTypes & CGT,CodeGenModule & CGM,const CallArgList & args,const FunctionType * fnType,unsigned numExtraRequiredArgs,bool chainCall)355f4a2713aSLionel Sambuc arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
356f4a2713aSLionel Sambuc                             CodeGenModule &CGM,
357f4a2713aSLionel Sambuc                             const CallArgList &args,
358f4a2713aSLionel Sambuc                             const FunctionType *fnType,
359*0a6a1f1dSLionel Sambuc                             unsigned numExtraRequiredArgs,
360*0a6a1f1dSLionel Sambuc                             bool chainCall) {
361f4a2713aSLionel Sambuc   assert(args.size() >= numExtraRequiredArgs);
362f4a2713aSLionel Sambuc 
363f4a2713aSLionel Sambuc   // In most cases, there are no optional arguments.
364f4a2713aSLionel Sambuc   RequiredArgs required = RequiredArgs::All;
365f4a2713aSLionel Sambuc 
366f4a2713aSLionel Sambuc   // If we have a variadic prototype, the required arguments are the
367f4a2713aSLionel Sambuc   // extra prefix plus the arguments in the prototype.
368f4a2713aSLionel Sambuc   if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
369f4a2713aSLionel Sambuc     if (proto->isVariadic())
370*0a6a1f1dSLionel Sambuc       required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
371f4a2713aSLionel Sambuc 
372f4a2713aSLionel Sambuc   // If we don't have a prototype at all, but we're supposed to
373f4a2713aSLionel Sambuc   // explicitly use the variadic convention for unprototyped calls,
374f4a2713aSLionel Sambuc   // treat all of the arguments as required but preserve the nominal
375f4a2713aSLionel Sambuc   // possibility of variadics.
376f4a2713aSLionel Sambuc   } else if (CGM.getTargetCodeGenInfo()
377f4a2713aSLionel Sambuc                 .isNoProtoCallVariadic(args,
378f4a2713aSLionel Sambuc                                        cast<FunctionNoProtoType>(fnType))) {
379f4a2713aSLionel Sambuc     required = RequiredArgs(args.size());
380f4a2713aSLionel Sambuc   }
381f4a2713aSLionel Sambuc 
382*0a6a1f1dSLionel Sambuc   // FIXME: Kill copy.
383*0a6a1f1dSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
384*0a6a1f1dSLionel Sambuc   for (const auto &arg : args)
385*0a6a1f1dSLionel Sambuc     argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
386*0a6a1f1dSLionel Sambuc   return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
387*0a6a1f1dSLionel Sambuc                                      /*instanceMethod=*/false, chainCall,
388*0a6a1f1dSLionel Sambuc                                      argTypes, fnType->getExtInfo(), required);
389f4a2713aSLionel Sambuc }
390f4a2713aSLionel Sambuc 
391f4a2713aSLionel Sambuc /// Figure out the rules for calling a function with the given formal
392f4a2713aSLionel Sambuc /// type using the given arguments.  The arguments are necessary
393f4a2713aSLionel Sambuc /// because the function might be unprototyped, in which case it's
394f4a2713aSLionel Sambuc /// target-dependent in crazy ways.
395f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeFreeFunctionCall(const CallArgList & args,const FunctionType * fnType,bool chainCall)396f4a2713aSLionel Sambuc CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
397*0a6a1f1dSLionel Sambuc                                       const FunctionType *fnType,
398*0a6a1f1dSLionel Sambuc                                       bool chainCall) {
399*0a6a1f1dSLionel Sambuc   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
400*0a6a1f1dSLionel Sambuc                                      chainCall ? 1 : 0, chainCall);
401f4a2713aSLionel Sambuc }
402f4a2713aSLionel Sambuc 
403f4a2713aSLionel Sambuc /// A block function call is essentially a free-function call with an
404f4a2713aSLionel Sambuc /// extra implicit argument.
405f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeBlockFunctionCall(const CallArgList & args,const FunctionType * fnType)406f4a2713aSLionel Sambuc CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
407f4a2713aSLionel Sambuc                                        const FunctionType *fnType) {
408*0a6a1f1dSLionel Sambuc   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
409*0a6a1f1dSLionel Sambuc                                      /*chainCall=*/false);
410f4a2713aSLionel Sambuc }
411f4a2713aSLionel Sambuc 
412f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeFreeFunctionCall(QualType resultType,const CallArgList & args,FunctionType::ExtInfo info,RequiredArgs required)413f4a2713aSLionel Sambuc CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
414f4a2713aSLionel Sambuc                                       const CallArgList &args,
415f4a2713aSLionel Sambuc                                       FunctionType::ExtInfo info,
416f4a2713aSLionel Sambuc                                       RequiredArgs required) {
417f4a2713aSLionel Sambuc   // FIXME: Kill copy.
418f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
419*0a6a1f1dSLionel Sambuc   for (const auto &Arg : args)
420*0a6a1f1dSLionel Sambuc     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
421*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(
422*0a6a1f1dSLionel Sambuc       GetReturnType(resultType), /*instanceMethod=*/false,
423*0a6a1f1dSLionel Sambuc       /*chainCall=*/false, argTypes, info, required);
424f4a2713aSLionel Sambuc }
425f4a2713aSLionel Sambuc 
426f4a2713aSLionel Sambuc /// Arrange a call to a C++ method, passing the given arguments.
427f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeCXXMethodCall(const CallArgList & args,const FunctionProtoType * FPT,RequiredArgs required)428f4a2713aSLionel Sambuc CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
429f4a2713aSLionel Sambuc                                    const FunctionProtoType *FPT,
430f4a2713aSLionel Sambuc                                    RequiredArgs required) {
431f4a2713aSLionel Sambuc   // FIXME: Kill copy.
432f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
433*0a6a1f1dSLionel Sambuc   for (const auto &Arg : args)
434*0a6a1f1dSLionel Sambuc     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
435f4a2713aSLionel Sambuc 
436f4a2713aSLionel Sambuc   FunctionType::ExtInfo info = FPT->getExtInfo();
437*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(
438*0a6a1f1dSLionel Sambuc       GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
439*0a6a1f1dSLionel Sambuc       /*chainCall=*/false, argTypes, info, required);
440f4a2713aSLionel Sambuc }
441f4a2713aSLionel Sambuc 
arrangeFreeFunctionDeclaration(QualType resultType,const FunctionArgList & args,const FunctionType::ExtInfo & info,bool isVariadic)442*0a6a1f1dSLionel Sambuc const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
443*0a6a1f1dSLionel Sambuc     QualType resultType, const FunctionArgList &args,
444*0a6a1f1dSLionel Sambuc     const FunctionType::ExtInfo &info, bool isVariadic) {
445f4a2713aSLionel Sambuc   // FIXME: Kill copy.
446f4a2713aSLionel Sambuc   SmallVector<CanQualType, 16> argTypes;
447*0a6a1f1dSLionel Sambuc   for (auto Arg : args)
448*0a6a1f1dSLionel Sambuc     argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
449f4a2713aSLionel Sambuc 
450f4a2713aSLionel Sambuc   RequiredArgs required =
451f4a2713aSLionel Sambuc     (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
452*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(
453*0a6a1f1dSLionel Sambuc       GetReturnType(resultType), /*instanceMethod=*/false,
454*0a6a1f1dSLionel Sambuc       /*chainCall=*/false, argTypes, info, required);
455f4a2713aSLionel Sambuc }
456f4a2713aSLionel Sambuc 
arrangeNullaryFunction()457f4a2713aSLionel Sambuc const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
458*0a6a1f1dSLionel Sambuc   return arrangeLLVMFunctionInfo(
459*0a6a1f1dSLionel Sambuc       getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
460*0a6a1f1dSLionel Sambuc       None, FunctionType::ExtInfo(), RequiredArgs::All);
461f4a2713aSLionel Sambuc }
462f4a2713aSLionel Sambuc 
463f4a2713aSLionel Sambuc /// Arrange the argument and result information for an abstract value
464f4a2713aSLionel Sambuc /// of a given function type.  This is the method which all of the
465f4a2713aSLionel Sambuc /// above functions ultimately defer to.
466f4a2713aSLionel Sambuc const CGFunctionInfo &
arrangeLLVMFunctionInfo(CanQualType resultType,bool instanceMethod,bool chainCall,ArrayRef<CanQualType> argTypes,FunctionType::ExtInfo info,RequiredArgs required)467f4a2713aSLionel Sambuc CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
468*0a6a1f1dSLionel Sambuc                                       bool instanceMethod,
469*0a6a1f1dSLionel Sambuc                                       bool chainCall,
470f4a2713aSLionel Sambuc                                       ArrayRef<CanQualType> argTypes,
471f4a2713aSLionel Sambuc                                       FunctionType::ExtInfo info,
472f4a2713aSLionel Sambuc                                       RequiredArgs required) {
473*0a6a1f1dSLionel Sambuc   assert(std::all_of(argTypes.begin(), argTypes.end(),
474*0a6a1f1dSLionel Sambuc                      std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
475f4a2713aSLionel Sambuc 
476f4a2713aSLionel Sambuc   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
477f4a2713aSLionel Sambuc 
478f4a2713aSLionel Sambuc   // Lookup or create unique function info.
479f4a2713aSLionel Sambuc   llvm::FoldingSetNodeID ID;
480*0a6a1f1dSLionel Sambuc   CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
481*0a6a1f1dSLionel Sambuc                           resultType, argTypes);
482f4a2713aSLionel Sambuc 
483*0a6a1f1dSLionel Sambuc   void *insertPos = nullptr;
484f4a2713aSLionel Sambuc   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
485f4a2713aSLionel Sambuc   if (FI)
486f4a2713aSLionel Sambuc     return *FI;
487f4a2713aSLionel Sambuc 
488f4a2713aSLionel Sambuc   // Construct the function info.  We co-allocate the ArgInfos.
489*0a6a1f1dSLionel Sambuc   FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
490*0a6a1f1dSLionel Sambuc                               resultType, argTypes, required);
491f4a2713aSLionel Sambuc   FunctionInfos.InsertNode(FI, insertPos);
492f4a2713aSLionel Sambuc 
493*0a6a1f1dSLionel Sambuc   bool inserted = FunctionsBeingProcessed.insert(FI).second;
494*0a6a1f1dSLionel Sambuc   (void)inserted;
495f4a2713aSLionel Sambuc   assert(inserted && "Recursively being processed?");
496f4a2713aSLionel Sambuc 
497f4a2713aSLionel Sambuc   // Compute ABI information.
498f4a2713aSLionel Sambuc   getABIInfo().computeInfo(*FI);
499f4a2713aSLionel Sambuc 
500f4a2713aSLionel Sambuc   // Loop over all of the computed argument and return value info.  If any of
501f4a2713aSLionel Sambuc   // them are direct or extend without a specified coerce type, specify the
502f4a2713aSLionel Sambuc   // default now.
503f4a2713aSLionel Sambuc   ABIArgInfo &retInfo = FI->getReturnInfo();
504*0a6a1f1dSLionel Sambuc   if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
505f4a2713aSLionel Sambuc     retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
506f4a2713aSLionel Sambuc 
507*0a6a1f1dSLionel Sambuc   for (auto &I : FI->arguments())
508*0a6a1f1dSLionel Sambuc     if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
509*0a6a1f1dSLionel Sambuc       I.info.setCoerceToType(ConvertType(I.type));
510f4a2713aSLionel Sambuc 
511f4a2713aSLionel Sambuc   bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
512f4a2713aSLionel Sambuc   assert(erased && "Not in set?");
513f4a2713aSLionel Sambuc 
514f4a2713aSLionel Sambuc   return *FI;
515f4a2713aSLionel Sambuc }
516f4a2713aSLionel Sambuc 
create(unsigned llvmCC,bool instanceMethod,bool chainCall,const FunctionType::ExtInfo & info,CanQualType resultType,ArrayRef<CanQualType> argTypes,RequiredArgs required)517f4a2713aSLionel Sambuc CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
518*0a6a1f1dSLionel Sambuc                                        bool instanceMethod,
519*0a6a1f1dSLionel Sambuc                                        bool chainCall,
520f4a2713aSLionel Sambuc                                        const FunctionType::ExtInfo &info,
521f4a2713aSLionel Sambuc                                        CanQualType resultType,
522f4a2713aSLionel Sambuc                                        ArrayRef<CanQualType> argTypes,
523f4a2713aSLionel Sambuc                                        RequiredArgs required) {
524f4a2713aSLionel Sambuc   void *buffer = operator new(sizeof(CGFunctionInfo) +
525f4a2713aSLionel Sambuc                               sizeof(ArgInfo) * (argTypes.size() + 1));
526f4a2713aSLionel Sambuc   CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
527f4a2713aSLionel Sambuc   FI->CallingConvention = llvmCC;
528f4a2713aSLionel Sambuc   FI->EffectiveCallingConvention = llvmCC;
529f4a2713aSLionel Sambuc   FI->ASTCallingConvention = info.getCC();
530*0a6a1f1dSLionel Sambuc   FI->InstanceMethod = instanceMethod;
531*0a6a1f1dSLionel Sambuc   FI->ChainCall = chainCall;
532f4a2713aSLionel Sambuc   FI->NoReturn = info.getNoReturn();
533f4a2713aSLionel Sambuc   FI->ReturnsRetained = info.getProducesResult();
534f4a2713aSLionel Sambuc   FI->Required = required;
535f4a2713aSLionel Sambuc   FI->HasRegParm = info.getHasRegParm();
536f4a2713aSLionel Sambuc   FI->RegParm = info.getRegParm();
537*0a6a1f1dSLionel Sambuc   FI->ArgStruct = nullptr;
538f4a2713aSLionel Sambuc   FI->NumArgs = argTypes.size();
539f4a2713aSLionel Sambuc   FI->getArgsBuffer()[0].type = resultType;
540f4a2713aSLionel Sambuc   for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
541f4a2713aSLionel Sambuc     FI->getArgsBuffer()[i + 1].type = argTypes[i];
542f4a2713aSLionel Sambuc   return FI;
543f4a2713aSLionel Sambuc }
544f4a2713aSLionel Sambuc 
545f4a2713aSLionel Sambuc /***/
546f4a2713aSLionel Sambuc 
547*0a6a1f1dSLionel Sambuc namespace {
548*0a6a1f1dSLionel Sambuc // ABIArgInfo::Expand implementation.
549*0a6a1f1dSLionel Sambuc 
550*0a6a1f1dSLionel Sambuc // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
551*0a6a1f1dSLionel Sambuc struct TypeExpansion {
552*0a6a1f1dSLionel Sambuc   enum TypeExpansionKind {
553*0a6a1f1dSLionel Sambuc     // Elements of constant arrays are expanded recursively.
554*0a6a1f1dSLionel Sambuc     TEK_ConstantArray,
555*0a6a1f1dSLionel Sambuc     // Record fields are expanded recursively (but if record is a union, only
556*0a6a1f1dSLionel Sambuc     // the field with the largest size is expanded).
557*0a6a1f1dSLionel Sambuc     TEK_Record,
558*0a6a1f1dSLionel Sambuc     // For complex types, real and imaginary parts are expanded recursively.
559*0a6a1f1dSLionel Sambuc     TEK_Complex,
560*0a6a1f1dSLionel Sambuc     // All other types are not expandable.
561*0a6a1f1dSLionel Sambuc     TEK_None
562*0a6a1f1dSLionel Sambuc   };
563*0a6a1f1dSLionel Sambuc 
564*0a6a1f1dSLionel Sambuc   const TypeExpansionKind Kind;
565*0a6a1f1dSLionel Sambuc 
TypeExpansion__anon2e5bceb70111::TypeExpansion566*0a6a1f1dSLionel Sambuc   TypeExpansion(TypeExpansionKind K) : Kind(K) {}
~TypeExpansion__anon2e5bceb70111::TypeExpansion567*0a6a1f1dSLionel Sambuc   virtual ~TypeExpansion() {}
568*0a6a1f1dSLionel Sambuc };
569*0a6a1f1dSLionel Sambuc 
570*0a6a1f1dSLionel Sambuc struct ConstantArrayExpansion : TypeExpansion {
571*0a6a1f1dSLionel Sambuc   QualType EltTy;
572*0a6a1f1dSLionel Sambuc   uint64_t NumElts;
573*0a6a1f1dSLionel Sambuc 
ConstantArrayExpansion__anon2e5bceb70111::ConstantArrayExpansion574*0a6a1f1dSLionel Sambuc   ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
575*0a6a1f1dSLionel Sambuc       : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
classof__anon2e5bceb70111::ConstantArrayExpansion576*0a6a1f1dSLionel Sambuc   static bool classof(const TypeExpansion *TE) {
577*0a6a1f1dSLionel Sambuc     return TE->Kind == TEK_ConstantArray;
578*0a6a1f1dSLionel Sambuc   }
579*0a6a1f1dSLionel Sambuc };
580*0a6a1f1dSLionel Sambuc 
581*0a6a1f1dSLionel Sambuc struct RecordExpansion : TypeExpansion {
582*0a6a1f1dSLionel Sambuc   SmallVector<const CXXBaseSpecifier *, 1> Bases;
583*0a6a1f1dSLionel Sambuc 
584*0a6a1f1dSLionel Sambuc   SmallVector<const FieldDecl *, 1> Fields;
585*0a6a1f1dSLionel Sambuc 
RecordExpansion__anon2e5bceb70111::RecordExpansion586*0a6a1f1dSLionel Sambuc   RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
587*0a6a1f1dSLionel Sambuc                   SmallVector<const FieldDecl *, 1> &&Fields)
588*0a6a1f1dSLionel Sambuc       : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
classof__anon2e5bceb70111::RecordExpansion589*0a6a1f1dSLionel Sambuc   static bool classof(const TypeExpansion *TE) {
590*0a6a1f1dSLionel Sambuc     return TE->Kind == TEK_Record;
591*0a6a1f1dSLionel Sambuc   }
592*0a6a1f1dSLionel Sambuc };
593*0a6a1f1dSLionel Sambuc 
594*0a6a1f1dSLionel Sambuc struct ComplexExpansion : TypeExpansion {
595*0a6a1f1dSLionel Sambuc   QualType EltTy;
596*0a6a1f1dSLionel Sambuc 
ComplexExpansion__anon2e5bceb70111::ComplexExpansion597*0a6a1f1dSLionel Sambuc   ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
classof__anon2e5bceb70111::ComplexExpansion598*0a6a1f1dSLionel Sambuc   static bool classof(const TypeExpansion *TE) {
599*0a6a1f1dSLionel Sambuc     return TE->Kind == TEK_Complex;
600*0a6a1f1dSLionel Sambuc   }
601*0a6a1f1dSLionel Sambuc };
602*0a6a1f1dSLionel Sambuc 
603*0a6a1f1dSLionel Sambuc struct NoExpansion : TypeExpansion {
NoExpansion__anon2e5bceb70111::NoExpansion604*0a6a1f1dSLionel Sambuc   NoExpansion() : TypeExpansion(TEK_None) {}
classof__anon2e5bceb70111::NoExpansion605*0a6a1f1dSLionel Sambuc   static bool classof(const TypeExpansion *TE) {
606*0a6a1f1dSLionel Sambuc     return TE->Kind == TEK_None;
607*0a6a1f1dSLionel Sambuc   }
608*0a6a1f1dSLionel Sambuc };
609*0a6a1f1dSLionel Sambuc }  // namespace
610*0a6a1f1dSLionel Sambuc 
611*0a6a1f1dSLionel Sambuc static std::unique_ptr<TypeExpansion>
getTypeExpansion(QualType Ty,const ASTContext & Context)612*0a6a1f1dSLionel Sambuc getTypeExpansion(QualType Ty, const ASTContext &Context) {
613*0a6a1f1dSLionel Sambuc   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
614*0a6a1f1dSLionel Sambuc     return llvm::make_unique<ConstantArrayExpansion>(
615*0a6a1f1dSLionel Sambuc         AT->getElementType(), AT->getSize().getZExtValue());
616*0a6a1f1dSLionel Sambuc   }
617*0a6a1f1dSLionel Sambuc   if (const RecordType *RT = Ty->getAs<RecordType>()) {
618*0a6a1f1dSLionel Sambuc     SmallVector<const CXXBaseSpecifier *, 1> Bases;
619*0a6a1f1dSLionel Sambuc     SmallVector<const FieldDecl *, 1> Fields;
620f4a2713aSLionel Sambuc     const RecordDecl *RD = RT->getDecl();
621f4a2713aSLionel Sambuc     assert(!RD->hasFlexibleArrayMember() &&
622f4a2713aSLionel Sambuc            "Cannot expand structure with flexible array.");
623f4a2713aSLionel Sambuc     if (RD->isUnion()) {
624f4a2713aSLionel Sambuc       // Unions can be here only in degenerative cases - all the fields are same
625f4a2713aSLionel Sambuc       // after flattening. Thus we have to use the "largest" field.
626*0a6a1f1dSLionel Sambuc       const FieldDecl *LargestFD = nullptr;
627f4a2713aSLionel Sambuc       CharUnits UnionSize = CharUnits::Zero();
628f4a2713aSLionel Sambuc 
629*0a6a1f1dSLionel Sambuc       for (const auto *FD : RD->fields()) {
630*0a6a1f1dSLionel Sambuc         // Skip zero length bitfields.
631*0a6a1f1dSLionel Sambuc         if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
632*0a6a1f1dSLionel Sambuc           continue;
633f4a2713aSLionel Sambuc         assert(!FD->isBitField() &&
634f4a2713aSLionel Sambuc                "Cannot expand structure with bit-field members.");
635*0a6a1f1dSLionel Sambuc         CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
636f4a2713aSLionel Sambuc         if (UnionSize < FieldSize) {
637f4a2713aSLionel Sambuc           UnionSize = FieldSize;
638f4a2713aSLionel Sambuc           LargestFD = FD;
639f4a2713aSLionel Sambuc         }
640f4a2713aSLionel Sambuc       }
641f4a2713aSLionel Sambuc       if (LargestFD)
642*0a6a1f1dSLionel Sambuc         Fields.push_back(LargestFD);
643f4a2713aSLionel Sambuc     } else {
644*0a6a1f1dSLionel Sambuc       if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
645*0a6a1f1dSLionel Sambuc         assert(!CXXRD->isDynamicClass() &&
646*0a6a1f1dSLionel Sambuc                "cannot expand vtable pointers in dynamic classes");
647*0a6a1f1dSLionel Sambuc         for (const CXXBaseSpecifier &BS : CXXRD->bases())
648*0a6a1f1dSLionel Sambuc           Bases.push_back(&BS);
649f4a2713aSLionel Sambuc       }
650f4a2713aSLionel Sambuc 
651*0a6a1f1dSLionel Sambuc       for (const auto *FD : RD->fields()) {
652*0a6a1f1dSLionel Sambuc         // Skip zero length bitfields.
653*0a6a1f1dSLionel Sambuc         if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
654*0a6a1f1dSLionel Sambuc           continue;
655*0a6a1f1dSLionel Sambuc         assert(!FD->isBitField() &&
656*0a6a1f1dSLionel Sambuc                "Cannot expand structure with bit-field members.");
657*0a6a1f1dSLionel Sambuc         Fields.push_back(FD);
658*0a6a1f1dSLionel Sambuc       }
659*0a6a1f1dSLionel Sambuc     }
660*0a6a1f1dSLionel Sambuc     return llvm::make_unique<RecordExpansion>(std::move(Bases),
661*0a6a1f1dSLionel Sambuc                                               std::move(Fields));
662*0a6a1f1dSLionel Sambuc   }
663*0a6a1f1dSLionel Sambuc   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
664*0a6a1f1dSLionel Sambuc     return llvm::make_unique<ComplexExpansion>(CT->getElementType());
665*0a6a1f1dSLionel Sambuc   }
666*0a6a1f1dSLionel Sambuc   return llvm::make_unique<NoExpansion>();
667*0a6a1f1dSLionel Sambuc }
668*0a6a1f1dSLionel Sambuc 
getExpansionSize(QualType Ty,const ASTContext & Context)669*0a6a1f1dSLionel Sambuc static int getExpansionSize(QualType Ty, const ASTContext &Context) {
670*0a6a1f1dSLionel Sambuc   auto Exp = getTypeExpansion(Ty, Context);
671*0a6a1f1dSLionel Sambuc   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
672*0a6a1f1dSLionel Sambuc     return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
673*0a6a1f1dSLionel Sambuc   }
674*0a6a1f1dSLionel Sambuc   if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
675*0a6a1f1dSLionel Sambuc     int Res = 0;
676*0a6a1f1dSLionel Sambuc     for (auto BS : RExp->Bases)
677*0a6a1f1dSLionel Sambuc       Res += getExpansionSize(BS->getType(), Context);
678*0a6a1f1dSLionel Sambuc     for (auto FD : RExp->Fields)
679*0a6a1f1dSLionel Sambuc       Res += getExpansionSize(FD->getType(), Context);
680*0a6a1f1dSLionel Sambuc     return Res;
681*0a6a1f1dSLionel Sambuc   }
682*0a6a1f1dSLionel Sambuc   if (isa<ComplexExpansion>(Exp.get()))
683*0a6a1f1dSLionel Sambuc     return 2;
684*0a6a1f1dSLionel Sambuc   assert(isa<NoExpansion>(Exp.get()));
685*0a6a1f1dSLionel Sambuc   return 1;
686*0a6a1f1dSLionel Sambuc }
687*0a6a1f1dSLionel Sambuc 
688*0a6a1f1dSLionel Sambuc void
getExpandedTypes(QualType Ty,SmallVectorImpl<llvm::Type * >::iterator & TI)689*0a6a1f1dSLionel Sambuc CodeGenTypes::getExpandedTypes(QualType Ty,
690*0a6a1f1dSLionel Sambuc                                SmallVectorImpl<llvm::Type *>::iterator &TI) {
691*0a6a1f1dSLionel Sambuc   auto Exp = getTypeExpansion(Ty, Context);
692*0a6a1f1dSLionel Sambuc   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
693*0a6a1f1dSLionel Sambuc     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
694*0a6a1f1dSLionel Sambuc       getExpandedTypes(CAExp->EltTy, TI);
695*0a6a1f1dSLionel Sambuc     }
696*0a6a1f1dSLionel Sambuc   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
697*0a6a1f1dSLionel Sambuc     for (auto BS : RExp->Bases)
698*0a6a1f1dSLionel Sambuc       getExpandedTypes(BS->getType(), TI);
699*0a6a1f1dSLionel Sambuc     for (auto FD : RExp->Fields)
700*0a6a1f1dSLionel Sambuc       getExpandedTypes(FD->getType(), TI);
701*0a6a1f1dSLionel Sambuc   } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
702*0a6a1f1dSLionel Sambuc     llvm::Type *EltTy = ConvertType(CExp->EltTy);
703*0a6a1f1dSLionel Sambuc     *TI++ = EltTy;
704*0a6a1f1dSLionel Sambuc     *TI++ = EltTy;
705*0a6a1f1dSLionel Sambuc   } else {
706*0a6a1f1dSLionel Sambuc     assert(isa<NoExpansion>(Exp.get()));
707*0a6a1f1dSLionel Sambuc     *TI++ = ConvertType(Ty);
708*0a6a1f1dSLionel Sambuc   }
709*0a6a1f1dSLionel Sambuc }
710*0a6a1f1dSLionel Sambuc 
ExpandTypeFromArgs(QualType Ty,LValue LV,SmallVectorImpl<llvm::Argument * >::iterator & AI)711*0a6a1f1dSLionel Sambuc void CodeGenFunction::ExpandTypeFromArgs(
712*0a6a1f1dSLionel Sambuc     QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
713f4a2713aSLionel Sambuc   assert(LV.isSimple() &&
714f4a2713aSLionel Sambuc          "Unexpected non-simple lvalue during struct expansion.");
715f4a2713aSLionel Sambuc 
716*0a6a1f1dSLionel Sambuc   auto Exp = getTypeExpansion(Ty, getContext());
717*0a6a1f1dSLionel Sambuc   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
718*0a6a1f1dSLionel Sambuc     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
719*0a6a1f1dSLionel Sambuc       llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
720*0a6a1f1dSLionel Sambuc       LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
721*0a6a1f1dSLionel Sambuc       ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
722f4a2713aSLionel Sambuc     }
723*0a6a1f1dSLionel Sambuc   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
724*0a6a1f1dSLionel Sambuc     llvm::Value *This = LV.getAddress();
725*0a6a1f1dSLionel Sambuc     for (const CXXBaseSpecifier *BS : RExp->Bases) {
726*0a6a1f1dSLionel Sambuc       // Perform a single step derived-to-base conversion.
727*0a6a1f1dSLionel Sambuc       llvm::Value *Base =
728*0a6a1f1dSLionel Sambuc           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
729*0a6a1f1dSLionel Sambuc                                 /*NullCheckValue=*/false, SourceLocation());
730*0a6a1f1dSLionel Sambuc       LValue SubLV = MakeAddrLValue(Base, BS->getType());
731f4a2713aSLionel Sambuc 
732*0a6a1f1dSLionel Sambuc       // Recurse onto bases.
733*0a6a1f1dSLionel Sambuc       ExpandTypeFromArgs(BS->getType(), SubLV, AI);
734f4a2713aSLionel Sambuc     }
735*0a6a1f1dSLionel Sambuc     for (auto FD : RExp->Fields) {
736f4a2713aSLionel Sambuc       // FIXME: What are the right qualifiers here?
737f4a2713aSLionel Sambuc       LValue SubLV = EmitLValueForField(LV, FD);
738*0a6a1f1dSLionel Sambuc       ExpandTypeFromArgs(FD->getType(), SubLV, AI);
739f4a2713aSLionel Sambuc     }
740*0a6a1f1dSLionel Sambuc   } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
741f4a2713aSLionel Sambuc     llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
742*0a6a1f1dSLionel Sambuc     EmitStoreThroughLValue(RValue::get(*AI++),
743*0a6a1f1dSLionel Sambuc                            MakeAddrLValue(RealAddr, CExp->EltTy));
744f4a2713aSLionel Sambuc     llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
745*0a6a1f1dSLionel Sambuc     EmitStoreThroughLValue(RValue::get(*AI++),
746*0a6a1f1dSLionel Sambuc                            MakeAddrLValue(ImagAddr, CExp->EltTy));
747f4a2713aSLionel Sambuc   } else {
748*0a6a1f1dSLionel Sambuc     assert(isa<NoExpansion>(Exp.get()));
749*0a6a1f1dSLionel Sambuc     EmitStoreThroughLValue(RValue::get(*AI++), LV);
750*0a6a1f1dSLionel Sambuc   }
751f4a2713aSLionel Sambuc }
752f4a2713aSLionel Sambuc 
ExpandTypeToArgs(QualType Ty,RValue RV,llvm::FunctionType * IRFuncTy,SmallVectorImpl<llvm::Value * > & IRCallArgs,unsigned & IRCallArgPos)753*0a6a1f1dSLionel Sambuc void CodeGenFunction::ExpandTypeToArgs(
754*0a6a1f1dSLionel Sambuc     QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
755*0a6a1f1dSLionel Sambuc     SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
756*0a6a1f1dSLionel Sambuc   auto Exp = getTypeExpansion(Ty, getContext());
757*0a6a1f1dSLionel Sambuc   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
758*0a6a1f1dSLionel Sambuc     llvm::Value *Addr = RV.getAggregateAddr();
759*0a6a1f1dSLionel Sambuc     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
760*0a6a1f1dSLionel Sambuc       llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
761*0a6a1f1dSLionel Sambuc       RValue EltRV =
762*0a6a1f1dSLionel Sambuc           convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
763*0a6a1f1dSLionel Sambuc       ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
764*0a6a1f1dSLionel Sambuc     }
765*0a6a1f1dSLionel Sambuc   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
766*0a6a1f1dSLionel Sambuc     llvm::Value *This = RV.getAggregateAddr();
767*0a6a1f1dSLionel Sambuc     for (const CXXBaseSpecifier *BS : RExp->Bases) {
768*0a6a1f1dSLionel Sambuc       // Perform a single step derived-to-base conversion.
769*0a6a1f1dSLionel Sambuc       llvm::Value *Base =
770*0a6a1f1dSLionel Sambuc           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
771*0a6a1f1dSLionel Sambuc                                 /*NullCheckValue=*/false, SourceLocation());
772*0a6a1f1dSLionel Sambuc       RValue BaseRV = RValue::getAggregate(Base);
773*0a6a1f1dSLionel Sambuc 
774*0a6a1f1dSLionel Sambuc       // Recurse onto bases.
775*0a6a1f1dSLionel Sambuc       ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
776*0a6a1f1dSLionel Sambuc                        IRCallArgPos);
777*0a6a1f1dSLionel Sambuc     }
778*0a6a1f1dSLionel Sambuc 
779*0a6a1f1dSLionel Sambuc     LValue LV = MakeAddrLValue(This, Ty);
780*0a6a1f1dSLionel Sambuc     for (auto FD : RExp->Fields) {
781*0a6a1f1dSLionel Sambuc       RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
782*0a6a1f1dSLionel Sambuc       ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
783*0a6a1f1dSLionel Sambuc                        IRCallArgPos);
784*0a6a1f1dSLionel Sambuc     }
785*0a6a1f1dSLionel Sambuc   } else if (isa<ComplexExpansion>(Exp.get())) {
786*0a6a1f1dSLionel Sambuc     ComplexPairTy CV = RV.getComplexVal();
787*0a6a1f1dSLionel Sambuc     IRCallArgs[IRCallArgPos++] = CV.first;
788*0a6a1f1dSLionel Sambuc     IRCallArgs[IRCallArgPos++] = CV.second;
789*0a6a1f1dSLionel Sambuc   } else {
790*0a6a1f1dSLionel Sambuc     assert(isa<NoExpansion>(Exp.get()));
791*0a6a1f1dSLionel Sambuc     assert(RV.isScalar() &&
792*0a6a1f1dSLionel Sambuc            "Unexpected non-scalar rvalue during struct expansion.");
793*0a6a1f1dSLionel Sambuc 
794*0a6a1f1dSLionel Sambuc     // Insert a bitcast as needed.
795*0a6a1f1dSLionel Sambuc     llvm::Value *V = RV.getScalarVal();
796*0a6a1f1dSLionel Sambuc     if (IRCallArgPos < IRFuncTy->getNumParams() &&
797*0a6a1f1dSLionel Sambuc         V->getType() != IRFuncTy->getParamType(IRCallArgPos))
798*0a6a1f1dSLionel Sambuc       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
799*0a6a1f1dSLionel Sambuc 
800*0a6a1f1dSLionel Sambuc     IRCallArgs[IRCallArgPos++] = V;
801*0a6a1f1dSLionel Sambuc   }
802f4a2713aSLionel Sambuc }
803f4a2713aSLionel Sambuc 
804f4a2713aSLionel Sambuc /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
805f4a2713aSLionel Sambuc /// accessing some number of bytes out of it, try to gep into the struct to get
806f4a2713aSLionel Sambuc /// at its inner goodness.  Dive as deep as possible without entering an element
807f4a2713aSLionel Sambuc /// with an in-memory size smaller than DstSize.
808f4a2713aSLionel Sambuc static llvm::Value *
EnterStructPointerForCoercedAccess(llvm::Value * SrcPtr,llvm::StructType * SrcSTy,uint64_t DstSize,CodeGenFunction & CGF)809f4a2713aSLionel Sambuc EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
810f4a2713aSLionel Sambuc                                    llvm::StructType *SrcSTy,
811f4a2713aSLionel Sambuc                                    uint64_t DstSize, CodeGenFunction &CGF) {
812f4a2713aSLionel Sambuc   // We can't dive into a zero-element struct.
813f4a2713aSLionel Sambuc   if (SrcSTy->getNumElements() == 0) return SrcPtr;
814f4a2713aSLionel Sambuc 
815f4a2713aSLionel Sambuc   llvm::Type *FirstElt = SrcSTy->getElementType(0);
816f4a2713aSLionel Sambuc 
817f4a2713aSLionel Sambuc   // If the first elt is at least as large as what we're looking for, or if the
818*0a6a1f1dSLionel Sambuc   // first element is the same size as the whole struct, we can enter it. The
819*0a6a1f1dSLionel Sambuc   // comparison must be made on the store size and not the alloca size. Using
820*0a6a1f1dSLionel Sambuc   // the alloca size may overstate the size of the load.
821f4a2713aSLionel Sambuc   uint64_t FirstEltSize =
822*0a6a1f1dSLionel Sambuc     CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
823f4a2713aSLionel Sambuc   if (FirstEltSize < DstSize &&
824*0a6a1f1dSLionel Sambuc       FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
825f4a2713aSLionel Sambuc     return SrcPtr;
826f4a2713aSLionel Sambuc 
827f4a2713aSLionel Sambuc   // GEP into the first element.
828f4a2713aSLionel Sambuc   SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
829f4a2713aSLionel Sambuc 
830f4a2713aSLionel Sambuc   // If the first element is a struct, recurse.
831f4a2713aSLionel Sambuc   llvm::Type *SrcTy =
832f4a2713aSLionel Sambuc     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
833f4a2713aSLionel Sambuc   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
834f4a2713aSLionel Sambuc     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
835f4a2713aSLionel Sambuc 
836f4a2713aSLionel Sambuc   return SrcPtr;
837f4a2713aSLionel Sambuc }
838f4a2713aSLionel Sambuc 
839f4a2713aSLionel Sambuc /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
840f4a2713aSLionel Sambuc /// are either integers or pointers.  This does a truncation of the value if it
841f4a2713aSLionel Sambuc /// is too large or a zero extension if it is too small.
842f4a2713aSLionel Sambuc ///
843f4a2713aSLionel Sambuc /// This behaves as if the value were coerced through memory, so on big-endian
844f4a2713aSLionel Sambuc /// targets the high bits are preserved in a truncation, while little-endian
845f4a2713aSLionel Sambuc /// targets preserve the low bits.
CoerceIntOrPtrToIntOrPtr(llvm::Value * Val,llvm::Type * Ty,CodeGenFunction & CGF)846f4a2713aSLionel Sambuc static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
847f4a2713aSLionel Sambuc                                              llvm::Type *Ty,
848f4a2713aSLionel Sambuc                                              CodeGenFunction &CGF) {
849f4a2713aSLionel Sambuc   if (Val->getType() == Ty)
850f4a2713aSLionel Sambuc     return Val;
851f4a2713aSLionel Sambuc 
852f4a2713aSLionel Sambuc   if (isa<llvm::PointerType>(Val->getType())) {
853f4a2713aSLionel Sambuc     // If this is Pointer->Pointer avoid conversion to and from int.
854f4a2713aSLionel Sambuc     if (isa<llvm::PointerType>(Ty))
855f4a2713aSLionel Sambuc       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
856f4a2713aSLionel Sambuc 
857f4a2713aSLionel Sambuc     // Convert the pointer to an integer so we can play with its width.
858f4a2713aSLionel Sambuc     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
859f4a2713aSLionel Sambuc   }
860f4a2713aSLionel Sambuc 
861f4a2713aSLionel Sambuc   llvm::Type *DestIntTy = Ty;
862f4a2713aSLionel Sambuc   if (isa<llvm::PointerType>(DestIntTy))
863f4a2713aSLionel Sambuc     DestIntTy = CGF.IntPtrTy;
864f4a2713aSLionel Sambuc 
865f4a2713aSLionel Sambuc   if (Val->getType() != DestIntTy) {
866f4a2713aSLionel Sambuc     const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
867f4a2713aSLionel Sambuc     if (DL.isBigEndian()) {
868f4a2713aSLionel Sambuc       // Preserve the high bits on big-endian targets.
869f4a2713aSLionel Sambuc       // That is what memory coercion does.
870*0a6a1f1dSLionel Sambuc       uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
871*0a6a1f1dSLionel Sambuc       uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
872*0a6a1f1dSLionel Sambuc 
873f4a2713aSLionel Sambuc       if (SrcSize > DstSize) {
874f4a2713aSLionel Sambuc         Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
875f4a2713aSLionel Sambuc         Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
876f4a2713aSLionel Sambuc       } else {
877f4a2713aSLionel Sambuc         Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
878f4a2713aSLionel Sambuc         Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
879f4a2713aSLionel Sambuc       }
880f4a2713aSLionel Sambuc     } else {
881f4a2713aSLionel Sambuc       // Little-endian targets preserve the low bits. No shifts required.
882f4a2713aSLionel Sambuc       Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
883f4a2713aSLionel Sambuc     }
884f4a2713aSLionel Sambuc   }
885f4a2713aSLionel Sambuc 
886f4a2713aSLionel Sambuc   if (isa<llvm::PointerType>(Ty))
887f4a2713aSLionel Sambuc     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
888f4a2713aSLionel Sambuc   return Val;
889f4a2713aSLionel Sambuc }
890f4a2713aSLionel Sambuc 
891f4a2713aSLionel Sambuc 
892f4a2713aSLionel Sambuc 
893f4a2713aSLionel Sambuc /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
894f4a2713aSLionel Sambuc /// a pointer to an object of type \arg Ty.
895f4a2713aSLionel Sambuc ///
896f4a2713aSLionel Sambuc /// This safely handles the case when the src type is smaller than the
897f4a2713aSLionel Sambuc /// destination type; in this situation the values of bits which not
898f4a2713aSLionel Sambuc /// present in the src are undefined.
CreateCoercedLoad(llvm::Value * SrcPtr,llvm::Type * Ty,CodeGenFunction & CGF)899f4a2713aSLionel Sambuc static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
900f4a2713aSLionel Sambuc                                       llvm::Type *Ty,
901f4a2713aSLionel Sambuc                                       CodeGenFunction &CGF) {
902f4a2713aSLionel Sambuc   llvm::Type *SrcTy =
903f4a2713aSLionel Sambuc     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
904f4a2713aSLionel Sambuc 
905f4a2713aSLionel Sambuc   // If SrcTy and Ty are the same, just do a load.
906f4a2713aSLionel Sambuc   if (SrcTy == Ty)
907f4a2713aSLionel Sambuc     return CGF.Builder.CreateLoad(SrcPtr);
908f4a2713aSLionel Sambuc 
909f4a2713aSLionel Sambuc   uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
910f4a2713aSLionel Sambuc 
911f4a2713aSLionel Sambuc   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
912f4a2713aSLionel Sambuc     SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
913f4a2713aSLionel Sambuc     SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
914f4a2713aSLionel Sambuc   }
915f4a2713aSLionel Sambuc 
916f4a2713aSLionel Sambuc   uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
917f4a2713aSLionel Sambuc 
918f4a2713aSLionel Sambuc   // If the source and destination are integer or pointer types, just do an
919f4a2713aSLionel Sambuc   // extension or truncation to the desired type.
920f4a2713aSLionel Sambuc   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
921f4a2713aSLionel Sambuc       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
922f4a2713aSLionel Sambuc     llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
923f4a2713aSLionel Sambuc     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
924f4a2713aSLionel Sambuc   }
925f4a2713aSLionel Sambuc 
926f4a2713aSLionel Sambuc   // If load is legal, just bitcast the src pointer.
927f4a2713aSLionel Sambuc   if (SrcSize >= DstSize) {
928f4a2713aSLionel Sambuc     // Generally SrcSize is never greater than DstSize, since this means we are
929f4a2713aSLionel Sambuc     // losing bits. However, this can happen in cases where the structure has
930f4a2713aSLionel Sambuc     // additional padding, for example due to a user specified alignment.
931f4a2713aSLionel Sambuc     //
932f4a2713aSLionel Sambuc     // FIXME: Assert that we aren't truncating non-padding bits when have access
933f4a2713aSLionel Sambuc     // to that information.
934f4a2713aSLionel Sambuc     llvm::Value *Casted =
935f4a2713aSLionel Sambuc       CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
936f4a2713aSLionel Sambuc     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
937f4a2713aSLionel Sambuc     // FIXME: Use better alignment / avoid requiring aligned load.
938f4a2713aSLionel Sambuc     Load->setAlignment(1);
939f4a2713aSLionel Sambuc     return Load;
940f4a2713aSLionel Sambuc   }
941f4a2713aSLionel Sambuc 
942f4a2713aSLionel Sambuc   // Otherwise do coercion through memory. This is stupid, but
943f4a2713aSLionel Sambuc   // simple.
944f4a2713aSLionel Sambuc   llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
945f4a2713aSLionel Sambuc   llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
946f4a2713aSLionel Sambuc   llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
947f4a2713aSLionel Sambuc   llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
948f4a2713aSLionel Sambuc   // FIXME: Use better alignment.
949f4a2713aSLionel Sambuc   CGF.Builder.CreateMemCpy(Casted, SrcCasted,
950f4a2713aSLionel Sambuc       llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
951f4a2713aSLionel Sambuc       1, false);
952f4a2713aSLionel Sambuc   return CGF.Builder.CreateLoad(Tmp);
953f4a2713aSLionel Sambuc }
954f4a2713aSLionel Sambuc 
955f4a2713aSLionel Sambuc // Function to store a first-class aggregate into memory.  We prefer to
956f4a2713aSLionel Sambuc // store the elements rather than the aggregate to be more friendly to
957f4a2713aSLionel Sambuc // fast-isel.
958f4a2713aSLionel Sambuc // FIXME: Do we need to recurse here?
BuildAggStore(CodeGenFunction & CGF,llvm::Value * Val,llvm::Value * DestPtr,bool DestIsVolatile,bool LowAlignment)959f4a2713aSLionel Sambuc static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
960f4a2713aSLionel Sambuc                           llvm::Value *DestPtr, bool DestIsVolatile,
961f4a2713aSLionel Sambuc                           bool LowAlignment) {
962f4a2713aSLionel Sambuc   // Prefer scalar stores to first-class aggregate stores.
963f4a2713aSLionel Sambuc   if (llvm::StructType *STy =
964f4a2713aSLionel Sambuc         dyn_cast<llvm::StructType>(Val->getType())) {
965f4a2713aSLionel Sambuc     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
966f4a2713aSLionel Sambuc       llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
967f4a2713aSLionel Sambuc       llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
968f4a2713aSLionel Sambuc       llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
969f4a2713aSLionel Sambuc                                                     DestIsVolatile);
970f4a2713aSLionel Sambuc       if (LowAlignment)
971f4a2713aSLionel Sambuc         SI->setAlignment(1);
972f4a2713aSLionel Sambuc     }
973f4a2713aSLionel Sambuc   } else {
974f4a2713aSLionel Sambuc     llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
975f4a2713aSLionel Sambuc     if (LowAlignment)
976f4a2713aSLionel Sambuc       SI->setAlignment(1);
977f4a2713aSLionel Sambuc   }
978f4a2713aSLionel Sambuc }
979f4a2713aSLionel Sambuc 
980f4a2713aSLionel Sambuc /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
981f4a2713aSLionel Sambuc /// where the source and destination may have different types.
982f4a2713aSLionel Sambuc ///
983f4a2713aSLionel Sambuc /// This safely handles the case when the src type is larger than the
984f4a2713aSLionel Sambuc /// destination type; the upper bits of the src will be lost.
CreateCoercedStore(llvm::Value * Src,llvm::Value * DstPtr,bool DstIsVolatile,CodeGenFunction & CGF)985f4a2713aSLionel Sambuc static void CreateCoercedStore(llvm::Value *Src,
986f4a2713aSLionel Sambuc                                llvm::Value *DstPtr,
987f4a2713aSLionel Sambuc                                bool DstIsVolatile,
988f4a2713aSLionel Sambuc                                CodeGenFunction &CGF) {
989f4a2713aSLionel Sambuc   llvm::Type *SrcTy = Src->getType();
990f4a2713aSLionel Sambuc   llvm::Type *DstTy =
991f4a2713aSLionel Sambuc     cast<llvm::PointerType>(DstPtr->getType())->getElementType();
992f4a2713aSLionel Sambuc   if (SrcTy == DstTy) {
993f4a2713aSLionel Sambuc     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
994f4a2713aSLionel Sambuc     return;
995f4a2713aSLionel Sambuc   }
996f4a2713aSLionel Sambuc 
997f4a2713aSLionel Sambuc   uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
998f4a2713aSLionel Sambuc 
999f4a2713aSLionel Sambuc   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1000f4a2713aSLionel Sambuc     DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
1001f4a2713aSLionel Sambuc     DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1002f4a2713aSLionel Sambuc   }
1003f4a2713aSLionel Sambuc 
1004f4a2713aSLionel Sambuc   // If the source and destination are integer or pointer types, just do an
1005f4a2713aSLionel Sambuc   // extension or truncation to the desired type.
1006f4a2713aSLionel Sambuc   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1007f4a2713aSLionel Sambuc       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1008f4a2713aSLionel Sambuc     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1009f4a2713aSLionel Sambuc     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1010f4a2713aSLionel Sambuc     return;
1011f4a2713aSLionel Sambuc   }
1012f4a2713aSLionel Sambuc 
1013f4a2713aSLionel Sambuc   uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1014f4a2713aSLionel Sambuc 
1015f4a2713aSLionel Sambuc   // If store is legal, just bitcast the src pointer.
1016f4a2713aSLionel Sambuc   if (SrcSize <= DstSize) {
1017f4a2713aSLionel Sambuc     llvm::Value *Casted =
1018f4a2713aSLionel Sambuc       CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
1019f4a2713aSLionel Sambuc     // FIXME: Use better alignment / avoid requiring aligned store.
1020f4a2713aSLionel Sambuc     BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
1021f4a2713aSLionel Sambuc   } else {
1022f4a2713aSLionel Sambuc     // Otherwise do coercion through memory. This is stupid, but
1023f4a2713aSLionel Sambuc     // simple.
1024f4a2713aSLionel Sambuc 
1025f4a2713aSLionel Sambuc     // Generally SrcSize is never greater than DstSize, since this means we are
1026f4a2713aSLionel Sambuc     // losing bits. However, this can happen in cases where the structure has
1027f4a2713aSLionel Sambuc     // additional padding, for example due to a user specified alignment.
1028f4a2713aSLionel Sambuc     //
1029f4a2713aSLionel Sambuc     // FIXME: Assert that we aren't truncating non-padding bits when have access
1030f4a2713aSLionel Sambuc     // to that information.
1031f4a2713aSLionel Sambuc     llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1032f4a2713aSLionel Sambuc     CGF.Builder.CreateStore(Src, Tmp);
1033f4a2713aSLionel Sambuc     llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1034f4a2713aSLionel Sambuc     llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1035f4a2713aSLionel Sambuc     llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
1036f4a2713aSLionel Sambuc     // FIXME: Use better alignment.
1037f4a2713aSLionel Sambuc     CGF.Builder.CreateMemCpy(DstCasted, Casted,
1038f4a2713aSLionel Sambuc         llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1039f4a2713aSLionel Sambuc         1, false);
1040f4a2713aSLionel Sambuc   }
1041f4a2713aSLionel Sambuc }
1042f4a2713aSLionel Sambuc 
1043*0a6a1f1dSLionel Sambuc namespace {
1044*0a6a1f1dSLionel Sambuc 
1045*0a6a1f1dSLionel Sambuc /// Encapsulates information about the way function arguments from
1046*0a6a1f1dSLionel Sambuc /// CGFunctionInfo should be passed to actual LLVM IR function.
1047*0a6a1f1dSLionel Sambuc class ClangToLLVMArgMapping {
1048*0a6a1f1dSLionel Sambuc   static const unsigned InvalidIndex = ~0U;
1049*0a6a1f1dSLionel Sambuc   unsigned InallocaArgNo;
1050*0a6a1f1dSLionel Sambuc   unsigned SRetArgNo;
1051*0a6a1f1dSLionel Sambuc   unsigned TotalIRArgs;
1052*0a6a1f1dSLionel Sambuc 
1053*0a6a1f1dSLionel Sambuc   /// Arguments of LLVM IR function corresponding to single Clang argument.
1054*0a6a1f1dSLionel Sambuc   struct IRArgs {
1055*0a6a1f1dSLionel Sambuc     unsigned PaddingArgIndex;
1056*0a6a1f1dSLionel Sambuc     // Argument is expanded to IR arguments at positions
1057*0a6a1f1dSLionel Sambuc     // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1058*0a6a1f1dSLionel Sambuc     unsigned FirstArgIndex;
1059*0a6a1f1dSLionel Sambuc     unsigned NumberOfArgs;
1060*0a6a1f1dSLionel Sambuc 
IRArgs__anon2e5bceb70211::ClangToLLVMArgMapping::IRArgs1061*0a6a1f1dSLionel Sambuc     IRArgs()
1062*0a6a1f1dSLionel Sambuc         : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1063*0a6a1f1dSLionel Sambuc           NumberOfArgs(0) {}
1064*0a6a1f1dSLionel Sambuc   };
1065*0a6a1f1dSLionel Sambuc 
1066*0a6a1f1dSLionel Sambuc   SmallVector<IRArgs, 8> ArgInfo;
1067*0a6a1f1dSLionel Sambuc 
1068*0a6a1f1dSLionel Sambuc public:
ClangToLLVMArgMapping(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs=false)1069*0a6a1f1dSLionel Sambuc   ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1070*0a6a1f1dSLionel Sambuc                         bool OnlyRequiredArgs = false)
1071*0a6a1f1dSLionel Sambuc       : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1072*0a6a1f1dSLionel Sambuc         ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1073*0a6a1f1dSLionel Sambuc     construct(Context, FI, OnlyRequiredArgs);
1074*0a6a1f1dSLionel Sambuc   }
1075*0a6a1f1dSLionel Sambuc 
hasInallocaArg() const1076*0a6a1f1dSLionel Sambuc   bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
getInallocaArgNo() const1077*0a6a1f1dSLionel Sambuc   unsigned getInallocaArgNo() const {
1078*0a6a1f1dSLionel Sambuc     assert(hasInallocaArg());
1079*0a6a1f1dSLionel Sambuc     return InallocaArgNo;
1080*0a6a1f1dSLionel Sambuc   }
1081*0a6a1f1dSLionel Sambuc 
hasSRetArg() const1082*0a6a1f1dSLionel Sambuc   bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
getSRetArgNo() const1083*0a6a1f1dSLionel Sambuc   unsigned getSRetArgNo() const {
1084*0a6a1f1dSLionel Sambuc     assert(hasSRetArg());
1085*0a6a1f1dSLionel Sambuc     return SRetArgNo;
1086*0a6a1f1dSLionel Sambuc   }
1087*0a6a1f1dSLionel Sambuc 
totalIRArgs() const1088*0a6a1f1dSLionel Sambuc   unsigned totalIRArgs() const { return TotalIRArgs; }
1089*0a6a1f1dSLionel Sambuc 
hasPaddingArg(unsigned ArgNo) const1090*0a6a1f1dSLionel Sambuc   bool hasPaddingArg(unsigned ArgNo) const {
1091*0a6a1f1dSLionel Sambuc     assert(ArgNo < ArgInfo.size());
1092*0a6a1f1dSLionel Sambuc     return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1093*0a6a1f1dSLionel Sambuc   }
getPaddingArgNo(unsigned ArgNo) const1094*0a6a1f1dSLionel Sambuc   unsigned getPaddingArgNo(unsigned ArgNo) const {
1095*0a6a1f1dSLionel Sambuc     assert(hasPaddingArg(ArgNo));
1096*0a6a1f1dSLionel Sambuc     return ArgInfo[ArgNo].PaddingArgIndex;
1097*0a6a1f1dSLionel Sambuc   }
1098*0a6a1f1dSLionel Sambuc 
1099*0a6a1f1dSLionel Sambuc   /// Returns index of first IR argument corresponding to ArgNo, and their
1100*0a6a1f1dSLionel Sambuc   /// quantity.
getIRArgs(unsigned ArgNo) const1101*0a6a1f1dSLionel Sambuc   std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1102*0a6a1f1dSLionel Sambuc     assert(ArgNo < ArgInfo.size());
1103*0a6a1f1dSLionel Sambuc     return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1104*0a6a1f1dSLionel Sambuc                           ArgInfo[ArgNo].NumberOfArgs);
1105*0a6a1f1dSLionel Sambuc   }
1106*0a6a1f1dSLionel Sambuc 
1107*0a6a1f1dSLionel Sambuc private:
1108*0a6a1f1dSLionel Sambuc   void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1109*0a6a1f1dSLionel Sambuc                  bool OnlyRequiredArgs);
1110*0a6a1f1dSLionel Sambuc };
1111*0a6a1f1dSLionel Sambuc 
construct(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs)1112*0a6a1f1dSLionel Sambuc void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1113*0a6a1f1dSLionel Sambuc                                       const CGFunctionInfo &FI,
1114*0a6a1f1dSLionel Sambuc                                       bool OnlyRequiredArgs) {
1115*0a6a1f1dSLionel Sambuc   unsigned IRArgNo = 0;
1116*0a6a1f1dSLionel Sambuc   bool SwapThisWithSRet = false;
1117*0a6a1f1dSLionel Sambuc   const ABIArgInfo &RetAI = FI.getReturnInfo();
1118*0a6a1f1dSLionel Sambuc 
1119*0a6a1f1dSLionel Sambuc   if (RetAI.getKind() == ABIArgInfo::Indirect) {
1120*0a6a1f1dSLionel Sambuc     SwapThisWithSRet = RetAI.isSRetAfterThis();
1121*0a6a1f1dSLionel Sambuc     SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1122*0a6a1f1dSLionel Sambuc   }
1123*0a6a1f1dSLionel Sambuc 
1124*0a6a1f1dSLionel Sambuc   unsigned ArgNo = 0;
1125*0a6a1f1dSLionel Sambuc   unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1126*0a6a1f1dSLionel Sambuc   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1127*0a6a1f1dSLionel Sambuc        ++I, ++ArgNo) {
1128*0a6a1f1dSLionel Sambuc     assert(I != FI.arg_end());
1129*0a6a1f1dSLionel Sambuc     QualType ArgType = I->type;
1130*0a6a1f1dSLionel Sambuc     const ABIArgInfo &AI = I->info;
1131*0a6a1f1dSLionel Sambuc     // Collect data about IR arguments corresponding to Clang argument ArgNo.
1132*0a6a1f1dSLionel Sambuc     auto &IRArgs = ArgInfo[ArgNo];
1133*0a6a1f1dSLionel Sambuc 
1134*0a6a1f1dSLionel Sambuc     if (AI.getPaddingType())
1135*0a6a1f1dSLionel Sambuc       IRArgs.PaddingArgIndex = IRArgNo++;
1136*0a6a1f1dSLionel Sambuc 
1137*0a6a1f1dSLionel Sambuc     switch (AI.getKind()) {
1138*0a6a1f1dSLionel Sambuc     case ABIArgInfo::Extend:
1139*0a6a1f1dSLionel Sambuc     case ABIArgInfo::Direct: {
1140*0a6a1f1dSLionel Sambuc       // FIXME: handle sseregparm someday...
1141*0a6a1f1dSLionel Sambuc       llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1142*0a6a1f1dSLionel Sambuc       if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1143*0a6a1f1dSLionel Sambuc         IRArgs.NumberOfArgs = STy->getNumElements();
1144*0a6a1f1dSLionel Sambuc       } else {
1145*0a6a1f1dSLionel Sambuc         IRArgs.NumberOfArgs = 1;
1146*0a6a1f1dSLionel Sambuc       }
1147*0a6a1f1dSLionel Sambuc       break;
1148*0a6a1f1dSLionel Sambuc     }
1149*0a6a1f1dSLionel Sambuc     case ABIArgInfo::Indirect:
1150*0a6a1f1dSLionel Sambuc       IRArgs.NumberOfArgs = 1;
1151*0a6a1f1dSLionel Sambuc       break;
1152*0a6a1f1dSLionel Sambuc     case ABIArgInfo::Ignore:
1153*0a6a1f1dSLionel Sambuc     case ABIArgInfo::InAlloca:
1154*0a6a1f1dSLionel Sambuc       // ignore and inalloca doesn't have matching LLVM parameters.
1155*0a6a1f1dSLionel Sambuc       IRArgs.NumberOfArgs = 0;
1156*0a6a1f1dSLionel Sambuc       break;
1157*0a6a1f1dSLionel Sambuc     case ABIArgInfo::Expand: {
1158*0a6a1f1dSLionel Sambuc       IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1159*0a6a1f1dSLionel Sambuc       break;
1160*0a6a1f1dSLionel Sambuc     }
1161*0a6a1f1dSLionel Sambuc     }
1162*0a6a1f1dSLionel Sambuc 
1163*0a6a1f1dSLionel Sambuc     if (IRArgs.NumberOfArgs > 0) {
1164*0a6a1f1dSLionel Sambuc       IRArgs.FirstArgIndex = IRArgNo;
1165*0a6a1f1dSLionel Sambuc       IRArgNo += IRArgs.NumberOfArgs;
1166*0a6a1f1dSLionel Sambuc     }
1167*0a6a1f1dSLionel Sambuc 
1168*0a6a1f1dSLionel Sambuc     // Skip over the sret parameter when it comes second.  We already handled it
1169*0a6a1f1dSLionel Sambuc     // above.
1170*0a6a1f1dSLionel Sambuc     if (IRArgNo == 1 && SwapThisWithSRet)
1171*0a6a1f1dSLionel Sambuc       IRArgNo++;
1172*0a6a1f1dSLionel Sambuc   }
1173*0a6a1f1dSLionel Sambuc   assert(ArgNo == ArgInfo.size());
1174*0a6a1f1dSLionel Sambuc 
1175*0a6a1f1dSLionel Sambuc   if (FI.usesInAlloca())
1176*0a6a1f1dSLionel Sambuc     InallocaArgNo = IRArgNo++;
1177*0a6a1f1dSLionel Sambuc 
1178*0a6a1f1dSLionel Sambuc   TotalIRArgs = IRArgNo;
1179*0a6a1f1dSLionel Sambuc }
1180*0a6a1f1dSLionel Sambuc }  // namespace
1181*0a6a1f1dSLionel Sambuc 
1182f4a2713aSLionel Sambuc /***/
1183f4a2713aSLionel Sambuc 
ReturnTypeUsesSRet(const CGFunctionInfo & FI)1184f4a2713aSLionel Sambuc bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1185f4a2713aSLionel Sambuc   return FI.getReturnInfo().isIndirect();
1186f4a2713aSLionel Sambuc }
1187f4a2713aSLionel Sambuc 
ReturnSlotInterferesWithArgs(const CGFunctionInfo & FI)1188*0a6a1f1dSLionel Sambuc bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1189*0a6a1f1dSLionel Sambuc   return ReturnTypeUsesSRet(FI) &&
1190*0a6a1f1dSLionel Sambuc          getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1191*0a6a1f1dSLionel Sambuc }
1192*0a6a1f1dSLionel Sambuc 
ReturnTypeUsesFPRet(QualType ResultType)1193f4a2713aSLionel Sambuc bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1194f4a2713aSLionel Sambuc   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1195f4a2713aSLionel Sambuc     switch (BT->getKind()) {
1196f4a2713aSLionel Sambuc     default:
1197f4a2713aSLionel Sambuc       return false;
1198f4a2713aSLionel Sambuc     case BuiltinType::Float:
1199f4a2713aSLionel Sambuc       return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
1200f4a2713aSLionel Sambuc     case BuiltinType::Double:
1201f4a2713aSLionel Sambuc       return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
1202f4a2713aSLionel Sambuc     case BuiltinType::LongDouble:
1203f4a2713aSLionel Sambuc       return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
1204f4a2713aSLionel Sambuc     }
1205f4a2713aSLionel Sambuc   }
1206f4a2713aSLionel Sambuc 
1207f4a2713aSLionel Sambuc   return false;
1208f4a2713aSLionel Sambuc }
1209f4a2713aSLionel Sambuc 
ReturnTypeUsesFP2Ret(QualType ResultType)1210f4a2713aSLionel Sambuc bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1211f4a2713aSLionel Sambuc   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1212f4a2713aSLionel Sambuc     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1213f4a2713aSLionel Sambuc       if (BT->getKind() == BuiltinType::LongDouble)
1214f4a2713aSLionel Sambuc         return getTarget().useObjCFP2RetForComplexLongDouble();
1215f4a2713aSLionel Sambuc     }
1216f4a2713aSLionel Sambuc   }
1217f4a2713aSLionel Sambuc 
1218f4a2713aSLionel Sambuc   return false;
1219f4a2713aSLionel Sambuc }
1220f4a2713aSLionel Sambuc 
GetFunctionType(GlobalDecl GD)1221f4a2713aSLionel Sambuc llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1222f4a2713aSLionel Sambuc   const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1223f4a2713aSLionel Sambuc   return GetFunctionType(FI);
1224f4a2713aSLionel Sambuc }
1225f4a2713aSLionel Sambuc 
1226f4a2713aSLionel Sambuc llvm::FunctionType *
GetFunctionType(const CGFunctionInfo & FI)1227f4a2713aSLionel Sambuc CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1228f4a2713aSLionel Sambuc 
1229*0a6a1f1dSLionel Sambuc   bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1230*0a6a1f1dSLionel Sambuc   (void)Inserted;
1231f4a2713aSLionel Sambuc   assert(Inserted && "Recursively being processed?");
1232f4a2713aSLionel Sambuc 
1233*0a6a1f1dSLionel Sambuc   llvm::Type *resultType = nullptr;
1234f4a2713aSLionel Sambuc   const ABIArgInfo &retAI = FI.getReturnInfo();
1235f4a2713aSLionel Sambuc   switch (retAI.getKind()) {
1236f4a2713aSLionel Sambuc   case ABIArgInfo::Expand:
1237f4a2713aSLionel Sambuc     llvm_unreachable("Invalid ABI kind for return argument");
1238f4a2713aSLionel Sambuc 
1239f4a2713aSLionel Sambuc   case ABIArgInfo::Extend:
1240f4a2713aSLionel Sambuc   case ABIArgInfo::Direct:
1241f4a2713aSLionel Sambuc     resultType = retAI.getCoerceToType();
1242f4a2713aSLionel Sambuc     break;
1243f4a2713aSLionel Sambuc 
1244*0a6a1f1dSLionel Sambuc   case ABIArgInfo::InAlloca:
1245*0a6a1f1dSLionel Sambuc     if (retAI.getInAllocaSRet()) {
1246*0a6a1f1dSLionel Sambuc       // sret things on win32 aren't void, they return the sret pointer.
1247f4a2713aSLionel Sambuc       QualType ret = FI.getReturnType();
1248f4a2713aSLionel Sambuc       llvm::Type *ty = ConvertType(ret);
1249f4a2713aSLionel Sambuc       unsigned addressSpace = Context.getTargetAddressSpace(ret);
1250*0a6a1f1dSLionel Sambuc       resultType = llvm::PointerType::get(ty, addressSpace);
1251*0a6a1f1dSLionel Sambuc     } else {
1252*0a6a1f1dSLionel Sambuc       resultType = llvm::Type::getVoidTy(getLLVMContext());
1253*0a6a1f1dSLionel Sambuc     }
1254*0a6a1f1dSLionel Sambuc     break;
1255*0a6a1f1dSLionel Sambuc 
1256*0a6a1f1dSLionel Sambuc   case ABIArgInfo::Indirect: {
1257*0a6a1f1dSLionel Sambuc     assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1258*0a6a1f1dSLionel Sambuc     resultType = llvm::Type::getVoidTy(getLLVMContext());
1259f4a2713aSLionel Sambuc     break;
1260f4a2713aSLionel Sambuc   }
1261f4a2713aSLionel Sambuc 
1262f4a2713aSLionel Sambuc   case ABIArgInfo::Ignore:
1263f4a2713aSLionel Sambuc     resultType = llvm::Type::getVoidTy(getLLVMContext());
1264f4a2713aSLionel Sambuc     break;
1265f4a2713aSLionel Sambuc   }
1266f4a2713aSLionel Sambuc 
1267*0a6a1f1dSLionel Sambuc   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1268*0a6a1f1dSLionel Sambuc   SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1269*0a6a1f1dSLionel Sambuc 
1270*0a6a1f1dSLionel Sambuc   // Add type for sret argument.
1271*0a6a1f1dSLionel Sambuc   if (IRFunctionArgs.hasSRetArg()) {
1272*0a6a1f1dSLionel Sambuc     QualType Ret = FI.getReturnType();
1273*0a6a1f1dSLionel Sambuc     llvm::Type *Ty = ConvertType(Ret);
1274*0a6a1f1dSLionel Sambuc     unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1275*0a6a1f1dSLionel Sambuc     ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1276*0a6a1f1dSLionel Sambuc         llvm::PointerType::get(Ty, AddressSpace);
1277f4a2713aSLionel Sambuc   }
1278*0a6a1f1dSLionel Sambuc 
1279*0a6a1f1dSLionel Sambuc   // Add type for inalloca argument.
1280*0a6a1f1dSLionel Sambuc   if (IRFunctionArgs.hasInallocaArg()) {
1281*0a6a1f1dSLionel Sambuc     auto ArgStruct = FI.getArgStruct();
1282*0a6a1f1dSLionel Sambuc     assert(ArgStruct);
1283*0a6a1f1dSLionel Sambuc     ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1284*0a6a1f1dSLionel Sambuc   }
1285*0a6a1f1dSLionel Sambuc 
1286*0a6a1f1dSLionel Sambuc   // Add in all of the required arguments.
1287*0a6a1f1dSLionel Sambuc   unsigned ArgNo = 0;
1288*0a6a1f1dSLionel Sambuc   CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1289*0a6a1f1dSLionel Sambuc                                      ie = it + FI.getNumRequiredArgs();
1290*0a6a1f1dSLionel Sambuc   for (; it != ie; ++it, ++ArgNo) {
1291*0a6a1f1dSLionel Sambuc     const ABIArgInfo &ArgInfo = it->info;
1292f4a2713aSLionel Sambuc 
1293f4a2713aSLionel Sambuc     // Insert a padding type to ensure proper alignment.
1294*0a6a1f1dSLionel Sambuc     if (IRFunctionArgs.hasPaddingArg(ArgNo))
1295*0a6a1f1dSLionel Sambuc       ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1296*0a6a1f1dSLionel Sambuc           ArgInfo.getPaddingType();
1297f4a2713aSLionel Sambuc 
1298*0a6a1f1dSLionel Sambuc     unsigned FirstIRArg, NumIRArgs;
1299*0a6a1f1dSLionel Sambuc     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1300*0a6a1f1dSLionel Sambuc 
1301*0a6a1f1dSLionel Sambuc     switch (ArgInfo.getKind()) {
1302f4a2713aSLionel Sambuc     case ABIArgInfo::Ignore:
1303*0a6a1f1dSLionel Sambuc     case ABIArgInfo::InAlloca:
1304*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 0);
1305f4a2713aSLionel Sambuc       break;
1306f4a2713aSLionel Sambuc 
1307f4a2713aSLionel Sambuc     case ABIArgInfo::Indirect: {
1308*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 1);
1309f4a2713aSLionel Sambuc       // indirect arguments are always on the stack, which is addr space #0.
1310f4a2713aSLionel Sambuc       llvm::Type *LTy = ConvertTypeForMem(it->type);
1311*0a6a1f1dSLionel Sambuc       ArgTypes[FirstIRArg] = LTy->getPointerTo();
1312f4a2713aSLionel Sambuc       break;
1313f4a2713aSLionel Sambuc     }
1314f4a2713aSLionel Sambuc 
1315f4a2713aSLionel Sambuc     case ABIArgInfo::Extend:
1316f4a2713aSLionel Sambuc     case ABIArgInfo::Direct: {
1317*0a6a1f1dSLionel Sambuc       // Fast-isel and the optimizer generally like scalar values better than
1318*0a6a1f1dSLionel Sambuc       // FCAs, so we flatten them if this is safe to do for this argument.
1319*0a6a1f1dSLionel Sambuc       llvm::Type *argType = ArgInfo.getCoerceToType();
1320*0a6a1f1dSLionel Sambuc       llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1321*0a6a1f1dSLionel Sambuc       if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1322*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == st->getNumElements());
1323f4a2713aSLionel Sambuc         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1324*0a6a1f1dSLionel Sambuc           ArgTypes[FirstIRArg + i] = st->getElementType(i);
1325f4a2713aSLionel Sambuc       } else {
1326*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == 1);
1327*0a6a1f1dSLionel Sambuc         ArgTypes[FirstIRArg] = argType;
1328f4a2713aSLionel Sambuc       }
1329f4a2713aSLionel Sambuc       break;
1330f4a2713aSLionel Sambuc     }
1331f4a2713aSLionel Sambuc 
1332f4a2713aSLionel Sambuc     case ABIArgInfo::Expand:
1333*0a6a1f1dSLionel Sambuc       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1334*0a6a1f1dSLionel Sambuc       getExpandedTypes(it->type, ArgTypesIter);
1335*0a6a1f1dSLionel Sambuc       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1336f4a2713aSLionel Sambuc       break;
1337f4a2713aSLionel Sambuc     }
1338f4a2713aSLionel Sambuc   }
1339f4a2713aSLionel Sambuc 
1340f4a2713aSLionel Sambuc   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1341f4a2713aSLionel Sambuc   assert(Erased && "Not in set?");
1342f4a2713aSLionel Sambuc 
1343*0a6a1f1dSLionel Sambuc   return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1344f4a2713aSLionel Sambuc }
1345f4a2713aSLionel Sambuc 
GetFunctionTypeForVTable(GlobalDecl GD)1346f4a2713aSLionel Sambuc llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1347f4a2713aSLionel Sambuc   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1348f4a2713aSLionel Sambuc   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1349f4a2713aSLionel Sambuc 
1350f4a2713aSLionel Sambuc   if (!isFuncTypeConvertible(FPT))
1351f4a2713aSLionel Sambuc     return llvm::StructType::get(getLLVMContext());
1352f4a2713aSLionel Sambuc 
1353f4a2713aSLionel Sambuc   const CGFunctionInfo *Info;
1354f4a2713aSLionel Sambuc   if (isa<CXXDestructorDecl>(MD))
1355*0a6a1f1dSLionel Sambuc     Info =
1356*0a6a1f1dSLionel Sambuc         &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
1357f4a2713aSLionel Sambuc   else
1358f4a2713aSLionel Sambuc     Info = &arrangeCXXMethodDeclaration(MD);
1359f4a2713aSLionel Sambuc   return GetFunctionType(*Info);
1360f4a2713aSLionel Sambuc }
1361f4a2713aSLionel Sambuc 
ConstructAttributeList(const CGFunctionInfo & FI,const Decl * TargetDecl,AttributeListType & PAL,unsigned & CallingConv,bool AttrOnCallSite)1362f4a2713aSLionel Sambuc void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
1363f4a2713aSLionel Sambuc                                            const Decl *TargetDecl,
1364f4a2713aSLionel Sambuc                                            AttributeListType &PAL,
1365f4a2713aSLionel Sambuc                                            unsigned &CallingConv,
1366f4a2713aSLionel Sambuc                                            bool AttrOnCallSite) {
1367f4a2713aSLionel Sambuc   llvm::AttrBuilder FuncAttrs;
1368f4a2713aSLionel Sambuc   llvm::AttrBuilder RetAttrs;
1369*0a6a1f1dSLionel Sambuc   bool HasOptnone = false;
1370f4a2713aSLionel Sambuc 
1371f4a2713aSLionel Sambuc   CallingConv = FI.getEffectiveCallingConvention();
1372f4a2713aSLionel Sambuc 
1373f4a2713aSLionel Sambuc   if (FI.isNoReturn())
1374f4a2713aSLionel Sambuc     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1375f4a2713aSLionel Sambuc 
1376f4a2713aSLionel Sambuc   // FIXME: handle sseregparm someday...
1377f4a2713aSLionel Sambuc   if (TargetDecl) {
1378f4a2713aSLionel Sambuc     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
1379f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
1380f4a2713aSLionel Sambuc     if (TargetDecl->hasAttr<NoThrowAttr>())
1381f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1382f4a2713aSLionel Sambuc     if (TargetDecl->hasAttr<NoReturnAttr>())
1383f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1384*0a6a1f1dSLionel Sambuc     if (TargetDecl->hasAttr<NoDuplicateAttr>())
1385*0a6a1f1dSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
1386f4a2713aSLionel Sambuc 
1387f4a2713aSLionel Sambuc     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1388f4a2713aSLionel Sambuc       const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
1389f4a2713aSLionel Sambuc       if (FPT && FPT->isNothrow(getContext()))
1390f4a2713aSLionel Sambuc         FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1391f4a2713aSLionel Sambuc       // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1392f4a2713aSLionel Sambuc       // These attributes are not inherited by overloads.
1393f4a2713aSLionel Sambuc       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1394f4a2713aSLionel Sambuc       if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
1395f4a2713aSLionel Sambuc         FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1396f4a2713aSLionel Sambuc     }
1397f4a2713aSLionel Sambuc 
1398f4a2713aSLionel Sambuc     // 'const' and 'pure' attribute functions are also nounwind.
1399f4a2713aSLionel Sambuc     if (TargetDecl->hasAttr<ConstAttr>()) {
1400f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1401f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1402f4a2713aSLionel Sambuc     } else if (TargetDecl->hasAttr<PureAttr>()) {
1403f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1404f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1405f4a2713aSLionel Sambuc     }
1406f4a2713aSLionel Sambuc     if (TargetDecl->hasAttr<MallocAttr>())
1407f4a2713aSLionel Sambuc       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1408*0a6a1f1dSLionel Sambuc     if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1409*0a6a1f1dSLionel Sambuc       RetAttrs.addAttribute(llvm::Attribute::NonNull);
1410*0a6a1f1dSLionel Sambuc 
1411*0a6a1f1dSLionel Sambuc     HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
1412f4a2713aSLionel Sambuc   }
1413f4a2713aSLionel Sambuc 
1414*0a6a1f1dSLionel Sambuc   // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1415*0a6a1f1dSLionel Sambuc   if (!HasOptnone) {
1416f4a2713aSLionel Sambuc     if (CodeGenOpts.OptimizeSize)
1417f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1418f4a2713aSLionel Sambuc     if (CodeGenOpts.OptimizeSize == 2)
1419f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1420*0a6a1f1dSLionel Sambuc   }
1421*0a6a1f1dSLionel Sambuc 
1422f4a2713aSLionel Sambuc   if (CodeGenOpts.DisableRedZone)
1423f4a2713aSLionel Sambuc     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1424f4a2713aSLionel Sambuc   if (CodeGenOpts.NoImplicitFloat)
1425f4a2713aSLionel Sambuc     FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1426*0a6a1f1dSLionel Sambuc   if (CodeGenOpts.EnableSegmentedStacks &&
1427*0a6a1f1dSLionel Sambuc       !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
1428*0a6a1f1dSLionel Sambuc     FuncAttrs.addAttribute("split-stack");
1429f4a2713aSLionel Sambuc 
1430f4a2713aSLionel Sambuc   if (AttrOnCallSite) {
1431f4a2713aSLionel Sambuc     // Attributes that should go on the call site only.
1432f4a2713aSLionel Sambuc     if (!CodeGenOpts.SimplifyLibCalls)
1433f4a2713aSLionel Sambuc       FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1434f4a2713aSLionel Sambuc   } else {
1435f4a2713aSLionel Sambuc     // Attributes that should go on the function, but not the call site.
1436f4a2713aSLionel Sambuc     if (!CodeGenOpts.DisableFPElim) {
1437f4a2713aSLionel Sambuc       FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1438f4a2713aSLionel Sambuc     } else if (CodeGenOpts.OmitLeafFramePointer) {
1439f4a2713aSLionel Sambuc       FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1440f4a2713aSLionel Sambuc       FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1441f4a2713aSLionel Sambuc     } else {
1442f4a2713aSLionel Sambuc       FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1443f4a2713aSLionel Sambuc       FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1444f4a2713aSLionel Sambuc     }
1445f4a2713aSLionel Sambuc 
1446f4a2713aSLionel Sambuc     FuncAttrs.addAttribute("less-precise-fpmad",
1447f4a2713aSLionel Sambuc                            llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1448f4a2713aSLionel Sambuc     FuncAttrs.addAttribute("no-infs-fp-math",
1449f4a2713aSLionel Sambuc                            llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1450f4a2713aSLionel Sambuc     FuncAttrs.addAttribute("no-nans-fp-math",
1451f4a2713aSLionel Sambuc                            llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1452f4a2713aSLionel Sambuc     FuncAttrs.addAttribute("unsafe-fp-math",
1453f4a2713aSLionel Sambuc                            llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1454f4a2713aSLionel Sambuc     FuncAttrs.addAttribute("use-soft-float",
1455f4a2713aSLionel Sambuc                            llvm::toStringRef(CodeGenOpts.SoftFloat));
1456f4a2713aSLionel Sambuc     FuncAttrs.addAttribute("stack-protector-buffer-size",
1457f4a2713aSLionel Sambuc                            llvm::utostr(CodeGenOpts.SSPBufferSize));
1458f4a2713aSLionel Sambuc 
1459f4a2713aSLionel Sambuc     if (!CodeGenOpts.StackRealignment)
1460f4a2713aSLionel Sambuc       FuncAttrs.addAttribute("no-realign-stack");
1461f4a2713aSLionel Sambuc   }
1462f4a2713aSLionel Sambuc 
1463*0a6a1f1dSLionel Sambuc   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
1464*0a6a1f1dSLionel Sambuc 
1465f4a2713aSLionel Sambuc   QualType RetTy = FI.getReturnType();
1466f4a2713aSLionel Sambuc   const ABIArgInfo &RetAI = FI.getReturnInfo();
1467f4a2713aSLionel Sambuc   switch (RetAI.getKind()) {
1468f4a2713aSLionel Sambuc   case ABIArgInfo::Extend:
1469f4a2713aSLionel Sambuc     if (RetTy->hasSignedIntegerRepresentation())
1470f4a2713aSLionel Sambuc       RetAttrs.addAttribute(llvm::Attribute::SExt);
1471f4a2713aSLionel Sambuc     else if (RetTy->hasUnsignedIntegerRepresentation())
1472f4a2713aSLionel Sambuc       RetAttrs.addAttribute(llvm::Attribute::ZExt);
1473f4a2713aSLionel Sambuc     // FALL THROUGH
1474f4a2713aSLionel Sambuc   case ABIArgInfo::Direct:
1475f4a2713aSLionel Sambuc     if (RetAI.getInReg())
1476f4a2713aSLionel Sambuc       RetAttrs.addAttribute(llvm::Attribute::InReg);
1477f4a2713aSLionel Sambuc     break;
1478f4a2713aSLionel Sambuc   case ABIArgInfo::Ignore:
1479f4a2713aSLionel Sambuc     break;
1480f4a2713aSLionel Sambuc 
1481*0a6a1f1dSLionel Sambuc   case ABIArgInfo::InAlloca:
1482f4a2713aSLionel Sambuc   case ABIArgInfo::Indirect: {
1483*0a6a1f1dSLionel Sambuc     // inalloca and sret disable readnone and readonly
1484f4a2713aSLionel Sambuc     FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1485f4a2713aSLionel Sambuc       .removeAttribute(llvm::Attribute::ReadNone);
1486f4a2713aSLionel Sambuc     break;
1487f4a2713aSLionel Sambuc   }
1488f4a2713aSLionel Sambuc 
1489f4a2713aSLionel Sambuc   case ABIArgInfo::Expand:
1490f4a2713aSLionel Sambuc     llvm_unreachable("Invalid ABI kind for return argument");
1491f4a2713aSLionel Sambuc   }
1492f4a2713aSLionel Sambuc 
1493*0a6a1f1dSLionel Sambuc   if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1494*0a6a1f1dSLionel Sambuc     QualType PTy = RefTy->getPointeeType();
1495*0a6a1f1dSLionel Sambuc     if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1496*0a6a1f1dSLionel Sambuc       RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1497*0a6a1f1dSLionel Sambuc                                         .getQuantity());
1498*0a6a1f1dSLionel Sambuc     else if (getContext().getTargetAddressSpace(PTy) == 0)
1499*0a6a1f1dSLionel Sambuc       RetAttrs.addAttribute(llvm::Attribute::NonNull);
1500*0a6a1f1dSLionel Sambuc   }
1501f4a2713aSLionel Sambuc 
1502*0a6a1f1dSLionel Sambuc   // Attach return attributes.
1503*0a6a1f1dSLionel Sambuc   if (RetAttrs.hasAttributes()) {
1504*0a6a1f1dSLionel Sambuc     PAL.push_back(llvm::AttributeSet::get(
1505*0a6a1f1dSLionel Sambuc         getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1506*0a6a1f1dSLionel Sambuc   }
1507*0a6a1f1dSLionel Sambuc 
1508*0a6a1f1dSLionel Sambuc   // Attach attributes to sret.
1509*0a6a1f1dSLionel Sambuc   if (IRFunctionArgs.hasSRetArg()) {
1510*0a6a1f1dSLionel Sambuc     llvm::AttrBuilder SRETAttrs;
1511*0a6a1f1dSLionel Sambuc     SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1512*0a6a1f1dSLionel Sambuc     if (RetAI.getInReg())
1513*0a6a1f1dSLionel Sambuc       SRETAttrs.addAttribute(llvm::Attribute::InReg);
1514*0a6a1f1dSLionel Sambuc     PAL.push_back(llvm::AttributeSet::get(
1515*0a6a1f1dSLionel Sambuc         getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1516*0a6a1f1dSLionel Sambuc   }
1517*0a6a1f1dSLionel Sambuc 
1518*0a6a1f1dSLionel Sambuc   // Attach attributes to inalloca argument.
1519*0a6a1f1dSLionel Sambuc   if (IRFunctionArgs.hasInallocaArg()) {
1520*0a6a1f1dSLionel Sambuc     llvm::AttrBuilder Attrs;
1521*0a6a1f1dSLionel Sambuc     Attrs.addAttribute(llvm::Attribute::InAlloca);
1522*0a6a1f1dSLionel Sambuc     PAL.push_back(llvm::AttributeSet::get(
1523*0a6a1f1dSLionel Sambuc         getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1524*0a6a1f1dSLionel Sambuc   }
1525*0a6a1f1dSLionel Sambuc 
1526*0a6a1f1dSLionel Sambuc   unsigned ArgNo = 0;
1527*0a6a1f1dSLionel Sambuc   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1528*0a6a1f1dSLionel Sambuc                                           E = FI.arg_end();
1529*0a6a1f1dSLionel Sambuc        I != E; ++I, ++ArgNo) {
1530*0a6a1f1dSLionel Sambuc     QualType ParamType = I->type;
1531*0a6a1f1dSLionel Sambuc     const ABIArgInfo &AI = I->info;
1532f4a2713aSLionel Sambuc     llvm::AttrBuilder Attrs;
1533f4a2713aSLionel Sambuc 
1534*0a6a1f1dSLionel Sambuc     // Add attribute for padding argument, if necessary.
1535*0a6a1f1dSLionel Sambuc     if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
1536f4a2713aSLionel Sambuc       if (AI.getPaddingInReg())
1537*0a6a1f1dSLionel Sambuc         PAL.push_back(llvm::AttributeSet::get(
1538*0a6a1f1dSLionel Sambuc             getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1539f4a2713aSLionel Sambuc             llvm::Attribute::InReg));
1540f4a2713aSLionel Sambuc     }
1541f4a2713aSLionel Sambuc 
1542f4a2713aSLionel Sambuc     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1543f4a2713aSLionel Sambuc     // have the corresponding parameter variable.  It doesn't make
1544f4a2713aSLionel Sambuc     // sense to do it here because parameters are so messed up.
1545f4a2713aSLionel Sambuc     switch (AI.getKind()) {
1546f4a2713aSLionel Sambuc     case ABIArgInfo::Extend:
1547f4a2713aSLionel Sambuc       if (ParamType->isSignedIntegerOrEnumerationType())
1548f4a2713aSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::SExt);
1549f4a2713aSLionel Sambuc       else if (ParamType->isUnsignedIntegerOrEnumerationType())
1550f4a2713aSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::ZExt);
1551f4a2713aSLionel Sambuc       // FALL THROUGH
1552f4a2713aSLionel Sambuc     case ABIArgInfo::Direct:
1553*0a6a1f1dSLionel Sambuc       if (ArgNo == 0 && FI.isChainCall())
1554*0a6a1f1dSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::Nest);
1555*0a6a1f1dSLionel Sambuc       else if (AI.getInReg())
1556f4a2713aSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::InReg);
1557f4a2713aSLionel Sambuc       break;
1558f4a2713aSLionel Sambuc 
1559f4a2713aSLionel Sambuc     case ABIArgInfo::Indirect:
1560f4a2713aSLionel Sambuc       if (AI.getInReg())
1561f4a2713aSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::InReg);
1562f4a2713aSLionel Sambuc 
1563f4a2713aSLionel Sambuc       if (AI.getIndirectByVal())
1564f4a2713aSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::ByVal);
1565f4a2713aSLionel Sambuc 
1566f4a2713aSLionel Sambuc       Attrs.addAlignmentAttr(AI.getIndirectAlign());
1567f4a2713aSLionel Sambuc 
1568f4a2713aSLionel Sambuc       // byval disables readnone and readonly.
1569f4a2713aSLionel Sambuc       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1570f4a2713aSLionel Sambuc         .removeAttribute(llvm::Attribute::ReadNone);
1571f4a2713aSLionel Sambuc       break;
1572f4a2713aSLionel Sambuc 
1573f4a2713aSLionel Sambuc     case ABIArgInfo::Ignore:
1574*0a6a1f1dSLionel Sambuc     case ABIArgInfo::Expand:
1575f4a2713aSLionel Sambuc       continue;
1576f4a2713aSLionel Sambuc 
1577*0a6a1f1dSLionel Sambuc     case ABIArgInfo::InAlloca:
1578*0a6a1f1dSLionel Sambuc       // inalloca disables readnone and readonly.
1579*0a6a1f1dSLionel Sambuc       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1580*0a6a1f1dSLionel Sambuc           .removeAttribute(llvm::Attribute::ReadNone);
1581f4a2713aSLionel Sambuc       continue;
1582f4a2713aSLionel Sambuc     }
1583*0a6a1f1dSLionel Sambuc 
1584*0a6a1f1dSLionel Sambuc     if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1585*0a6a1f1dSLionel Sambuc       QualType PTy = RefTy->getPointeeType();
1586*0a6a1f1dSLionel Sambuc       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1587*0a6a1f1dSLionel Sambuc         Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1588*0a6a1f1dSLionel Sambuc                                        .getQuantity());
1589*0a6a1f1dSLionel Sambuc       else if (getContext().getTargetAddressSpace(PTy) == 0)
1590*0a6a1f1dSLionel Sambuc         Attrs.addAttribute(llvm::Attribute::NonNull);
1591f4a2713aSLionel Sambuc     }
1592f4a2713aSLionel Sambuc 
1593*0a6a1f1dSLionel Sambuc     if (Attrs.hasAttributes()) {
1594*0a6a1f1dSLionel Sambuc       unsigned FirstIRArg, NumIRArgs;
1595*0a6a1f1dSLionel Sambuc       std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1596*0a6a1f1dSLionel Sambuc       for (unsigned i = 0; i < NumIRArgs; i++)
1597*0a6a1f1dSLionel Sambuc         PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1598*0a6a1f1dSLionel Sambuc                                               FirstIRArg + i + 1, Attrs));
1599f4a2713aSLionel Sambuc     }
1600*0a6a1f1dSLionel Sambuc   }
1601*0a6a1f1dSLionel Sambuc   assert(ArgNo == FI.arg_size());
1602*0a6a1f1dSLionel Sambuc 
1603f4a2713aSLionel Sambuc   if (FuncAttrs.hasAttributes())
1604f4a2713aSLionel Sambuc     PAL.push_back(llvm::
1605f4a2713aSLionel Sambuc                   AttributeSet::get(getLLVMContext(),
1606f4a2713aSLionel Sambuc                                     llvm::AttributeSet::FunctionIndex,
1607f4a2713aSLionel Sambuc                                     FuncAttrs));
1608f4a2713aSLionel Sambuc }
1609f4a2713aSLionel Sambuc 
1610f4a2713aSLionel Sambuc /// An argument came in as a promoted argument; demote it back to its
1611f4a2713aSLionel Sambuc /// declared type.
emitArgumentDemotion(CodeGenFunction & CGF,const VarDecl * var,llvm::Value * value)1612f4a2713aSLionel Sambuc static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1613f4a2713aSLionel Sambuc                                          const VarDecl *var,
1614f4a2713aSLionel Sambuc                                          llvm::Value *value) {
1615f4a2713aSLionel Sambuc   llvm::Type *varType = CGF.ConvertType(var->getType());
1616f4a2713aSLionel Sambuc 
1617f4a2713aSLionel Sambuc   // This can happen with promotions that actually don't change the
1618f4a2713aSLionel Sambuc   // underlying type, like the enum promotions.
1619f4a2713aSLionel Sambuc   if (value->getType() == varType) return value;
1620f4a2713aSLionel Sambuc 
1621f4a2713aSLionel Sambuc   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1622f4a2713aSLionel Sambuc          && "unexpected promotion type");
1623f4a2713aSLionel Sambuc 
1624f4a2713aSLionel Sambuc   if (isa<llvm::IntegerType>(varType))
1625f4a2713aSLionel Sambuc     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1626f4a2713aSLionel Sambuc 
1627f4a2713aSLionel Sambuc   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1628f4a2713aSLionel Sambuc }
1629f4a2713aSLionel Sambuc 
1630*0a6a1f1dSLionel Sambuc /// Returns the attribute (either parameter attribute, or function
1631*0a6a1f1dSLionel Sambuc /// attribute), which declares argument ArgNo to be non-null.
getNonNullAttr(const Decl * FD,const ParmVarDecl * PVD,QualType ArgType,unsigned ArgNo)1632*0a6a1f1dSLionel Sambuc static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1633*0a6a1f1dSLionel Sambuc                                          QualType ArgType, unsigned ArgNo) {
1634*0a6a1f1dSLionel Sambuc   // FIXME: __attribute__((nonnull)) can also be applied to:
1635*0a6a1f1dSLionel Sambuc   //   - references to pointers, where the pointee is known to be
1636*0a6a1f1dSLionel Sambuc   //     nonnull (apparently a Clang extension)
1637*0a6a1f1dSLionel Sambuc   //   - transparent unions containing pointers
1638*0a6a1f1dSLionel Sambuc   // In the former case, LLVM IR cannot represent the constraint. In
1639*0a6a1f1dSLionel Sambuc   // the latter case, we have no guarantee that the transparent union
1640*0a6a1f1dSLionel Sambuc   // is in fact passed as a pointer.
1641*0a6a1f1dSLionel Sambuc   if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1642*0a6a1f1dSLionel Sambuc     return nullptr;
1643*0a6a1f1dSLionel Sambuc   // First, check attribute on parameter itself.
1644*0a6a1f1dSLionel Sambuc   if (PVD) {
1645*0a6a1f1dSLionel Sambuc     if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1646*0a6a1f1dSLionel Sambuc       return ParmNNAttr;
1647*0a6a1f1dSLionel Sambuc   }
1648*0a6a1f1dSLionel Sambuc   // Check function attributes.
1649*0a6a1f1dSLionel Sambuc   if (!FD)
1650*0a6a1f1dSLionel Sambuc     return nullptr;
1651*0a6a1f1dSLionel Sambuc   for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
1652*0a6a1f1dSLionel Sambuc     if (NNAttr->isNonNull(ArgNo))
1653*0a6a1f1dSLionel Sambuc       return NNAttr;
1654*0a6a1f1dSLionel Sambuc   }
1655*0a6a1f1dSLionel Sambuc   return nullptr;
1656*0a6a1f1dSLionel Sambuc }
1657*0a6a1f1dSLionel Sambuc 
EmitFunctionProlog(const CGFunctionInfo & FI,llvm::Function * Fn,const FunctionArgList & Args)1658f4a2713aSLionel Sambuc void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1659f4a2713aSLionel Sambuc                                          llvm::Function *Fn,
1660f4a2713aSLionel Sambuc                                          const FunctionArgList &Args) {
1661*0a6a1f1dSLionel Sambuc   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1662*0a6a1f1dSLionel Sambuc     // Naked functions don't have prologues.
1663*0a6a1f1dSLionel Sambuc     return;
1664*0a6a1f1dSLionel Sambuc 
1665f4a2713aSLionel Sambuc   // If this is an implicit-return-zero function, go ahead and
1666f4a2713aSLionel Sambuc   // initialize the return value.  TODO: it might be nice to have
1667f4a2713aSLionel Sambuc   // a more general mechanism for this that didn't require synthesized
1668f4a2713aSLionel Sambuc   // return statements.
1669f4a2713aSLionel Sambuc   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
1670f4a2713aSLionel Sambuc     if (FD->hasImplicitReturnZero()) {
1671*0a6a1f1dSLionel Sambuc       QualType RetTy = FD->getReturnType().getUnqualifiedType();
1672f4a2713aSLionel Sambuc       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
1673f4a2713aSLionel Sambuc       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
1674f4a2713aSLionel Sambuc       Builder.CreateStore(Zero, ReturnValue);
1675f4a2713aSLionel Sambuc     }
1676f4a2713aSLionel Sambuc   }
1677f4a2713aSLionel Sambuc 
1678f4a2713aSLionel Sambuc   // FIXME: We no longer need the types from FunctionArgList; lift up and
1679f4a2713aSLionel Sambuc   // simplify.
1680f4a2713aSLionel Sambuc 
1681*0a6a1f1dSLionel Sambuc   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
1682*0a6a1f1dSLionel Sambuc   // Flattened function arguments.
1683*0a6a1f1dSLionel Sambuc   SmallVector<llvm::Argument *, 16> FnArgs;
1684*0a6a1f1dSLionel Sambuc   FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1685*0a6a1f1dSLionel Sambuc   for (auto &Arg : Fn->args()) {
1686*0a6a1f1dSLionel Sambuc     FnArgs.push_back(&Arg);
1687*0a6a1f1dSLionel Sambuc   }
1688*0a6a1f1dSLionel Sambuc   assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
1689f4a2713aSLionel Sambuc 
1690*0a6a1f1dSLionel Sambuc   // If we're using inalloca, all the memory arguments are GEPs off of the last
1691*0a6a1f1dSLionel Sambuc   // parameter, which is a pointer to the complete memory area.
1692*0a6a1f1dSLionel Sambuc   llvm::Value *ArgStruct = nullptr;
1693*0a6a1f1dSLionel Sambuc   if (IRFunctionArgs.hasInallocaArg()) {
1694*0a6a1f1dSLionel Sambuc     ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
1695*0a6a1f1dSLionel Sambuc     assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1696f4a2713aSLionel Sambuc   }
1697f4a2713aSLionel Sambuc 
1698*0a6a1f1dSLionel Sambuc   // Name the struct return parameter.
1699*0a6a1f1dSLionel Sambuc   if (IRFunctionArgs.hasSRetArg()) {
1700*0a6a1f1dSLionel Sambuc     auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
1701*0a6a1f1dSLionel Sambuc     AI->setName("agg.result");
1702*0a6a1f1dSLionel Sambuc     AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
1703*0a6a1f1dSLionel Sambuc                                         llvm::Attribute::NoAlias));
1704*0a6a1f1dSLionel Sambuc   }
1705*0a6a1f1dSLionel Sambuc 
1706*0a6a1f1dSLionel Sambuc   // Track if we received the parameter as a pointer (indirect, byval, or
1707*0a6a1f1dSLionel Sambuc   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
1708*0a6a1f1dSLionel Sambuc   // into a local alloca for us.
1709*0a6a1f1dSLionel Sambuc   enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
1710*0a6a1f1dSLionel Sambuc   typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
1711*0a6a1f1dSLionel Sambuc   SmallVector<ValueAndIsPtr, 16> ArgVals;
1712*0a6a1f1dSLionel Sambuc   ArgVals.reserve(Args.size());
1713*0a6a1f1dSLionel Sambuc 
1714*0a6a1f1dSLionel Sambuc   // Create a pointer value for every parameter declaration.  This usually
1715*0a6a1f1dSLionel Sambuc   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
1716*0a6a1f1dSLionel Sambuc   // any cleanups or do anything that might unwind.  We do that separately, so
1717*0a6a1f1dSLionel Sambuc   // we can push the cleanups in the correct order for the ABI.
1718f4a2713aSLionel Sambuc   assert(FI.arg_size() == Args.size() &&
1719f4a2713aSLionel Sambuc          "Mismatch between function signature & arguments.");
1720*0a6a1f1dSLionel Sambuc   unsigned ArgNo = 0;
1721f4a2713aSLionel Sambuc   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
1722f4a2713aSLionel Sambuc   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1723f4a2713aSLionel Sambuc        i != e; ++i, ++info_it, ++ArgNo) {
1724f4a2713aSLionel Sambuc     const VarDecl *Arg = *i;
1725f4a2713aSLionel Sambuc     QualType Ty = info_it->type;
1726f4a2713aSLionel Sambuc     const ABIArgInfo &ArgI = info_it->info;
1727f4a2713aSLionel Sambuc 
1728f4a2713aSLionel Sambuc     bool isPromoted =
1729f4a2713aSLionel Sambuc       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1730f4a2713aSLionel Sambuc 
1731*0a6a1f1dSLionel Sambuc     unsigned FirstIRArg, NumIRArgs;
1732*0a6a1f1dSLionel Sambuc     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1733f4a2713aSLionel Sambuc 
1734f4a2713aSLionel Sambuc     switch (ArgI.getKind()) {
1735*0a6a1f1dSLionel Sambuc     case ABIArgInfo::InAlloca: {
1736*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 0);
1737*0a6a1f1dSLionel Sambuc       llvm::Value *V = Builder.CreateStructGEP(
1738*0a6a1f1dSLionel Sambuc           ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1739*0a6a1f1dSLionel Sambuc       ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1740*0a6a1f1dSLionel Sambuc       break;
1741*0a6a1f1dSLionel Sambuc     }
1742*0a6a1f1dSLionel Sambuc 
1743f4a2713aSLionel Sambuc     case ABIArgInfo::Indirect: {
1744*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 1);
1745*0a6a1f1dSLionel Sambuc       llvm::Value *V = FnArgs[FirstIRArg];
1746f4a2713aSLionel Sambuc 
1747f4a2713aSLionel Sambuc       if (!hasScalarEvaluationKind(Ty)) {
1748f4a2713aSLionel Sambuc         // Aggregates and complex variables are accessed by reference.  All we
1749f4a2713aSLionel Sambuc         // need to do is realign the value, if requested
1750f4a2713aSLionel Sambuc         if (ArgI.getIndirectRealign()) {
1751f4a2713aSLionel Sambuc           llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1752f4a2713aSLionel Sambuc 
1753f4a2713aSLionel Sambuc           // Copy from the incoming argument pointer to the temporary with the
1754f4a2713aSLionel Sambuc           // appropriate alignment.
1755f4a2713aSLionel Sambuc           //
1756f4a2713aSLionel Sambuc           // FIXME: We should have a common utility for generating an aggregate
1757f4a2713aSLionel Sambuc           // copy.
1758f4a2713aSLionel Sambuc           llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
1759f4a2713aSLionel Sambuc           CharUnits Size = getContext().getTypeSizeInChars(Ty);
1760f4a2713aSLionel Sambuc           llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1761f4a2713aSLionel Sambuc           llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1762f4a2713aSLionel Sambuc           Builder.CreateMemCpy(Dst,
1763f4a2713aSLionel Sambuc                                Src,
1764f4a2713aSLionel Sambuc                                llvm::ConstantInt::get(IntPtrTy,
1765f4a2713aSLionel Sambuc                                                       Size.getQuantity()),
1766f4a2713aSLionel Sambuc                                ArgI.getIndirectAlign(),
1767f4a2713aSLionel Sambuc                                false);
1768f4a2713aSLionel Sambuc           V = AlignedTemp;
1769f4a2713aSLionel Sambuc         }
1770*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1771f4a2713aSLionel Sambuc       } else {
1772f4a2713aSLionel Sambuc         // Load scalar value from indirect argument.
1773f4a2713aSLionel Sambuc         CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1774f4a2713aSLionel Sambuc         V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1775f4a2713aSLionel Sambuc                              Arg->getLocStart());
1776f4a2713aSLionel Sambuc 
1777f4a2713aSLionel Sambuc         if (isPromoted)
1778f4a2713aSLionel Sambuc           V = emitArgumentDemotion(*this, Arg, V);
1779*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1780f4a2713aSLionel Sambuc       }
1781f4a2713aSLionel Sambuc       break;
1782f4a2713aSLionel Sambuc     }
1783f4a2713aSLionel Sambuc 
1784f4a2713aSLionel Sambuc     case ABIArgInfo::Extend:
1785f4a2713aSLionel Sambuc     case ABIArgInfo::Direct: {
1786f4a2713aSLionel Sambuc 
1787f4a2713aSLionel Sambuc       // If we have the trivial case, handle it with no muss and fuss.
1788f4a2713aSLionel Sambuc       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
1789f4a2713aSLionel Sambuc           ArgI.getCoerceToType() == ConvertType(Ty) &&
1790f4a2713aSLionel Sambuc           ArgI.getDirectOffset() == 0) {
1791*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == 1);
1792*0a6a1f1dSLionel Sambuc         auto AI = FnArgs[FirstIRArg];
1793f4a2713aSLionel Sambuc         llvm::Value *V = AI;
1794f4a2713aSLionel Sambuc 
1795*0a6a1f1dSLionel Sambuc         if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
1796*0a6a1f1dSLionel Sambuc           if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1797*0a6a1f1dSLionel Sambuc                              PVD->getFunctionScopeIndex()))
1798*0a6a1f1dSLionel Sambuc             AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1799*0a6a1f1dSLionel Sambuc                                                 AI->getArgNo() + 1,
1800*0a6a1f1dSLionel Sambuc                                                 llvm::Attribute::NonNull));
1801*0a6a1f1dSLionel Sambuc 
1802*0a6a1f1dSLionel Sambuc           QualType OTy = PVD->getOriginalType();
1803*0a6a1f1dSLionel Sambuc           if (const auto *ArrTy =
1804*0a6a1f1dSLionel Sambuc               getContext().getAsConstantArrayType(OTy)) {
1805*0a6a1f1dSLionel Sambuc             // A C99 array parameter declaration with the static keyword also
1806*0a6a1f1dSLionel Sambuc             // indicates dereferenceability, and if the size is constant we can
1807*0a6a1f1dSLionel Sambuc             // use the dereferenceable attribute (which requires the size in
1808*0a6a1f1dSLionel Sambuc             // bytes).
1809*0a6a1f1dSLionel Sambuc             if (ArrTy->getSizeModifier() == ArrayType::Static) {
1810*0a6a1f1dSLionel Sambuc               QualType ETy = ArrTy->getElementType();
1811*0a6a1f1dSLionel Sambuc               uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1812*0a6a1f1dSLionel Sambuc               if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1813*0a6a1f1dSLionel Sambuc                   ArrSize) {
1814*0a6a1f1dSLionel Sambuc                 llvm::AttrBuilder Attrs;
1815*0a6a1f1dSLionel Sambuc                 Attrs.addDereferenceableAttr(
1816*0a6a1f1dSLionel Sambuc                   getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1817*0a6a1f1dSLionel Sambuc                 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1818*0a6a1f1dSLionel Sambuc                                                     AI->getArgNo() + 1, Attrs));
1819*0a6a1f1dSLionel Sambuc               } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1820*0a6a1f1dSLionel Sambuc                 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1821*0a6a1f1dSLionel Sambuc                                                     AI->getArgNo() + 1,
1822*0a6a1f1dSLionel Sambuc                                                     llvm::Attribute::NonNull));
1823*0a6a1f1dSLionel Sambuc               }
1824*0a6a1f1dSLionel Sambuc             }
1825*0a6a1f1dSLionel Sambuc           } else if (const auto *ArrTy =
1826*0a6a1f1dSLionel Sambuc                      getContext().getAsVariableArrayType(OTy)) {
1827*0a6a1f1dSLionel Sambuc             // For C99 VLAs with the static keyword, we don't know the size so
1828*0a6a1f1dSLionel Sambuc             // we can't use the dereferenceable attribute, but in addrspace(0)
1829*0a6a1f1dSLionel Sambuc             // we know that it must be nonnull.
1830*0a6a1f1dSLionel Sambuc             if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1831*0a6a1f1dSLionel Sambuc                 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1832*0a6a1f1dSLionel Sambuc               AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1833*0a6a1f1dSLionel Sambuc                                                   AI->getArgNo() + 1,
1834*0a6a1f1dSLionel Sambuc                                                   llvm::Attribute::NonNull));
1835*0a6a1f1dSLionel Sambuc           }
1836*0a6a1f1dSLionel Sambuc 
1837*0a6a1f1dSLionel Sambuc           const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1838*0a6a1f1dSLionel Sambuc           if (!AVAttr)
1839*0a6a1f1dSLionel Sambuc             if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1840*0a6a1f1dSLionel Sambuc               AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1841*0a6a1f1dSLionel Sambuc           if (AVAttr) {
1842*0a6a1f1dSLionel Sambuc             llvm::Value *AlignmentValue =
1843*0a6a1f1dSLionel Sambuc               EmitScalarExpr(AVAttr->getAlignment());
1844*0a6a1f1dSLionel Sambuc             llvm::ConstantInt *AlignmentCI =
1845*0a6a1f1dSLionel Sambuc               cast<llvm::ConstantInt>(AlignmentValue);
1846*0a6a1f1dSLionel Sambuc             unsigned Alignment =
1847*0a6a1f1dSLionel Sambuc               std::min((unsigned) AlignmentCI->getZExtValue(),
1848*0a6a1f1dSLionel Sambuc                        +llvm::Value::MaximumAlignment);
1849*0a6a1f1dSLionel Sambuc 
1850*0a6a1f1dSLionel Sambuc             llvm::AttrBuilder Attrs;
1851*0a6a1f1dSLionel Sambuc             Attrs.addAlignmentAttr(Alignment);
1852*0a6a1f1dSLionel Sambuc             AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1853*0a6a1f1dSLionel Sambuc                                                 AI->getArgNo() + 1, Attrs));
1854*0a6a1f1dSLionel Sambuc           }
1855*0a6a1f1dSLionel Sambuc         }
1856*0a6a1f1dSLionel Sambuc 
1857f4a2713aSLionel Sambuc         if (Arg->getType().isRestrictQualified())
1858f4a2713aSLionel Sambuc           AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1859f4a2713aSLionel Sambuc                                               AI->getArgNo() + 1,
1860f4a2713aSLionel Sambuc                                               llvm::Attribute::NoAlias));
1861f4a2713aSLionel Sambuc 
1862f4a2713aSLionel Sambuc         // Ensure the argument is the correct type.
1863f4a2713aSLionel Sambuc         if (V->getType() != ArgI.getCoerceToType())
1864f4a2713aSLionel Sambuc           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1865f4a2713aSLionel Sambuc 
1866f4a2713aSLionel Sambuc         if (isPromoted)
1867f4a2713aSLionel Sambuc           V = emitArgumentDemotion(*this, Arg, V);
1868f4a2713aSLionel Sambuc 
1869f4a2713aSLionel Sambuc         if (const CXXMethodDecl *MD =
1870f4a2713aSLionel Sambuc             dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1871f4a2713aSLionel Sambuc           if (MD->isVirtual() && Arg == CXXABIThisDecl)
1872f4a2713aSLionel Sambuc             V = CGM.getCXXABI().
1873f4a2713aSLionel Sambuc                 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
1874f4a2713aSLionel Sambuc         }
1875f4a2713aSLionel Sambuc 
1876f4a2713aSLionel Sambuc         // Because of merging of function types from multiple decls it is
1877f4a2713aSLionel Sambuc         // possible for the type of an argument to not match the corresponding
1878f4a2713aSLionel Sambuc         // type in the function type. Since we are codegening the callee
1879f4a2713aSLionel Sambuc         // in here, add a cast to the argument type.
1880f4a2713aSLionel Sambuc         llvm::Type *LTy = ConvertType(Arg->getType());
1881f4a2713aSLionel Sambuc         if (V->getType() != LTy)
1882f4a2713aSLionel Sambuc           V = Builder.CreateBitCast(V, LTy);
1883f4a2713aSLionel Sambuc 
1884*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1885f4a2713aSLionel Sambuc         break;
1886f4a2713aSLionel Sambuc       }
1887f4a2713aSLionel Sambuc 
1888f4a2713aSLionel Sambuc       llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
1889f4a2713aSLionel Sambuc 
1890f4a2713aSLionel Sambuc       // The alignment we need to use is the max of the requested alignment for
1891f4a2713aSLionel Sambuc       // the argument plus the alignment required by our access code below.
1892f4a2713aSLionel Sambuc       unsigned AlignmentToUse =
1893f4a2713aSLionel Sambuc         CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
1894f4a2713aSLionel Sambuc       AlignmentToUse = std::max(AlignmentToUse,
1895f4a2713aSLionel Sambuc                         (unsigned)getContext().getDeclAlign(Arg).getQuantity());
1896f4a2713aSLionel Sambuc 
1897f4a2713aSLionel Sambuc       Alloca->setAlignment(AlignmentToUse);
1898f4a2713aSLionel Sambuc       llvm::Value *V = Alloca;
1899f4a2713aSLionel Sambuc       llvm::Value *Ptr = V;    // Pointer to store into.
1900f4a2713aSLionel Sambuc 
1901f4a2713aSLionel Sambuc       // If the value is offset in memory, apply the offset now.
1902f4a2713aSLionel Sambuc       if (unsigned Offs = ArgI.getDirectOffset()) {
1903f4a2713aSLionel Sambuc         Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1904f4a2713aSLionel Sambuc         Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
1905f4a2713aSLionel Sambuc         Ptr = Builder.CreateBitCast(Ptr,
1906f4a2713aSLionel Sambuc                           llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1907f4a2713aSLionel Sambuc       }
1908f4a2713aSLionel Sambuc 
1909*0a6a1f1dSLionel Sambuc       // Fast-isel and the optimizer generally like scalar values better than
1910*0a6a1f1dSLionel Sambuc       // FCAs, so we flatten them if this is safe to do for this argument.
1911f4a2713aSLionel Sambuc       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1912*0a6a1f1dSLionel Sambuc       if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1913*0a6a1f1dSLionel Sambuc           STy->getNumElements() > 1) {
1914f4a2713aSLionel Sambuc         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
1915f4a2713aSLionel Sambuc         llvm::Type *DstTy =
1916f4a2713aSLionel Sambuc           cast<llvm::PointerType>(Ptr->getType())->getElementType();
1917f4a2713aSLionel Sambuc         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
1918f4a2713aSLionel Sambuc 
1919f4a2713aSLionel Sambuc         if (SrcSize <= DstSize) {
1920f4a2713aSLionel Sambuc           Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1921f4a2713aSLionel Sambuc 
1922*0a6a1f1dSLionel Sambuc           assert(STy->getNumElements() == NumIRArgs);
1923f4a2713aSLionel Sambuc           for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1924*0a6a1f1dSLionel Sambuc             auto AI = FnArgs[FirstIRArg + i];
1925f4a2713aSLionel Sambuc             AI->setName(Arg->getName() + ".coerce" + Twine(i));
1926f4a2713aSLionel Sambuc             llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1927*0a6a1f1dSLionel Sambuc             Builder.CreateStore(AI, EltPtr);
1928f4a2713aSLionel Sambuc           }
1929f4a2713aSLionel Sambuc         } else {
1930f4a2713aSLionel Sambuc           llvm::AllocaInst *TempAlloca =
1931f4a2713aSLionel Sambuc             CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1932f4a2713aSLionel Sambuc           TempAlloca->setAlignment(AlignmentToUse);
1933f4a2713aSLionel Sambuc           llvm::Value *TempV = TempAlloca;
1934f4a2713aSLionel Sambuc 
1935*0a6a1f1dSLionel Sambuc           assert(STy->getNumElements() == NumIRArgs);
1936f4a2713aSLionel Sambuc           for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1937*0a6a1f1dSLionel Sambuc             auto AI = FnArgs[FirstIRArg + i];
1938f4a2713aSLionel Sambuc             AI->setName(Arg->getName() + ".coerce" + Twine(i));
1939f4a2713aSLionel Sambuc             llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1940*0a6a1f1dSLionel Sambuc             Builder.CreateStore(AI, EltPtr);
1941f4a2713aSLionel Sambuc           }
1942f4a2713aSLionel Sambuc 
1943f4a2713aSLionel Sambuc           Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
1944f4a2713aSLionel Sambuc         }
1945f4a2713aSLionel Sambuc       } else {
1946f4a2713aSLionel Sambuc         // Simple case, just do a coerced store of the argument into the alloca.
1947*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == 1);
1948*0a6a1f1dSLionel Sambuc         auto AI = FnArgs[FirstIRArg];
1949f4a2713aSLionel Sambuc         AI->setName(Arg->getName() + ".coerce");
1950*0a6a1f1dSLionel Sambuc         CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
1951f4a2713aSLionel Sambuc       }
1952f4a2713aSLionel Sambuc 
1953f4a2713aSLionel Sambuc 
1954f4a2713aSLionel Sambuc       // Match to what EmitParmDecl is expecting for this type.
1955f4a2713aSLionel Sambuc       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
1956f4a2713aSLionel Sambuc         V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
1957f4a2713aSLionel Sambuc         if (isPromoted)
1958f4a2713aSLionel Sambuc           V = emitArgumentDemotion(*this, Arg, V);
1959*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1960*0a6a1f1dSLionel Sambuc       } else {
1961*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1962f4a2713aSLionel Sambuc       }
1963*0a6a1f1dSLionel Sambuc       break;
1964f4a2713aSLionel Sambuc     }
1965f4a2713aSLionel Sambuc 
1966f4a2713aSLionel Sambuc     case ABIArgInfo::Expand: {
1967f4a2713aSLionel Sambuc       // If this structure was expanded into multiple arguments then
1968f4a2713aSLionel Sambuc       // we need to create a temporary and reconstruct it from the
1969f4a2713aSLionel Sambuc       // arguments.
1970f4a2713aSLionel Sambuc       llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
1971f4a2713aSLionel Sambuc       CharUnits Align = getContext().getDeclAlign(Arg);
1972f4a2713aSLionel Sambuc       Alloca->setAlignment(Align.getQuantity());
1973f4a2713aSLionel Sambuc       LValue LV = MakeAddrLValue(Alloca, Ty, Align);
1974*0a6a1f1dSLionel Sambuc       ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
1975f4a2713aSLionel Sambuc 
1976*0a6a1f1dSLionel Sambuc       auto FnArgIter = FnArgs.begin() + FirstIRArg;
1977*0a6a1f1dSLionel Sambuc       ExpandTypeFromArgs(Ty, LV, FnArgIter);
1978*0a6a1f1dSLionel Sambuc       assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1979*0a6a1f1dSLionel Sambuc       for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1980*0a6a1f1dSLionel Sambuc         auto AI = FnArgs[FirstIRArg + i];
1981*0a6a1f1dSLionel Sambuc         AI->setName(Arg->getName() + "." + Twine(i));
1982*0a6a1f1dSLionel Sambuc       }
1983*0a6a1f1dSLionel Sambuc       break;
1984f4a2713aSLionel Sambuc     }
1985f4a2713aSLionel Sambuc 
1986f4a2713aSLionel Sambuc     case ABIArgInfo::Ignore:
1987*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 0);
1988f4a2713aSLionel Sambuc       // Initialize the local variable appropriately.
1989*0a6a1f1dSLionel Sambuc       if (!hasScalarEvaluationKind(Ty)) {
1990*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1991*0a6a1f1dSLionel Sambuc       } else {
1992*0a6a1f1dSLionel Sambuc         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1993*0a6a1f1dSLionel Sambuc         ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1994*0a6a1f1dSLionel Sambuc       }
1995*0a6a1f1dSLionel Sambuc       break;
1996*0a6a1f1dSLionel Sambuc     }
1997f4a2713aSLionel Sambuc   }
1998f4a2713aSLionel Sambuc 
1999*0a6a1f1dSLionel Sambuc   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2000*0a6a1f1dSLionel Sambuc     for (int I = Args.size() - 1; I >= 0; --I)
2001*0a6a1f1dSLionel Sambuc       EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2002*0a6a1f1dSLionel Sambuc                    I + 1);
2003*0a6a1f1dSLionel Sambuc   } else {
2004*0a6a1f1dSLionel Sambuc     for (unsigned I = 0, E = Args.size(); I != E; ++I)
2005*0a6a1f1dSLionel Sambuc       EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2006*0a6a1f1dSLionel Sambuc                    I + 1);
2007f4a2713aSLionel Sambuc   }
2008f4a2713aSLionel Sambuc }
2009f4a2713aSLionel Sambuc 
eraseUnusedBitCasts(llvm::Instruction * insn)2010f4a2713aSLionel Sambuc static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2011f4a2713aSLionel Sambuc   while (insn->use_empty()) {
2012f4a2713aSLionel Sambuc     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2013f4a2713aSLionel Sambuc     if (!bitcast) return;
2014f4a2713aSLionel Sambuc 
2015f4a2713aSLionel Sambuc     // This is "safe" because we would have used a ConstantExpr otherwise.
2016f4a2713aSLionel Sambuc     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2017f4a2713aSLionel Sambuc     bitcast->eraseFromParent();
2018f4a2713aSLionel Sambuc   }
2019f4a2713aSLionel Sambuc }
2020f4a2713aSLionel Sambuc 
2021f4a2713aSLionel Sambuc /// Try to emit a fused autorelease of a return result.
tryEmitFusedAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)2022f4a2713aSLionel Sambuc static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2023f4a2713aSLionel Sambuc                                                     llvm::Value *result) {
2024f4a2713aSLionel Sambuc   // We must be immediately followed the cast.
2025f4a2713aSLionel Sambuc   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
2026*0a6a1f1dSLionel Sambuc   if (BB->empty()) return nullptr;
2027*0a6a1f1dSLionel Sambuc   if (&BB->back() != result) return nullptr;
2028f4a2713aSLionel Sambuc 
2029f4a2713aSLionel Sambuc   llvm::Type *resultType = result->getType();
2030f4a2713aSLionel Sambuc 
2031f4a2713aSLionel Sambuc   // result is in a BasicBlock and is therefore an Instruction.
2032f4a2713aSLionel Sambuc   llvm::Instruction *generator = cast<llvm::Instruction>(result);
2033f4a2713aSLionel Sambuc 
2034f4a2713aSLionel Sambuc   SmallVector<llvm::Instruction*,4> insnsToKill;
2035f4a2713aSLionel Sambuc 
2036f4a2713aSLionel Sambuc   // Look for:
2037f4a2713aSLionel Sambuc   //  %generator = bitcast %type1* %generator2 to %type2*
2038f4a2713aSLionel Sambuc   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2039f4a2713aSLionel Sambuc     // We would have emitted this as a constant if the operand weren't
2040f4a2713aSLionel Sambuc     // an Instruction.
2041f4a2713aSLionel Sambuc     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2042f4a2713aSLionel Sambuc 
2043f4a2713aSLionel Sambuc     // Require the generator to be immediately followed by the cast.
2044f4a2713aSLionel Sambuc     if (generator->getNextNode() != bitcast)
2045*0a6a1f1dSLionel Sambuc       return nullptr;
2046f4a2713aSLionel Sambuc 
2047f4a2713aSLionel Sambuc     insnsToKill.push_back(bitcast);
2048f4a2713aSLionel Sambuc   }
2049f4a2713aSLionel Sambuc 
2050f4a2713aSLionel Sambuc   // Look for:
2051f4a2713aSLionel Sambuc   //   %generator = call i8* @objc_retain(i8* %originalResult)
2052f4a2713aSLionel Sambuc   // or
2053f4a2713aSLionel Sambuc   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2054f4a2713aSLionel Sambuc   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
2055*0a6a1f1dSLionel Sambuc   if (!call) return nullptr;
2056f4a2713aSLionel Sambuc 
2057f4a2713aSLionel Sambuc   bool doRetainAutorelease;
2058f4a2713aSLionel Sambuc 
2059f4a2713aSLionel Sambuc   if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2060f4a2713aSLionel Sambuc     doRetainAutorelease = true;
2061f4a2713aSLionel Sambuc   } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2062f4a2713aSLionel Sambuc                                           .objc_retainAutoreleasedReturnValue) {
2063f4a2713aSLionel Sambuc     doRetainAutorelease = false;
2064f4a2713aSLionel Sambuc 
2065f4a2713aSLionel Sambuc     // If we emitted an assembly marker for this call (and the
2066f4a2713aSLionel Sambuc     // ARCEntrypoints field should have been set if so), go looking
2067f4a2713aSLionel Sambuc     // for that call.  If we can't find it, we can't do this
2068f4a2713aSLionel Sambuc     // optimization.  But it should always be the immediately previous
2069f4a2713aSLionel Sambuc     // instruction, unless we needed bitcasts around the call.
2070f4a2713aSLionel Sambuc     if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2071f4a2713aSLionel Sambuc       llvm::Instruction *prev = call->getPrevNode();
2072f4a2713aSLionel Sambuc       assert(prev);
2073f4a2713aSLionel Sambuc       if (isa<llvm::BitCastInst>(prev)) {
2074f4a2713aSLionel Sambuc         prev = prev->getPrevNode();
2075f4a2713aSLionel Sambuc         assert(prev);
2076f4a2713aSLionel Sambuc       }
2077f4a2713aSLionel Sambuc       assert(isa<llvm::CallInst>(prev));
2078f4a2713aSLionel Sambuc       assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2079f4a2713aSLionel Sambuc                CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2080f4a2713aSLionel Sambuc       insnsToKill.push_back(prev);
2081f4a2713aSLionel Sambuc     }
2082f4a2713aSLionel Sambuc   } else {
2083*0a6a1f1dSLionel Sambuc     return nullptr;
2084f4a2713aSLionel Sambuc   }
2085f4a2713aSLionel Sambuc 
2086f4a2713aSLionel Sambuc   result = call->getArgOperand(0);
2087f4a2713aSLionel Sambuc   insnsToKill.push_back(call);
2088f4a2713aSLionel Sambuc 
2089f4a2713aSLionel Sambuc   // Keep killing bitcasts, for sanity.  Note that we no longer care
2090f4a2713aSLionel Sambuc   // about precise ordering as long as there's exactly one use.
2091f4a2713aSLionel Sambuc   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2092f4a2713aSLionel Sambuc     if (!bitcast->hasOneUse()) break;
2093f4a2713aSLionel Sambuc     insnsToKill.push_back(bitcast);
2094f4a2713aSLionel Sambuc     result = bitcast->getOperand(0);
2095f4a2713aSLionel Sambuc   }
2096f4a2713aSLionel Sambuc 
2097f4a2713aSLionel Sambuc   // Delete all the unnecessary instructions, from latest to earliest.
2098f4a2713aSLionel Sambuc   for (SmallVectorImpl<llvm::Instruction*>::iterator
2099f4a2713aSLionel Sambuc          i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2100f4a2713aSLionel Sambuc     (*i)->eraseFromParent();
2101f4a2713aSLionel Sambuc 
2102f4a2713aSLionel Sambuc   // Do the fused retain/autorelease if we were asked to.
2103f4a2713aSLionel Sambuc   if (doRetainAutorelease)
2104f4a2713aSLionel Sambuc     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2105f4a2713aSLionel Sambuc 
2106f4a2713aSLionel Sambuc   // Cast back to the result type.
2107f4a2713aSLionel Sambuc   return CGF.Builder.CreateBitCast(result, resultType);
2108f4a2713aSLionel Sambuc }
2109f4a2713aSLionel Sambuc 
2110f4a2713aSLionel Sambuc /// If this is a +1 of the value of an immutable 'self', remove it.
tryRemoveRetainOfSelf(CodeGenFunction & CGF,llvm::Value * result)2111f4a2713aSLionel Sambuc static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2112f4a2713aSLionel Sambuc                                           llvm::Value *result) {
2113f4a2713aSLionel Sambuc   // This is only applicable to a method with an immutable 'self'.
2114f4a2713aSLionel Sambuc   const ObjCMethodDecl *method =
2115f4a2713aSLionel Sambuc     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
2116*0a6a1f1dSLionel Sambuc   if (!method) return nullptr;
2117f4a2713aSLionel Sambuc   const VarDecl *self = method->getSelfDecl();
2118*0a6a1f1dSLionel Sambuc   if (!self->getType().isConstQualified()) return nullptr;
2119f4a2713aSLionel Sambuc 
2120f4a2713aSLionel Sambuc   // Look for a retain call.
2121f4a2713aSLionel Sambuc   llvm::CallInst *retainCall =
2122f4a2713aSLionel Sambuc     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2123f4a2713aSLionel Sambuc   if (!retainCall ||
2124f4a2713aSLionel Sambuc       retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
2125*0a6a1f1dSLionel Sambuc     return nullptr;
2126f4a2713aSLionel Sambuc 
2127f4a2713aSLionel Sambuc   // Look for an ordinary load of 'self'.
2128f4a2713aSLionel Sambuc   llvm::Value *retainedValue = retainCall->getArgOperand(0);
2129f4a2713aSLionel Sambuc   llvm::LoadInst *load =
2130f4a2713aSLionel Sambuc     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2131f4a2713aSLionel Sambuc   if (!load || load->isAtomic() || load->isVolatile() ||
2132f4a2713aSLionel Sambuc       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
2133*0a6a1f1dSLionel Sambuc     return nullptr;
2134f4a2713aSLionel Sambuc 
2135f4a2713aSLionel Sambuc   // Okay!  Burn it all down.  This relies for correctness on the
2136f4a2713aSLionel Sambuc   // assumption that the retain is emitted as part of the return and
2137f4a2713aSLionel Sambuc   // that thereafter everything is used "linearly".
2138f4a2713aSLionel Sambuc   llvm::Type *resultType = result->getType();
2139f4a2713aSLionel Sambuc   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2140f4a2713aSLionel Sambuc   assert(retainCall->use_empty());
2141f4a2713aSLionel Sambuc   retainCall->eraseFromParent();
2142f4a2713aSLionel Sambuc   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2143f4a2713aSLionel Sambuc 
2144f4a2713aSLionel Sambuc   return CGF.Builder.CreateBitCast(load, resultType);
2145f4a2713aSLionel Sambuc }
2146f4a2713aSLionel Sambuc 
2147f4a2713aSLionel Sambuc /// Emit an ARC autorelease of the result of a function.
2148f4a2713aSLionel Sambuc ///
2149f4a2713aSLionel Sambuc /// \return the value to actually return from the function
emitAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)2150f4a2713aSLionel Sambuc static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2151f4a2713aSLionel Sambuc                                             llvm::Value *result) {
2152f4a2713aSLionel Sambuc   // If we're returning 'self', kill the initial retain.  This is a
2153f4a2713aSLionel Sambuc   // heuristic attempt to "encourage correctness" in the really unfortunate
2154f4a2713aSLionel Sambuc   // case where we have a return of self during a dealloc and we desperately
2155f4a2713aSLionel Sambuc   // need to avoid the possible autorelease.
2156f4a2713aSLionel Sambuc   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2157f4a2713aSLionel Sambuc     return self;
2158f4a2713aSLionel Sambuc 
2159f4a2713aSLionel Sambuc   // At -O0, try to emit a fused retain/autorelease.
2160f4a2713aSLionel Sambuc   if (CGF.shouldUseFusedARCCalls())
2161f4a2713aSLionel Sambuc     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2162f4a2713aSLionel Sambuc       return fused;
2163f4a2713aSLionel Sambuc 
2164f4a2713aSLionel Sambuc   return CGF.EmitARCAutoreleaseReturnValue(result);
2165f4a2713aSLionel Sambuc }
2166f4a2713aSLionel Sambuc 
2167f4a2713aSLionel Sambuc /// Heuristically search for a dominating store to the return-value slot.
findDominatingStoreToReturnValue(CodeGenFunction & CGF)2168f4a2713aSLionel Sambuc static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2169f4a2713aSLionel Sambuc   // If there are multiple uses of the return-value slot, just check
2170f4a2713aSLionel Sambuc   // for something immediately preceding the IP.  Sometimes this can
2171f4a2713aSLionel Sambuc   // happen with how we generate implicit-returns; it can also happen
2172f4a2713aSLionel Sambuc   // with noreturn cleanups.
2173f4a2713aSLionel Sambuc   if (!CGF.ReturnValue->hasOneUse()) {
2174f4a2713aSLionel Sambuc     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2175*0a6a1f1dSLionel Sambuc     if (IP->empty()) return nullptr;
2176f4a2713aSLionel Sambuc     llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
2177*0a6a1f1dSLionel Sambuc     if (!store) return nullptr;
2178*0a6a1f1dSLionel Sambuc     if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
2179f4a2713aSLionel Sambuc     assert(!store->isAtomic() && !store->isVolatile()); // see below
2180f4a2713aSLionel Sambuc     return store;
2181f4a2713aSLionel Sambuc   }
2182f4a2713aSLionel Sambuc 
2183f4a2713aSLionel Sambuc   llvm::StoreInst *store =
2184*0a6a1f1dSLionel Sambuc     dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
2185*0a6a1f1dSLionel Sambuc   if (!store) return nullptr;
2186f4a2713aSLionel Sambuc 
2187f4a2713aSLionel Sambuc   // These aren't actually possible for non-coerced returns, and we
2188f4a2713aSLionel Sambuc   // only care about non-coerced returns on this code path.
2189f4a2713aSLionel Sambuc   assert(!store->isAtomic() && !store->isVolatile());
2190f4a2713aSLionel Sambuc 
2191f4a2713aSLionel Sambuc   // Now do a first-and-dirty dominance check: just walk up the
2192f4a2713aSLionel Sambuc   // single-predecessors chain from the current insertion point.
2193f4a2713aSLionel Sambuc   llvm::BasicBlock *StoreBB = store->getParent();
2194f4a2713aSLionel Sambuc   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2195f4a2713aSLionel Sambuc   while (IP != StoreBB) {
2196f4a2713aSLionel Sambuc     if (!(IP = IP->getSinglePredecessor()))
2197*0a6a1f1dSLionel Sambuc       return nullptr;
2198f4a2713aSLionel Sambuc   }
2199f4a2713aSLionel Sambuc 
2200f4a2713aSLionel Sambuc   // Okay, the store's basic block dominates the insertion point; we
2201f4a2713aSLionel Sambuc   // can do our thing.
2202f4a2713aSLionel Sambuc   return store;
2203f4a2713aSLionel Sambuc }
2204f4a2713aSLionel Sambuc 
EmitFunctionEpilog(const CGFunctionInfo & FI,bool EmitRetDbgLoc,SourceLocation EndLoc)2205f4a2713aSLionel Sambuc void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
2206f4a2713aSLionel Sambuc                                          bool EmitRetDbgLoc,
2207f4a2713aSLionel Sambuc                                          SourceLocation EndLoc) {
2208*0a6a1f1dSLionel Sambuc   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2209*0a6a1f1dSLionel Sambuc     // Naked functions don't have epilogues.
2210*0a6a1f1dSLionel Sambuc     Builder.CreateUnreachable();
2211*0a6a1f1dSLionel Sambuc     return;
2212*0a6a1f1dSLionel Sambuc   }
2213*0a6a1f1dSLionel Sambuc 
2214f4a2713aSLionel Sambuc   // Functions with no result always return void.
2215*0a6a1f1dSLionel Sambuc   if (!ReturnValue) {
2216f4a2713aSLionel Sambuc     Builder.CreateRetVoid();
2217f4a2713aSLionel Sambuc     return;
2218f4a2713aSLionel Sambuc   }
2219f4a2713aSLionel Sambuc 
2220f4a2713aSLionel Sambuc   llvm::DebugLoc RetDbgLoc;
2221*0a6a1f1dSLionel Sambuc   llvm::Value *RV = nullptr;
2222f4a2713aSLionel Sambuc   QualType RetTy = FI.getReturnType();
2223f4a2713aSLionel Sambuc   const ABIArgInfo &RetAI = FI.getReturnInfo();
2224f4a2713aSLionel Sambuc 
2225f4a2713aSLionel Sambuc   switch (RetAI.getKind()) {
2226*0a6a1f1dSLionel Sambuc   case ABIArgInfo::InAlloca:
2227*0a6a1f1dSLionel Sambuc     // Aggregrates get evaluated directly into the destination.  Sometimes we
2228*0a6a1f1dSLionel Sambuc     // need to return the sret value in a register, though.
2229*0a6a1f1dSLionel Sambuc     assert(hasAggregateEvaluationKind(RetTy));
2230*0a6a1f1dSLionel Sambuc     if (RetAI.getInAllocaSRet()) {
2231*0a6a1f1dSLionel Sambuc       llvm::Function::arg_iterator EI = CurFn->arg_end();
2232*0a6a1f1dSLionel Sambuc       --EI;
2233*0a6a1f1dSLionel Sambuc       llvm::Value *ArgStruct = EI;
2234*0a6a1f1dSLionel Sambuc       llvm::Value *SRet =
2235*0a6a1f1dSLionel Sambuc           Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2236*0a6a1f1dSLionel Sambuc       RV = Builder.CreateLoad(SRet, "sret");
2237*0a6a1f1dSLionel Sambuc     }
2238*0a6a1f1dSLionel Sambuc     break;
2239*0a6a1f1dSLionel Sambuc 
2240f4a2713aSLionel Sambuc   case ABIArgInfo::Indirect: {
2241*0a6a1f1dSLionel Sambuc     auto AI = CurFn->arg_begin();
2242*0a6a1f1dSLionel Sambuc     if (RetAI.isSRetAfterThis())
2243*0a6a1f1dSLionel Sambuc       ++AI;
2244f4a2713aSLionel Sambuc     switch (getEvaluationKind(RetTy)) {
2245f4a2713aSLionel Sambuc     case TEK_Complex: {
2246f4a2713aSLionel Sambuc       ComplexPairTy RT =
2247f4a2713aSLionel Sambuc         EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2248f4a2713aSLionel Sambuc                           EndLoc);
2249*0a6a1f1dSLionel Sambuc       EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
2250f4a2713aSLionel Sambuc                          /*isInit*/ true);
2251f4a2713aSLionel Sambuc       break;
2252f4a2713aSLionel Sambuc     }
2253f4a2713aSLionel Sambuc     case TEK_Aggregate:
2254f4a2713aSLionel Sambuc       // Do nothing; aggregrates get evaluated directly into the destination.
2255f4a2713aSLionel Sambuc       break;
2256f4a2713aSLionel Sambuc     case TEK_Scalar:
2257f4a2713aSLionel Sambuc       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
2258*0a6a1f1dSLionel Sambuc                         MakeNaturalAlignAddrLValue(AI, RetTy),
2259f4a2713aSLionel Sambuc                         /*isInit*/ true);
2260f4a2713aSLionel Sambuc       break;
2261f4a2713aSLionel Sambuc     }
2262f4a2713aSLionel Sambuc     break;
2263f4a2713aSLionel Sambuc   }
2264f4a2713aSLionel Sambuc 
2265f4a2713aSLionel Sambuc   case ABIArgInfo::Extend:
2266f4a2713aSLionel Sambuc   case ABIArgInfo::Direct:
2267f4a2713aSLionel Sambuc     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2268f4a2713aSLionel Sambuc         RetAI.getDirectOffset() == 0) {
2269f4a2713aSLionel Sambuc       // The internal return value temp always will have pointer-to-return-type
2270f4a2713aSLionel Sambuc       // type, just do a load.
2271f4a2713aSLionel Sambuc 
2272f4a2713aSLionel Sambuc       // If there is a dominating store to ReturnValue, we can elide
2273f4a2713aSLionel Sambuc       // the load, zap the store, and usually zap the alloca.
2274f4a2713aSLionel Sambuc       if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
2275f4a2713aSLionel Sambuc         // Reuse the debug location from the store unless there is
2276f4a2713aSLionel Sambuc         // cleanup code to be emitted between the store and return
2277f4a2713aSLionel Sambuc         // instruction.
2278f4a2713aSLionel Sambuc         if (EmitRetDbgLoc && !AutoreleaseResult)
2279f4a2713aSLionel Sambuc           RetDbgLoc = SI->getDebugLoc();
2280f4a2713aSLionel Sambuc         // Get the stored value and nuke the now-dead store.
2281f4a2713aSLionel Sambuc         RV = SI->getValueOperand();
2282f4a2713aSLionel Sambuc         SI->eraseFromParent();
2283f4a2713aSLionel Sambuc 
2284f4a2713aSLionel Sambuc         // If that was the only use of the return value, nuke it as well now.
2285f4a2713aSLionel Sambuc         if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2286f4a2713aSLionel Sambuc           cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
2287*0a6a1f1dSLionel Sambuc           ReturnValue = nullptr;
2288f4a2713aSLionel Sambuc         }
2289f4a2713aSLionel Sambuc 
2290f4a2713aSLionel Sambuc       // Otherwise, we have to do a simple load.
2291f4a2713aSLionel Sambuc       } else {
2292f4a2713aSLionel Sambuc         RV = Builder.CreateLoad(ReturnValue);
2293f4a2713aSLionel Sambuc       }
2294f4a2713aSLionel Sambuc     } else {
2295f4a2713aSLionel Sambuc       llvm::Value *V = ReturnValue;
2296f4a2713aSLionel Sambuc       // If the value is offset in memory, apply the offset now.
2297f4a2713aSLionel Sambuc       if (unsigned Offs = RetAI.getDirectOffset()) {
2298f4a2713aSLionel Sambuc         V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2299f4a2713aSLionel Sambuc         V = Builder.CreateConstGEP1_32(V, Offs);
2300f4a2713aSLionel Sambuc         V = Builder.CreateBitCast(V,
2301f4a2713aSLionel Sambuc                          llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2302f4a2713aSLionel Sambuc       }
2303f4a2713aSLionel Sambuc 
2304f4a2713aSLionel Sambuc       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
2305f4a2713aSLionel Sambuc     }
2306f4a2713aSLionel Sambuc 
2307f4a2713aSLionel Sambuc     // In ARC, end functions that return a retainable type with a call
2308f4a2713aSLionel Sambuc     // to objc_autoreleaseReturnValue.
2309f4a2713aSLionel Sambuc     if (AutoreleaseResult) {
2310f4a2713aSLionel Sambuc       assert(getLangOpts().ObjCAutoRefCount &&
2311f4a2713aSLionel Sambuc              !FI.isReturnsRetained() &&
2312f4a2713aSLionel Sambuc              RetTy->isObjCRetainableType());
2313f4a2713aSLionel Sambuc       RV = emitAutoreleaseOfResult(*this, RV);
2314f4a2713aSLionel Sambuc     }
2315f4a2713aSLionel Sambuc 
2316f4a2713aSLionel Sambuc     break;
2317f4a2713aSLionel Sambuc 
2318f4a2713aSLionel Sambuc   case ABIArgInfo::Ignore:
2319f4a2713aSLionel Sambuc     break;
2320f4a2713aSLionel Sambuc 
2321f4a2713aSLionel Sambuc   case ABIArgInfo::Expand:
2322f4a2713aSLionel Sambuc     llvm_unreachable("Invalid ABI kind for return argument");
2323f4a2713aSLionel Sambuc   }
2324f4a2713aSLionel Sambuc 
2325*0a6a1f1dSLionel Sambuc   llvm::Instruction *Ret;
2326*0a6a1f1dSLionel Sambuc   if (RV) {
2327*0a6a1f1dSLionel Sambuc     if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2328*0a6a1f1dSLionel Sambuc       if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2329*0a6a1f1dSLionel Sambuc         SanitizerScope SanScope(this);
2330*0a6a1f1dSLionel Sambuc         llvm::Value *Cond = Builder.CreateICmpNE(
2331*0a6a1f1dSLionel Sambuc             RV, llvm::Constant::getNullValue(RV->getType()));
2332*0a6a1f1dSLionel Sambuc         llvm::Constant *StaticData[] = {
2333*0a6a1f1dSLionel Sambuc             EmitCheckSourceLocation(EndLoc),
2334*0a6a1f1dSLionel Sambuc             EmitCheckSourceLocation(RetNNAttr->getLocation()),
2335*0a6a1f1dSLionel Sambuc         };
2336*0a6a1f1dSLionel Sambuc         EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2337*0a6a1f1dSLionel Sambuc                   "nonnull_return", StaticData, None);
2338*0a6a1f1dSLionel Sambuc       }
2339*0a6a1f1dSLionel Sambuc     }
2340*0a6a1f1dSLionel Sambuc     Ret = Builder.CreateRet(RV);
2341*0a6a1f1dSLionel Sambuc   } else {
2342*0a6a1f1dSLionel Sambuc     Ret = Builder.CreateRetVoid();
2343*0a6a1f1dSLionel Sambuc   }
2344*0a6a1f1dSLionel Sambuc 
2345f4a2713aSLionel Sambuc   if (!RetDbgLoc.isUnknown())
2346f4a2713aSLionel Sambuc     Ret->setDebugLoc(RetDbgLoc);
2347f4a2713aSLionel Sambuc }
2348f4a2713aSLionel Sambuc 
isInAllocaArgument(CGCXXABI & ABI,QualType type)2349*0a6a1f1dSLionel Sambuc static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2350*0a6a1f1dSLionel Sambuc   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2351*0a6a1f1dSLionel Sambuc   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2352*0a6a1f1dSLionel Sambuc }
2353*0a6a1f1dSLionel Sambuc 
createPlaceholderSlot(CodeGenFunction & CGF,QualType Ty)2354*0a6a1f1dSLionel Sambuc static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2355*0a6a1f1dSLionel Sambuc   // FIXME: Generate IR in one pass, rather than going back and fixing up these
2356*0a6a1f1dSLionel Sambuc   // placeholders.
2357*0a6a1f1dSLionel Sambuc   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2358*0a6a1f1dSLionel Sambuc   llvm::Value *Placeholder =
2359*0a6a1f1dSLionel Sambuc       llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2360*0a6a1f1dSLionel Sambuc   Placeholder = CGF.Builder.CreateLoad(Placeholder);
2361*0a6a1f1dSLionel Sambuc   return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2362*0a6a1f1dSLionel Sambuc                                Ty.getQualifiers(),
2363*0a6a1f1dSLionel Sambuc                                AggValueSlot::IsNotDestructed,
2364*0a6a1f1dSLionel Sambuc                                AggValueSlot::DoesNotNeedGCBarriers,
2365*0a6a1f1dSLionel Sambuc                                AggValueSlot::IsNotAliased);
2366*0a6a1f1dSLionel Sambuc }
2367*0a6a1f1dSLionel Sambuc 
EmitDelegateCallArg(CallArgList & args,const VarDecl * param,SourceLocation loc)2368f4a2713aSLionel Sambuc void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
2369f4a2713aSLionel Sambuc                                           const VarDecl *param,
2370f4a2713aSLionel Sambuc                                           SourceLocation loc) {
2371f4a2713aSLionel Sambuc   // StartFunction converted the ABI-lowered parameter(s) into a
2372f4a2713aSLionel Sambuc   // local alloca.  We need to turn that into an r-value suitable
2373f4a2713aSLionel Sambuc   // for EmitCall.
2374f4a2713aSLionel Sambuc   llvm::Value *local = GetAddrOfLocalVar(param);
2375f4a2713aSLionel Sambuc 
2376f4a2713aSLionel Sambuc   QualType type = param->getType();
2377f4a2713aSLionel Sambuc 
2378f4a2713aSLionel Sambuc   // For the most part, we just need to load the alloca, except:
2379f4a2713aSLionel Sambuc   // 1) aggregate r-values are actually pointers to temporaries, and
2380f4a2713aSLionel Sambuc   // 2) references to non-scalars are pointers directly to the aggregate.
2381f4a2713aSLionel Sambuc   // I don't know why references to scalars are different here.
2382f4a2713aSLionel Sambuc   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2383f4a2713aSLionel Sambuc     if (!hasScalarEvaluationKind(ref->getPointeeType()))
2384f4a2713aSLionel Sambuc       return args.add(RValue::getAggregate(local), type);
2385f4a2713aSLionel Sambuc 
2386f4a2713aSLionel Sambuc     // Locals which are references to scalars are represented
2387f4a2713aSLionel Sambuc     // with allocas holding the pointer.
2388f4a2713aSLionel Sambuc     return args.add(RValue::get(Builder.CreateLoad(local)), type);
2389f4a2713aSLionel Sambuc   }
2390f4a2713aSLionel Sambuc 
2391*0a6a1f1dSLionel Sambuc   assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2392*0a6a1f1dSLionel Sambuc          "cannot emit delegate call arguments for inalloca arguments!");
2393*0a6a1f1dSLionel Sambuc 
2394f4a2713aSLionel Sambuc   args.add(convertTempToRValue(local, type, loc), type);
2395f4a2713aSLionel Sambuc }
2396f4a2713aSLionel Sambuc 
isProvablyNull(llvm::Value * addr)2397f4a2713aSLionel Sambuc static bool isProvablyNull(llvm::Value *addr) {
2398f4a2713aSLionel Sambuc   return isa<llvm::ConstantPointerNull>(addr);
2399f4a2713aSLionel Sambuc }
2400f4a2713aSLionel Sambuc 
isProvablyNonNull(llvm::Value * addr)2401f4a2713aSLionel Sambuc static bool isProvablyNonNull(llvm::Value *addr) {
2402f4a2713aSLionel Sambuc   return isa<llvm::AllocaInst>(addr);
2403f4a2713aSLionel Sambuc }
2404f4a2713aSLionel Sambuc 
2405f4a2713aSLionel Sambuc /// Emit the actual writing-back of a writeback.
emitWriteback(CodeGenFunction & CGF,const CallArgList::Writeback & writeback)2406f4a2713aSLionel Sambuc static void emitWriteback(CodeGenFunction &CGF,
2407f4a2713aSLionel Sambuc                           const CallArgList::Writeback &writeback) {
2408f4a2713aSLionel Sambuc   const LValue &srcLV = writeback.Source;
2409f4a2713aSLionel Sambuc   llvm::Value *srcAddr = srcLV.getAddress();
2410f4a2713aSLionel Sambuc   assert(!isProvablyNull(srcAddr) &&
2411f4a2713aSLionel Sambuc          "shouldn't have writeback for provably null argument");
2412f4a2713aSLionel Sambuc 
2413*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *contBB = nullptr;
2414f4a2713aSLionel Sambuc 
2415f4a2713aSLionel Sambuc   // If the argument wasn't provably non-null, we need to null check
2416f4a2713aSLionel Sambuc   // before doing the store.
2417f4a2713aSLionel Sambuc   bool provablyNonNull = isProvablyNonNull(srcAddr);
2418f4a2713aSLionel Sambuc   if (!provablyNonNull) {
2419f4a2713aSLionel Sambuc     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2420f4a2713aSLionel Sambuc     contBB = CGF.createBasicBlock("icr.done");
2421f4a2713aSLionel Sambuc 
2422f4a2713aSLionel Sambuc     llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2423f4a2713aSLionel Sambuc     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2424f4a2713aSLionel Sambuc     CGF.EmitBlock(writebackBB);
2425f4a2713aSLionel Sambuc   }
2426f4a2713aSLionel Sambuc 
2427f4a2713aSLionel Sambuc   // Load the value to writeback.
2428f4a2713aSLionel Sambuc   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2429f4a2713aSLionel Sambuc 
2430f4a2713aSLionel Sambuc   // Cast it back, in case we're writing an id to a Foo* or something.
2431f4a2713aSLionel Sambuc   value = CGF.Builder.CreateBitCast(value,
2432f4a2713aSLionel Sambuc                cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2433f4a2713aSLionel Sambuc                             "icr.writeback-cast");
2434f4a2713aSLionel Sambuc 
2435f4a2713aSLionel Sambuc   // Perform the writeback.
2436f4a2713aSLionel Sambuc 
2437f4a2713aSLionel Sambuc   // If we have a "to use" value, it's something we need to emit a use
2438f4a2713aSLionel Sambuc   // of.  This has to be carefully threaded in: if it's done after the
2439f4a2713aSLionel Sambuc   // release it's potentially undefined behavior (and the optimizer
2440f4a2713aSLionel Sambuc   // will ignore it), and if it happens before the retain then the
2441f4a2713aSLionel Sambuc   // optimizer could move the release there.
2442f4a2713aSLionel Sambuc   if (writeback.ToUse) {
2443f4a2713aSLionel Sambuc     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2444f4a2713aSLionel Sambuc 
2445f4a2713aSLionel Sambuc     // Retain the new value.  No need to block-copy here:  the block's
2446f4a2713aSLionel Sambuc     // being passed up the stack.
2447f4a2713aSLionel Sambuc     value = CGF.EmitARCRetainNonBlock(value);
2448f4a2713aSLionel Sambuc 
2449f4a2713aSLionel Sambuc     // Emit the intrinsic use here.
2450f4a2713aSLionel Sambuc     CGF.EmitARCIntrinsicUse(writeback.ToUse);
2451f4a2713aSLionel Sambuc 
2452f4a2713aSLionel Sambuc     // Load the old value (primitively).
2453f4a2713aSLionel Sambuc     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
2454f4a2713aSLionel Sambuc 
2455f4a2713aSLionel Sambuc     // Put the new value in place (primitively).
2456f4a2713aSLionel Sambuc     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2457f4a2713aSLionel Sambuc 
2458f4a2713aSLionel Sambuc     // Release the old value.
2459f4a2713aSLionel Sambuc     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2460f4a2713aSLionel Sambuc 
2461f4a2713aSLionel Sambuc   // Otherwise, we can just do a normal lvalue store.
2462f4a2713aSLionel Sambuc   } else {
2463f4a2713aSLionel Sambuc     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2464f4a2713aSLionel Sambuc   }
2465f4a2713aSLionel Sambuc 
2466f4a2713aSLionel Sambuc   // Jump to the continuation block.
2467f4a2713aSLionel Sambuc   if (!provablyNonNull)
2468f4a2713aSLionel Sambuc     CGF.EmitBlock(contBB);
2469f4a2713aSLionel Sambuc }
2470f4a2713aSLionel Sambuc 
emitWritebacks(CodeGenFunction & CGF,const CallArgList & args)2471f4a2713aSLionel Sambuc static void emitWritebacks(CodeGenFunction &CGF,
2472f4a2713aSLionel Sambuc                            const CallArgList &args) {
2473*0a6a1f1dSLionel Sambuc   for (const auto &I : args.writebacks())
2474*0a6a1f1dSLionel Sambuc     emitWriteback(CGF, I);
2475f4a2713aSLionel Sambuc }
2476f4a2713aSLionel Sambuc 
deactivateArgCleanupsBeforeCall(CodeGenFunction & CGF,const CallArgList & CallArgs)2477f4a2713aSLionel Sambuc static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2478f4a2713aSLionel Sambuc                                             const CallArgList &CallArgs) {
2479*0a6a1f1dSLionel Sambuc   assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
2480f4a2713aSLionel Sambuc   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2481f4a2713aSLionel Sambuc     CallArgs.getCleanupsToDeactivate();
2482f4a2713aSLionel Sambuc   // Iterate in reverse to increase the likelihood of popping the cleanup.
2483f4a2713aSLionel Sambuc   for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2484f4a2713aSLionel Sambuc          I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2485f4a2713aSLionel Sambuc     CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2486f4a2713aSLionel Sambuc     I->IsActiveIP->eraseFromParent();
2487f4a2713aSLionel Sambuc   }
2488f4a2713aSLionel Sambuc }
2489f4a2713aSLionel Sambuc 
maybeGetUnaryAddrOfOperand(const Expr * E)2490f4a2713aSLionel Sambuc static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2491f4a2713aSLionel Sambuc   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2492f4a2713aSLionel Sambuc     if (uop->getOpcode() == UO_AddrOf)
2493f4a2713aSLionel Sambuc       return uop->getSubExpr();
2494*0a6a1f1dSLionel Sambuc   return nullptr;
2495f4a2713aSLionel Sambuc }
2496f4a2713aSLionel Sambuc 
2497f4a2713aSLionel Sambuc /// Emit an argument that's being passed call-by-writeback.  That is,
2498f4a2713aSLionel Sambuc /// we are passing the address of
emitWritebackArg(CodeGenFunction & CGF,CallArgList & args,const ObjCIndirectCopyRestoreExpr * CRE)2499f4a2713aSLionel Sambuc static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2500f4a2713aSLionel Sambuc                              const ObjCIndirectCopyRestoreExpr *CRE) {
2501f4a2713aSLionel Sambuc   LValue srcLV;
2502f4a2713aSLionel Sambuc 
2503f4a2713aSLionel Sambuc   // Make an optimistic effort to emit the address as an l-value.
2504f4a2713aSLionel Sambuc   // This can fail if the the argument expression is more complicated.
2505f4a2713aSLionel Sambuc   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2506f4a2713aSLionel Sambuc     srcLV = CGF.EmitLValue(lvExpr);
2507f4a2713aSLionel Sambuc 
2508f4a2713aSLionel Sambuc   // Otherwise, just emit it as a scalar.
2509f4a2713aSLionel Sambuc   } else {
2510f4a2713aSLionel Sambuc     llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2511f4a2713aSLionel Sambuc 
2512f4a2713aSLionel Sambuc     QualType srcAddrType =
2513f4a2713aSLionel Sambuc       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2514f4a2713aSLionel Sambuc     srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2515f4a2713aSLionel Sambuc   }
2516f4a2713aSLionel Sambuc   llvm::Value *srcAddr = srcLV.getAddress();
2517f4a2713aSLionel Sambuc 
2518f4a2713aSLionel Sambuc   // The dest and src types don't necessarily match in LLVM terms
2519f4a2713aSLionel Sambuc   // because of the crazy ObjC compatibility rules.
2520f4a2713aSLionel Sambuc 
2521f4a2713aSLionel Sambuc   llvm::PointerType *destType =
2522f4a2713aSLionel Sambuc     cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2523f4a2713aSLionel Sambuc 
2524f4a2713aSLionel Sambuc   // If the address is a constant null, just pass the appropriate null.
2525f4a2713aSLionel Sambuc   if (isProvablyNull(srcAddr)) {
2526f4a2713aSLionel Sambuc     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2527f4a2713aSLionel Sambuc              CRE->getType());
2528f4a2713aSLionel Sambuc     return;
2529f4a2713aSLionel Sambuc   }
2530f4a2713aSLionel Sambuc 
2531f4a2713aSLionel Sambuc   // Create the temporary.
2532f4a2713aSLionel Sambuc   llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2533f4a2713aSLionel Sambuc                                            "icr.temp");
2534f4a2713aSLionel Sambuc   // Loading an l-value can introduce a cleanup if the l-value is __weak,
2535f4a2713aSLionel Sambuc   // and that cleanup will be conditional if we can't prove that the l-value
2536f4a2713aSLionel Sambuc   // isn't null, so we need to register a dominating point so that the cleanups
2537f4a2713aSLionel Sambuc   // system will make valid IR.
2538f4a2713aSLionel Sambuc   CodeGenFunction::ConditionalEvaluation condEval(CGF);
2539f4a2713aSLionel Sambuc 
2540f4a2713aSLionel Sambuc   // Zero-initialize it if we're not doing a copy-initialization.
2541f4a2713aSLionel Sambuc   bool shouldCopy = CRE->shouldCopy();
2542f4a2713aSLionel Sambuc   if (!shouldCopy) {
2543f4a2713aSLionel Sambuc     llvm::Value *null =
2544f4a2713aSLionel Sambuc       llvm::ConstantPointerNull::get(
2545f4a2713aSLionel Sambuc         cast<llvm::PointerType>(destType->getElementType()));
2546f4a2713aSLionel Sambuc     CGF.Builder.CreateStore(null, temp);
2547f4a2713aSLionel Sambuc   }
2548f4a2713aSLionel Sambuc 
2549*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *contBB = nullptr;
2550*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *originBB = nullptr;
2551f4a2713aSLionel Sambuc 
2552f4a2713aSLionel Sambuc   // If the address is *not* known to be non-null, we need to switch.
2553f4a2713aSLionel Sambuc   llvm::Value *finalArgument;
2554f4a2713aSLionel Sambuc 
2555f4a2713aSLionel Sambuc   bool provablyNonNull = isProvablyNonNull(srcAddr);
2556f4a2713aSLionel Sambuc   if (provablyNonNull) {
2557f4a2713aSLionel Sambuc     finalArgument = temp;
2558f4a2713aSLionel Sambuc   } else {
2559f4a2713aSLionel Sambuc     llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2560f4a2713aSLionel Sambuc 
2561f4a2713aSLionel Sambuc     finalArgument = CGF.Builder.CreateSelect(isNull,
2562f4a2713aSLionel Sambuc                                    llvm::ConstantPointerNull::get(destType),
2563f4a2713aSLionel Sambuc                                              temp, "icr.argument");
2564f4a2713aSLionel Sambuc 
2565f4a2713aSLionel Sambuc     // If we need to copy, then the load has to be conditional, which
2566f4a2713aSLionel Sambuc     // means we need control flow.
2567f4a2713aSLionel Sambuc     if (shouldCopy) {
2568f4a2713aSLionel Sambuc       originBB = CGF.Builder.GetInsertBlock();
2569f4a2713aSLionel Sambuc       contBB = CGF.createBasicBlock("icr.cont");
2570f4a2713aSLionel Sambuc       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2571f4a2713aSLionel Sambuc       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2572f4a2713aSLionel Sambuc       CGF.EmitBlock(copyBB);
2573f4a2713aSLionel Sambuc       condEval.begin(CGF);
2574f4a2713aSLionel Sambuc     }
2575f4a2713aSLionel Sambuc   }
2576f4a2713aSLionel Sambuc 
2577*0a6a1f1dSLionel Sambuc   llvm::Value *valueToUse = nullptr;
2578f4a2713aSLionel Sambuc 
2579f4a2713aSLionel Sambuc   // Perform a copy if necessary.
2580f4a2713aSLionel Sambuc   if (shouldCopy) {
2581f4a2713aSLionel Sambuc     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
2582f4a2713aSLionel Sambuc     assert(srcRV.isScalar());
2583f4a2713aSLionel Sambuc 
2584f4a2713aSLionel Sambuc     llvm::Value *src = srcRV.getScalarVal();
2585f4a2713aSLionel Sambuc     src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2586f4a2713aSLionel Sambuc                                     "icr.cast");
2587f4a2713aSLionel Sambuc 
2588f4a2713aSLionel Sambuc     // Use an ordinary store, not a store-to-lvalue.
2589f4a2713aSLionel Sambuc     CGF.Builder.CreateStore(src, temp);
2590f4a2713aSLionel Sambuc 
2591f4a2713aSLionel Sambuc     // If optimization is enabled, and the value was held in a
2592f4a2713aSLionel Sambuc     // __strong variable, we need to tell the optimizer that this
2593f4a2713aSLionel Sambuc     // value has to stay alive until we're doing the store back.
2594f4a2713aSLionel Sambuc     // This is because the temporary is effectively unretained,
2595f4a2713aSLionel Sambuc     // and so otherwise we can violate the high-level semantics.
2596f4a2713aSLionel Sambuc     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2597f4a2713aSLionel Sambuc         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2598f4a2713aSLionel Sambuc       valueToUse = src;
2599f4a2713aSLionel Sambuc     }
2600f4a2713aSLionel Sambuc   }
2601f4a2713aSLionel Sambuc 
2602f4a2713aSLionel Sambuc   // Finish the control flow if we needed it.
2603f4a2713aSLionel Sambuc   if (shouldCopy && !provablyNonNull) {
2604f4a2713aSLionel Sambuc     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
2605f4a2713aSLionel Sambuc     CGF.EmitBlock(contBB);
2606f4a2713aSLionel Sambuc 
2607f4a2713aSLionel Sambuc     // Make a phi for the value to intrinsically use.
2608f4a2713aSLionel Sambuc     if (valueToUse) {
2609f4a2713aSLionel Sambuc       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2610f4a2713aSLionel Sambuc                                                       "icr.to-use");
2611f4a2713aSLionel Sambuc       phiToUse->addIncoming(valueToUse, copyBB);
2612f4a2713aSLionel Sambuc       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2613f4a2713aSLionel Sambuc                             originBB);
2614f4a2713aSLionel Sambuc       valueToUse = phiToUse;
2615f4a2713aSLionel Sambuc     }
2616f4a2713aSLionel Sambuc 
2617f4a2713aSLionel Sambuc     condEval.end(CGF);
2618f4a2713aSLionel Sambuc   }
2619f4a2713aSLionel Sambuc 
2620f4a2713aSLionel Sambuc   args.addWriteback(srcLV, temp, valueToUse);
2621f4a2713aSLionel Sambuc   args.add(RValue::get(finalArgument), CRE->getType());
2622f4a2713aSLionel Sambuc }
2623f4a2713aSLionel Sambuc 
allocateArgumentMemory(CodeGenFunction & CGF)2624*0a6a1f1dSLionel Sambuc void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2625*0a6a1f1dSLionel Sambuc   assert(!StackBase && !StackCleanup.isValid());
2626*0a6a1f1dSLionel Sambuc 
2627*0a6a1f1dSLionel Sambuc   // Save the stack.
2628*0a6a1f1dSLionel Sambuc   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2629*0a6a1f1dSLionel Sambuc   StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2630*0a6a1f1dSLionel Sambuc 
2631*0a6a1f1dSLionel Sambuc   // Control gets really tied up in landing pads, so we have to spill the
2632*0a6a1f1dSLionel Sambuc   // stacksave to an alloca to avoid violating SSA form.
2633*0a6a1f1dSLionel Sambuc   // TODO: This is dead if we never emit the cleanup.  We should create the
2634*0a6a1f1dSLionel Sambuc   // alloca and store lazily on the first cleanup emission.
2635*0a6a1f1dSLionel Sambuc   StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2636*0a6a1f1dSLionel Sambuc   CGF.Builder.CreateStore(StackBase, StackBaseMem);
2637*0a6a1f1dSLionel Sambuc   CGF.pushStackRestore(EHCleanup, StackBaseMem);
2638*0a6a1f1dSLionel Sambuc   StackCleanup = CGF.EHStack.getInnermostEHScope();
2639*0a6a1f1dSLionel Sambuc   assert(StackCleanup.isValid());
2640*0a6a1f1dSLionel Sambuc }
2641*0a6a1f1dSLionel Sambuc 
freeArgumentMemory(CodeGenFunction & CGF) const2642*0a6a1f1dSLionel Sambuc void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2643*0a6a1f1dSLionel Sambuc   if (StackBase) {
2644*0a6a1f1dSLionel Sambuc     CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2645*0a6a1f1dSLionel Sambuc     llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2646*0a6a1f1dSLionel Sambuc     // We could load StackBase from StackBaseMem, but in the non-exceptional
2647*0a6a1f1dSLionel Sambuc     // case we can skip it.
2648*0a6a1f1dSLionel Sambuc     CGF.Builder.CreateCall(F, StackBase);
2649*0a6a1f1dSLionel Sambuc   }
2650*0a6a1f1dSLionel Sambuc }
2651*0a6a1f1dSLionel Sambuc 
emitNonNullArgCheck(CodeGenFunction & CGF,RValue RV,QualType ArgType,SourceLocation ArgLoc,const FunctionDecl * FD,unsigned ParmNum)2652*0a6a1f1dSLionel Sambuc static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2653*0a6a1f1dSLionel Sambuc                                 QualType ArgType, SourceLocation ArgLoc,
2654*0a6a1f1dSLionel Sambuc                                 const FunctionDecl *FD, unsigned ParmNum) {
2655*0a6a1f1dSLionel Sambuc   if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
2656*0a6a1f1dSLionel Sambuc     return;
2657*0a6a1f1dSLionel Sambuc   auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2658*0a6a1f1dSLionel Sambuc   unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2659*0a6a1f1dSLionel Sambuc   auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2660*0a6a1f1dSLionel Sambuc   if (!NNAttr)
2661*0a6a1f1dSLionel Sambuc     return;
2662*0a6a1f1dSLionel Sambuc   CodeGenFunction::SanitizerScope SanScope(&CGF);
2663*0a6a1f1dSLionel Sambuc   assert(RV.isScalar());
2664*0a6a1f1dSLionel Sambuc   llvm::Value *V = RV.getScalarVal();
2665*0a6a1f1dSLionel Sambuc   llvm::Value *Cond =
2666*0a6a1f1dSLionel Sambuc       CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2667*0a6a1f1dSLionel Sambuc   llvm::Constant *StaticData[] = {
2668*0a6a1f1dSLionel Sambuc       CGF.EmitCheckSourceLocation(ArgLoc),
2669*0a6a1f1dSLionel Sambuc       CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2670*0a6a1f1dSLionel Sambuc       llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2671*0a6a1f1dSLionel Sambuc   };
2672*0a6a1f1dSLionel Sambuc   CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2673*0a6a1f1dSLionel Sambuc                 "nonnull_arg", StaticData, None);
2674*0a6a1f1dSLionel Sambuc }
2675*0a6a1f1dSLionel Sambuc 
EmitCallArgs(CallArgList & Args,ArrayRef<QualType> ArgTypes,CallExpr::const_arg_iterator ArgBeg,CallExpr::const_arg_iterator ArgEnd,const FunctionDecl * CalleeDecl,unsigned ParamsToSkip,bool ForceColumnInfo)2676*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2677*0a6a1f1dSLionel Sambuc                                    ArrayRef<QualType> ArgTypes,
2678*0a6a1f1dSLionel Sambuc                                    CallExpr::const_arg_iterator ArgBeg,
2679*0a6a1f1dSLionel Sambuc                                    CallExpr::const_arg_iterator ArgEnd,
2680*0a6a1f1dSLionel Sambuc                                    const FunctionDecl *CalleeDecl,
2681*0a6a1f1dSLionel Sambuc                                    unsigned ParamsToSkip,
2682*0a6a1f1dSLionel Sambuc                                    bool ForceColumnInfo) {
2683*0a6a1f1dSLionel Sambuc   CGDebugInfo *DI = getDebugInfo();
2684*0a6a1f1dSLionel Sambuc   SourceLocation CallLoc;
2685*0a6a1f1dSLionel Sambuc   if (DI) CallLoc = DI->getLocation();
2686*0a6a1f1dSLionel Sambuc 
2687*0a6a1f1dSLionel Sambuc   // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2688*0a6a1f1dSLionel Sambuc   // because arguments are destroyed left to right in the callee.
2689*0a6a1f1dSLionel Sambuc   if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2690*0a6a1f1dSLionel Sambuc     // Insert a stack save if we're going to need any inalloca args.
2691*0a6a1f1dSLionel Sambuc     bool HasInAllocaArgs = false;
2692*0a6a1f1dSLionel Sambuc     for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2693*0a6a1f1dSLionel Sambuc          I != E && !HasInAllocaArgs; ++I)
2694*0a6a1f1dSLionel Sambuc       HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2695*0a6a1f1dSLionel Sambuc     if (HasInAllocaArgs) {
2696*0a6a1f1dSLionel Sambuc       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2697*0a6a1f1dSLionel Sambuc       Args.allocateArgumentMemory(*this);
2698*0a6a1f1dSLionel Sambuc     }
2699*0a6a1f1dSLionel Sambuc 
2700*0a6a1f1dSLionel Sambuc     // Evaluate each argument.
2701*0a6a1f1dSLionel Sambuc     size_t CallArgsStart = Args.size();
2702*0a6a1f1dSLionel Sambuc     for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2703*0a6a1f1dSLionel Sambuc       CallExpr::const_arg_iterator Arg = ArgBeg + I;
2704*0a6a1f1dSLionel Sambuc       EmitCallArg(Args, *Arg, ArgTypes[I]);
2705*0a6a1f1dSLionel Sambuc       emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2706*0a6a1f1dSLionel Sambuc                           CalleeDecl, ParamsToSkip + I);
2707*0a6a1f1dSLionel Sambuc       // Restore the debug location.
2708*0a6a1f1dSLionel Sambuc       if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2709*0a6a1f1dSLionel Sambuc     }
2710*0a6a1f1dSLionel Sambuc 
2711*0a6a1f1dSLionel Sambuc     // Un-reverse the arguments we just evaluated so they match up with the LLVM
2712*0a6a1f1dSLionel Sambuc     // IR function.
2713*0a6a1f1dSLionel Sambuc     std::reverse(Args.begin() + CallArgsStart, Args.end());
2714*0a6a1f1dSLionel Sambuc     return;
2715*0a6a1f1dSLionel Sambuc   }
2716*0a6a1f1dSLionel Sambuc 
2717*0a6a1f1dSLionel Sambuc   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2718*0a6a1f1dSLionel Sambuc     CallExpr::const_arg_iterator Arg = ArgBeg + I;
2719*0a6a1f1dSLionel Sambuc     assert(Arg != ArgEnd);
2720*0a6a1f1dSLionel Sambuc     EmitCallArg(Args, *Arg, ArgTypes[I]);
2721*0a6a1f1dSLionel Sambuc     emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2722*0a6a1f1dSLionel Sambuc                         CalleeDecl, ParamsToSkip + I);
2723*0a6a1f1dSLionel Sambuc     // Restore the debug location.
2724*0a6a1f1dSLionel Sambuc     if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2725*0a6a1f1dSLionel Sambuc   }
2726*0a6a1f1dSLionel Sambuc }
2727*0a6a1f1dSLionel Sambuc 
2728*0a6a1f1dSLionel Sambuc namespace {
2729*0a6a1f1dSLionel Sambuc 
2730*0a6a1f1dSLionel Sambuc struct DestroyUnpassedArg : EHScopeStack::Cleanup {
DestroyUnpassedArg__anon2e5bceb70311::DestroyUnpassedArg2731*0a6a1f1dSLionel Sambuc   DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2732*0a6a1f1dSLionel Sambuc       : Addr(Addr), Ty(Ty) {}
2733*0a6a1f1dSLionel Sambuc 
2734*0a6a1f1dSLionel Sambuc   llvm::Value *Addr;
2735*0a6a1f1dSLionel Sambuc   QualType Ty;
2736*0a6a1f1dSLionel Sambuc 
Emit__anon2e5bceb70311::DestroyUnpassedArg2737*0a6a1f1dSLionel Sambuc   void Emit(CodeGenFunction &CGF, Flags flags) override {
2738*0a6a1f1dSLionel Sambuc     const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2739*0a6a1f1dSLionel Sambuc     assert(!Dtor->isTrivial());
2740*0a6a1f1dSLionel Sambuc     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2741*0a6a1f1dSLionel Sambuc                               /*Delegating=*/false, Addr);
2742*0a6a1f1dSLionel Sambuc   }
2743*0a6a1f1dSLionel Sambuc };
2744*0a6a1f1dSLionel Sambuc 
2745*0a6a1f1dSLionel Sambuc }
2746*0a6a1f1dSLionel Sambuc 
EmitCallArg(CallArgList & args,const Expr * E,QualType type)2747f4a2713aSLionel Sambuc void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2748f4a2713aSLionel Sambuc                                   QualType type) {
2749f4a2713aSLionel Sambuc   if (const ObjCIndirectCopyRestoreExpr *CRE
2750f4a2713aSLionel Sambuc         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
2751f4a2713aSLionel Sambuc     assert(getLangOpts().ObjCAutoRefCount);
2752f4a2713aSLionel Sambuc     assert(getContext().hasSameType(E->getType(), type));
2753f4a2713aSLionel Sambuc     return emitWritebackArg(*this, args, CRE);
2754f4a2713aSLionel Sambuc   }
2755f4a2713aSLionel Sambuc 
2756f4a2713aSLionel Sambuc   assert(type->isReferenceType() == E->isGLValue() &&
2757f4a2713aSLionel Sambuc          "reference binding to unmaterialized r-value!");
2758f4a2713aSLionel Sambuc 
2759f4a2713aSLionel Sambuc   if (E->isGLValue()) {
2760f4a2713aSLionel Sambuc     assert(E->getObjectKind() == OK_Ordinary);
2761f4a2713aSLionel Sambuc     return args.add(EmitReferenceBindingToExpr(E), type);
2762f4a2713aSLionel Sambuc   }
2763f4a2713aSLionel Sambuc 
2764f4a2713aSLionel Sambuc   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2765f4a2713aSLionel Sambuc 
2766f4a2713aSLionel Sambuc   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2767f4a2713aSLionel Sambuc   // However, we still have to push an EH-only cleanup in case we unwind before
2768f4a2713aSLionel Sambuc   // we make it to the call.
2769f4a2713aSLionel Sambuc   if (HasAggregateEvalKind &&
2770*0a6a1f1dSLionel Sambuc       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2771*0a6a1f1dSLionel Sambuc     // If we're using inalloca, use the argument memory.  Otherwise, use a
2772*0a6a1f1dSLionel Sambuc     // temporary.
2773*0a6a1f1dSLionel Sambuc     AggValueSlot Slot;
2774*0a6a1f1dSLionel Sambuc     if (args.isUsingInAlloca())
2775*0a6a1f1dSLionel Sambuc       Slot = createPlaceholderSlot(*this, type);
2776*0a6a1f1dSLionel Sambuc     else
2777*0a6a1f1dSLionel Sambuc       Slot = CreateAggTemp(type, "agg.tmp");
2778*0a6a1f1dSLionel Sambuc 
2779f4a2713aSLionel Sambuc     const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2780*0a6a1f1dSLionel Sambuc     bool DestroyedInCallee =
2781*0a6a1f1dSLionel Sambuc         RD && RD->hasNonTrivialDestructor() &&
2782*0a6a1f1dSLionel Sambuc         CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2783*0a6a1f1dSLionel Sambuc     if (DestroyedInCallee)
2784f4a2713aSLionel Sambuc       Slot.setExternallyDestructed();
2785*0a6a1f1dSLionel Sambuc 
2786f4a2713aSLionel Sambuc     EmitAggExpr(E, Slot);
2787f4a2713aSLionel Sambuc     RValue RV = Slot.asRValue();
2788f4a2713aSLionel Sambuc     args.add(RV, type);
2789f4a2713aSLionel Sambuc 
2790*0a6a1f1dSLionel Sambuc     if (DestroyedInCallee) {
2791*0a6a1f1dSLionel Sambuc       // Create a no-op GEP between the placeholder and the cleanup so we can
2792*0a6a1f1dSLionel Sambuc       // RAUW it successfully.  It also serves as a marker of the first
2793*0a6a1f1dSLionel Sambuc       // instruction where the cleanup is active.
2794*0a6a1f1dSLionel Sambuc       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
2795f4a2713aSLionel Sambuc       // This unreachable is a temporary marker which will be removed later.
2796f4a2713aSLionel Sambuc       llvm::Instruction *IsActive = Builder.CreateUnreachable();
2797f4a2713aSLionel Sambuc       args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2798f4a2713aSLionel Sambuc     }
2799*0a6a1f1dSLionel Sambuc     return;
2800f4a2713aSLionel Sambuc   }
2801f4a2713aSLionel Sambuc 
2802f4a2713aSLionel Sambuc   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
2803f4a2713aSLionel Sambuc       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2804f4a2713aSLionel Sambuc     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2805f4a2713aSLionel Sambuc     assert(L.isSimple());
2806f4a2713aSLionel Sambuc     if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2807f4a2713aSLionel Sambuc       args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2808f4a2713aSLionel Sambuc     } else {
2809f4a2713aSLionel Sambuc       // We can't represent a misaligned lvalue in the CallArgList, so copy
2810f4a2713aSLionel Sambuc       // to an aligned temporary now.
2811f4a2713aSLionel Sambuc       llvm::Value *tmp = CreateMemTemp(type);
2812f4a2713aSLionel Sambuc       EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2813f4a2713aSLionel Sambuc                         L.getAlignment());
2814f4a2713aSLionel Sambuc       args.add(RValue::getAggregate(tmp), type);
2815f4a2713aSLionel Sambuc     }
2816f4a2713aSLionel Sambuc     return;
2817f4a2713aSLionel Sambuc   }
2818f4a2713aSLionel Sambuc 
2819f4a2713aSLionel Sambuc   args.add(EmitAnyExprToTemp(E), type);
2820f4a2713aSLionel Sambuc }
2821f4a2713aSLionel Sambuc 
getVarArgType(const Expr * Arg)2822*0a6a1f1dSLionel Sambuc QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2823*0a6a1f1dSLionel Sambuc   // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2824*0a6a1f1dSLionel Sambuc   // implicitly widens null pointer constants that are arguments to varargs
2825*0a6a1f1dSLionel Sambuc   // functions to pointer-sized ints.
2826*0a6a1f1dSLionel Sambuc   if (!getTarget().getTriple().isOSWindows())
2827*0a6a1f1dSLionel Sambuc     return Arg->getType();
2828*0a6a1f1dSLionel Sambuc 
2829*0a6a1f1dSLionel Sambuc   if (Arg->getType()->isIntegerType() &&
2830*0a6a1f1dSLionel Sambuc       getContext().getTypeSize(Arg->getType()) <
2831*0a6a1f1dSLionel Sambuc           getContext().getTargetInfo().getPointerWidth(0) &&
2832*0a6a1f1dSLionel Sambuc       Arg->isNullPointerConstant(getContext(),
2833*0a6a1f1dSLionel Sambuc                                  Expr::NPC_ValueDependentIsNotNull)) {
2834*0a6a1f1dSLionel Sambuc     return getContext().getIntPtrType();
2835*0a6a1f1dSLionel Sambuc   }
2836*0a6a1f1dSLionel Sambuc 
2837*0a6a1f1dSLionel Sambuc   return Arg->getType();
2838*0a6a1f1dSLionel Sambuc }
2839*0a6a1f1dSLionel Sambuc 
2840f4a2713aSLionel Sambuc // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2841f4a2713aSLionel Sambuc // optimizer it can aggressively ignore unwind edges.
2842f4a2713aSLionel Sambuc void
AddObjCARCExceptionMetadata(llvm::Instruction * Inst)2843f4a2713aSLionel Sambuc CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2844f4a2713aSLionel Sambuc   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2845f4a2713aSLionel Sambuc       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2846f4a2713aSLionel Sambuc     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2847f4a2713aSLionel Sambuc                       CGM.getNoObjCARCExceptionsMetadata());
2848f4a2713aSLionel Sambuc }
2849f4a2713aSLionel Sambuc 
2850f4a2713aSLionel Sambuc /// Emits a call to the given no-arguments nounwind runtime function.
2851f4a2713aSLionel Sambuc llvm::CallInst *
EmitNounwindRuntimeCall(llvm::Value * callee,const llvm::Twine & name)2852f4a2713aSLionel Sambuc CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2853f4a2713aSLionel Sambuc                                          const llvm::Twine &name) {
2854*0a6a1f1dSLionel Sambuc   return EmitNounwindRuntimeCall(callee, None, name);
2855f4a2713aSLionel Sambuc }
2856f4a2713aSLionel Sambuc 
2857f4a2713aSLionel Sambuc /// Emits a call to the given nounwind runtime function.
2858f4a2713aSLionel Sambuc llvm::CallInst *
EmitNounwindRuntimeCall(llvm::Value * callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)2859f4a2713aSLionel Sambuc CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2860f4a2713aSLionel Sambuc                                          ArrayRef<llvm::Value*> args,
2861f4a2713aSLionel Sambuc                                          const llvm::Twine &name) {
2862f4a2713aSLionel Sambuc   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2863f4a2713aSLionel Sambuc   call->setDoesNotThrow();
2864f4a2713aSLionel Sambuc   return call;
2865f4a2713aSLionel Sambuc }
2866f4a2713aSLionel Sambuc 
2867f4a2713aSLionel Sambuc /// Emits a simple call (never an invoke) to the given no-arguments
2868f4a2713aSLionel Sambuc /// runtime function.
2869f4a2713aSLionel Sambuc llvm::CallInst *
EmitRuntimeCall(llvm::Value * callee,const llvm::Twine & name)2870f4a2713aSLionel Sambuc CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2871f4a2713aSLionel Sambuc                                  const llvm::Twine &name) {
2872*0a6a1f1dSLionel Sambuc   return EmitRuntimeCall(callee, None, name);
2873f4a2713aSLionel Sambuc }
2874f4a2713aSLionel Sambuc 
2875f4a2713aSLionel Sambuc /// Emits a simple call (never an invoke) to the given runtime
2876f4a2713aSLionel Sambuc /// function.
2877f4a2713aSLionel Sambuc llvm::CallInst *
EmitRuntimeCall(llvm::Value * callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)2878f4a2713aSLionel Sambuc CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2879f4a2713aSLionel Sambuc                                  ArrayRef<llvm::Value*> args,
2880f4a2713aSLionel Sambuc                                  const llvm::Twine &name) {
2881f4a2713aSLionel Sambuc   llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2882f4a2713aSLionel Sambuc   call->setCallingConv(getRuntimeCC());
2883f4a2713aSLionel Sambuc   return call;
2884f4a2713aSLionel Sambuc }
2885f4a2713aSLionel Sambuc 
2886f4a2713aSLionel Sambuc /// Emits a call or invoke to the given noreturn runtime function.
EmitNoreturnRuntimeCallOrInvoke(llvm::Value * callee,ArrayRef<llvm::Value * > args)2887f4a2713aSLionel Sambuc void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2888f4a2713aSLionel Sambuc                                                ArrayRef<llvm::Value*> args) {
2889f4a2713aSLionel Sambuc   if (getInvokeDest()) {
2890f4a2713aSLionel Sambuc     llvm::InvokeInst *invoke =
2891f4a2713aSLionel Sambuc       Builder.CreateInvoke(callee,
2892f4a2713aSLionel Sambuc                            getUnreachableBlock(),
2893f4a2713aSLionel Sambuc                            getInvokeDest(),
2894f4a2713aSLionel Sambuc                            args);
2895f4a2713aSLionel Sambuc     invoke->setDoesNotReturn();
2896f4a2713aSLionel Sambuc     invoke->setCallingConv(getRuntimeCC());
2897f4a2713aSLionel Sambuc   } else {
2898f4a2713aSLionel Sambuc     llvm::CallInst *call = Builder.CreateCall(callee, args);
2899f4a2713aSLionel Sambuc     call->setDoesNotReturn();
2900f4a2713aSLionel Sambuc     call->setCallingConv(getRuntimeCC());
2901f4a2713aSLionel Sambuc     Builder.CreateUnreachable();
2902f4a2713aSLionel Sambuc   }
2903*0a6a1f1dSLionel Sambuc   PGO.setCurrentRegionUnreachable();
2904f4a2713aSLionel Sambuc }
2905f4a2713aSLionel Sambuc 
2906f4a2713aSLionel Sambuc /// Emits a call or invoke instruction to the given nullary runtime
2907f4a2713aSLionel Sambuc /// function.
2908f4a2713aSLionel Sambuc llvm::CallSite
EmitRuntimeCallOrInvoke(llvm::Value * callee,const Twine & name)2909f4a2713aSLionel Sambuc CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2910f4a2713aSLionel Sambuc                                          const Twine &name) {
2911*0a6a1f1dSLionel Sambuc   return EmitRuntimeCallOrInvoke(callee, None, name);
2912f4a2713aSLionel Sambuc }
2913f4a2713aSLionel Sambuc 
2914f4a2713aSLionel Sambuc /// Emits a call or invoke instruction to the given runtime function.
2915f4a2713aSLionel Sambuc llvm::CallSite
EmitRuntimeCallOrInvoke(llvm::Value * callee,ArrayRef<llvm::Value * > args,const Twine & name)2916f4a2713aSLionel Sambuc CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2917f4a2713aSLionel Sambuc                                          ArrayRef<llvm::Value*> args,
2918f4a2713aSLionel Sambuc                                          const Twine &name) {
2919f4a2713aSLionel Sambuc   llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2920f4a2713aSLionel Sambuc   callSite.setCallingConv(getRuntimeCC());
2921f4a2713aSLionel Sambuc   return callSite;
2922f4a2713aSLionel Sambuc }
2923f4a2713aSLionel Sambuc 
2924f4a2713aSLionel Sambuc llvm::CallSite
EmitCallOrInvoke(llvm::Value * Callee,const Twine & Name)2925f4a2713aSLionel Sambuc CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2926f4a2713aSLionel Sambuc                                   const Twine &Name) {
2927*0a6a1f1dSLionel Sambuc   return EmitCallOrInvoke(Callee, None, Name);
2928f4a2713aSLionel Sambuc }
2929f4a2713aSLionel Sambuc 
2930f4a2713aSLionel Sambuc /// Emits a call or invoke instruction to the given function, depending
2931f4a2713aSLionel Sambuc /// on the current state of the EH stack.
2932f4a2713aSLionel Sambuc llvm::CallSite
EmitCallOrInvoke(llvm::Value * Callee,ArrayRef<llvm::Value * > Args,const Twine & Name)2933f4a2713aSLionel Sambuc CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2934f4a2713aSLionel Sambuc                                   ArrayRef<llvm::Value *> Args,
2935f4a2713aSLionel Sambuc                                   const Twine &Name) {
2936f4a2713aSLionel Sambuc   llvm::BasicBlock *InvokeDest = getInvokeDest();
2937f4a2713aSLionel Sambuc 
2938f4a2713aSLionel Sambuc   llvm::Instruction *Inst;
2939f4a2713aSLionel Sambuc   if (!InvokeDest)
2940f4a2713aSLionel Sambuc     Inst = Builder.CreateCall(Callee, Args, Name);
2941f4a2713aSLionel Sambuc   else {
2942f4a2713aSLionel Sambuc     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2943f4a2713aSLionel Sambuc     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2944f4a2713aSLionel Sambuc     EmitBlock(ContBB);
2945f4a2713aSLionel Sambuc   }
2946f4a2713aSLionel Sambuc 
2947f4a2713aSLionel Sambuc   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2948f4a2713aSLionel Sambuc   // optimizer it can aggressively ignore unwind edges.
2949f4a2713aSLionel Sambuc   if (CGM.getLangOpts().ObjCAutoRefCount)
2950f4a2713aSLionel Sambuc     AddObjCARCExceptionMetadata(Inst);
2951f4a2713aSLionel Sambuc 
2952f4a2713aSLionel Sambuc   return Inst;
2953f4a2713aSLionel Sambuc }
2954f4a2713aSLionel Sambuc 
2955*0a6a1f1dSLionel Sambuc /// \brief Store a non-aggregate value to an address to initialize it.  For
2956*0a6a1f1dSLionel Sambuc /// initialization, a non-atomic store will be used.
EmitInitStoreOfNonAggregate(CodeGenFunction & CGF,RValue Src,LValue Dst)2957*0a6a1f1dSLionel Sambuc static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2958*0a6a1f1dSLionel Sambuc                                         LValue Dst) {
2959*0a6a1f1dSLionel Sambuc   if (Src.isScalar())
2960*0a6a1f1dSLionel Sambuc     CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2961f4a2713aSLionel Sambuc   else
2962*0a6a1f1dSLionel Sambuc     CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2963f4a2713aSLionel Sambuc }
2964f4a2713aSLionel Sambuc 
deferPlaceholderReplacement(llvm::Instruction * Old,llvm::Value * New)2965*0a6a1f1dSLionel Sambuc void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2966*0a6a1f1dSLionel Sambuc                                                   llvm::Value *New) {
2967*0a6a1f1dSLionel Sambuc   DeferredReplacements.push_back(std::make_pair(Old, New));
2968f4a2713aSLionel Sambuc }
2969f4a2713aSLionel Sambuc 
EmitCall(const CGFunctionInfo & CallInfo,llvm::Value * Callee,ReturnValueSlot ReturnValue,const CallArgList & CallArgs,const Decl * TargetDecl,llvm::Instruction ** callOrInvoke)2970f4a2713aSLionel Sambuc RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
2971f4a2713aSLionel Sambuc                                  llvm::Value *Callee,
2972f4a2713aSLionel Sambuc                                  ReturnValueSlot ReturnValue,
2973f4a2713aSLionel Sambuc                                  const CallArgList &CallArgs,
2974f4a2713aSLionel Sambuc                                  const Decl *TargetDecl,
2975f4a2713aSLionel Sambuc                                  llvm::Instruction **callOrInvoke) {
2976f4a2713aSLionel Sambuc   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
2977f4a2713aSLionel Sambuc 
2978f4a2713aSLionel Sambuc   // Handle struct-return functions by passing a pointer to the
2979f4a2713aSLionel Sambuc   // location that we would like to return into.
2980f4a2713aSLionel Sambuc   QualType RetTy = CallInfo.getReturnType();
2981f4a2713aSLionel Sambuc   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
2982f4a2713aSLionel Sambuc 
2983f4a2713aSLionel Sambuc   llvm::FunctionType *IRFuncTy =
2984f4a2713aSLionel Sambuc     cast<llvm::FunctionType>(
2985f4a2713aSLionel Sambuc                   cast<llvm::PointerType>(Callee->getType())->getElementType());
2986f4a2713aSLionel Sambuc 
2987*0a6a1f1dSLionel Sambuc   // If we're using inalloca, insert the allocation after the stack save.
2988*0a6a1f1dSLionel Sambuc   // FIXME: Do this earlier rather than hacking it in here!
2989*0a6a1f1dSLionel Sambuc   llvm::Value *ArgMemory = nullptr;
2990*0a6a1f1dSLionel Sambuc   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
2991*0a6a1f1dSLionel Sambuc     llvm::Instruction *IP = CallArgs.getStackBase();
2992*0a6a1f1dSLionel Sambuc     llvm::AllocaInst *AI;
2993*0a6a1f1dSLionel Sambuc     if (IP) {
2994*0a6a1f1dSLionel Sambuc       IP = IP->getNextNode();
2995*0a6a1f1dSLionel Sambuc       AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2996*0a6a1f1dSLionel Sambuc     } else {
2997*0a6a1f1dSLionel Sambuc       AI = CreateTempAlloca(ArgStruct, "argmem");
2998*0a6a1f1dSLionel Sambuc     }
2999*0a6a1f1dSLionel Sambuc     AI->setUsedWithInAlloca(true);
3000*0a6a1f1dSLionel Sambuc     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3001*0a6a1f1dSLionel Sambuc     ArgMemory = AI;
3002*0a6a1f1dSLionel Sambuc   }
3003*0a6a1f1dSLionel Sambuc 
3004*0a6a1f1dSLionel Sambuc   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
3005*0a6a1f1dSLionel Sambuc   SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3006*0a6a1f1dSLionel Sambuc 
3007f4a2713aSLionel Sambuc   // If the call returns a temporary with struct return, create a temporary
3008f4a2713aSLionel Sambuc   // alloca to hold the result, unless one is given to us.
3009*0a6a1f1dSLionel Sambuc   llvm::Value *SRetPtr = nullptr;
3010*0a6a1f1dSLionel Sambuc   if (RetAI.isIndirect() || RetAI.isInAlloca()) {
3011*0a6a1f1dSLionel Sambuc     SRetPtr = ReturnValue.getValue();
3012*0a6a1f1dSLionel Sambuc     if (!SRetPtr)
3013*0a6a1f1dSLionel Sambuc       SRetPtr = CreateMemTemp(RetTy);
3014*0a6a1f1dSLionel Sambuc     if (IRFunctionArgs.hasSRetArg()) {
3015*0a6a1f1dSLionel Sambuc       IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
3016*0a6a1f1dSLionel Sambuc     } else {
3017*0a6a1f1dSLionel Sambuc       llvm::Value *Addr =
3018*0a6a1f1dSLionel Sambuc           Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
3019*0a6a1f1dSLionel Sambuc       Builder.CreateStore(SRetPtr, Addr);
3020*0a6a1f1dSLionel Sambuc     }
3021f4a2713aSLionel Sambuc   }
3022f4a2713aSLionel Sambuc 
3023f4a2713aSLionel Sambuc   assert(CallInfo.arg_size() == CallArgs.size() &&
3024f4a2713aSLionel Sambuc          "Mismatch between function signature & arguments.");
3025*0a6a1f1dSLionel Sambuc   unsigned ArgNo = 0;
3026f4a2713aSLionel Sambuc   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
3027f4a2713aSLionel Sambuc   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
3028*0a6a1f1dSLionel Sambuc        I != E; ++I, ++info_it, ++ArgNo) {
3029f4a2713aSLionel Sambuc     const ABIArgInfo &ArgInfo = info_it->info;
3030f4a2713aSLionel Sambuc     RValue RV = I->RV;
3031f4a2713aSLionel Sambuc 
3032f4a2713aSLionel Sambuc     CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
3033f4a2713aSLionel Sambuc 
3034f4a2713aSLionel Sambuc     // Insert a padding argument to ensure proper alignment.
3035*0a6a1f1dSLionel Sambuc     if (IRFunctionArgs.hasPaddingArg(ArgNo))
3036*0a6a1f1dSLionel Sambuc       IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3037*0a6a1f1dSLionel Sambuc           llvm::UndefValue::get(ArgInfo.getPaddingType());
3038*0a6a1f1dSLionel Sambuc 
3039*0a6a1f1dSLionel Sambuc     unsigned FirstIRArg, NumIRArgs;
3040*0a6a1f1dSLionel Sambuc     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3041f4a2713aSLionel Sambuc 
3042f4a2713aSLionel Sambuc     switch (ArgInfo.getKind()) {
3043*0a6a1f1dSLionel Sambuc     case ABIArgInfo::InAlloca: {
3044*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 0);
3045*0a6a1f1dSLionel Sambuc       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3046*0a6a1f1dSLionel Sambuc       if (RV.isAggregate()) {
3047*0a6a1f1dSLionel Sambuc         // Replace the placeholder with the appropriate argument slot GEP.
3048*0a6a1f1dSLionel Sambuc         llvm::Instruction *Placeholder =
3049*0a6a1f1dSLionel Sambuc             cast<llvm::Instruction>(RV.getAggregateAddr());
3050*0a6a1f1dSLionel Sambuc         CGBuilderTy::InsertPoint IP = Builder.saveIP();
3051*0a6a1f1dSLionel Sambuc         Builder.SetInsertPoint(Placeholder);
3052*0a6a1f1dSLionel Sambuc         llvm::Value *Addr = Builder.CreateStructGEP(
3053*0a6a1f1dSLionel Sambuc             ArgMemory, ArgInfo.getInAllocaFieldIndex());
3054*0a6a1f1dSLionel Sambuc         Builder.restoreIP(IP);
3055*0a6a1f1dSLionel Sambuc         deferPlaceholderReplacement(Placeholder, Addr);
3056*0a6a1f1dSLionel Sambuc       } else {
3057*0a6a1f1dSLionel Sambuc         // Store the RValue into the argument struct.
3058*0a6a1f1dSLionel Sambuc         llvm::Value *Addr =
3059*0a6a1f1dSLionel Sambuc             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
3060*0a6a1f1dSLionel Sambuc         unsigned AS = Addr->getType()->getPointerAddressSpace();
3061*0a6a1f1dSLionel Sambuc         llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3062*0a6a1f1dSLionel Sambuc         // There are some cases where a trivial bitcast is not avoidable.  The
3063*0a6a1f1dSLionel Sambuc         // definition of a type later in a translation unit may change it's type
3064*0a6a1f1dSLionel Sambuc         // from {}* to (%struct.foo*)*.
3065*0a6a1f1dSLionel Sambuc         if (Addr->getType() != MemType)
3066*0a6a1f1dSLionel Sambuc           Addr = Builder.CreateBitCast(Addr, MemType);
3067*0a6a1f1dSLionel Sambuc         LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3068*0a6a1f1dSLionel Sambuc         EmitInitStoreOfNonAggregate(*this, RV, argLV);
3069*0a6a1f1dSLionel Sambuc       }
3070*0a6a1f1dSLionel Sambuc       break;
3071*0a6a1f1dSLionel Sambuc     }
3072*0a6a1f1dSLionel Sambuc 
3073f4a2713aSLionel Sambuc     case ABIArgInfo::Indirect: {
3074*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 1);
3075f4a2713aSLionel Sambuc       if (RV.isScalar() || RV.isComplex()) {
3076f4a2713aSLionel Sambuc         // Make a temporary alloca to pass the argument.
3077f4a2713aSLionel Sambuc         llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3078f4a2713aSLionel Sambuc         if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3079f4a2713aSLionel Sambuc           AI->setAlignment(ArgInfo.getIndirectAlign());
3080*0a6a1f1dSLionel Sambuc         IRCallArgs[FirstIRArg] = AI;
3081f4a2713aSLionel Sambuc 
3082*0a6a1f1dSLionel Sambuc         LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
3083*0a6a1f1dSLionel Sambuc         EmitInitStoreOfNonAggregate(*this, RV, argLV);
3084f4a2713aSLionel Sambuc       } else {
3085f4a2713aSLionel Sambuc         // We want to avoid creating an unnecessary temporary+copy here;
3086f4a2713aSLionel Sambuc         // however, we need one in three cases:
3087f4a2713aSLionel Sambuc         // 1. If the argument is not byval, and we are required to copy the
3088f4a2713aSLionel Sambuc         //    source.  (This case doesn't occur on any common architecture.)
3089f4a2713aSLionel Sambuc         // 2. If the argument is byval, RV is not sufficiently aligned, and
3090f4a2713aSLionel Sambuc         //    we cannot force it to be sufficiently aligned.
3091f4a2713aSLionel Sambuc         // 3. If the argument is byval, but RV is located in an address space
3092f4a2713aSLionel Sambuc         //    different than that of the argument (0).
3093f4a2713aSLionel Sambuc         llvm::Value *Addr = RV.getAggregateAddr();
3094f4a2713aSLionel Sambuc         unsigned Align = ArgInfo.getIndirectAlign();
3095f4a2713aSLionel Sambuc         const llvm::DataLayout *TD = &CGM.getDataLayout();
3096f4a2713aSLionel Sambuc         const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
3097*0a6a1f1dSLionel Sambuc         const unsigned ArgAddrSpace =
3098*0a6a1f1dSLionel Sambuc             (FirstIRArg < IRFuncTy->getNumParams()
3099*0a6a1f1dSLionel Sambuc                  ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3100*0a6a1f1dSLionel Sambuc                  : 0);
3101f4a2713aSLionel Sambuc         if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
3102f4a2713aSLionel Sambuc             (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
3103f4a2713aSLionel Sambuc              llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3104f4a2713aSLionel Sambuc              (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
3105f4a2713aSLionel Sambuc           // Create an aligned temporary, and copy to it.
3106f4a2713aSLionel Sambuc           llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3107f4a2713aSLionel Sambuc           if (Align > AI->getAlignment())
3108f4a2713aSLionel Sambuc             AI->setAlignment(Align);
3109*0a6a1f1dSLionel Sambuc           IRCallArgs[FirstIRArg] = AI;
3110f4a2713aSLionel Sambuc           EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
3111f4a2713aSLionel Sambuc         } else {
3112f4a2713aSLionel Sambuc           // Skip the extra memcpy call.
3113*0a6a1f1dSLionel Sambuc           IRCallArgs[FirstIRArg] = Addr;
3114f4a2713aSLionel Sambuc         }
3115f4a2713aSLionel Sambuc       }
3116f4a2713aSLionel Sambuc       break;
3117f4a2713aSLionel Sambuc     }
3118f4a2713aSLionel Sambuc 
3119f4a2713aSLionel Sambuc     case ABIArgInfo::Ignore:
3120*0a6a1f1dSLionel Sambuc       assert(NumIRArgs == 0);
3121f4a2713aSLionel Sambuc       break;
3122f4a2713aSLionel Sambuc 
3123f4a2713aSLionel Sambuc     case ABIArgInfo::Extend:
3124f4a2713aSLionel Sambuc     case ABIArgInfo::Direct: {
3125f4a2713aSLionel Sambuc       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
3126f4a2713aSLionel Sambuc           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3127f4a2713aSLionel Sambuc           ArgInfo.getDirectOffset() == 0) {
3128*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == 1);
3129f4a2713aSLionel Sambuc         llvm::Value *V;
3130f4a2713aSLionel Sambuc         if (RV.isScalar())
3131f4a2713aSLionel Sambuc           V = RV.getScalarVal();
3132f4a2713aSLionel Sambuc         else
3133f4a2713aSLionel Sambuc           V = Builder.CreateLoad(RV.getAggregateAddr());
3134f4a2713aSLionel Sambuc 
3135*0a6a1f1dSLionel Sambuc         // We might have to widen integers, but we should never truncate.
3136*0a6a1f1dSLionel Sambuc         if (ArgInfo.getCoerceToType() != V->getType() &&
3137*0a6a1f1dSLionel Sambuc             V->getType()->isIntegerTy())
3138*0a6a1f1dSLionel Sambuc           V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3139*0a6a1f1dSLionel Sambuc 
3140f4a2713aSLionel Sambuc         // If the argument doesn't match, perform a bitcast to coerce it.  This
3141f4a2713aSLionel Sambuc         // can happen due to trivial type mismatches.
3142*0a6a1f1dSLionel Sambuc         if (FirstIRArg < IRFuncTy->getNumParams() &&
3143*0a6a1f1dSLionel Sambuc             V->getType() != IRFuncTy->getParamType(FirstIRArg))
3144*0a6a1f1dSLionel Sambuc           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3145*0a6a1f1dSLionel Sambuc         IRCallArgs[FirstIRArg] = V;
3146f4a2713aSLionel Sambuc         break;
3147f4a2713aSLionel Sambuc       }
3148f4a2713aSLionel Sambuc 
3149f4a2713aSLionel Sambuc       // FIXME: Avoid the conversion through memory if possible.
3150f4a2713aSLionel Sambuc       llvm::Value *SrcPtr;
3151f4a2713aSLionel Sambuc       if (RV.isScalar() || RV.isComplex()) {
3152f4a2713aSLionel Sambuc         SrcPtr = CreateMemTemp(I->Ty, "coerce");
3153f4a2713aSLionel Sambuc         LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
3154*0a6a1f1dSLionel Sambuc         EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
3155f4a2713aSLionel Sambuc       } else
3156f4a2713aSLionel Sambuc         SrcPtr = RV.getAggregateAddr();
3157f4a2713aSLionel Sambuc 
3158f4a2713aSLionel Sambuc       // If the value is offset in memory, apply the offset now.
3159f4a2713aSLionel Sambuc       if (unsigned Offs = ArgInfo.getDirectOffset()) {
3160f4a2713aSLionel Sambuc         SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3161f4a2713aSLionel Sambuc         SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
3162f4a2713aSLionel Sambuc         SrcPtr = Builder.CreateBitCast(SrcPtr,
3163f4a2713aSLionel Sambuc                        llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3164f4a2713aSLionel Sambuc 
3165f4a2713aSLionel Sambuc       }
3166f4a2713aSLionel Sambuc 
3167*0a6a1f1dSLionel Sambuc       // Fast-isel and the optimizer generally like scalar values better than
3168*0a6a1f1dSLionel Sambuc       // FCAs, so we flatten them if this is safe to do for this argument.
3169*0a6a1f1dSLionel Sambuc       llvm::StructType *STy =
3170*0a6a1f1dSLionel Sambuc             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
3171*0a6a1f1dSLionel Sambuc       if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
3172f4a2713aSLionel Sambuc         llvm::Type *SrcTy =
3173f4a2713aSLionel Sambuc           cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3174f4a2713aSLionel Sambuc         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3175f4a2713aSLionel Sambuc         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3176f4a2713aSLionel Sambuc 
3177f4a2713aSLionel Sambuc         // If the source type is smaller than the destination type of the
3178f4a2713aSLionel Sambuc         // coerce-to logic, copy the source value into a temp alloca the size
3179f4a2713aSLionel Sambuc         // of the destination type to allow loading all of it. The bits past
3180f4a2713aSLionel Sambuc         // the source value are left undef.
3181f4a2713aSLionel Sambuc         if (SrcSize < DstSize) {
3182f4a2713aSLionel Sambuc           llvm::AllocaInst *TempAlloca
3183f4a2713aSLionel Sambuc             = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3184f4a2713aSLionel Sambuc           Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3185f4a2713aSLionel Sambuc           SrcPtr = TempAlloca;
3186f4a2713aSLionel Sambuc         } else {
3187f4a2713aSLionel Sambuc           SrcPtr = Builder.CreateBitCast(SrcPtr,
3188f4a2713aSLionel Sambuc                                          llvm::PointerType::getUnqual(STy));
3189f4a2713aSLionel Sambuc         }
3190f4a2713aSLionel Sambuc 
3191*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == STy->getNumElements());
3192f4a2713aSLionel Sambuc         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3193f4a2713aSLionel Sambuc           llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
3194f4a2713aSLionel Sambuc           llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3195f4a2713aSLionel Sambuc           // We don't know what we're loading from.
3196f4a2713aSLionel Sambuc           LI->setAlignment(1);
3197*0a6a1f1dSLionel Sambuc           IRCallArgs[FirstIRArg + i] = LI;
3198f4a2713aSLionel Sambuc         }
3199f4a2713aSLionel Sambuc       } else {
3200f4a2713aSLionel Sambuc         // In the simple case, just pass the coerced loaded value.
3201*0a6a1f1dSLionel Sambuc         assert(NumIRArgs == 1);
3202*0a6a1f1dSLionel Sambuc         IRCallArgs[FirstIRArg] =
3203*0a6a1f1dSLionel Sambuc             CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
3204f4a2713aSLionel Sambuc       }
3205f4a2713aSLionel Sambuc 
3206f4a2713aSLionel Sambuc       break;
3207f4a2713aSLionel Sambuc     }
3208f4a2713aSLionel Sambuc 
3209f4a2713aSLionel Sambuc     case ABIArgInfo::Expand:
3210*0a6a1f1dSLionel Sambuc       unsigned IRArgPos = FirstIRArg;
3211*0a6a1f1dSLionel Sambuc       ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3212*0a6a1f1dSLionel Sambuc       assert(IRArgPos == FirstIRArg + NumIRArgs);
3213f4a2713aSLionel Sambuc       break;
3214f4a2713aSLionel Sambuc     }
3215f4a2713aSLionel Sambuc   }
3216f4a2713aSLionel Sambuc 
3217*0a6a1f1dSLionel Sambuc   if (ArgMemory) {
3218*0a6a1f1dSLionel Sambuc     llvm::Value *Arg = ArgMemory;
3219*0a6a1f1dSLionel Sambuc     if (CallInfo.isVariadic()) {
3220*0a6a1f1dSLionel Sambuc       // When passing non-POD arguments by value to variadic functions, we will
3221*0a6a1f1dSLionel Sambuc       // end up with a variadic prototype and an inalloca call site.  In such
3222*0a6a1f1dSLionel Sambuc       // cases, we can't do any parameter mismatch checks.  Give up and bitcast
3223*0a6a1f1dSLionel Sambuc       // the callee.
3224*0a6a1f1dSLionel Sambuc       unsigned CalleeAS =
3225*0a6a1f1dSLionel Sambuc           cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3226*0a6a1f1dSLionel Sambuc       Callee = Builder.CreateBitCast(
3227*0a6a1f1dSLionel Sambuc           Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3228*0a6a1f1dSLionel Sambuc     } else {
3229*0a6a1f1dSLionel Sambuc       llvm::Type *LastParamTy =
3230*0a6a1f1dSLionel Sambuc           IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3231*0a6a1f1dSLionel Sambuc       if (Arg->getType() != LastParamTy) {
3232*0a6a1f1dSLionel Sambuc #ifndef NDEBUG
3233*0a6a1f1dSLionel Sambuc         // Assert that these structs have equivalent element types.
3234*0a6a1f1dSLionel Sambuc         llvm::StructType *FullTy = CallInfo.getArgStruct();
3235*0a6a1f1dSLionel Sambuc         llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3236*0a6a1f1dSLionel Sambuc             cast<llvm::PointerType>(LastParamTy)->getElementType());
3237*0a6a1f1dSLionel Sambuc         assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3238*0a6a1f1dSLionel Sambuc         for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3239*0a6a1f1dSLionel Sambuc                                                 DE = DeclaredTy->element_end(),
3240*0a6a1f1dSLionel Sambuc                                                 FI = FullTy->element_begin();
3241*0a6a1f1dSLionel Sambuc              DI != DE; ++DI, ++FI)
3242*0a6a1f1dSLionel Sambuc           assert(*DI == *FI);
3243*0a6a1f1dSLionel Sambuc #endif
3244*0a6a1f1dSLionel Sambuc         Arg = Builder.CreateBitCast(Arg, LastParamTy);
3245*0a6a1f1dSLionel Sambuc       }
3246*0a6a1f1dSLionel Sambuc     }
3247*0a6a1f1dSLionel Sambuc     assert(IRFunctionArgs.hasInallocaArg());
3248*0a6a1f1dSLionel Sambuc     IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
3249*0a6a1f1dSLionel Sambuc   }
3250*0a6a1f1dSLionel Sambuc 
3251f4a2713aSLionel Sambuc   if (!CallArgs.getCleanupsToDeactivate().empty())
3252f4a2713aSLionel Sambuc     deactivateArgCleanupsBeforeCall(*this, CallArgs);
3253f4a2713aSLionel Sambuc 
3254f4a2713aSLionel Sambuc   // If the callee is a bitcast of a function to a varargs pointer to function
3255f4a2713aSLionel Sambuc   // type, check to see if we can remove the bitcast.  This handles some cases
3256f4a2713aSLionel Sambuc   // with unprototyped functions.
3257f4a2713aSLionel Sambuc   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3258f4a2713aSLionel Sambuc     if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
3259f4a2713aSLionel Sambuc       llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3260f4a2713aSLionel Sambuc       llvm::FunctionType *CurFT =
3261f4a2713aSLionel Sambuc         cast<llvm::FunctionType>(CurPT->getElementType());
3262f4a2713aSLionel Sambuc       llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
3263f4a2713aSLionel Sambuc 
3264f4a2713aSLionel Sambuc       if (CE->getOpcode() == llvm::Instruction::BitCast &&
3265f4a2713aSLionel Sambuc           ActualFT->getReturnType() == CurFT->getReturnType() &&
3266f4a2713aSLionel Sambuc           ActualFT->getNumParams() == CurFT->getNumParams() &&
3267*0a6a1f1dSLionel Sambuc           ActualFT->getNumParams() == IRCallArgs.size() &&
3268f4a2713aSLionel Sambuc           (CurFT->isVarArg() || !ActualFT->isVarArg())) {
3269f4a2713aSLionel Sambuc         bool ArgsMatch = true;
3270f4a2713aSLionel Sambuc         for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3271f4a2713aSLionel Sambuc           if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3272f4a2713aSLionel Sambuc             ArgsMatch = false;
3273f4a2713aSLionel Sambuc             break;
3274f4a2713aSLionel Sambuc           }
3275f4a2713aSLionel Sambuc 
3276f4a2713aSLionel Sambuc         // Strip the cast if we can get away with it.  This is a nice cleanup,
3277f4a2713aSLionel Sambuc         // but also allows us to inline the function at -O0 if it is marked
3278f4a2713aSLionel Sambuc         // always_inline.
3279f4a2713aSLionel Sambuc         if (ArgsMatch)
3280f4a2713aSLionel Sambuc           Callee = CalleeF;
3281f4a2713aSLionel Sambuc       }
3282f4a2713aSLionel Sambuc     }
3283f4a2713aSLionel Sambuc 
3284*0a6a1f1dSLionel Sambuc   assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3285*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3286*0a6a1f1dSLionel Sambuc     // Inalloca argument can have different type.
3287*0a6a1f1dSLionel Sambuc     if (IRFunctionArgs.hasInallocaArg() &&
3288*0a6a1f1dSLionel Sambuc         i == IRFunctionArgs.getInallocaArgNo())
3289*0a6a1f1dSLionel Sambuc       continue;
3290*0a6a1f1dSLionel Sambuc     if (i < IRFuncTy->getNumParams())
3291*0a6a1f1dSLionel Sambuc       assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3292*0a6a1f1dSLionel Sambuc   }
3293*0a6a1f1dSLionel Sambuc 
3294f4a2713aSLionel Sambuc   unsigned CallingConv;
3295f4a2713aSLionel Sambuc   CodeGen::AttributeListType AttributeList;
3296f4a2713aSLionel Sambuc   CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3297f4a2713aSLionel Sambuc                              CallingConv, true);
3298f4a2713aSLionel Sambuc   llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
3299f4a2713aSLionel Sambuc                                                      AttributeList);
3300f4a2713aSLionel Sambuc 
3301*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *InvokeDest = nullptr;
3302f4a2713aSLionel Sambuc   if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3303f4a2713aSLionel Sambuc                           llvm::Attribute::NoUnwind))
3304f4a2713aSLionel Sambuc     InvokeDest = getInvokeDest();
3305f4a2713aSLionel Sambuc 
3306f4a2713aSLionel Sambuc   llvm::CallSite CS;
3307f4a2713aSLionel Sambuc   if (!InvokeDest) {
3308*0a6a1f1dSLionel Sambuc     CS = Builder.CreateCall(Callee, IRCallArgs);
3309f4a2713aSLionel Sambuc   } else {
3310f4a2713aSLionel Sambuc     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
3311*0a6a1f1dSLionel Sambuc     CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
3312f4a2713aSLionel Sambuc     EmitBlock(Cont);
3313f4a2713aSLionel Sambuc   }
3314f4a2713aSLionel Sambuc   if (callOrInvoke)
3315f4a2713aSLionel Sambuc     *callOrInvoke = CS.getInstruction();
3316f4a2713aSLionel Sambuc 
3317*0a6a1f1dSLionel Sambuc   if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3318*0a6a1f1dSLionel Sambuc       !CS.hasFnAttr(llvm::Attribute::NoInline))
3319*0a6a1f1dSLionel Sambuc     Attrs =
3320*0a6a1f1dSLionel Sambuc         Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3321*0a6a1f1dSLionel Sambuc                            llvm::Attribute::AlwaysInline);
3322*0a6a1f1dSLionel Sambuc 
3323f4a2713aSLionel Sambuc   CS.setAttributes(Attrs);
3324f4a2713aSLionel Sambuc   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
3325f4a2713aSLionel Sambuc 
3326f4a2713aSLionel Sambuc   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3327f4a2713aSLionel Sambuc   // optimizer it can aggressively ignore unwind edges.
3328f4a2713aSLionel Sambuc   if (CGM.getLangOpts().ObjCAutoRefCount)
3329f4a2713aSLionel Sambuc     AddObjCARCExceptionMetadata(CS.getInstruction());
3330f4a2713aSLionel Sambuc 
3331f4a2713aSLionel Sambuc   // If the call doesn't return, finish the basic block and clear the
3332f4a2713aSLionel Sambuc   // insertion point; this allows the rest of IRgen to discard
3333f4a2713aSLionel Sambuc   // unreachable code.
3334f4a2713aSLionel Sambuc   if (CS.doesNotReturn()) {
3335f4a2713aSLionel Sambuc     Builder.CreateUnreachable();
3336f4a2713aSLionel Sambuc     Builder.ClearInsertionPoint();
3337f4a2713aSLionel Sambuc 
3338f4a2713aSLionel Sambuc     // FIXME: For now, emit a dummy basic block because expr emitters in
3339f4a2713aSLionel Sambuc     // generally are not ready to handle emitting expressions at unreachable
3340f4a2713aSLionel Sambuc     // points.
3341f4a2713aSLionel Sambuc     EnsureInsertPoint();
3342f4a2713aSLionel Sambuc 
3343f4a2713aSLionel Sambuc     // Return a reasonable RValue.
3344f4a2713aSLionel Sambuc     return GetUndefRValue(RetTy);
3345f4a2713aSLionel Sambuc   }
3346f4a2713aSLionel Sambuc 
3347f4a2713aSLionel Sambuc   llvm::Instruction *CI = CS.getInstruction();
3348f4a2713aSLionel Sambuc   if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
3349f4a2713aSLionel Sambuc     CI->setName("call");
3350f4a2713aSLionel Sambuc 
3351f4a2713aSLionel Sambuc   // Emit any writebacks immediately.  Arguably this should happen
3352f4a2713aSLionel Sambuc   // after any return-value munging.
3353f4a2713aSLionel Sambuc   if (CallArgs.hasWritebacks())
3354f4a2713aSLionel Sambuc     emitWritebacks(*this, CallArgs);
3355f4a2713aSLionel Sambuc 
3356*0a6a1f1dSLionel Sambuc   // The stack cleanup for inalloca arguments has to run out of the normal
3357*0a6a1f1dSLionel Sambuc   // lexical order, so deactivate it and run it manually here.
3358*0a6a1f1dSLionel Sambuc   CallArgs.freeArgumentMemory(*this);
3359*0a6a1f1dSLionel Sambuc 
3360*0a6a1f1dSLionel Sambuc   RValue Ret = [&] {
3361f4a2713aSLionel Sambuc     switch (RetAI.getKind()) {
3362*0a6a1f1dSLionel Sambuc     case ABIArgInfo::InAlloca:
3363f4a2713aSLionel Sambuc     case ABIArgInfo::Indirect:
3364*0a6a1f1dSLionel Sambuc       return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3365f4a2713aSLionel Sambuc 
3366f4a2713aSLionel Sambuc     case ABIArgInfo::Ignore:
3367f4a2713aSLionel Sambuc       // If we are ignoring an argument that had a result, make sure to
3368f4a2713aSLionel Sambuc       // construct the appropriate return value for our caller.
3369f4a2713aSLionel Sambuc       return GetUndefRValue(RetTy);
3370f4a2713aSLionel Sambuc 
3371f4a2713aSLionel Sambuc     case ABIArgInfo::Extend:
3372f4a2713aSLionel Sambuc     case ABIArgInfo::Direct: {
3373f4a2713aSLionel Sambuc       llvm::Type *RetIRTy = ConvertType(RetTy);
3374f4a2713aSLionel Sambuc       if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3375f4a2713aSLionel Sambuc         switch (getEvaluationKind(RetTy)) {
3376f4a2713aSLionel Sambuc         case TEK_Complex: {
3377f4a2713aSLionel Sambuc           llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3378f4a2713aSLionel Sambuc           llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3379f4a2713aSLionel Sambuc           return RValue::getComplex(std::make_pair(Real, Imag));
3380f4a2713aSLionel Sambuc         }
3381f4a2713aSLionel Sambuc         case TEK_Aggregate: {
3382f4a2713aSLionel Sambuc           llvm::Value *DestPtr = ReturnValue.getValue();
3383f4a2713aSLionel Sambuc           bool DestIsVolatile = ReturnValue.isVolatile();
3384f4a2713aSLionel Sambuc 
3385f4a2713aSLionel Sambuc           if (!DestPtr) {
3386f4a2713aSLionel Sambuc             DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3387f4a2713aSLionel Sambuc             DestIsVolatile = false;
3388f4a2713aSLionel Sambuc           }
3389f4a2713aSLionel Sambuc           BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3390f4a2713aSLionel Sambuc           return RValue::getAggregate(DestPtr);
3391f4a2713aSLionel Sambuc         }
3392f4a2713aSLionel Sambuc         case TEK_Scalar: {
3393f4a2713aSLionel Sambuc           // If the argument doesn't match, perform a bitcast to coerce it.  This
3394f4a2713aSLionel Sambuc           // can happen due to trivial type mismatches.
3395f4a2713aSLionel Sambuc           llvm::Value *V = CI;
3396f4a2713aSLionel Sambuc           if (V->getType() != RetIRTy)
3397f4a2713aSLionel Sambuc             V = Builder.CreateBitCast(V, RetIRTy);
3398f4a2713aSLionel Sambuc           return RValue::get(V);
3399f4a2713aSLionel Sambuc         }
3400f4a2713aSLionel Sambuc         }
3401f4a2713aSLionel Sambuc         llvm_unreachable("bad evaluation kind");
3402f4a2713aSLionel Sambuc       }
3403f4a2713aSLionel Sambuc 
3404f4a2713aSLionel Sambuc       llvm::Value *DestPtr = ReturnValue.getValue();
3405f4a2713aSLionel Sambuc       bool DestIsVolatile = ReturnValue.isVolatile();
3406f4a2713aSLionel Sambuc 
3407f4a2713aSLionel Sambuc       if (!DestPtr) {
3408f4a2713aSLionel Sambuc         DestPtr = CreateMemTemp(RetTy, "coerce");
3409f4a2713aSLionel Sambuc         DestIsVolatile = false;
3410f4a2713aSLionel Sambuc       }
3411f4a2713aSLionel Sambuc 
3412f4a2713aSLionel Sambuc       // If the value is offset in memory, apply the offset now.
3413f4a2713aSLionel Sambuc       llvm::Value *StorePtr = DestPtr;
3414f4a2713aSLionel Sambuc       if (unsigned Offs = RetAI.getDirectOffset()) {
3415f4a2713aSLionel Sambuc         StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3416f4a2713aSLionel Sambuc         StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3417f4a2713aSLionel Sambuc         StorePtr = Builder.CreateBitCast(StorePtr,
3418f4a2713aSLionel Sambuc                            llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3419f4a2713aSLionel Sambuc       }
3420f4a2713aSLionel Sambuc       CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3421f4a2713aSLionel Sambuc 
3422f4a2713aSLionel Sambuc       return convertTempToRValue(DestPtr, RetTy, SourceLocation());
3423f4a2713aSLionel Sambuc     }
3424f4a2713aSLionel Sambuc 
3425f4a2713aSLionel Sambuc     case ABIArgInfo::Expand:
3426f4a2713aSLionel Sambuc       llvm_unreachable("Invalid ABI kind for return argument");
3427f4a2713aSLionel Sambuc     }
3428f4a2713aSLionel Sambuc 
3429f4a2713aSLionel Sambuc     llvm_unreachable("Unhandled ABIArgInfo::Kind");
3430*0a6a1f1dSLionel Sambuc   } ();
3431*0a6a1f1dSLionel Sambuc 
3432*0a6a1f1dSLionel Sambuc   if (Ret.isScalar() && TargetDecl) {
3433*0a6a1f1dSLionel Sambuc     if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3434*0a6a1f1dSLionel Sambuc       llvm::Value *OffsetValue = nullptr;
3435*0a6a1f1dSLionel Sambuc       if (const auto *Offset = AA->getOffset())
3436*0a6a1f1dSLionel Sambuc         OffsetValue = EmitScalarExpr(Offset);
3437*0a6a1f1dSLionel Sambuc 
3438*0a6a1f1dSLionel Sambuc       llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3439*0a6a1f1dSLionel Sambuc       llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3440*0a6a1f1dSLionel Sambuc       EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3441*0a6a1f1dSLionel Sambuc                               OffsetValue);
3442*0a6a1f1dSLionel Sambuc     }
3443*0a6a1f1dSLionel Sambuc   }
3444*0a6a1f1dSLionel Sambuc 
3445*0a6a1f1dSLionel Sambuc   return Ret;
3446f4a2713aSLionel Sambuc }
3447f4a2713aSLionel Sambuc 
3448f4a2713aSLionel Sambuc /* VarArg handling */
3449f4a2713aSLionel Sambuc 
EmitVAArg(llvm::Value * VAListAddr,QualType Ty)3450f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3451f4a2713aSLionel Sambuc   return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3452f4a2713aSLionel Sambuc }
3453